diff --git a/.config/nextest.toml b/.config/nextest.toml index b1f10fc0fd..922a54fdb4 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -63,7 +63,7 @@ archive.include = [ # warning still comes at 15 s; a run past 90 s is terminated. [[profile.ci.overrides]] filter = 'binary(panic_hunt)' -slow-timeout = { period = "15s", terminate-after = 6 } +slow-timeout = { period = "15s", terminate-after = 12 } # Content-Aware Move solves on rayon across every core. On the Windows runner the GPU tests draw # on the CPU-backed adapter, so two of these beside a GPU test starve it until its device poll diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index 1c4e9a434c..c9404bb1a6 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -4,10 +4,10 @@ "repository_id": 1398080271, "producer_workflow_id": 428462603, "producer_workflow_path": ".github/workflows/nightly.yml", - "producer_tooling_revision": "8389cad8b849ea6bdb5e15fbce16772c3457565a", - "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@8389cad8b849ea6bdb5e15fbce16772c3457565a", + "producer_tooling_revision": "main", + "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main", "signer_workflow_path": ".github/workflows/nightly-sign.yml", - "signer_tooling_revision": "8389cad8b849ea6bdb5e15fbce16772c3457565a", + "signer_tooling_revision": "main", "release_branch": "nightly-signer", "manual_actors": [ "bflatastic", @@ -186,14 +186,6 @@ "severity": "MAJOR", "hash": "487390be64dd83ce33912f980c863775" }, - { - "key": "AaH2uKhnARfBzs_vH5to", - "rule": "pythonsecurity:S2083", - "component": "storytold_photocraft:scripts/ci-test-times.py", - "type": "VULNERABILITY", - "severity": "BLOCKER", - "hash": "49be67b6e92adfd1925fe265def3f32f" - }, { "key": "AaH2uKhnARfBzs_vH5tp", "rule": "pythonsecurity:S8705", diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4359272aca..47c0dc60c0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -369,7 +369,7 @@ jobs: libgtk-3-dev - id: rust - uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939 + uses: storytold/craft-common-actions/actions/rust-channel@main - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 with: toolchain: ${{ steps.rust.outputs.toolchain }} @@ -417,7 +417,7 @@ jobs: uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main - id: rust - uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939 + uses: storytold/craft-common-actions/actions/rust-channel@main - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 with: toolchain: ${{ steps.rust.outputs.toolchain }} @@ -542,7 +542,7 @@ jobs: libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev libgtk-3-dev - id: rust - uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939 + uses: storytold/craft-common-actions/actions/rust-channel@main - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 with: toolchain: ${{ steps.rust.outputs.toolchain }} @@ -579,7 +579,7 @@ jobs: libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev libgtk-3-dev - id: rust - uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939 + uses: storytold/craft-common-actions/actions/rust-channel@main - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 with: toolchain: ${{ steps.rust.outputs.toolchain }} @@ -615,7 +615,7 @@ jobs: with: persist-credentials: false - id: rust - uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939 + uses: storytold/craft-common-actions/actions/rust-channel@main - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 with: toolchain: ${{ steps.rust.outputs.toolchain }} @@ -652,7 +652,7 @@ jobs: with: persist-credentials: false - id: rust - uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939 + uses: storytold/craft-common-actions/actions/rust-channel@main - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 with: toolchain: ${{ steps.rust.outputs.toolchain }} @@ -689,7 +689,7 @@ jobs: ref: ${{ inputs.brush_tip_base }} path: before - id: rust - uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939 + uses: storytold/craft-common-actions/actions/rust-channel@main - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 with: toolchain: ${{ steps.rust.outputs.toolchain }} @@ -744,7 +744,7 @@ jobs: mkdir -p "$RUNNER_TEMP/photocraft-baseline/crates/engine/examples" cp crates/engine/examples/bench_dry_mixer.rs "$RUNNER_TEMP/photocraft-baseline/crates/engine/examples/bench_dry_mixer.rs" - id: rust - uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939 + uses: storytold/craft-common-actions/actions/rust-channel@main - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 with: toolchain: ${{ steps.rust.outputs.toolchain }} diff --git a/.github/workflows/nightly-macos.yml b/.github/workflows/nightly-macos.yml index be5008ff53..1857158444 100644 --- a/.github/workflows/nightly-macos.yml +++ b/.github/workflows/nightly-macos.yml @@ -44,12 +44,12 @@ jobs: persist-credentials: false # The release's pin (release.yml craft-fonts-ref), so the bundle's notices match a shipped build. - name: Check out craft-fonts - uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939 + uses: storytold/craft-common-actions/actions/checkout-craft-fonts@main with: ref: cc9269cd8d8258785dac603fba3122e5d2556795 - - uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939 + - uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main - id: rust - uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939 + uses: storytold/craft-common-actions/actions/rust-channel@main with: targets: aarch64-apple-darwin - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml index a1dce98818..4be859caf7 100644 --- a/.github/workflows/nightly-sign.yml +++ b/.github/workflows/nightly-sign.yml @@ -35,12 +35,25 @@ jobs: checks: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@8389cad8b849ea6bdb5e15fbce16772c3457565a + uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main with: - tooling-revision: 8389cad8b849ea6bdb5e15fbce16772c3457565a + tooling-revision: main app-name: photocraft producer_run_id: ${{ inputs.producer_run_id }} producer_run_attempt: ${{ inputs.producer_run_attempt }} - # No secrets: inherit or raw platform values in this caller. Only the isolated native - # callee job may bind the existing release environment (which trusts release and - # nightly-signer) and export keys in its signing step. + # Declare only same-name inputs required by the reusable signer. Only native callee + # signing jobs bind the release environment; do not copy credentials to caller scope. + secrets: + APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} + APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} + KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }} + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }} + AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }} + AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }} + AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }} + AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }} + AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }} + LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }} diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 2257309d10..c52b72705a 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -22,12 +22,13 @@ jobs: actions: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@8389cad8b849ea6bdb5e15fbce16772c3457565a + uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main with: - tooling-revision: 8389cad8b849ea6bdb5e15fbce16772c3457565a + tooling-revision: main app-name: photocraft manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' craft-fonts-ref: cc9269cd8d8258785dac603fba3122e5d2556795 # One producer run builds every listed platform for one all-or-nothing release. The pin is the # craft-common-actions main commit that merged #371 (built-commit Sonar admission), on #370. platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]' + linux-package-formats: '["deb","rpm","appimage","flatpak","oci"]' diff --git a/.github/workflows/notify-services.yml b/.github/workflows/notify-services.yml new file mode 100644 index 0000000000..3dc8eaf4ac --- /dev/null +++ b/.github/workflows/notify-services.yml @@ -0,0 +1,20 @@ +name: Notify Services on Release Change + +on: + release: + types: + - published + - unpublished + - created + - edited + - deleted + - prereleased + - released + +permissions: {} + +jobs: + notify: + uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main + secrets: + ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }} diff --git a/.github/workflows/perf-nightly.yml b/.github/workflows/perf-nightly.yml index eeb8101b6d..50db0066d7 100644 --- a/.github/workflows/perf-nightly.yml +++ b/.github/workflows/perf-nightly.yml @@ -52,7 +52,7 @@ jobs: persist-credentials: false - id: rust - uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939 + uses: storytold/craft-common-actions/actions/rust-channel@main - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 with: toolchain: ${{ steps.rust.outputs.toolchain }} diff --git a/AGENTS.md b/AGENTS.md index a92f36f12f..490b9f8905 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -87,6 +87,7 @@ cargo xtask test-corpus # psd, io, codecs, compose, gpu, text, format Conventions and paths: - `unsafe` is allowed only in `crates/tablet/src/macos.rs` and `windows.rs`; the workspace sets `unsafe_code = "forbid"`. The example plug-in in `examples/plugins/` is outside the workspace and uses `unsafe` for the WebAssembly host calls. Every new crate sets `[lints] workspace = true`. +- Parity headless column ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `cargo xtask parity` marks a catalog item `headless: yes` only when `photocraft_engine::commands::find` has its id, the registry `photocraft-cli` and the MCP server load. Panel toggles, workspaces and tool shortcuts that are live only in the desktop app are `no` (window). Other ids take a `no`/`partial` mark with a `window`, `os` or `engine-gap` reach from `HEADLESS` in `crates/ui-egui/src/menus/parity.rs`, or read `unknown`. Never write `yes` there; stale marks fail `headless_marks_are_current`. - Attribution file: `ATTRIBUTION.md`. Fonts come from storytold/craft-fonts through `CRAFT_FONTS_DIR` (`docs/development.md` > Fonts). - Test corpora: storytold/photocraft-corpus, fetched into `corpus/` by `cargo xtask corpus --all` at the pins in `xtask/src/corpus_pins.rs`. `cargo xtask test-corpus` runs each directory's fixed sample; `PHOTOCRAFT_FULL_SWEEP=1` runs every file (CI: samples on pull requests and main, every file nightly). - Feature names are recorded in `docs/feature-names.md`. diff --git a/Cargo.lock b/Cargo.lock index f184c74d1e..eac136adde 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1365,7 +1365,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-automation", "craft-behavior", @@ -1406,7 +1406,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "crc32fast", "flate2", @@ -1427,7 +1427,7 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -1438,7 +1438,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "rustix 1.1.6", ] @@ -1446,7 +1446,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1471,7 +1471,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1489,7 +1489,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-behavior", "craft-docpath", @@ -1507,7 +1507,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "egui", ] @@ -1515,7 +1515,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "md-5", "rayon", @@ -1524,12 +1524,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" [[package]] name = "craft-color" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "serde", ] @@ -1537,7 +1537,7 @@ dependencies = [ [[package]] name = "craft-color-transform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-cms", "craft-color", @@ -1547,7 +1547,7 @@ dependencies = [ [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-behavior", "craft-cms", @@ -1567,23 +1567,33 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-ai-agents", "craft-atomic", + "craft-control-protocol", "craft-flags", "craft-platform", "dirs", - "getrandom 0.3.4", "log", "serde", "serde_json", ] +[[package]] +name = "craft-control-protocol" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" +dependencies = [ + "getrandom 0.3.4", + "serde_json", + "subtle", +] + [[package]] name = "craft-crs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-metadata", "craft-xml", @@ -1593,7 +1603,7 @@ dependencies = [ [[package]] name = "craft-crw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "thiserror 2.0.21", ] @@ -1601,7 +1611,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "rayon", ] @@ -1609,7 +1619,7 @@ dependencies = [ [[package]] name = "craft-develop" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-color", "craft-color-transform", @@ -1624,7 +1634,7 @@ dependencies = [ [[package]] name = "craft-develop-model" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-geom", "craft-metadata", @@ -1636,7 +1646,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "block2 0.6.2", "craft-appkit", @@ -1662,7 +1672,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "serde", ] @@ -1670,7 +1680,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1689,12 +1699,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" [[package]] name = "craft-file-formats" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-eps", "craft-idml", @@ -1712,7 +1722,7 @@ dependencies = [ [[package]] name = "craft-flags" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-atomic", "dirs", @@ -1722,7 +1732,7 @@ dependencies = [ [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1737,7 +1747,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1757,7 +1767,7 @@ dependencies = [ [[package]] name = "craft-font-os-windows" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "windows-registry", "windows-sys 0.61.2", @@ -1766,7 +1776,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "cap-primitives", "craft-atomic", @@ -1789,12 +1799,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" [[package]] name = "craft-geom" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "serde", ] @@ -1802,7 +1812,7 @@ dependencies = [ [[package]] name = "craft-heif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "heic-rs", "rayon", @@ -1811,7 +1821,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1824,7 +1834,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "chrono", "fixed_decimal", @@ -1852,7 +1862,7 @@ dependencies = [ [[package]] name = "craft-idml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-xml", "craft-zip", @@ -1862,7 +1872,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-dds", "craft-heif", @@ -1890,7 +1900,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1908,12 +1918,12 @@ dependencies = [ [[package]] name = "craft-ipp" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#af4e8181e69dd26d6f3537b881dd78ec466d374d" [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "thiserror 2.0.21", ] @@ -1921,7 +1931,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-host", "craft-i18n", @@ -1936,7 +1946,7 @@ dependencies = [ [[package]] name = "craft-kra" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-xml", "craft-zip", @@ -1946,7 +1956,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-behavior", "craft-i18n", @@ -1960,7 +1970,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-behavior", "craft-host", @@ -1978,7 +1988,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1990,7 +2000,7 @@ dependencies = [ [[package]] name = "craft-ora" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-xml", "craft-zip", @@ -2000,7 +2010,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-behavior", "craft-keymap", @@ -2016,11 +2026,11 @@ dependencies = [ [[package]] name = "craft-pcraft-bundle" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "blake3", "craft-atomic", - "craft-pcraft-format", + "craft-pcraft-format 0.1.0 (git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d)", "craft-zip", "ruzstd", "thiserror 2.0.21", @@ -2029,7 +2039,18 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#af4e8181e69dd26d6f3537b881dd78ec466d374d" +dependencies = [ + "flate2", + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-pcraft-format" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "flate2", "serde", @@ -2040,7 +2061,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "bytemuck", "flate2", @@ -2055,7 +2076,7 @@ dependencies = [ [[package]] name = "craft-pdn" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2064,7 +2085,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "async-channel", "async-io", @@ -2095,7 +2116,7 @@ dependencies = [ [[package]] name = "craft-plist" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "thiserror 2.0.21", ] @@ -2103,7 +2124,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-behavior", "craft-host", @@ -2127,7 +2148,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "encoding_rs", "flate2", @@ -2138,7 +2159,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "dispatch2", "egui", @@ -2151,7 +2172,7 @@ dependencies = [ [[package]] name = "craft-raw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "chrono", "craft-crw", @@ -2169,7 +2190,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -2188,7 +2209,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-atomic", "craft-host", @@ -2205,7 +2226,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2226,7 +2247,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-behavior", "craft-keymap", @@ -2238,12 +2259,15 @@ dependencies = [ [[package]] name = "craft-testkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" +dependencies = [ + "rustix 1.1.6", +] [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2266,7 +2290,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2281,7 +2305,7 @@ dependencies = [ [[package]] name = "craft-theme-editor" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-behavior", "craft-theme", @@ -2292,7 +2316,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-atomic", "craft-behavior", @@ -2307,7 +2331,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "serde", "thiserror 2.0.21", @@ -2317,7 +2341,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "serde", "thiserror 2.0.21", @@ -2326,7 +2350,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-behavior", "craft-keymap", @@ -2341,7 +2365,7 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "serde", ] @@ -2349,7 +2373,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2363,7 +2387,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-behavior", "craft-i18n", @@ -2379,7 +2403,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "accesskit", "craft-behavior", @@ -2421,7 +2445,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2432,7 +2456,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-behavior", "craft-host", @@ -2450,7 +2474,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-behavior", "craft-host", @@ -2471,7 +2495,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-behavior", "craft-host", @@ -2491,7 +2515,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-behavior", "craft-host", @@ -2510,13 +2534,15 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ + "base64 0.22.1", "chrono", "craft-host", "craft-theme", "craft-ui", "dunce", + "ed25519-dalek", "egui", "flate2", "image", @@ -2529,6 +2555,7 @@ dependencies = [ "sha2 0.10.9", "tar", "tempfile", + "toml", "ureq", "verifysign", "winreg", @@ -2539,7 +2566,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "winsafe", ] @@ -2547,7 +2574,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "craft-appkit", "craft-atomic", @@ -2579,7 +2606,7 @@ dependencies = [ [[package]] name = "craft-xcf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2588,7 +2615,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "quick-xml 0.41.0", "serde", @@ -2598,7 +2625,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2724,6 +2751,33 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "curve25519-dalek-derive", + "digest 0.10.7", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "darling" version = "0.24.1" @@ -2988,17 +3042,41 @@ dependencies = [ [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "bytemuck", "emath", "serde", ] +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8", + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek", + "ed25519", + "serde", + "sha2 0.10.9", + "subtle", + "zeroize", +] + [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "ahash", "bytemuck", @@ -3035,7 +3113,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "accesskit", "ahash", @@ -3056,7 +3134,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "ahash", "bytemuck", @@ -3075,7 +3153,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "accesskit_winit", "arboard", @@ -3101,7 +3179,7 @@ dependencies = [ [[package]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "ahash", "egui", @@ -3115,7 +3193,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "bytemuck", "egui", @@ -3128,7 +3206,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "dify", "eframe", @@ -3154,7 +3232,7 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "bytemuck", "serde", @@ -3247,7 +3325,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "ahash", "bytemuck", @@ -3274,7 +3352,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" [[package]] name = "equivalent" @@ -3388,6 +3466,12 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693" +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + [[package]] name = "filetime" version = "0.2.29" @@ -4061,7 +4145,7 @@ dependencies = [ [[package]] name = "hayro" version = "0.7.1" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "bytemuck", "hayro-interpret", @@ -4091,7 +4175,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -4109,7 +4193,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -4133,7 +4217,7 @@ checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "flate2", "hayro-ccitt", @@ -4844,9 +4928,9 @@ dependencies = [ [[package]] name = "jpeg-encoder" -version = "0.6.1" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b454d911ac55068f53495488d8ccd0646eaa540c033a28ee15b07838afafb01f" +checksum = "a0370574b86f7eca156b9f298392b5e69a23f8c86f3f865add60bbc2e79467a6" [[package]] name = "js-sys" @@ -5226,7 +5310,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -6657,7 +6741,7 @@ dependencies = [ "craft-develop-model", "craft-file-formats", "craft-image-codecs", - "craft-pcraft-format", + "craft-pcraft-format 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff)", "craft-print", "craft-psd", "craft-tracked", @@ -6749,7 +6833,7 @@ dependencies = [ "blake3", "craft-image-codecs", "craft-pcraft-bundle", - "craft-pcraft-format", + "craft-pcraft-format 0.1.0 (git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d)", "craft-zip", "crc32fast", "exacl", @@ -7147,6 +7231,16 @@ dependencies = [ "system-deps", ] +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + [[package]] name = "pkg-config" version = "0.3.34" @@ -7528,6 +7622,9 @@ name = "rand_core" version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] [[package]] name = "rand_core" @@ -9267,9 +9364,9 @@ dependencies = [ [[package]] name = "toml" -version = "1.2.1+spec-1.1.0" +version = "1.1.8+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" dependencies = [ "indexmap", "serde_core", @@ -9723,7 +9820,7 @@ dependencies = [ [[package]] name = "vello_common" version = "0.0.8" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "bytemuck", "fearless_simd", @@ -9771,7 +9868,7 @@ dependencies = [ [[package]] name = "vello_cpu" version = "0.0.8" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" dependencies = [ "bytemuck", "glifo 0.1.1", @@ -10708,7 +10805,7 @@ checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" [[package]] name = "winit" version = "0.30.13" -source = "git+https://github.com/storytold/winit.git?rev=a517b3846ee8457d84ee4975110bfda6797c44dc#a517b3846ee8457d84ee4975110bfda6797c44dc" +source = "git+https://github.com/storytold/winit.git?rev=f8b490f135ea439dd31aae100bb5591c63cb076f#f8b490f135ea439dd31aae100bb5591c63cb076f" dependencies = [ "ahash", "android-activity", @@ -11402,29 +11499,29 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" [[patch.unused]] name = "egui_inspection" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" [[patch.unused]] name = "egui_system_font_provider" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" [[patch.unused]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" [[patch.unused]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" [[patch.unused]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=af4e8181e69dd26d6f3537b881dd78ec466d374d#af4e8181e69dd26d6f3537b881dd78ec466d374d" diff --git a/Cargo.toml b/Cargo.toml index f888fb6da9..61a0b4004b 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 = "a46af76c7c74dd8dd375d694baaef00d5ae836a2", default-features = false } -craft-tracked = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-ui-macros = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d", default-features = false } +craft-tracked = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } +craft-ui-macros = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } # 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 = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] } +craft-plist = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } +photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } +photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d", 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 = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } photocraft-compose = { path = "crates/compose" } photocraft-gpu = { path = "crates/gpu" } photocraft-paint = { path = "crates/paint" } @@ -48,36 +48,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 = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } # HEIC/HEIF: the shared decoder (replaces crates/heif; craft-libs#784). -craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2", features = ["raster", "write-raster"] } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } +craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d", features = ["raster", "write-raster"] } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } +craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } +craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } +craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } +craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } +craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } +craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } +craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } # Keep the shared embedded-image validation API until the framework revision includes it. -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2", features = ["tree-render", "tree-render-system-fonts"] } -craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d", features = ["tree-render", "tree-render-system-fonts"] } +craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } # Camera-field EXIF reader/writer, shared prerequisite craft-libs#1563. -craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-develop = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-develop-model = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } +craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } +craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } +craft-develop = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } +craft-develop-model = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } # 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 = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } +craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } # 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 = "a46af76c7c74dd8dd375d694baaef00d5ae836a2", features = ["ui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d", features = ["ui"] } thiserror = "2" serde = { version = "1", features = ["derive", "rc"] } serde_json = "1" @@ -350,28 +350,28 @@ 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 = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -hayro = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -vello_common = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -vello_cpu = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } +hayro = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } +vello_common = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } +vello_cpu = { git = "https://github.com/storytold/craft-libs", rev = "af4e8181e69dd26d6f3537b881dd78ec466d374d" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +winit = { git = "https://github.com/storytold/winit.git", rev = "f8b490f135ea439dd31aae100bb5591c63cb076f" } diff --git a/apps/photocraft-cli/build.rs b/apps/photocraft-cli/build.rs index 8983b9c8d6..c1e78c550a 100644 --- a/apps/photocraft-cli/build.rs +++ b/apps/photocraft-cli/build.rs @@ -1,15 +1,21 @@ -//! Windows only: embed the app icon and version info (VERSIONINFO) into `photocraft-cli.exe`. +//! Records the checkout's git commit for `--version` (`git_checkout.rs`, every target), and on +//! Windows only embeds the app icon and version info (VERSIONINFO) into `photocraft-cli.exe`. //! -//! On every other target this does nothing, even when `PHOTOCRAFT_REQUIRE_WINRES` is set. A +//! On every other target the Windows part does nothing, even when `PHOTOCRAFT_REQUIRE_WINRES` is set. A //! missing resource compiler is a warning, so a cross-compile from macOS or Linux still links, //! unless `PHOTOCRAFT_REQUIRE_WINRES=1` (set by the release packaging script) turns it into a //! build error. +#[path = "../photocraft/git_checkout.rs"] +mod git_checkout; + /// Embeds the Windows resources and delay-loads the print-only system DLLs (#8272). fn main() -> std::io::Result<()> { println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-changed=../../assets/app-icon/photocraft.ico"); println!("cargo:rerun-if-env-changed=PHOTOCRAFT_REQUIRE_WINRES"); + println!("cargo:rerun-if-changed=../photocraft/git_checkout.rs"); + git_checkout::emit(); if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { return Ok(()); } diff --git a/apps/photocraft-cli/src/main.rs b/apps/photocraft-cli/src/main.rs index 6e21c2ac44..5113c2c04a 100644 --- a/apps/photocraft-cli/src/main.rs +++ b/apps/photocraft-cli/src/main.rs @@ -3,6 +3,9 @@ fn main() { // May re-execute this process with glibc tuned to return freed document memory (#8743). photocraft_engine::malloc_tuning::apply(); + // The git commit of a dev build's checkout, for `--version` (build.rs, #5247). Before `run`: + // clap reads the version string once. + photocraft_engine::build_info::set_checkout(option_env!("PHOTOCRAFT_CHECKOUT_SHA")); // `args_os`, not `args`: a non-Unicode argument (a Latin-1 file name on Linux) must reach clap, // not panic before anything is printed (issue #1108). let code = photocraft_cli::run(std::env::args_os().skip(1), &mut std::io::stdout(), &mut std::io::stderr()); diff --git a/apps/photocraft/build.rs b/apps/photocraft/build.rs index a4bcba0756..f49abe6a17 100644 --- a/apps/photocraft/build.rs +++ b/apps/photocraft/build.rs @@ -1,9 +1,12 @@ -//! Windows only: embed the app icon and version info (VERSIONINFO) into `photocraft.exe`. +//! Records the checkout's git commit for `--version` (`git_checkout.rs`, every target), and on +//! Windows only embeds the app icon and version info (VERSIONINFO) into `photocraft.exe`. //! -//! On every other target this does nothing. A missing resource compiler is a warning, so a +//! On every other target the Windows part does nothing. A missing resource compiler is a warning, so a //! cross-compile from macOS or Linux still links, unless `PHOTOCRAFT_REQUIRE_WINRES=1` (set by the //! release workflow) turns it into an error. +mod git_checkout; + #[path = "src/build_channel.rs"] mod build_channel; @@ -27,6 +30,8 @@ fn main() { println!("cargo:rerun-if-changed=../../assets/app-icon/photocraft.ico"); println!("cargo:rerun-if-changed=../../assets/app-icon/photocraft-nightly.ico"); println!("cargo:rerun-if-env-changed=PHOTOCRAFT_REQUIRE_WINRES"); + println!("cargo:rerun-if-changed=git_checkout.rs"); + git_checkout::emit(); println!("cargo:rerun-if-env-changed=PHOTOCRAFT_VERSION"); let built_version = if nightly { match std::env::var("PHOTOCRAFT_VERSION") { diff --git a/apps/photocraft/git_checkout.rs b/apps/photocraft/git_checkout.rs new file mode 100644 index 0000000000..38cfa185ec --- /dev/null +++ b/apps/photocraft/git_checkout.rs @@ -0,0 +1,71 @@ +//! Build-script helper shared by the `photocraft` and `photocraft-cli` binaries: the git commit +//! of the source checkout, so a plain `cargo build` from git reports `0.8.2 (dev build, 6f8505421)` +//! (#5247). Release builds set `PHOTOCRAFT_BUILD_SHA` instead and are left alone; without git or +//! outside a checkout of this workspace (a source tarball) nothing is set and the build stays +//! `(dev build)`. The binaries pass the value to `photocraft_engine::build_info::set_checkout`. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +/// Runs `git ` in `dir`; its trimmed output when it succeeds. +fn git(dir: &Path, args: &[&str]) -> Option { + let out = Command::new("git").arg("-C").arg(dir).args(args).output().ok()?; + let s = String::from_utf8(out.stdout).ok()?.trim().to_string(); + (out.status.success() && !s.is_empty()).then_some(s) +} + +/// Emits `PHOTOCRAFT_CHECKOUT_SHA` for the crate whose build script calls it. +pub fn emit() { + println!("cargo:rerun-if-env-changed=PHOTOCRAFT_BUILD_SHA"); + if std::env::var("PHOTOCRAFT_BUILD_SHA").is_ok_and(|s| !s.trim().is_empty()) { + return; + } + let Some(manifest) = std::env::var_os("CARGO_MANIFEST_DIR").map(PathBuf::from) else { return }; + // apps/ → the workspace root. A tarball unpacked inside some other repository must not + // report that repository's commit. + let Some(root) = manifest.parent().and_then(Path::parent).and_then(|r| r.canonicalize().ok()) else { return }; + let Some(top) = git(&root, &["rev-parse", "--show-toplevel"]).and_then(|t| PathBuf::from(t).canonicalize().ok()) else { return }; + if top != root { + return; + } + // Watch before asking for the commit: on an unborn branch `rev-parse HEAD` fails, and the + // first commit must still re-run this script. + for path in watch_paths(&root) { + println!("cargo:rerun-if-changed={}", path.display()); + } + let Some(sha) = git(&root, &["rev-parse", "HEAD"]) else { return }; + println!("cargo:rustc-env=PHOTOCRAFT_CHECKOUT_SHA={sha}"); +} + +/// The git files whose change means HEAD moved: a commit or checkout changes HEAD (detached) or the +/// branch's ref. Cargo treats a watched path that does not exist as always changed (it re-runs the +/// build script and recompiles the binary on every build), so only existing paths are returned. +pub(crate) fn watch_paths(root: &Path) -> Vec { + let mut paths = Vec::new(); + if let Some(dir) = git(root, &["rev-parse", "--absolute-git-dir"]) { + let head = Path::new(&dir).join("HEAD"); + paths.extend(watched(&head, &head)); + } + let Some(common) = git(root, &["rev-parse", "--path-format=absolute", "--git-common-dir"]) else { return paths }; + let common = Path::new(&common); + if git(root, &["rev-parse", "--show-ref-format"]).as_deref() == Some("reftable") { + // Every ref update in a reftable repository rewrites the table stack. + let tables = common.join("reftable").join("tables.list"); + paths.extend(watched(&tables, &tables)); + return paths; + } + if let Some(head_ref) = git(root, &["symbolic-ref", "-q", "HEAD"]) { + // A packed or unborn branch has no loose ref file; the first commit on it creates one, + // which changes the nearest existing directory above it under `refs/`. + paths.extend(watched(&common.join(&head_ref), &common.join("refs"))); + } + let packed = common.join("packed-refs"); + paths.extend(watched(&packed, &packed)); + paths +} + +/// The path Cargo should watch for `path`: `path` itself when it exists, else its nearest existing +/// ancestor that is still inside `stop`; `None` when neither exists. +pub(crate) fn watched(path: &Path, stop: &Path) -> Option { + path.ancestors().take_while(|p| p.starts_with(stop)).find(|p| p.exists()).map(Path::to_path_buf) +} diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index 85f44aa191..b8e0a15926 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -495,6 +495,8 @@ fn main() -> eframe::Result { // Before anything starts a thread: may re-execute this process with glibc tuned to return // the memory of closed documents (#8743). photocraft_engine::malloc_tuning::apply(); + // The git commit of a dev build's checkout, for `--version` and About (build.rs, #5247). + photocraft_engine::build_info::set_checkout(option_env!("PHOTOCRAFT_CHECKOUT_SHA")); // Then, so the panic hook and every start-up warning are recorded (`logging`). let logger = logging::install(); crash_guard::install_hook(); diff --git a/apps/photocraft/src/profile_root.rs b/apps/photocraft/src/profile_root.rs index 8e515c65d9..a51c45504b 100644 --- a/apps/photocraft/src/profile_root.rs +++ b/apps/photocraft/src/profile_root.rs @@ -150,9 +150,17 @@ fn private_subdirectory(root: &Path, name: impl AsRef, label: &str) -> Res if child == chosen || !child.starts_with(&chosen) { return Err(format!("the nightly {label} must stay inside its selected profile")); } + match std::fs::symlink_metadata(&child) { + Ok(metadata) if !metadata.is_dir() => return Err(format!("the nightly {label} must be a directory")), + Ok(_) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")), + } Ok(child) } +const PROFILE_FOLDERS: [&str; 4] = ["Recovery", "AgentFiles", "Presets", "logs"]; + /// Every existing entry directly in the profile (Presets, logs, settings and so on) must resolve /// inside it, so a link there cannot point Nightly's writes at another app's data. fn entries_stay_inside(root: &Path) -> Result<(), String> { @@ -163,11 +171,56 @@ fn entries_stay_inside(root: &Path) -> Result<(), String> { }; for entry in entries { let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; - private_subdirectory(root, entry.file_name(), "profile entry")?; + let path = entry.path(); + let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; + // Settings and session state are ordinary files, not directories. Keep the existing + // directory-boundary check for folders (including the known folder-only entries). + let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name)); + if metadata.is_file() && !folder_only { + private_regular_file(&path, &metadata)?; + } else { + private_subdirectory(root, entry.file_name(), "profile entry")?; + } } Ok(()) } +/// Persisted files must have their own ordinary file identity, not an alias to other data. +fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt as _; + if metadata.nlink() != 1 { + return Err("the nightly profile file must not be shared".into()); + } + } + #[cfg(windows)] + { + use winsafe::{HFILE, co}; + let (file, _) = HFILE::CreateFile( + path.to_str().ok_or("the nightly profile file path is not textual")?, + co::GENERIC::default(), + Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE), + None, + co::DISPOSITION::OPEN_EXISTING, + co::FILE_ATTRIBUTE::NORMAL, + Some(co::FILE_FLAG::OPEN_REPARSE_POINT), + None, + None, + ) + .map_err(|e| e.to_string())?; + let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?; + if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT | co::FILE_ATTRIBUTE::DIRECTORY) { + return Err("the nightly profile file must not be an alias or directory".into()); + } + if info.nNumberOfLinks != 1 { + return Err("the nightly profile file must not be shared".into()); + } + } + let _ = (path, metadata); + Ok(()) +} + /// Recognise the shared portable data namespace in both the supplied and resolved path. /// This is not an inventory of arbitrary custom Stable overrides or a Launcher ownership proof. fn is_portable_layout(path: &Path, platform: Platform) -> bool { @@ -510,6 +563,31 @@ mod tests { assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0); } + #[test] + fn nightly_profile_reopens_after_saving_settings_and_session_state() { + let fixture = Fixture::new(); + for platform in [Platform::Mac, Platform::Linux, Platform::Windows] { + let private = fixture.root.join(format!("nightly-reopen-{platform:?}")); + assert_eq!(fixture.check(platform, &private).unwrap(), private); + for name in ["ui.ron", "settings.json", "nightly-session.lock", "nightly-session.json"] { + std::fs::write(private.join(name), b"saved profile data").unwrap(); + } + for name in PROFILE_FOLDERS { + std::fs::create_dir(private.join(name)).unwrap(); + } + assert_eq!(fixture.check(platform, &private).unwrap(), private); + assert_eq!(std::fs::read(private.join("ui.ron")).unwrap(), b"saved profile data"); + for name in PROFILE_FOLDERS { + let path = private.join(name); + std::fs::remove_dir(&path).unwrap(); + std::fs::write(&path, b"not a directory").unwrap(); + assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory"); + std::fs::remove_file(&path).unwrap(); + std::fs::create_dir(&path).unwrap(); + } + } + } + #[test] fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() { let mut fixture = Fixture::new(); diff --git a/apps/photocraft/tests/it/command_line_usage.rs b/apps/photocraft/tests/it/command_line_usage.rs index a0d8377638..116e1440c8 100644 --- a/apps/photocraft/tests/it/command_line_usage.rs +++ b/apps/photocraft/tests/it/command_line_usage.rs @@ -88,6 +88,9 @@ fn help_wins_over_later_arguments() { fn version_prints_the_long_version() { let Run { status, stdout, .. } = run_photocraft(&["--version", "--safegpu"]); assert_eq!(status.code(), Some(0)); + // The binary records its checkout's commit at startup (#5247); the build script hands the + // same value to this test. + photocraft_engine::build_info::set_checkout(option_env!("PHOTOCRAFT_CHECKOUT_SHA")); assert_eq!(stdout, format!("photocraft {}\n", photocraft_engine::build_info::long_version())); } diff --git a/apps/photocraft/tests/it/git_checkout.rs b/apps/photocraft/tests/it/git_checkout.rs new file mode 100644 index 0000000000..8b05503e78 --- /dev/null +++ b/apps/photocraft/tests/it/git_checkout.rs @@ -0,0 +1,152 @@ +//! The build-script helper `git_checkout.rs` (#5247): Cargo re-runs a build script on every build +//! when a `rerun-if-changed` path is missing, so only existing paths may be watched. + +#[allow(dead_code)] +#[path = "../../git_checkout.rs"] +mod helper; + +use helper::{watch_paths, watched}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command; + +fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("photocraft-git-checkout-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).expect("scratch dir"); + dir +} + +#[test] +fn an_existing_path_is_watched_itself() { + let git = scratch("exists"); + let packed = git.join("packed-refs"); + fs::write(&packed, "").expect("write"); + assert_eq!(watched(&packed, &packed), Some(packed.clone())); + let _ = fs::remove_dir_all(&git); +} + +#[test] +fn a_missing_file_with_no_room_to_climb_is_not_watched() { + let git = scratch("missing"); + let packed = git.join("packed-refs"); + assert_eq!(watched(&packed, &packed), None); + let _ = fs::remove_dir_all(&git); +} + +#[test] +fn a_packed_branch_watches_the_nearest_existing_ref_directory() { + let git = scratch("packed-branch"); + let refs = git.join("refs"); + fs::create_dir_all(refs.join("heads")).expect("refs/heads"); + // `refs/heads/fix/5247` with no `fix/` directory yet: watch `refs/heads`. + assert_eq!(watched(&refs.join("heads/fix/5247"), &refs), Some(refs.join("heads"))); + // Once the loose ref exists it is watched directly. + fs::create_dir_all(refs.join("heads/fix")).expect("refs/heads/fix"); + fs::write(refs.join("heads/fix/5247"), "abc\n").expect("loose ref"); + assert_eq!(watched(&refs.join("heads/fix/5247"), &refs), Some(refs.join("heads/fix/5247"))); + let _ = fs::remove_dir_all(&git); +} + +#[test] +fn the_search_never_leaves_the_stop_directory() { + let git = scratch("stop"); + // `refs/` itself is missing: its parent (the git dir) exists but is outside `stop`. + assert_eq!(watched(&git.join("refs/heads/main"), &git.join("refs")), None); + let _ = fs::remove_dir_all(&git); +} + +/// `git` with the variables that point it at another repository or pick its ref format removed, +/// so a fixture is the repository in its own directory whatever the environment says. +fn git() -> Command { + let mut c = Command::new("git"); + for var in ["GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", "GIT_DEFAULT_REF_FORMAT"] { + c.env_remove(var); + } + c +} + +/// `git init` in a fresh scratch directory with `args`; `None` when this git cannot do it. The +/// files ref format unless `args` ask for another, whatever `init.defaultRefFormat` says (older +/// git ignores the setting). +fn init(name: &str, args: &[&str]) -> Option { + let dir = scratch(name); + let mut cmd = git(); + if !args.iter().any(|a| a.starts_with("--ref-format")) { + cmd.args(["-c", "init.defaultRefFormat=files"]); + } + let ok = cmd.arg("init").arg("-q").args(args).arg(&dir).status().is_ok_and(|s| s.success()); + if ok { + dir.canonicalize().ok() + } else { + let _ = fs::remove_dir_all(&dir); + None + } +} + +fn git_dir(root: &Path) -> PathBuf { + root.join(".git") +} + +/// `watch_paths(root)` canonicalised, so git's `C:/…` output compares equal to the scratch path on +/// Windows and `/var` to `/private/var` on macOS. Panics if any watched path is missing. +fn watched_in(root: &Path) -> Vec { + watch_paths(root).iter().map(|p| p.canonicalize().unwrap_or_else(|e| panic!("{} is watched but missing: {e}", p.display()))).collect() +} + +#[test] +fn an_unborn_branch_still_watches_head_and_the_ref_directory() { + // Before the first commit `rev-parse HEAD` fails; the first commit creates refs/heads/main, + // which must re-run the build script. + let Some(root) = init("unborn", &["-b", "main"]) else { + eprintln!("git init unavailable, skipped"); + return; + }; + let paths = watched_in(&root); + let git = git_dir(&root); + assert!(paths.contains(&git.join("HEAD")), "{paths:?}"); + assert!(paths.iter().any(|p| p.starts_with(git.join("refs"))), "{paths:?}"); + let _ = fs::remove_dir_all(&root); +} + +#[test] +fn a_reftable_checkout_watches_the_table_stack() { + // Branch updates in a reftable repository rewrite reftable/tables.list, not a loose ref or + // packed-refs. Needs git 2.45 or newer; older git cannot create the repository. + let Some(root) = init("reftable", &["-b", "main", "--ref-format=reftable"]) else { + eprintln!("git without reftable support, skipped"); + return; + }; + let paths = watched_in(&root); + let git = git_dir(&root); + assert!(paths.contains(&git.join("reftable").join("tables.list")), "{paths:?}"); + assert!(paths.contains(&git.join("HEAD")), "{paths:?}"); + let _ = fs::remove_dir_all(&root); +} + +#[test] +fn a_files_checkout_watches_the_branch_ref_and_not_a_table_stack() { + let Some(root) = init("files", &["-b", "main"]) else { + eprintln!("git init unavailable, skipped"); + return; + }; + fs::write(git_dir(&root).join("packed-refs"), "").expect("packed-refs"); + let paths = watched_in(&root); + let git = git_dir(&root); + assert!(paths.contains(&git.join("packed-refs")), "{paths:?}"); + assert!(!paths.iter().any(|p| p.starts_with(git.join("reftable"))), "{paths:?}"); + let _ = fs::remove_dir_all(&root); +} + +#[test] +fn outside_a_repository_nothing_is_watched() { + let dir = scratch("no-repo"); + // GIT_CEILING_DIRECTORIES is not set here, so a scratch dir inside a checkout would find it; + // the system temp dir is not inside one on CI or on a developer machine. + if git().arg("-C").arg(&dir).args(["rev-parse", "--git-dir"]).output().is_ok_and(|o| o.status.success()) { + eprintln!("temp dir is inside a git repository, skipped"); + } else { + assert!(watched_in(&dir).is_empty()); + } + let _ = fs::remove_dir_all(&dir); +} diff --git a/apps/photocraft/tests/it/main.rs b/apps/photocraft/tests/it/main.rs index 73bea9196a..f0248ad210 100644 --- a/apps/photocraft/tests/it/main.rs +++ b/apps/photocraft/tests/it/main.rs @@ -2,6 +2,7 @@ mod command_line_usage; mod control_exit_code; +mod git_checkout; mod startup_without_display; /// Nextest archives relocate binaries; plain Cargo keeps the compile-time path valid. diff --git a/crates/algo/src/retouch.rs b/crates/algo/src/retouch.rs index 69ed15194c..ba496d0e48 100644 --- a/crates/algo/src/retouch.rs +++ b/crates/algo/src/retouch.rs @@ -83,6 +83,20 @@ pub fn dodge_burn(c: [f32; 3], e: f32, range: ToneRange, burn: bool, protect_ton } } +/// The default Midtones Dodge (`burn = false`) or Burn of one grey value `v` (0..1) in a Grayscale +/// document or on a layer mask, at Exposure 50 % with Protect Tones on: `v + 0.094·v^0.2·(1 − v)` +/// for Dodge and `v − 0.236·v·(1 − v)^1.15` for Burn. Both are fitted to the reference's 8-bit +/// single-channel results (#12689, #12675), which differ from what an RGB grey gets; each lands +/// within 1 level of the six measured greys. Black and white stay put, tones stay in order, and +/// values outside 0..1 are returned as they are. +#[inline] +pub fn single_channel_midtones(v: f32, burn: bool) -> f32 { + if !(v > 0.0 && v < 1.0) { + return v; + } + if burn { v - 0.236 * v * (1.0 - v).powf(1.15) } else { v + 0.094 * v.powf(0.2) * (1.0 - v) } +} + /// HSV-style saturation (chroma / max) of an RGB triple. #[inline] pub fn saturation(c: [f32; 3]) -> f32 { diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rs index 4164e43cdf..a6021bbccc 100644 --- a/crates/compose/src/effects.rs +++ b/crates/compose/src/effects.rs @@ -246,6 +246,8 @@ impl FxMaps { } } +#[cfg(test)] +mod drop_shadow_anti_alias_tests; #[cfg(test)] mod inner_shadow_anti_alias_tests; #[cfg(test)] diff --git a/crates/compose/src/effects/drop_shadow_anti_alias_tests.rs b/crates/compose/src/effects/drop_shadow_anti_alias_tests.rs new file mode 100644 index 0000000000..2de9b6a114 --- /dev/null +++ b/crates/compose/src/effects/drop_shadow_anti_alias_tests.rs @@ -0,0 +1,241 @@ +//! #14881 - BUG-LAYER-STYLE-DROP-SHADOW-ANTI-ALIASED-IGNORED. +//! +//! Measured on the issue's test document: 400 x 300 px, 72 ppi, RGB 8 bit, white Background, a +//! pixel layer with an orange (255, 128, 0) rectangle at x 100..=299, y 75..=224, Global Light +//! 120 / 30. Black Drop Shadow, Multiply 100 %, Size 10, Distance 0, Spread 0, Noise 0, Contour +//! Gaussian. The tables are the R channel of the flattened image read from a layer edge outwards +//! (255 = no shadow): top = column x 200 from y 74 up, left = row y 150 from x 99, bottom = column +//! x 200 from y 225 down, right = row y 150 from x 300. Outside the layer the shadow multiplies +//! the white Background, so R = 255 x (1 - coverage). +//! +//! On main `shadow_map` read `Shadow::anti_alias` for the Inner Shadow only (#14934), so a Drop +//! Shadow gave one map both ways: every edge read 115 161 205 231 244 250 252 253 254. The +//! reference application's Anti-aliased profile is a drop shadow whose source sits a third of a +//! pixel towards the top-left, the same offset #14934 measured for the Inner Shadow: the top and +//! left edges read 98 147 191 223 241 249 252 254 255, the bottom and right 130 177 214 236 247 +//! 252 254 254 255. + +use super::*; + +const DOC_W: usize = 400; +const DOC_H: usize = 300; + +/// The layer's alpha over the whole document: solid over x 100..=299, y 75..=224. +fn document_shape() -> Map { + let mut m = Map::new(DOC_W, DOC_H, 0.0); + for y in 75..=224 { + for x in 100..=299 { + m.v[y * DOC_W + x] = 1.0; + } + } + m +} + +fn curve(name: &str, pts: &[(f32, f32)]) -> Contour { + Contour::Custom { + name: name.into(), + points: pts.iter().map(|(input, output)| photocraft_doc::adjust::CurvePoint { input: *input, output: *output }).collect(), + // Every inner point of a built-in preset is a corner (the Contour picker stores it that + // way), so the curve is its polyline. + corners: (0..pts.len()).map(|i| i > 0 && i < pts.len() - 1).collect(), + } +} + +/// The Gaussian contour as the built-in preset carries it (`layer_style::CONTOURS`). +fn gaussian() -> Contour { + curve( + "Gaussian", + &[ + (0.0, 0.0), + (0.117, 0.023), + (0.172, 0.055), + (0.234, 0.117), + (0.305, 0.234), + (0.383, 0.414), + (0.523, 0.688), + (0.617, 0.812), + (0.703, 0.891), + (0.805, 0.953), + (1.0, 1.0), + ], + ) +} + +/// A second built-in preset, to show the gate is "the measured contour", not "any curve". +fn cone() -> Contour { + curve( + "Cone", + &[ + (0.0, 0.0), + (0.172, 0.477), + (0.195, 0.555), + (0.266, 0.711), + (0.383, 0.922), + (0.43, 0.969), + (0.477, 0.992), + (0.523, 0.992), + (0.57, 0.969), + (0.664, 0.859), + (0.703, 0.789), + (0.742, 0.711), + (0.836, 0.477), + (0.859, 0.398), + (0.914, 0.266), + (0.945, 0.156), + (0.977, 0.078), + (1.0, 0.0), + ], + ) +} + +/// The issue's Drop Shadow: black, Multiply, 100 %, Global Light 120 / 30, Spread `spread`. +fn shadow(size: f32, distance: f32, spread: f32, contour: Contour, anti_aliased: bool) -> Shadow { + Shadow { + common: photocraft_doc::FxCommon::new(BlendMode::Multiply, 1.0), + color: photocraft_color::Color::BLACK, + angle: 120.0, + use_global_light: true, + distance, + spread, + size, + contour, + anti_alias: anti_aliased, + noise: 0.0, + knocks_out: false, + } +} + +fn map(size: f32, distance: f32, spread: f32, contour: Contour, anti_aliased: bool) -> Map { + shadow_map(&document_shape(), &shadow(size, distance, spread, contour, anti_aliased), &GlobalLight::default(), false, (0, 0)) +} + +/// The R channel of the white Background under a black Multiply drop shadow of coverage `c`. +fn r(c: f32) -> f32 { + 255.0 * (1.0 - c) +} + +/// The nine R values outwards from each of the issue's four edges, in the order it reads them. +fn ramps(m: &Map) -> [Vec; 4] { + let line = |first: (i64, i64), step: (i64, i64)| (0..9).map(|k| r(m.get(first.0 + k * step.0, first.1 + k * step.1))).collect(); + [line((200, 74), (0, -1)), line((99, 150), (-1, 0)), line((200, 225), (0, 1)), line((300, 150), (1, 0))] +} + +/// Assert each edge's ramp against `want` within `tol` levels. +fn assert_edges(m: &Map, want: &[&[f32]; 4], tol: f32, what: &str) { + for ((side, got), w) in ["top", "left", "bottom", "right"].iter().zip(ramps(m)).zip(want) { + for (d, (got, want)) in got.iter().zip(*w).enumerate() { + assert!((got - want).abs() <= tol, "{what}, {side} edge, {d} px out: {got:.1} vs measured {want} (within {tol})"); + } + } +} + +/// A hash over every coverage value of a map: the map is bit-for-bit unchanged iff this is. +fn bit_hash(m: &Map) -> u64 { + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for v in &m.v { + h = (h ^ u64::from(v.to_bits())).wrapping_mul(0x0000_0100_0000_01b3); + } + h +} + +/// Done when: on the issue's test document, Gaussian with Anti-aliased gives the measured +/// top/left and bottom/right profiles within 3 levels. *Why* the two pairs of edges differ is not +/// measured; one sub-pixel source offset reproduces both, as it does for the Inner Shadow. +#[test] +fn anti_aliased_gaussian_gives_both_measured_profiles() { + let tl: &[f32] = &[98.0, 147.0, 191.0, 223.0, 241.0, 249.0, 252.0, 254.0, 255.0]; + let br: &[f32] = &[130.0, 177.0, 214.0, 236.0, 247.0, 252.0, 254.0, 254.0, 255.0]; + assert_edges(&map(10.0, 0.0, 0.0, gaussian(), true), &[tl, tl, br, br], 3.0, "Size 10 Gaussian, Anti-aliased"); +} + +/// Done when: without Anti-aliased the profiles stay as today. These are the R values +/// `shadow_map` gave on main, and they sit within 3 levels of the issue's measured Anti-aliased +/// off profile, 114 163 205 231 244 251 253 254 255, on every edge. +#[test] +fn without_anti_alias_the_profiles_stay_as_today() { + let today: [i32; 9] = [115, 161, 205, 231, 244, 250, 252, 253, 254]; + let measured: &[f32] = &[114.0, 163.0, 205.0, 231.0, 244.0, 251.0, 253.0, 254.0, 255.0]; + let m = map(10.0, 0.0, 0.0, gaussian(), false); + for (side, got) in ["top", "left", "bottom", "right"].iter().zip(ramps(&m)) { + for (d, got) in got.iter().enumerate() { + assert_eq!(got.round() as i32, today[d], "Anti-aliased off moved the {side} edge, {d} px out: {got:.2}"); + } + } + assert_edges(&m, &[measured, measured, measured, measured], 3.0, "Size 10 Gaussian, Anti-aliased off"); + assert_eq!(bit_hash(&m), 0x5e49_20b6_9751_cc45, "the Size 10 Gaussian drop shadow map (Anti-aliased off) moved"); +} + +/// The offset is a third of a pixel, so the shadow reaches at most one pixel further at the top +/// and left: it stays inside the effect margin (`margin`: Size + Distance + 2) on every side. +#[test] +fn anti_aliased_stays_inside_the_effect_margin() { + let m = map(10.0, 0.0, 0.0, gaussian(), true); + for (x, y) in [(200i64, 75 - 12), (200, 224 + 12), (100 - 12, 150), (299 + 12, 150), (100 - 12, 75 - 12), (299 + 12, 224 + 12)] { + assert_eq!(m.get(x, y), 0.0, "Anti-aliased drop shadow beyond the effect margin at ({x},{y})"); + } +} + +/// Not measured: Anti-aliased with a contour other than Gaussian. Those keep today's map +/// bit-for-bit - the Linear default and a second built-in curve. +#[test] +fn other_contours_keep_todays_map() { + assert_eq!(bit_hash(&map(10.0, 0.0, 0.0, Contour::Linear, true)), 0x8dc3_4139_f452_da9d, "a Linear drop shadow with Anti-aliased moved"); + assert_eq!(bit_hash(&map(10.0, 0.0, 0.0, Contour::Linear, false)), 0x8dc3_4139_f452_da9d, "a Linear drop shadow without Anti-aliased moved"); + assert_eq!(bit_hash(&map(10.0, 0.0, 0.0, cone(), true)), bit_hash(&map(10.0, 0.0, 0.0, cone(), false)), "a Cone drop shadow moved with Anti-aliased"); +} + +/// The flag off leaves every other Size, Distance and Spread exactly as it was: whole-map hashes +/// `shadow_map` gave on main 610c86b969 before this change. +#[test] +fn the_off_path_is_bit_for_bit_unchanged() { + let hashes: [(f32, u64); 9] = [ + (0.5, 0xa067_0cbe_8a34_6225), + (1.0, 0xa067_0cbe_8a34_6225), + (1.5, 0xdc2a_66a2_b0c4_a04d), + (2.0, 0x2b77_3190_0ec6_f501), + (3.0, 0x202a_f725_63f0_d551), + (6.0, 0x1ba8_550d_7781_8ee9), + (10.0, 0x5e49_20b6_9751_cc45), + (20.0, 0xf1a6_f4c4_f2f3_5d11), + (250.0, 0x0842_22f2_601f_bfb1), + ]; + for (size, want) in hashes { + assert_eq!(bit_hash(&map(size, 0.0, 0.0, gaussian(), false)), want, "the whole Size {size} drop shadow map (Anti-aliased off) moved"); + } + assert_eq!(bit_hash(&map(10.0, 5.0, 0.0, gaussian(), false)), 0xda80_8e81_2a08_7185, "the Size 10 Distance 5 drop shadow map moved"); + assert_eq!(bit_hash(&map(10.0, 0.0, 0.5, gaussian(), false)), 0x5419_4d5e_753c_77a1, "the Size 10 Spread 50 % drop shadow map moved"); +} + +/// The Inner Shadow's gate (`aa_shift`) applies unchanged: a Size whose blur is the identity +/// (Size 1, Size 2 at Spread 50 %) would turn the offset into the whole map, and a Spread that +/// dilates makes the CPU recompute its distance on the offset map while the GPU shifts a +/// whole-pixel field of the unshifted shape. None of them was measured, so they keep today's map. +#[test] +fn degenerate_and_dilating_neighbours_keep_todays_map() { + for (size, spread, what) in [(1.0, 0.0, "Size 1"), (2.0, 0.5, "Size 2 Spread 50 %"), (10.0, 0.5, "Size 10 Spread 50 %"), (10.0, 0.05, "Size 10 Spread 5 %")] + { + assert_eq!( + bit_hash(&map(size, 0.0, spread, gaussian(), true)), + bit_hash(&map(size, 0.0, spread, gaussian(), false)), + "the {what} drop shadow map moved with Anti-aliased" + ); + } +} + +/// Guard: the rule is in the inputs, not keyed to the measured Size 10. Every Size whose blur is +/// wider than the identity takes the offset at Spread 0, and so does a Distance other than 0. +#[test] +fn the_offset_follows_the_inputs_not_the_measured_size() { + for size in [1.5, 2.0, 3.0, 6.0, 20.0, 250.0] { + assert_ne!( + bit_hash(&map(size, 0.0, 0.0, gaussian(), true)), + bit_hash(&map(size, 0.0, 0.0, gaussian(), false)), + "Anti-aliased did nothing at Size {size}, Spread 0" + ); + } + assert_ne!( + bit_hash(&map(10.0, 5.0, 0.0, gaussian(), true)), + bit_hash(&map(10.0, 5.0, 0.0, gaussian(), false)), + "Anti-aliased did nothing at Size 10, Distance 5" + ); +} diff --git a/crates/compose/src/effects/inner_shadow_anti_alias_tests.rs b/crates/compose/src/effects/inner_shadow_anti_alias_tests.rs index 97831c75ba..7bde053c40 100644 --- a/crates/compose/src/effects/inner_shadow_anti_alias_tests.rs +++ b/crates/compose/src/effects/inner_shadow_anti_alias_tests.rs @@ -188,15 +188,16 @@ fn anti_aliased_still_paints_nothing_outside_the_layer() { } /// Not measured: Anti-aliased with a contour other than Gaussian. Those keep today's map -/// bit-for-bit - the Linear default, a second built-in curve, and the Drop Shadow (its own item is -/// #14881). Hashes are the ones these maps had on upstream/main before the change. +/// bit-for-bit - the Linear default and a second built-in curve. Hashes are the ones these maps had +/// on upstream/main before the change. The Drop Shadow's off path is pinned here too; with the flag +/// on it takes the same offset since #14881 (`drop_shadow_anti_alias_tests`). #[test] -fn other_contours_and_the_drop_shadow_keep_todays_map() { +fn other_contours_keep_todays_map() { assert_eq!(bit_hash(&map(10.0, 0.0, 0.0, 0.0, Contour::Linear, true)), 0x2200_2b2d_61bc_9c2d, "a Linear-contour inner shadow with Anti-aliased moved"); assert_eq!(bit_hash(&map(10.0, 0.0, 0.0, 0.0, cone(), true)), 0xb86c_68a7_8a2f_e689, "a Cone-contour inner shadow with Anti-aliased moved"); let drop = |aa: bool| shadow_map(&document_shape(), &shadow(10.0, 0.0, 0.0, 0.0, gaussian(), aa), &GlobalLight::default(), false, (0, 0)); assert_eq!(bit_hash(&drop(false)), 0x5e49_20b6_9751_cc45, "the Drop Shadow Gaussian map (Anti-aliased off) moved"); - assert_eq!(bit_hash(&drop(true)), 0x5e49_20b6_9751_cc45, "the Drop Shadow still ignores Anti-aliased (#14881)"); + assert_ne!(bit_hash(&drop(true)), 0x5e49_20b6_9751_cc45, "the Drop Shadow honours Anti-aliased since #14881"); } /// The flag off leaves every other Size, Distance and Choke exactly as it was. These are the whole diff --git a/crates/compose/src/effects/paint.rs b/crates/compose/src/effects/paint.rs index b079fea59d..84dd4d8fea 100644 --- a/crates/compose/src/effects/paint.rs +++ b/crates/compose/src/effects/paint.rs @@ -502,10 +502,10 @@ pub fn spread_split(size: f32, spread: f32) -> (f32, f32) { pub(super) fn shadow_map(shape: &Map, s: &Shadow, light: &GlobalLight, inner: bool, origin: (i32, i32)) -> Map { let angle = if s.use_global_light { light.angle } else { s.angle }; let (dx, dy) = offset(angle, s.distance); - // #14934: an Anti-aliased Inner Shadow builds its map from the shape off-centre (`aa_shift`). - // Only the inner branch was measured, so a Drop Shadow keeps today's map (#14881 is its own), - // and `aa_shift` leaves every Choke that dilates and every Size whose blur is the identity. - let aa = aa_shift(inner && s.anti_alias, &s.contour, s.size, s.spread); + // #14934 (Inner Shadow) and #14881 (Drop Shadow): an Anti-aliased shadow builds its map from + // the shape off-centre (`aa_shift`); both measured the same third of a pixel. `aa_shift` + // leaves every Choke / Spread that dilates and every Size whose blur is the identity. + let aa = aa_shift(s.anti_alias, &s.contour, s.size, s.spread); let src = if inner { shape.clone().map(|a| 1.0 - a) } else { shape.clone() }; let mut m = src.shifted(dx + aa, dy + aa, if inner { 1.0 } else { 0.0 }); let (r, bw) = spread_split(s.size, s.spread); diff --git a/crates/engine-core/Cargo.toml b/crates/engine-core/Cargo.toml index d947a91afa..9e98cbb775 100644 --- a/crates/engine-core/Cargo.toml +++ b/crates/engine-core/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 = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } +craft-pcraft-tip = { package = "craft-pcraft-format", git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } photocraft-raster = { workspace = true } photocraft-doc = { workspace = true } photocraft-ops = { workspace = true } diff --git a/crates/engine-core/src/build_info.rs b/crates/engine-core/src/build_info.rs index 3ad4da1aba..76267af92a 100644 --- a/crates/engine-core/src/build_info.rs +++ b/crates/engine-core/src/build_info.rs @@ -8,7 +8,11 @@ //! - `PHOTOCRAFT_BUILD_DATE`: the build date, conventionally `YYYY-MM-DD` //! //! Without them (a plain `cargo build`) the build reports itself as a dev build. Nothing here -//! shells out to git, so builds work from a source tarball and for wasm. +//! shells out to git, so builds work from a source tarball and for wasm. The desktop and CLI +//! binaries' build scripts do read the commit of a git checkout and hand it over with +//! [`set_checkout`] at startup, so a dev build from git says which commit it is +//! (`0.1.0 (dev build, 3f2a9c1d0)`); keeping it out of this crate means a commit doesn't rebuild +//! the engine. /// The workspace version, such as `0.1.0` or `0.2.0-rc.1`. pub const VERSION: &str = match option_env!("PHOTOCRAFT_OVERRIDE_VERSION") { @@ -31,12 +35,30 @@ pub fn build_date() -> Option<&'static str> { /// The commit shortened for display. pub fn short_sha() -> Option<&'static str> { - git_sha().map(|s| &s[..s.len().min(9)]) + git_sha().map(shorten) } -/// `0.1.0 (3f2a9c1d0, 2026-10-01)`, or `0.1.0 (dev build)` without provenance. +fn shorten(sha: &str) -> &str { + sha.get(..9).unwrap_or(sha) +} + +static CHECKOUT: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// Records the git commit of the checkout a dev build was compiled from (the binaries' build +/// scripts read it; `None` or empty from a source tarball). Only the first call counts. +pub fn set_checkout(sha: Option<&str>) { + if let Some(sha) = sha.map(str::trim).filter(|s| !s.is_empty()) { + let _ = CHECKOUT.set(sha.to_string()); + } +} + +/// `0.1.0 (3f2a9c1d0, 2026-10-01)`; a dev build `0.1.0 (dev build, 3f2a9c1d0)` from a git +/// checkout, or `0.1.0 (dev build)` without provenance. pub fn long_version() -> String { - format_long(VERSION, short_sha(), build_date()) + match short_sha() { + Some(s) => format_long(VERSION, Some(s), build_date()), + None => format_dev(VERSION, CHECKOUT.get().map(|s| shorten(s)), build_date()), + } } /// [`long_version`] worked out once, for a `&'static str` such as clap's `version`. @@ -54,6 +76,14 @@ fn format_long(version: &str, sha: Option<&str>, date: Option<&str>) -> String { } } +/// A build without `PHOTOCRAFT_BUILD_SHA`: the checkout's commit, when known, marked as a dev build. +fn format_dev(version: &str, checkout: Option<&str>, date: Option<&str>) -> String { + match checkout { + Some(c) => format!("{version} (dev build, {c})"), + None => format_long(version, None, date), + } +} + #[cfg(test)] mod tests { use super::*; @@ -64,6 +94,11 @@ mod tests { assert_eq!(format_long("1.2.3", Some("abc"), None), "1.2.3 (abc)"); assert_eq!(format_long("1.2.3", None, Some("2026-10-01")), "1.2.3 (2026-10-01)"); assert_eq!(format_long("1.2.3-rc.1", None, None), "1.2.3-rc.1 (dev build)"); + // #5247: a dev build from a git checkout names its commit. + assert_eq!(format_dev("0.8.2", Some(shorten("6f8505421abcdef")), None), "0.8.2 (dev build, 6f8505421)"); + assert_eq!(format_dev("0.8.2", None, None), "0.8.2 (dev build)"); + assert_eq!(format_dev("0.8.2", None, Some("2026-10-01")), "0.8.2 (2026-10-01)"); + assert_eq!(shorten("abc"), "abc"); } #[test] diff --git a/crates/engine-core/src/cmd.rs b/crates/engine-core/src/cmd.rs index 764d48d423..16cdb14180 100644 --- a/crates/engine-core/src/cmd.rs +++ b/crates/engine-core/src/cmd.rs @@ -74,6 +74,8 @@ pub mod layer_copy_cmds; #[cfg(test)] mod layer_duplicate_new_document_history_tests; #[cfg(test)] +mod layer_duplicate_new_document_name_tests; +#[cfg(test)] mod layer_from_background_name_tests; pub mod layer_label_cmds; pub mod layer_list_cmds; diff --git a/crates/engine-core/src/cmd/artboard_cmds.rs b/crates/engine-core/src/cmd/artboard_cmds.rs index 76012bd600..bae9c00caa 100644 --- a/crates/engine-core/src/cmd/artboard_cmds.rs +++ b/crates/engine-core/src/cmd/artboard_cmds.rs @@ -369,9 +369,19 @@ fn artboard_from_group(s: &mut Session, p: &Value) -> Result { if !doc.layers.iter().any(|t| t.id == id && t.is_group() && t.artboard().is_none()) { return Err(EngineError::Other("artboards are made from a top-level layer group".into())); } + let topmost = doc.artboards().last().map(|b| b.2.rect); let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; // A hidden group keeps today's measure (not measured in the reference). - let rect = if l.visible { shown_children_bounds(l) } else { crate::layer_multi_cmds::layer_bounds(l) }.unwrap_or(canvas); + let bounds = if l.visible { shown_children_bounds(l) } else { crate::layer_multi_cmds::layer_bounds(l) }; + // A group without bounds covers the canvas, or once there are boards, takes the slot + // right of the topmost one (#14558). A hidden group keeps the canvas (not measured). + let rect = match (bounds, topmost) { + (Some(r), _) => r, + (None, Some(board)) if l.visible => { + right_of(board).ok_or_else(|| bad(cmd, format!("no room for an artboard right of the topmost one (its right edge is x = {})", board.x1)))? + } + (None, _) => canvas, + }; set_artboard(l, Artboard { rect, background, preset }); // As in the reference application, the new artboard is Normal at 100 % whatever the group had. l.blend = photocraft_color::BlendMode::Normal; @@ -385,6 +395,14 @@ fn artboard_from_group(s: &mut Session, p: &Value) -> Result { Ok(json!({"layer": id.0, "rect": [rect.x0, rect.y0, rect.width(), rect.height()]})) } +/// A board the size of `board`, [`GAP`] right of it at the same top; `None` past the 32-bit range +/// (computed in i64, #931). +fn right_of(board: Rect) -> Option { + let x0 = i32::try_from(i64::from(board.x1) + i64::from(GAP)).ok()?; + let x1 = i32::try_from(i64::from(x0) + i64::from(board.width())).ok()?; + Some(Rect::new(x0, board.y0, x1, board.y1)) +} + /// [`layer_multi_cmds::layer_bounds`](crate::layer_multi_cmds::layer_bounds) of what shows: a /// group unions only its visible children, so hidden layers (and a hidden group's children) don't /// size the board Artboard from Group makes (#14553). @@ -410,6 +428,11 @@ pub fn from_layers_defaults(s: &Session) -> Option<(String, [i64; 2])> { Some((next_artboard_name(&d.doc), [w, h])) } +/// The smallest width or height Artboard from Layers takes, in pixels (#14577). +pub const FROM_LAYERS_MIN: i64 = 4; +/// The largest width or height Artboard from Layers takes, in pixels (#14577). +pub const FROM_LAYERS_MAX: i64 = 32_000; + fn artboard_from_layers(s: &mut Session, p: &Value) -> Result { let sel = crate::layer_multi_cmds::selected(s); let d = s.active().ok_or(EngineError::NoDocument)?; @@ -422,8 +445,9 @@ fn artboard_from_layers(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "the artboard width and height must not be negative")); } // A size of the user's own (a post, a story…) from the layers' top left; 0 or none keeps - // their bounds on that axis (#9087). - let size = [int(p, "width").filter(|v| *v != 0), int(p, "height").filter(|v| *v != 0)]; + // their bounds on that axis (#9087). As the dialog's fields do, a size outside 4..=32000 px + // is clamped to it (#14577). + let size = [int(p, "width"), int(p, "height")].map(|v| v.filter(|v| *v != 0).map(|v| v.clamp(FROM_LAYERS_MIN, FROM_LAYERS_MAX))); let (gid, rect, shift) = s.edit("New Artboard From Layers", |doc, active| { let ids = crate::layer_multi_cmds::top_level(doc, &sel); if ids.is_empty() || ids.iter().any(|id| doc.artboard_of(*id).is_some()) { @@ -1161,12 +1185,12 @@ fn rgb_copy(one: &Document) -> Result { /// `one` flattened over white as a JPEG, for a PDF page. A board past the compositor's render /// limit is refused before it is flattened (the flatten would be empty). fn jpeg_page(one: &Document, quality: Option, cmd: &str) -> Result> { - Ok(jpeg_page_masked(one, quality, false, cmd)?.0) + Ok(jpeg_page_masked(one, quality, false, false, cmd)?.0) } -/// [`jpeg_page`] and, when `masked`, the page's [`soft_mask`] taken from the composite before it -/// goes over white. -fn jpeg_page_masked(one: &Document, quality: Option, masked: bool, cmd: &str) -> Result<(Vec, Option>)> { +/// [`jpeg_page`], or with `zip` the page's exact 8-bit RGB samples as a zlib stream (#13651), and, +/// when `masked`, the page's [`soft_mask`] taken from the composite before it goes over white. +fn jpeg_page_masked(one: &Document, quality: Option, zip: bool, masked: bool, cmd: &str) -> Result<(Vec, Option>)> { crate::file_cmds::check_flattenable(one, cmd)?; let composite = photocraft_compose::flatten(one); let mask = if masked { soft_mask(&composite.px)? } else { None }; @@ -1176,12 +1200,19 @@ fn jpeg_page_masked(one: &Document, quality: Option, masked: bool, cmd: &st let mut surf = Surface::new(fmt); let vals: Vec = buf.px.iter().flat_map(|px| photocraft_raster::from_rgba(&fmt, *px)).collect(); surf.write_region(one.bounds(), &vals); + if zip { + // Lossless (#13651): the exact 8-bit RGB samples, alpha dropped, Flate-compressed. + let rgb: Vec = surf.to_interleaved(one.bounds()).as_chunks::<4>().0.iter().flat_map(|&[r, g, b, _]| [r, g, b]).collect(); + let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + let data = std::io::Write::write_all(&mut z, &rgb).and_then(|()| z.finish()).map_err(|e| EngineError::Other(format!("compressing a PDF page: {e}")))?; + return Ok((data, mask)); + } flat.layers.push(Layer::new("Background", LayerContent::Raster(surf))); Ok((encode(&flat, "page.jpg", quality)?.0, mask)) } -/// A minimal PDF with one page per JPEG image: (width px, height px, dpi, JPEG bytes). -/// Pages are sized so the image prints at its resolution. +/// A minimal PDF with one page per image: (width px, height px, dpi, JPEG bytes or a zlib +/// stream of 8-bit RGB samples). Pages are sized so the image prints at its resolution. pub fn raster_pdf(pages: &[(u32, u32, f32, Vec)]) -> Vec { let pages: Vec = pages.iter().map(|(w, h, dpi, jpeg)| (*w, *h, *dpi, jpeg.clone(), None)).collect(); raster_pdf_masked(&pages) @@ -1231,8 +1262,10 @@ fn raster_pdf_masked(pages: &[PdfPage]) -> Vec { let stream = format!("q {pw:.3} 0 0 {ph:.3} 0 0 cm /Im0 Do Q"); obj(&mut out, format!("<< /Length {} >>\nstream\n{stream}\nendstream", stream.len()).as_bytes()); let soft = if mask.is_some() { format!(" /SMask {smask} 0 R") } else { String::new() }; + // JPEG data opens with the SOI marker FF D8; a zlib stream never starts with FF. + let filter = if jpeg.starts_with(&[0xff, 0xd8]) { "DCTDecode" } else { "FlateDecode" }; let mut img = format!( - "<< /Type /XObject /Subtype /Image /Width {w} /Height {h} /ColorSpace /DeviceRGB /BitsPerComponent 8{soft} /Filter /DCTDecode /Length {} >>\nstream\n", + "<< /Type /XObject /Subtype /Image /Width {w} /Height {h} /ColorSpace /DeviceRGB /BitsPerComponent 8{soft} /Filter /{filter} /Length {} >>\nstream\n", jpeg.len() ) .into_bytes(); @@ -1323,6 +1356,14 @@ fn artboards_to_pdf(s: &mut Session, p: &Value) -> Result { None => stem(&path), }; let quality = f64_param(p, "quality").or(Some(10.0)); + let zip = match p.get("encoding") { + None | Some(Value::Null) => false, + Some(v) => match v.as_str() { + Some("jpeg") => false, + Some("zip") => true, + _ => return Err(bad(cmd, format!("`encoding` must be \"jpeg\" or \"zip\", not {v}"))), + }, + }; let background = p.get("includeBackground").and_then(Value::as_bool).unwrap_or(true); // Reverse Page Order (#13644): the default page order the other way round. let reverse = match p.get("reversePageOrder") { @@ -1340,7 +1381,7 @@ fn artboards_to_pdf(s: &mut Session, p: &Value) -> Result { // shows the board, so its visibility is read from the source. let visible = doc.layer(id).is_some_and(|l| l.visible); let masked = !background && visible && drop_white_fill(&mut one); - let (jpeg, mask) = jpeg_page_masked(&one, quality, masked, cmd)?; + let (jpeg, mask) = jpeg_page_masked(&one, quality, zip, masked, cmd)?; pages.push((one.size.width, one.size.height, doc.resolution_dpi, jpeg, mask)); names.push(one.name); } @@ -1421,7 +1462,7 @@ pub fn specs() -> Vec { "layer.new.artboardFromLayers", "Artboard from Layers…", &["Layer", "New"], - r##"{"name":text,"background":"white|black|transparent|custom"="white","color":color,"width":px=0,"height":px=0} (the selected layers; name: empty gives Artboard N; color: for custom; width, height: the board's size from the layers' top left, 0 keeps their bounds) → {layer, rect}"##, + r##"{"name":text,"background":"white|black|transparent|custom"="white","color":color,"width":px=0,"height":px=0} (the selected layers; name: empty gives Artboard N; color: for custom; width, height: the board's size from the layers' top left, 4..32000 px, a size outside is clamped to it, 0 keeps their bounds) → {layer, rect}"##, has_free_layers, artboard_from_layers ), @@ -1461,7 +1502,7 @@ pub fn specs() -> Vec { "file.export.artboardsToPdf", "Artboards to PDF…", &["File", "Export"], - r##"{"path":str (.pdf; with "mode":"perArtboard" only gives the defaults of "dir" and "prefix"),"mode":"multiPage|perArtboard"="multiPage" (Multi-Page Document: one file at "path"; Document Per Artboard: one single-page file per board, "/.pdf", spaces kept, characters a file name can't hold become "_", a name an earlier board already took, ignoring case, gets "-2", "-3"…),"dir":folder=folder of "path","prefix":str=file name of "path" without ".pdf", else the document name,"content":"overlapping|artboard"="overlapping" (Include Overlapping Areas: a board's page also shows the visible boards above it where they overlap it; artboard: Artboard Content Only),"artboards":[id]?,"quality":0..12=10,"includeBackground":bool=true (false: a white board's fill is left out and the page gets a soft mask, so it is transparent where the board's layers have no pixels; an empty board, other fills and documents other than 8-bit RGB keep it),"reversePageOrder":bool=false (the default page order the other way round)} → {path (multi-page), pages, files} (one raster page per board, bottom artboard of the Layers panel first)"##, + r##"{"path":str (.pdf; with "mode":"perArtboard" only gives the defaults of "dir" and "prefix"),"mode":"multiPage|perArtboard"="multiPage" (Multi-Page Document: one file at "path"; Document Per Artboard: one single-page file per board, "/.pdf", spaces kept, characters a file name can't hold become "_", a name an earlier board already took, ignoring case, gets "-2", "-3"…),"dir":folder=folder of "path","prefix":str=file name of "path" without ".pdf", else the document name,"content":"overlapping|artboard"="overlapping" (Include Overlapping Areas: a board's page also shows the visible boards above it where they overlap it; artboard: Artboard Content Only),"artboards":[id]?,"quality":0..12=10,"includeBackground":bool=true (false: a white board's fill is left out and the page gets a soft mask, so it is transparent where the board's layers have no pixels; an empty board, other fills and documents other than 8-bit RGB keep it),"reversePageOrder":bool=false (the default page order the other way round),"encoding":"jpeg|zip"="jpeg" (zip: lossless Flate pages, quality ignored)} → {path (multi-page), pages, files} (one raster page per board, bottom artboard of the Layers panel first)"##, export_artboards, artboards_to_pdf ), @@ -1497,10 +1538,18 @@ mod include_name_tests; #[path = "artboard_cmds/from_layers_history_name_tests.rs"] mod from_layers_history_name_tests; +#[cfg(test)] +#[path = "artboard_cmds/from_layers_size_range_tests.rs"] +mod from_layers_size_range_tests; + #[cfg(test)] #[path = "artboard_cmds/from_group_hidden_bounds_tests.rs"] mod from_group_hidden_bounds_tests; +#[cfg(test)] +#[path = "artboard_cmds/from_group_empty_placement_tests.rs"] +mod from_group_empty_placement_tests; + #[cfg(test)] #[path = "artboard_cmds/overlapping_areas_tests.rs"] mod overlapping_areas_tests; @@ -1514,9 +1563,13 @@ mod pdf_overlapping_areas_tests; #[cfg(test)] #[path = "artboard_cmds/pdf_page_order_tests.rs"] mod pdf_page_order_tests; + #[cfg(test)] #[path = "artboard_cmds/pdf_reverse_page_order_tests.rs"] mod pdf_reverse_page_order_tests; #[cfg(test)] +#[path = "artboard_cmds/pdf_zip_encoding_tests.rs"] +mod pdf_zip_encoding_tests; +#[cfg(test)] #[path = "artboard_cmds/tests.rs"] mod tests; diff --git a/crates/engine-core/src/cmd/artboard_cmds/from_group_empty_placement_tests.rs b/crates/engine-core/src/cmd/artboard_cmds/from_group_empty_placement_tests.rs new file mode 100644 index 0000000000..ef7e526980 --- /dev/null +++ b/crates/engine-core/src/cmd/artboard_cmds/from_group_empty_placement_tests.rs @@ -0,0 +1,128 @@ +//! Artboard from Group on a group without bounds (#14558): the canvas when the document has no +//! artboard yet, else a board of the topmost artboard's size, `GAP` right of it at the same top. +//! A hidden group keeps the canvas (not measured, #14553). + +use super::*; +use photocraft_geom::Rect; + +/// 800 x 600 with the white Background, the artboards `boards` (`[x, y, w, h]`, bottom to top) +/// and an empty top-level group "Empty" above them. Returns the session and Empty's id. +fn session_with(boards: &[[i32; 4]]) -> (Session, LayerId) { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + for b in boards { + s.execute("layer.new.artboard", json!({"rect": b})).unwrap(); + } + let id = s.edit("Empty", |doc, active| Ok(*active.insert(doc.insert_above(None, Layer::group("Empty", vec![]))))).unwrap(); + (s, id) +} + +/// [`session_with`] with no board, or with "Artboard 1" at 100,100 to 600,450. +fn session(board: bool) -> (Session, LayerId) { + session_with(if board { &[[100, 100, 500, 350]] } else { &[] }) +} + +fn doc(s: &Session) -> &Document { + &s.active().unwrap().doc +} + +fn from_group(s: &mut Session, id: LayerId) -> Result { + s.execute("layer.new.artboardFromGroup", json!({"layer": id.0})) +} + +fn board_rect(s: &Session, id: LayerId) -> Rect { + doc(s).layer(id).unwrap().artboard().unwrap().rect +} + +#[test] +fn an_empty_group_goes_right_of_the_topmost_board() { + let (mut s, id) = session(true); + let r = from_group(&mut s, id).unwrap(); + assert_eq!(r["rect"], json!([700, 100, 500, 350])); + assert_eq!(board_rect(&s, id), Rect::new(700, 100, 1200, 450)); + assert!(doc(&s).bounds().contains_rect(&Rect::new(700, 100, 1200, 450)), "the canvas grew to show it: {:?}", doc(&s).bounds()); +} + +#[test] +fn without_artboards_an_empty_group_covers_the_canvas() { + let (mut s, id) = session(false); + from_group(&mut s, id).unwrap(); + assert_eq!(board_rect(&s, id), Rect::new(0, 0, 800, 600)); + assert_eq!(doc(&s).bounds(), Rect::new(0, 0, 800, 600)); +} + +/// A hidden empty group keeps today's canvas rectangle even when a board exists: #14553 leaves a +/// hidden top-level group unmeasured. +#[test] +fn a_hidden_empty_group_keeps_the_canvas_beside_a_board() { + let (mut s, id) = session(true); + s.edit("Hide", |doc, _| { + doc.layer_mut(id).unwrap().visible = false; + Ok(()) + }) + .unwrap(); + let canvas = doc(&s).bounds(); + from_group(&mut s, id).unwrap(); + assert_eq!(board_rect(&s, id), canvas); +} + +/// A visible group whose children are all hidden counts as empty (#14553), so it takes the slot. +#[test] +fn a_visible_group_of_hidden_layers_goes_right_of_the_board() { + let (mut s, id) = session(true); + s.edit("Hidden red", |doc, _| { + let fmt = doc.pixel_format(); + let mut l = Layer::raster("Hidden red", fmt); + l.surface_mut().unwrap().fill_rect(Rect::new(10, 10, 50, 50), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); + l.visible = false; + doc.layer_mut(id).and_then(Layer::children_mut).unwrap().push(l); + Ok(()) + }) + .unwrap(); + from_group(&mut s, id).unwrap(); + assert_eq!(board_rect(&s, id), Rect::new(700, 100, 1200, 450)); +} + +/// A group with content keeps its own bounds when boards exist. +#[test] +fn a_group_with_content_keeps_its_bounds_beside_boards() { + let (mut s, id) = session(true); + s.edit("Red", |doc, _| { + let fmt = doc.pixel_format(); + let mut l = Layer::raster("Red", fmt); + l.surface_mut().unwrap().fill_rect(Rect::new(650, 50, 750, 150), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); + doc.layer_mut(id).and_then(Layer::children_mut).unwrap().push(l); + Ok(()) + }) + .unwrap(); + from_group(&mut s, id).unwrap(); + assert_eq!(board_rect(&s, id), Rect::new(650, 50, 750, 150)); +} + +/// With several boards (not measured) the slot follows the topmost board in the Layers panel, +/// not the rightmost one. +#[test] +fn the_slot_follows_the_topmost_board_not_the_rightmost() { + // The topmost board is a small one left of the 100,100 to 600,450 board. + let (mut s, id) = session_with(&[[100, 100, 500, 350], [0, 480, 60, 40]]); + from_group(&mut s, id).unwrap(); + assert_eq!(board_rect(&s, id), Rect::new(60 + GAP, 480, 120 + GAP, 520)); +} + +/// #931: a topmost board at the far right edge leaves no room right of it; the command says so +/// and changes nothing, instead of wrapping. +#[test] +fn no_room_right_of_a_far_right_board_is_an_error() { + let (mut s, id) = session(false); + s.edit("Far", |doc, _| { + let mut g = Layer::group("Far", vec![]); + set_artboard(&mut g, Artboard::new(Rect::new(i32::MAX - 600, 0, i32::MAX - 50, 300))); + doc.insert_above(None, g); + Ok(()) + }) + .unwrap(); + let before = s.active().unwrap().doc.clone(); + let e = from_group(&mut s, id).unwrap_err().to_string(); + assert!(e.contains("no room"), "{e}"); + assert!(std::sync::Arc::ptr_eq(&before, &s.active().unwrap().doc), "the document changed"); +} diff --git a/crates/engine-core/src/cmd/artboard_cmds/from_layers_size_range_tests.rs b/crates/engine-core/src/cmd/artboard_cmds/from_layers_size_range_tests.rs new file mode 100644 index 0000000000..95197bb42e --- /dev/null +++ b/crates/engine-core/src/cmd/artboard_cmds/from_layers_size_range_tests.rs @@ -0,0 +1,67 @@ +//! Artboard from Layers takes a width and height of 4 to 32000 px and clamps a scripted size +//! outside that range, as its dialog's fields do when you leave them (#14577). 0 or no size keeps +//! the selected layers' bounds on that axis. + +use super::*; +use photocraft_geom::Rect; + +/// 100 x 80 RGB at `depth` with a pixel layer "Red" holding a square at 10,10 to 30,30. +fn session(depth: u32) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 100, "height": 80, "depth": depth, "background": "white"})).unwrap(); + s.edit("Red", |doc, active| { + let fmt = doc.pixel_format(); + let mut l = Layer::raster("Red", fmt); + l.surface_mut().unwrap().fill_rect(Rect::new(10, 10, 30, 30), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); + let id = doc.insert_above(None, l); + *active = Some(id); + Ok(id) + }) + .unwrap(); + s +} + +/// The new board's `[x, y, width, height]` and the canvas size after Artboard from Layers. +fn board(depth: u32, params: Value) -> ([i64; 4], (u32, u32)) { + let mut s = session(depth); + let out = s.execute("layer.new.artboardFromLayers", params.clone()).unwrap_or_else(|e| panic!("{params} at {depth} bit: {e}")); + let rect: Vec = out["rect"].as_array().unwrap().iter().map(|v| v.as_i64().unwrap()).collect(); + let doc = &s.active().unwrap().doc; + (rect.try_into().unwrap(), (doc.size.width, doc.size.height)) +} + +#[test] +fn a_scripted_size_past_the_range_is_clamped_to_4_to_32000() { + for depth in [8, 16, 32] { + let (rect, canvas) = board(depth, json!({"width": 99999, "height": 1})); + assert_eq!(rect, [10, 10, 32_000, 4], "99999 -> 32000, 1 -> 4 at {depth} bit"); + assert!(canvas.0 <= 32_100, "the canvas grows only to the clamped board at {depth} bit: {canvas:?}"); + let (rect, _) = board(depth, json!({"width": 2, "height": 50_000})); + assert_eq!(rect, [10, 10, 4, 32_000], "2 -> 4, 50000 -> 32000 at {depth} bit"); + } +} + +#[test] +fn sizes_at_the_ends_of_the_range_are_kept() { + let (rect, _) = board(8, json!({"width": 4, "height": 32_000})); + assert_eq!(rect, [10, 10, 4, 32_000]); + let (rect, _) = board(8, json!({"width": 640, "height": 480})); + assert_eq!(rect, [10, 10, 640, 480]); +} + +#[test] +fn zero_or_no_size_keeps_the_layers_bounds() { + for params in [json!({}), json!({"width": 0, "height": 0}), json!({"width": 0})] { + let (rect, _) = board(8, params.clone()); + assert_eq!(rect, [10, 10, 20, 20], "{params}"); + } + let (rect, _) = board(8, json!({"width": 0, "height": 1})); + assert_eq!(rect, [10, 10, 20, 4], "0 keeps the width, 1 is clamped to 4"); +} + +#[test] +fn a_negative_size_is_still_refused() { + let mut s = session(8); + let err = s.execute("layer.new.artboardFromLayers", json!({"width": -5})).unwrap_err(); + assert!(err.to_string().contains("must not be negative"), "{err}"); +} diff --git a/crates/engine-core/src/cmd/artboard_cmds/pdf_overlapping_areas_tests.rs b/crates/engine-core/src/cmd/artboard_cmds/pdf_overlapping_areas_tests.rs index 4885213edf..07cae8ea1b 100644 --- a/crates/engine-core/src/cmd/artboard_cmds/pdf_overlapping_areas_tests.rs +++ b/crates/engine-core/src/cmd/artboard_cmds/pdf_overlapping_areas_tests.rs @@ -27,7 +27,7 @@ fn session(depth: u32) -> (Session, [u64; 3]) { } /// A pixel layer `name` of `color` over `rect`, on top of board `board`'s layers. -fn paint(s: &mut Session, board: u64, name: &str, rect: Rect, color: [u8; 3]) { +pub(super) fn paint(s: &mut Session, board: u64, name: &str, rect: Rect, color: [u8; 3]) { s.edit(name, |doc, _| { let fmt = doc.pixel_format(); let mut l = Layer::raster(name, fmt); diff --git a/crates/engine-core/src/cmd/artboard_cmds/pdf_zip_encoding_tests.rs b/crates/engine-core/src/cmd/artboard_cmds/pdf_zip_encoding_tests.rs new file mode 100644 index 0000000000..736fb375a1 --- /dev/null +++ b/crates/engine-core/src/cmd/artboard_cmds/pdf_zip_encoding_tests.rs @@ -0,0 +1,137 @@ +//! Artboards to PDF's Encoding (#13651): `"zip"` writes every page as a lossless Flate image, +//! `"jpeg"` (the default) as before. The measured document: 800 x 400, bottom to top `Red Board` +//! 0,0-200,150 (white, pixel layer `Red` 220,30,30 at 20,20-120,100), `Blue Board` +//! 120,30-320,230 (white, pixel layer `Blue`) and `Empty Board` 600,0-700,100 (white, no layers). + +use std::io::Read; + +use super::pdf_overlapping_areas_tests::paint; +use super::*; +use photocraft_geom::Rect; + +const CMD: &str = "file.export.artboardsToPdf"; + +fn session() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 800, "height": 400, "depth": 8, "resolution": 72, "background": "transparent"})).unwrap(); + let mut board = |rect: [i64; 4], name: &str| { + s.execute("layer.new.artboard", json!({"rect": rect, "name": name, "background": "white"})).unwrap()["layer"].as_u64().unwrap() + }; + let red = board([0, 0, 200, 150], "Red Board"); + let blue = board([120, 30, 200, 200], "Blue Board"); + board([600, 0, 100, 100], "Empty Board"); + paint(&mut s, red, "Red", Rect::new(20, 20, 120, 100), [220, 30, 30]); + paint(&mut s, blue, "Blue", Rect::new(130, 40, 230, 140), [30, 30, 220]); + s +} + +/// Runs the command with `params` plus a fresh `path`; the PDF's bytes, or the command's error. +fn export(s: &mut Session, tag: &str, params: Value) -> Result> { + let dir = std::env::temp_dir().join(format!("photocraft-pdf-zip-{}-{tag}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = join(&dir.to_string_lossy(), "boards.pdf"); + let mut params = params; + params["path"] = json!(path); + let r = s.execute(CMD, params); + let bytes = std::fs::read(&path); + let _ = std::fs::remove_dir_all(&dir); + r.map(|_| bytes.unwrap()) +} + +/// The first position of `needle` in `pdf` at or after `from` (byte offsets: streams are binary). +fn find(pdf: &[u8], from: usize, needle: &[u8]) -> Option { + pdf[from..].windows(needle.len()).position(|w| w == needle).map(|i| from + i) +} + +/// Every page image in page order: its dictionary and its stream bytes. +fn images(pdf: &[u8]) -> Vec<(String, &[u8])> { + let mut out = Vec::new(); + let mut at = 0; + while let Some(start) = find(pdf, at, b"/Subtype /Image") { + let dict_end = find(pdf, start, b">>\nstream\n").unwrap(); + let dict = String::from_utf8(pdf[start..dict_end].to_vec()).unwrap(); + let len: usize = dict.split("/Length ").nth(1).unwrap().trim().parse().unwrap(); + let data = dict_end + b">>\nstream\n".len(); + out.push((dict, &pdf[data..data + len])); + at = data + len; + } + out +} + +fn inflate(data: &[u8]) -> Vec { + let mut out = Vec::new(); + flate2::read::ZlibDecoder::new(data).read_to_end(&mut out).unwrap(); + out +} + +#[test] +fn zip_pages_are_flate_rgb_images_with_the_exact_pixels() { + // Artboard Content Only: the default Include Overlapping Areas would show Blue Board's corner on Red Board's page. + let pdf = export(&mut session(), "exact", json!({"encoding": "zip", "content": "artboard"})).unwrap(); + let pages = images(&pdf); + assert_eq!(pages.len(), 3); + for (dict, _) in &pages { + assert!(dict.contains("/ColorSpace /DeviceRGB /BitsPerComponent 8") && dict.contains("/Filter /FlateDecode"), "{dict}"); + } + assert!(find(&pdf, 0, b"/DCTDecode").is_none()); + // Page 1 is Red Board, 200 x 150: the red layer exactly 220,30,30, white elsewhere. + assert!(pages[0].0.contains("/Width 200 /Height 150"), "{}", pages[0].0); + let rgb = inflate(pages[0].1); + assert_eq!(rgb.len(), 200 * 150 * 3); + for (i, px) in rgb.as_chunks::<3>().0.iter().enumerate() { + let (x, y) = (i % 200, i / 200); + let want = if (20..120).contains(&x) && (20..100).contains(&y) { [220, 30, 30] } else { [255, 255, 255] }; + assert_eq!(*px, want, "page pixel {x},{y}"); + } + // Empty Board is plain white. + assert!(inflate(pages[2].1).iter().all(|&v| v == 255)); +} + +#[test] +fn zip_pdf_xref_offsets_point_at_their_objects() { + let pdf = export(&mut session(), "xref", json!({"encoding": "zip"})).unwrap(); + assert!(images(&pdf).iter().all(|(dict, _)| dict.contains("/Filter /FlateDecode"))); + let xref = pdf.windows(6).rposition(|w| w == b"\nxref\n").unwrap() + 1; + assert!(pdf.ends_with(format!("startxref\n{xref}\n%%EOF\n").as_bytes())); + let table = String::from_utf8(pdf[xref..].to_vec()).unwrap(); + // Catalog, page tree, then page, contents and image per page. + let offsets: Vec = table.lines().skip(3).take(2 + 3 * 3).map(|l| l[..10].parse().unwrap()).collect(); + assert_eq!(offsets.len(), 11); + for (i, o) in offsets.iter().enumerate() { + assert!(pdf[*o..].starts_with(format!("{} 0 obj", i + 1).as_bytes()), "object {}", i + 1); + } +} + +#[test] +fn zip_ignores_quality() { + let mut s = session(); + let low = export(&mut s, "q0", json!({"encoding": "zip", "quality": 0})).unwrap(); + let high = export(&mut s, "q12", json!({"encoding": "zip", "quality": 12})).unwrap(); + assert_eq!(low, high); +} + +#[test] +fn jpeg_and_no_encoding_give_todays_pdf() { + let mut s = session(); + let default = export(&mut s, "none", json!({"quality": 8})).unwrap(); + assert_eq!(export(&mut s, "jpeg", json!({"encoding": "jpeg", "quality": 8})).unwrap(), default); + assert_eq!(export(&mut s, "null", json!({"encoding": null, "quality": 8})).unwrap(), default); + let pages = images(&default); + assert_eq!(pages.len(), 3); + assert!(pages.iter().all(|(dict, data)| dict.contains("/Filter /DCTDecode") && data.starts_with(&[0xff, 0xd8]))); +} + +#[test] +fn an_unknown_encoding_is_an_error() { + let mut s = session(); + for (i, encoding) in [json!("lzw"), json!(5), json!(""), json!("ZIP"), json!(true)].into_iter().enumerate() { + let err = export(&mut s, &format!("bad{i}"), json!({"encoding": encoding})).unwrap_err(); + assert!(err.to_string().contains("`encoding` must be"), "{encoding}: {err}"); + } +} + +#[test] +fn the_params_document_the_encoding() { + let spec = specs().into_iter().find(|c| c.id == CMD).unwrap(); + assert!(spec.params.contains(r#""encoding":"jpeg|zip"="jpeg""#), "{}", spec.params); +} diff --git a/crates/engine-core/src/cmd/channel_cmds.rs b/crates/engine-core/src/cmd/channel_cmds.rs index f5160db3f2..0c7619d0cb 100644 --- a/crates/engine-core/src/cmd/channel_cmds.rs +++ b/crates/engine-core/src/cmd/channel_cmds.rs @@ -119,6 +119,9 @@ mod targeting; mod tone_target; mod view; +#[cfg(test)] +mod undo_channel_target_tests; + use calc::{apply_image, calculations}; use manage::{delete_channel, duplicate_channel, move_channel, new_channel, new_spot, options, rename_channel, set_visible}; use planes::edit_mode; @@ -147,8 +150,8 @@ pub(crate) use targeting::{ targeted_channel, }; pub use tone_target::{ToneTarget, resolve_tone_target}; -pub(crate) use view::fix_view; pub use view::{ChannelTarget, ChannelView, QuickMaskOptions, color_names, composite_name}; +pub(crate) use view::{fix_view, restore_view_after_undo}; pub fn specs() -> Vec { vec![ diff --git a/crates/engine-core/src/cmd/channel_cmds/calc.rs b/crates/engine-core/src/cmd/channel_cmds/calc.rs index a72783de40..b086a8ba0e 100644 --- a/crates/engine-core/src/cmd/channel_cmds/calc.rs +++ b/crates/engine-core/src/cmd/channel_cmds/calc.rs @@ -2,6 +2,7 @@ use super::manage::gray_document; use super::planes::{channel_format, edit_mode, next_alpha_name, plane_surface, read_plane, tone}; use super::refs::{Blending, bad, doc_index, mask_plane, source, source_spec}; use super::targeting::{Target, is_channel_target, is_spot_target, target_of, target_surface}; +use super::view::{keep_view_for_undo, view_before_step}; use super::{AlphaChannel, ColorMode, EngineError, Result, SelectionMode, Session, Value, json, sel}; use photocraft_color::blend::blend_rgb; @@ -151,6 +152,7 @@ pub(super) fn calculations(s: &mut Session, p: &Value) -> Result { let name = p.get("name").and_then(Value::as_str).map(str::to_string); match p.get("result").and_then(Value::as_str).unwrap_or("newChannel") { "newChannel" => { + let before = view_before_step(s); let i = s.edit("Calculations", |doc, _| { let name = name.clone().unwrap_or_else(|| next_alpha_name(doc, "Alpha")); let area = doc.bounds(); @@ -158,6 +160,8 @@ pub(super) fn calculations(s: &mut Session, p: &Value) -> Result { doc.channels.push(AlphaChannel::new(name, plane_surface(&out, area, fmt))); Ok(doc.channels.len() - 1) })?; + // Undo targets and shows what was before, as after New Channel (#14683). + keep_view_for_undo(s, before); Ok(json!({ "channel": i })) } "newDocument" => { diff --git a/crates/engine-core/src/cmd/channel_cmds/manage.rs b/crates/engine-core/src/cmd/channel_cmds/manage.rs index 9c81381bf4..c213238210 100644 --- a/crates/engine-core/src/cmd/channel_cmds/manage.rs +++ b/crates/engine-core/src/cmd/channel_cmds/manage.rs @@ -2,7 +2,7 @@ use super::planes::{channel_format, color_count, edit_mode, next_alpha_name, pla use super::refs::{ChanRef, alpha_index, bad, doc_index, gray_plane, parse_ref}; use super::selection::{uniform, unselected_surface}; use super::targeting::target; -use super::view::{ChannelTarget, QuickMaskOptions, color_names, composite_name, fix_view, touch}; +use super::view::{ChannelTarget, QuickMaskOptions, color_names, composite_name, fix_view, keep_view_for_undo, touch, view_before_step}; use super::{ AlphaChannel, Color, ColorIndicates, ColorMode, DocState, Document, EngineError, Layer, PixelFormat, Result, Session, Surface, Value, json, list, sel, }; @@ -32,6 +32,7 @@ pub(super) fn new_channel(s: &mut Session, p: &Value) -> Result { let indicates = indicates_param(p.get("indicates")); let color = color_value("channel.new", p, "color")?; let opacity = p.get("opacity").and_then(Value::as_f64).map(|v| (v as f32 / 100.0).clamp(0.0, 1.0)); + let before = view_before_step(s); let i = s.edit("New Channel", |doc, _| { let area = doc.bounds(); let fmt = channel_format(doc); @@ -53,7 +54,8 @@ pub(super) fn new_channel(s: &mut Session, p: &Value) -> Result { doc.channels.push(ch); Ok(doc.channels.len() - 1) })?; - // Photoshop targets and shows a new channel on its own. + // Photoshop targets and shows a new channel on its own; undo targets what was before. + keep_view_for_undo(s, before); target(s, ChannelTarget::Alpha(i)); Ok(json!({ "channel": i })) } diff --git a/crates/engine-core/src/cmd/channel_cmds/refs.rs b/crates/engine-core/src/cmd/channel_cmds/refs.rs index 19c4a345e1..329763f109 100644 --- a/crates/engine-core/src/cmd/channel_cmds/refs.rs +++ b/crates/engine-core/src/cmd/channel_cmds/refs.rs @@ -285,6 +285,18 @@ pub(super) fn source(s: &Session, p: &Value, cmd: &str, gray: bool) -> Result Result { Ok(json!({ "channel": i, "name": name, "document": di })) } +/// The history name of `select.loadSelection` with `p`. The Layers panel names its layer by id (a thumbnail +/// ⌘-click, Select Pixels), and those loads take Photoshop's names (#16786): `Selection Change` for a shape's +/// path or a vector mask, `Load Selection` for another layer's transparency or a layer mask. Calls that don't +/// name a layer by id (Select › Load Selection) keep their names. +fn load_label(doc: &Document, p: &Value) -> &'static str { + let channel = p.get("channel").and_then(|v| parse_ref(v, doc)); + let layer = p.get("layer").and_then(Value::as_u64).and_then(|id| doc.layer(super::LayerId(id))); + match (channel, layer) { + (Some(ChanRef::Transparency), Some(l)) if matches!(l.content, super::LayerContent::Shape(_)) => "Selection Change", + (Some(ChanRef::Transparency), Some(l)) if !l.is_group() => "Load Selection", + (Some(ChanRef::VectorMask), Some(l)) if l.vector_mask.is_some() => "Selection Change", + (Some(ChanRef::Transparency), _) => "Load Transparency", + (Some(ChanRef::LayerMask), None) => "Load Layer Mask", + _ => "Load Selection", + } +} + pub(super) fn load_selection(s: &mut Session, p: &Value) -> Result { let cmd = "select.loadSelection"; let mode = match operation(p, "operation") { @@ -89,11 +106,7 @@ pub(super) fn load_selection(s: &mut Session, p: &Value) -> Result { // Composite and colour channels load their luminosity / values, as ⌘-clicking them does. let plane = source(s, p, cmd, true)?.into_iter().next().ok_or_else(|| bad(cmd, "the channel has no pixels"))?; let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; - let label = match p.get("channel").and_then(|v| parse_ref(v, doc)) { - Some(ChanRef::Transparency) => "Load Transparency", - Some(ChanRef::LayerMask) => "Load Layer Mask", - _ => "Load Selection", - }; + let label = load_label(doc, p); let selected = s.edit(label, |doc, _| { doc.selection = sel::combine(doc.selection.as_ref(), &plane, doc.bounds(), mode); Ok(doc.selection.is_some()) diff --git a/crates/engine-core/src/cmd/channel_cmds/undo_channel_target_tests.rs b/crates/engine-core/src/cmd/channel_cmds/undo_channel_target_tests.rs new file mode 100644 index 0000000000..3eaa9cc078 --- /dev/null +++ b/crates/engine-core/src/cmd/channel_cmds/undo_channel_target_tests.rs @@ -0,0 +1,121 @@ +//! Undo of a step that targeted a new alpha channel brings back the channel view from before it: +//! the targeted colour channel and the eyes (#14683). + +use super::*; +use crate::channel_cmds::ChannelView; + +fn session() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 40, "height": 20})).unwrap(); + s +} + +fn view(s: &Session) -> ChannelView { + s.active().unwrap().channel_view.clone() +} + +/// Red targeted (shown alone), then `command`, then undo: Red is the target again and the only +/// colour channel shown, as before the command. +fn undo_returns_to_red(command: &str, params: Value) { + let mut s = session(); + s.execute("channel.target", json!({"channel": "red"})).unwrap(); + let before = view(&s); + assert_eq!(before.target, ChannelTarget::Color(0)); + s.execute(command, params).unwrap(); + assert!(s.undo()); + assert!(doc(&s).channels.is_empty()); + let after = view(&s); + assert_eq!((after.target, &after.color_hidden), (before.target, &before.color_hidden), "{command}"); + assert_eq!(channels_json(s.active().unwrap()), channels_json_of(before, &s), "{command}"); +} + +fn doc(s: &Session) -> &Document { + &s.active().unwrap().doc +} + +/// The Channels panel as `view` would show the current document. +fn channels_json_of(view: ChannelView, s: &Session) -> Value { + let mut st = s.active().unwrap().clone(); + st.channel_view = view; + channels_json(&st) +} + +#[test] +fn undo_of_new_channel_targets_the_colour_channel_again() { + undo_returns_to_red("channel.new", json!({})); +} + +#[test] +fn undo_of_calculations_new_channel_targets_the_colour_channel_again() { + undo_returns_to_red("image.calculations", json!({"result": "newChannel"})); +} + +/// From the composite, undo returns to the composite with every colour channel shown, as today. +#[test] +fn undo_from_the_composite_keeps_working() { + for command in ["channel.new", "image.calculations"] { + let mut s = session(); + let before = view(&s); + s.execute(command, json!({})).unwrap(); + assert!(s.undo()); + let after = view(&s); + assert_eq!(after.target, ChannelTarget::Composite, "{command}"); + assert_eq!(channels_json(s.active().unwrap()), channels_json_of(before, &s), "{command}"); + } +} + +/// Redo brings the new channel back, and undo after it returns to Red again. +#[test] +fn undo_after_redo_returns_to_red_again() { + let mut s = session(); + s.execute("channel.target", json!({"channel": "red"})).unwrap(); + s.execute("channel.new", json!({})).unwrap(); + assert!(s.undo()); + assert!(s.redo()); + assert_eq!(doc(&s).channels.len(), 1); + assert!(s.undo()); + assert_eq!(view(&s).target, ChannelTarget::Color(0)); +} + +/// Other commands' undo leaves the channel view as it is: a selection made with Red targeted, +/// then Green targeted, undone, keeps Green. +#[test] +fn other_steps_do_not_restore_the_view() { + let mut s = session(); + s.execute("channel.target", json!({"channel": "red"})).unwrap(); + s.execute("select.rect", json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap(); + s.execute("channel.target", json!({"channel": "green"})).unwrap(); + assert!(s.undo()); + assert_eq!(view(&s).target, ChannelTarget::Color(1)); +} + +/// New Channel from Red, undone, then a selection made from the same state with Green targeted: +/// undo of the selection lands on the state New Channel started from but undoes the selection, so +/// Green stays targeted. +#[test] +fn undo_of_a_later_step_from_the_same_state_keeps_the_target() { + let mut s = session(); + s.execute("channel.target", json!({"channel": "red"})).unwrap(); + s.execute("channel.new", json!({})).unwrap(); + assert!(s.undo()); + s.execute("channel.target", json!({"channel": "green"})).unwrap(); + s.execute("select.rect", json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap(); + assert!(s.undo()); + assert_eq!(view(&s).target, ChannelTarget::Color(1)); +} + +/// The remembered view stays with the New Channel step: every undo of it, after any number of +/// redos, returns to Red. +#[test] +fn every_undo_of_new_channel_returns_to_red() { + let mut s = session(); + s.execute("channel.target", json!({"channel": "red"})).unwrap(); + s.execute("channel.new", json!({})).unwrap(); + for round in 0..3 { + assert!(s.undo()); + assert_eq!(view(&s).target, ChannelTarget::Color(0), "undo {round}"); + s.execute("channel.target", json!({"channel": "blue"})).unwrap(); + assert!(s.redo()); + assert_eq!(doc(&s).channels.len(), 1); + } +} diff --git a/crates/engine-core/src/cmd/channel_cmds/view.rs b/crates/engine-core/src/cmd/channel_cmds/view.rs index 02d70cc16b..fbd5157f4b 100644 --- a/crates/engine-core/src/cmd/channel_cmds/view.rs +++ b/crates/engine-core/src/cmd/channel_cmds/view.rs @@ -1,5 +1,5 @@ use super::planes::color_count; -use super::{ColorMode, DocState, Document, Serialize}; +use super::{ColorMode, DocState, Document, Serialize, Session}; // --------------------------------------------------------------------------------------------- // View state @@ -155,3 +155,34 @@ pub fn composite_name(mode: ColorMode) -> &'static str { _ => "RGB", } } + +// --------------------------------------------------------------------------------------------- +// Undo of a step that targets the channel it creates + +/// Before New Channel or Calculations (Result: New Channel), which target the channel they make: +/// the history state the step starts from and the channel view then. +pub(super) fn view_before_step(s: &Session) -> Option<(u64, ChannelView)> { + let st = s.active()?; + Some((st.history.row_id(st.history.past_len())?, st.channel_view.clone())) +} + +/// After that step: undoing it (leaving the state it made for the one it started from) brings +/// `before`'s view back (#14683). Kept for the step, so undo after redo brings it back again. The +/// views of steps history no longer holds are dropped. +pub(super) fn keep_view_for_undo(s: &mut Session, before: Option<(u64, ChannelView)>) { + let (Some(st), Some((from, view))) = (s.active_mut(), before) else { return }; + let Some(to) = st.history.row_id(st.history.past_len()) else { return }; + let history = &st.history; + st.undo_channel_views.retain(|(kept_from, kept_to, _)| *kept_to != to && history.row_of(*kept_from).is_some() && history.row_of(*kept_to).is_some()); + st.undo_channel_views.push((from, to, view)); +} + +/// Undo just left the state `left` for the current one: when that undid a step with a kept view, +/// target and show the channels it did. +pub(crate) fn restore_view_after_undo(st: &mut DocState, left: Option) { + let Some(left) = left else { return }; + let Some(id) = st.history.row_id(st.history.past_len()) else { return }; + let Some((_, _, view)) = st.undo_channel_views.iter().find(|(from, to, _)| *from == id && *to == left) else { return }; + st.channel_view = view.clone(); + fix_view(st); +} diff --git a/crates/engine-core/src/cmd/color_cmds.rs b/crates/engine-core/src/cmd/color_cmds.rs index 11e74ac672..c709bb6d43 100644 --- a/crates/engine-core/src/cmd/color_cmds.rs +++ b/crates/engine-core/src/cmd/color_cmds.rs @@ -759,6 +759,51 @@ pub fn working_profile(mode: ColorMode) -> Arc { Arc::new(craft_cms::builtin::default_for(mode_space(mode)).unwrap_or(Builtin::Srgb.profile()).clone()) } +/// Resolve an export copy's working profile under the session's existing profile-read gate. +/// The actual spec is authorized so an implicit working space cannot hide an ICC path. +pub(crate) fn export_working_profile(s: &Session, mode: ColorMode) -> Result> { + let _authorization = crate::jobs::render_authorization_scope(s.authorize); + if let Some(spec) = s.color().settings.working_spec(mode_space(mode)) { + crate::jobs::authorize_render_command("edit.profileInfo", &json!({"profile": spec}))?; + } + Ok(s.color().working(mode)) +} + +/// Refuse an export's implicit profile read before dispatch drops a floating selection. +pub(crate) fn check_export_working_profile(s: &Session, id: &str, p: &Value) -> Result<()> { + if !matches!(id, "file.export.layersToFiles" | "file.export.saveForWebLegacy" | "file.export.quickExport") { + return Ok(()); + } + let Some(st) = s.active() else { return Ok(()) }; + let doc = &st.doc; + if doc.icc_profile.is_some() || !matches!(doc.mode, ColorMode::Rgb | ColorMode::Grayscale) { + return Ok(()); + } + let needed = match id { + "file.export.layersToFiles" => p.get("iccProfile").and_then(Value::as_bool) == Some(true), + "file.export.saveForWebLegacy" if doc.mode == ColorMode::Rgb => { + let settings = crate::web_cmds::WebSettings::from_params(p, id)?; + settings.embed_icc && !settings.convert_to_srgb + } + "file.export.quickExport" if doc.mode == ColorMode::Rgb => { + let prefs = s.prefs().export.clone(); + let path = + p.get("path").and_then(Value::as_str).filter(|path| !path.is_empty()).map(str::to_owned).or_else(|| crate::web_cmds::quick_export_target(s)); + let format = path.map(|path| { + crate::file_cmds::extension(&path).unwrap_or_else(|| { + serde_json::to_value(prefs.quick_export_format).ok().and_then(|value| value.as_str().map(str::to_owned)).unwrap_or_default() + }) + }); + !prefs.convert_to_srgb && format.as_deref() == Some("webp") + } + _ => false, + }; + if needed { + export_working_profile(s, doc.mode)?; + } + Ok(()) +} + /// Parses ICC bytes, caching by allocation so repeated lookups for the same document are free. pub fn profile_from_bytes(bytes: &Arc>) -> std::result::Result, craft_cms::CmsError> { type Cache = Mutex>, Arc)>>; diff --git a/crates/engine-core/src/cmd/extra_cmds.rs b/crates/engine-core/src/cmd/extra_cmds.rs index aadcfc89ca..6aa06a7c00 100644 --- a/crates/engine-core/src/cmd/extra_cmds.rs +++ b/crates/engine-core/src/cmd/extra_cmds.rs @@ -550,7 +550,16 @@ pub fn background_to_layer(doc: &mut photocraft_doc::Document, id: photocraft_do fn toggle_mask(s: &mut Session, p: &Value, key: &str) -> Result { let id = layer_param(s, p)?; - let label = if key == "enabled" { "Enable/Disable Layer Mask" } else { "Link/Unlink Layer Mask" }; + // A call that says the direction (the Layers panel's ⇧-click and chain) is named by it, as in Photoshop + // (#16786); a plain toggle (Layer › Layer Mask) keeps its two-way name. + let label = match (key, p.get(key).and_then(Value::as_bool)) { + ("enabled", Some(true)) => "Enable Layer Mask", + ("enabled", Some(false)) => "Disable Layer Mask", + ("enabled", None) => "Enable/Disable Layer Mask", + (_, Some(true)) => "Link Mask", + (_, Some(false)) => "Unlink Mask", + (_, None) => "Link/Unlink Layer Mask", + }; let v = s.edit(label, |doc, _| { let m = doc.layer_mut(id).and_then(|l| l.mask.as_mut()).ok_or(EngineError::Other("the layer has no layer mask".into()))?; let slot = if key == "enabled" { &mut m.enabled } else { &mut m.linked }; diff --git a/crates/engine-core/src/cmd/file_cmds/export.rs b/crates/engine-core/src/cmd/file_cmds/export.rs index d7724ec064..9614b13179 100644 --- a/crates/engine-core/src/cmd/file_cmds/export.rs +++ b/crates/engine-core/src/cmd/file_cmds/export.rs @@ -71,7 +71,12 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& return Err(EngineError::Other("Layers to Files needs a document with multiple layers.".into())); } let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name)); - let doc = d.doc.clone(); + let mut doc = d.doc.clone(); + if icc == Some(true) && doc.icc_profile.is_none() && matches!(doc.mode, ColorMode::Rgb | ColorMode::Grayscale) { + // Only the exported copy gains a tag; the open document remains untagged. + let profile = crate::color_cmds::export_working_profile(s, doc.mode)?.to_bytes(); + std::sync::Arc::make_mut(&mut doc).icc_profile = Some(profile); + } let mut report = LayerExportReport::default(); // Every layer takes its panel-order index, even one skipped as hidden or as an adjustment, // so a file keeps the same number whether Visible Layers Only is on or off (#13959). diff --git a/crates/engine-core/src/cmd/file_cmds/layers_to_files_icc_tests.rs b/crates/engine-core/src/cmd/file_cmds/layers_to_files_icc_tests.rs index 19f2b9c24e..c1c41c9fdd 100644 --- a/crates/engine-core/src/cmd/file_cmds/layers_to_files_icc_tests.rs +++ b/crates/engine-core/src/cmd/file_cmds/layers_to_files_icc_tests.rs @@ -4,6 +4,7 @@ #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use super::*; +use crate::color_cmds::ColorExt; fn session(mode: &str, depth: u32) -> Session { let mut s = crate::session(); @@ -181,3 +182,87 @@ fn an_indexed_documents_files_follow_the_setting() { assert!(layered.iter().all(|(_, icc)| icc.is_none()), "indexed layered tif: no profile"); assert_eq!(one(&mut s, "psd", json!({"iccProfile": true})).1, Some("RGB".into()), "indexed psd: the profile"); } + +/// #17199: Include ICC describes an untagged layer in the session's working space, +/// without assigning that profile to the source document or changing its samples. +#[test] +fn include_icc_uses_the_working_space_only_for_untagged_layers() { + let export_profile = |s: &mut Session| { + let dir = tempfile::tempdir().unwrap(); + let out = s.execute("file.export.layersToFiles", json!({"dir": dir.path().to_string_lossy(), "format": "png", "iccProfile": true})).unwrap(); + let files = out["files"].as_array().unwrap(); + assert_eq!(files.len(), 1); + let bytes = std::fs::read(files[0].as_str().unwrap()).unwrap(); + photocraft_codecs::decode(&bytes).unwrap().icc.unwrap() + }; + for (mode, key, working, tagged) in [("rgb", "workingRgb", "prophoto-compat", "display-p3"), ("grayscale", "workingGray", "gray-gamma-2.2", "sgray")] { + let mut s = session(mode, 8); + s.execute("edit.assignProfile", json!({"profile": "none"})).unwrap(); + let mut settings = json!({}); + settings[key] = json!(working); + s.execute("edit.colorSettings", settings).unwrap(); + let original = s.active().unwrap().doc.clone(); + assert!(original.icc_profile.is_none()); + let samples = photocraft_compose::flatten(&original).px.to_vec(); + let expected = s.color().working(original.mode).to_bytes(); + assert_ne!(expected, crate::color_cmds::working_profile(original.mode).to_bytes(), "{mode}: the nondefault profile must distinguish the old fallback"); + assert_eq!(export_profile(&mut s).as_slice(), expected.as_slice(), "{mode}"); + assert!(s.active().unwrap().doc.icc_profile.is_none()); + assert_eq!(photocraft_compose::flatten(&s.active().unwrap().doc).px.to_vec(), samples); + + s.execute("edit.assignProfile", json!({"profile": tagged})).unwrap(); + let own = s.active().unwrap().doc.icc_profile.clone().unwrap(); + assert_ne!(own, expected); + assert_eq!(export_profile(&mut s).as_slice(), own.as_slice(), "{mode}: a tag wins over the working space"); + assert_eq!(s.active().unwrap().doc.icc_profile.as_deref(), Some(own.as_ref())); + assert_eq!(photocraft_compose::flatten(&s.active().unwrap().doc).px.to_vec(), samples); + } + let mut s = session("rgb", 8); + s.execute("edit.assignProfile", json!({"profile": "none"})).unwrap(); + s.execute("edit.colorSettings", json!({"workingRgb": "prophoto-compat"})).unwrap(); + let expected = s.color().working(ColorMode::Rgb).to_bytes(); + + // An export may be authorized while a stored working-profile path is not. The inherited + // job gate must run before resolving that path, including APIs without Session::execute. + fn deny_profile_path(id: &str, params: &Value) -> crate::Result<()> { + if id == "edit.profileInfo" && params.get("profile").and_then(Value::as_str).is_some_and(|p| p.ends_with("blocked-working.icc")) { + return Err(EngineError::Other("denied working ICC read 17199".into())); + } + Ok(()) + } + let profile_dir = tempfile::tempdir().unwrap(); + let profile_path = profile_dir.path().join("blocked-working.icc"); + std::fs::write(&profile_path, expected.as_slice()).unwrap(); + s.execute("edit.colorSettings", json!({"workingRgb": profile_path.to_string_lossy()})).unwrap(); + let _authorization = crate::jobs::render_authorization_scope(Some(deny_profile_path)); + + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 2, "height": 2})).unwrap(); + s.execute("select.float", json!({"dx": 2})).unwrap(); + assert!(crate::float_cmds::floating(s.active().unwrap()).is_some()); + let document = s.active().unwrap().doc.clone(); + let revision = s.active().unwrap().revision; + let history = s.active().unwrap().history.entries(); + + let mut writes = 0; + let error = export_layers_report_with(&s, &json!({"format": "png", "iccProfile": true}), |_, _| { + writes += 1; + Ok(()) + }) + .unwrap_err(); + assert!(error.to_string().contains("denied working ICC read 17199")); + assert_eq!(writes, 0, "a rejected implicit profile read must not produce a layer file"); + assert!(s.active().unwrap().doc.icc_profile.is_none()); + assert!(crate::float_cmds::floating(s.active().unwrap()).is_some(), "a denied profile read leaves the move floating"); + assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &document)); + assert_eq!(s.active().unwrap().revision, revision); + assert_eq!(s.active().unwrap().history.entries(), history, "no History step is added"); + + let output = tempfile::tempdir().unwrap(); + let error = s.execute("file.export.layersToFiles", json!({"dir": output.path().to_string_lossy(), "format": "png", "iccProfile": true})).unwrap_err(); + assert!(error.to_string().contains("denied working ICC read 17199")); + assert_eq!(std::fs::read_dir(output.path()).unwrap().count(), 0); + assert!(crate::float_cmds::floating(s.active().unwrap()).is_some(), "a denied profile read leaves the move floating"); + assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &document)); + assert_eq!(s.active().unwrap().revision, revision); + assert_eq!(s.active().unwrap().history.entries(), history, "no History step is added"); +} diff --git a/crates/engine-core/src/cmd/layer_copy_cmds.rs b/crates/engine-core/src/cmd/layer_copy_cmds.rs index 176518f937..4671ed0ee8 100644 --- a/crates/engine-core/src/cmd/layer_copy_cmds.rs +++ b/crates/engine-core/src/cmd/layer_copy_cmds.rs @@ -370,7 +370,12 @@ pub(crate) fn duplicate_to_new_document(s: &mut Session, p: &Value) -> Result copy". + +use serde_json::json; + +use crate::Session; + +fn doc_name(s: &Session, i: usize) -> String { + s.documents().get(i).map(|d| d.doc.name.clone()).unwrap_or_default() +} + +/// A one-layer document named `name`, with its only layer active. +fn source(name: &str) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"name": name, "width": 40, "height": 30, "background": "white"})).unwrap(); + s +} + +#[test] +fn an_empty_name_makes_the_next_untitled_document() { + let mut s = source("oracle"); + s.execute("layer.duplicate", json!({"document": "new"})).unwrap(); + assert_eq!(doc_name(&s, 0), "oracle", "the source keeps its name"); + assert_eq!(doc_name(&s, 1), "Untitled-1"); +} + +#[test] +fn the_counter_skips_untitled_documents_already_open() { + let mut s = source("oracle"); + // An Untitled-1 is open beside the source; the copy takes the next number. + s.execute("file.new", json!({"name": "Untitled-1", "width": 8, "height": 8})).unwrap(); + let oracle = s.documents().iter().position(|d| d.doc.name == "oracle").unwrap(); + s.set_active(oracle); + s.execute("layer.duplicate", json!({"document": "new"})).unwrap(); + assert_eq!(doc_name(&s, s.active_index().unwrap()), "Untitled-2"); +} + +#[test] +fn a_typed_name_is_used_as_given() { + let mut s = source("oracle"); + s.execute("layer.duplicate", json!({"document": "new", "documentName": "MyNew"})).unwrap(); + assert_eq!(doc_name(&s, 1), "MyNew"); +} + +#[test] +fn an_empty_typed_name_falls_back_to_untitled() { + let mut s = source("oracle"); + s.execute("layer.duplicate", json!({"document": "new", "documentName": ""})).unwrap(); + assert_eq!(doc_name(&s, 1), "Untitled-1"); +} diff --git a/crates/engine-core/src/cmd/layer_multi_cmds.rs b/crates/engine-core/src/cmd/layer_multi_cmds.rs index a308da2541..e74f50849d 100644 --- a/crates/engine-core/src/cmd/layer_multi_cmds.rs +++ b/crates/engine-core/src/cmd/layer_multi_cmds.rs @@ -158,8 +158,8 @@ pub fn specs() -> Vec { &["Layer", "New"], None, r##"{"layer":id?,"name":text?,"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":str="passThrough" (blend mode),"opacity":0..100=100 (percent)} (no layer: every selected layer; the new group starts collapsed)"##, - has_layer, - group_layers + structure::can_group_from_layers, + structure::group_from_layers ), spec!("layer.arrange.reverse", "Reverse", &["Layer", "Arrange"], None, "{}", two_plus, |s, _| reverse(s)), spec!( @@ -183,3 +183,6 @@ mod layers_panel_parity_tests; #[cfg(test)] mod tile_damage_tests; + +#[cfg(test)] +mod group_from_layers_background_tests; diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/group_from_layers_background_tests.rs b/crates/engine-core/src/cmd/layer_multi_cmds/group_from_layers_background_tests.rs new file mode 100644 index 0000000000..cd25687371 --- /dev/null +++ b/crates/engine-core/src/cmd/layer_multi_cmds/group_from_layers_background_tests.rs @@ -0,0 +1,112 @@ +//! Group from Layers is refused while the Background is among the selected layers (#14709), as +//! the menu rows already grey it. Layer > Group Layers keeps grouping it (not measured). + +use super::*; + +/// A 32 x 32 document with a white Background and the pixel layers Red, Green and Blue above it. +fn session() -> (Session, LayerId, [LayerId; 3]) { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 32, "height": 32, "background": "white"})).unwrap(); + let bg = s.active().unwrap().doc.layers[0].id; + assert!(s.active().unwrap().doc.is_background(bg)); + let ids = ["Red", "Green", "Blue"].map(|name| LayerId(s.execute("layer.new.layer", json!({"name": name})).unwrap()["layer"].as_u64().unwrap())); + (s, bg, ids) +} + +fn select(s: &mut Session, ids: &[LayerId], active: LayerId) { + set_selection(s, ids.to_vec(), Some(active), Some(active)).unwrap(); +} + +/// Everything a refused command must leave alone: the layer tree, the selection and the history. +fn snapshot(s: &Session) -> (photocraft_doc::layer_tree::LayerTree, Vec, Option, Vec) { + let d = s.active().unwrap(); + (d.doc.layers.clone(), d.selected_layers().to_vec(), d.active_layer, d.history.entries()) +} + +fn enabled(s: &Session) -> std::result::Result<(), String> { + (crate::commands::find("layer.new.groupFromLayers").unwrap().enabled)(s) +} + +fn refused(s: &mut Session, params: Value) { + let before = snapshot(s); + assert!(s.execute("layer.new.groupFromLayers", params.clone()).is_err(), "{params} must be refused"); + assert!(snapshot(s) == before, "{params} changed the document"); + assert!(s.active().unwrap().doc.background().is_some(), "the Background is still there"); +} + +#[test] +fn the_background_alone_is_refused() { + let (mut s, bg, _) = session(); + select(&mut s, &[bg], bg); + assert!(enabled(&s).is_err(), "disabled with the Background selected"); + refused(&mut s, json!({})); + refused(&mut s, json!({"name": "Set", "color": "red", "mode": "normal", "opacity": 50})); +} + +#[test] +fn the_background_with_other_layers_is_refused() { + let (mut s, bg, [red, green, _]) = session(); + for active in [red, bg] { + select(&mut s, &[bg, red], active); + assert!(enabled(&s).is_err(), "disabled with the Background and Red selected"); + refused(&mut s, json!({})); + } + select(&mut s, &[bg, red, green], green); + refused(&mut s, json!({})); +} + +#[test] +fn an_explicit_background_layer_is_refused() { + let (mut s, bg, [red, _, blue]) = session(); + select(&mut s, &[blue], blue); + refused(&mut s, json!({"layer": bg.0})); + select(&mut s, &[red, blue], red); + refused(&mut s, json!({"layer": bg.0})); + select(&mut s, &[bg], bg); + refused(&mut s, json!({"layer": bg.0})); +} + +#[test] +fn a_background_only_document_is_refused() { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 32, "height": 32, "background": "white"})).unwrap(); + assert_eq!(s.active().unwrap().doc.layers.len(), 1); + assert!(enabled(&s).is_err()); + refused(&mut s, json!({})); +} + +fn children(s: &Session, group: LayerId) -> Vec { + s.active().unwrap().doc.layer(group).unwrap().children().unwrap().iter().map(|l| l.id).collect() +} + +#[test] +fn layers_without_the_background_still_group() { + let (mut s, bg, [red, green, blue]) = session(); + select(&mut s, &[blue], blue); + assert!(enabled(&s).is_ok()); + let g = LayerId(s.execute("layer.new.groupFromLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); + assert_eq!(children(&s, g), vec![blue]); + + select(&mut s, &[red, green], green); + let g = LayerId(s.execute("layer.new.groupFromLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); + assert_eq!(children(&s, g), vec![red, green]); + assert!(s.active().unwrap().doc.is_background(bg), "the Background stays"); +} + +#[test] +fn an_explicit_layer_other_than_the_background_still_groups() { + let (mut s, bg, [red, _, blue]) = session(); + select(&mut s, &[blue], blue); + let g = LayerId(s.execute("layer.new.groupFromLayers", json!({"layer": red.0})).unwrap()["layer"].as_u64().unwrap()); + assert_eq!(children(&s, g), vec![red]); + assert!(s.active().unwrap().doc.is_background(bg)); +} + +/// Layer > Group Layers with the Background selected is not measured: it keeps today's result. +#[test] +fn group_layers_keeps_grouping_the_background() { + let (mut s, bg, [red, ..]) = session(); + select(&mut s, &[bg, red], red); + let g = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); + assert_eq!(children(&s, g), vec![bg, red]); +} diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/structure.rs b/crates/engine-core/src/cmd/layer_multi_cmds/structure.rs index 967fff2f55..bcd49eafdf 100644 --- a/crates/engine-core/src/cmd/layer_multi_cmds/structure.rs +++ b/crates/engine-core/src/cmd/layer_multi_cmds/structure.rs @@ -111,6 +111,32 @@ pub(crate) fn check_group_depth(doc: &Document, what: &str) -> Result<()> { Ok(()) } +/// Group from Layers is greyed while the Background is among the selected layers, as in the +/// menus (#14709). +pub(super) fn can_group_from_layers(s: &Session) -> std::result::Result<(), String> { + super::has_layer(s)?; + let d = s.active().ok_or("no document open")?; + if d.selected_layers().iter().any(|id| d.doc.is_background(*id)) { + return Err("the Background layer can't go into a group".into()); + } + Ok(()) +} + +/// Group from Layers: [`group_layers`], refused with the Background among the layers it would +/// move, also when the `layer` param names it (#14709). Group Layers (⌘G) is not measured and +/// keeps grouping it. +pub(super) fn group_from_layers(s: &mut Session, p: &Value) -> Result { + let ids = match crate::commands::explicit_layer(s, p)? { + Some(id) => vec![id], + None => selected(s), + }; + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + if ids.iter().any(|id| doc.is_background(*id)) { + return Err(EngineError::Other("the Background layer can't go into a group".into())); + } + group_layers(s, p) +} + /// Group Layers (⌘G) / Group from Layers: the explicit layer, or every selected layer, moves /// into a new, collapsed group placed where the top-most of them was. Bottom-to-top order is /// preserved. The New Group dialog's colour, mode and opacity are set in the same history step. diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/tests.rs b/crates/engine-core/src/cmd/layer_multi_cmds/tests.rs index c690b0d0ae..7d915f0eb2 100644 --- a/crates/engine-core/src/cmd/layer_multi_cmds/tests.rs +++ b/crates/engine-core/src/cmd/layer_multi_cmds/tests.rs @@ -1014,7 +1014,8 @@ fn a_locked_group_keeps_a_grouped_background_locked() { let mut s = session(8); let bg = doc(&s).layers[0].id; s.execute("layer.select", json!({"layer": bg.0})).unwrap(); - let g = s.execute("layer.new.groupFromLayers", json!({})).unwrap()["layer"].as_u64().unwrap(); + // Group from Layers refuses the Background (#14709); Group Layers still groups it. + let g = s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap(); s.execute("layer.setProps", json!({"layer": g, "locked": true})).unwrap(); s.execute("layer.select", json!({"layer": bg.0})).unwrap(); for (cmd, p) in [ diff --git a/crates/engine-core/src/cmd/ops.rs b/crates/engine-core/src/cmd/ops.rs index 7e08493d68..e892c43325 100644 --- a/crates/engine-core/src/cmd/ops.rs +++ b/crates/engine-core/src/cmd/ops.rs @@ -99,7 +99,8 @@ fn set_mask_with(s: &mut Session, p: &Value, label: &str, mask: Option Result { let bad = |m: &str| EngineError::BadParams { cmd: "layer.layerMask.moveTo".into(), msg: m.into() }; let from = layer_param(s, p)?; @@ -109,8 +110,7 @@ pub(super) fn move_mask(s: &mut Session, p: &Value) -> Result { if from == to { return Err(bad("the mask is already on that layer")); } - let label = if copy { "Copy Layer Mask" } else { "Move Layer Mask" }; - s.edit(label, |doc, _| { + s.edit("Add Layer Mask", |doc, _| { let mask = doc.layer(from).ok_or(EngineError::NoLayer(from))?.mask.clone().ok_or_else(|| bad("the layer has no layer mask"))?; if doc.layer(to).ok_or(EngineError::NoLayer(to))?.mask.is_some() && !replace { return Err(bad("the layer already has a layer mask (pass `replace`)")); diff --git a/crates/engine-core/src/cmd/vector_cmds.rs b/crates/engine-core/src/cmd/vector_cmds.rs index af1b91eae5..89cdab1e9a 100644 --- a/crates/engine-core/src/cmd/vector_cmds.rs +++ b/crates/engine-core/src/cmd/vector_cmds.rs @@ -88,8 +88,8 @@ use shape::{ can_paste_shape_fill, can_paste_shape_stroke, combine_shapes, copy_shape_fill, copy_shape_stroke, has_shape_fill, has_shape_stroke, merge_components, paste_shape_fill, paste_shape_stroke, path_to_shape, selection_to_shape, shape_create, shape_edit, shape_info, shape_rasterize, }; +pub use shape::{line_frame_scale, line_frame_size, preview_shape_stroke, refresh_shape, shape_path, transform_shape, translate_vectors}; pub(crate) use shape::{map_path, map_shape, shift_shape, translate_vectors_wrapped}; -pub use shape::{preview_shape_stroke, refresh_shape, shape_path, transform_shape, translate_vectors}; use vector_mask::{toggle_vector_mask, vector_mask_add, vector_mask_delete, vector_mask_edit, vector_mask_info, vector_mask_rasterize, with}; pub fn leak(s: String) -> &'static str { diff --git a/crates/engine-core/src/cmd/vector_cmds/shape.rs b/crates/engine-core/src/cmd/vector_cmds/shape.rs index d2e62f2d4b..419e883a67 100644 --- a/crates/engine-core/src/cmd/vector_cmds/shape.rs +++ b/crates/engine-core/src/cmd/vector_cmds/shape.rs @@ -189,6 +189,95 @@ fn arrow_axis_scales(a: &Affine, from: [f64; 2], to: [f64; 2]) -> Option<(f64, f (dot.abs() <= 1e-10 * axial * perpendicular).then_some((axial, perpendicular)) } +/// A live line's own frame. +struct LineFrame { + /// The start. + from: [f64; 2], + /// The unit direction from the start to the end. + u: [f64; 2], + /// The normal, `(-u.y, u.x)`. + n: [f64; 2], + length: f64, + /// The weight, or the arrowhead width when it is wider and an arrowhead is on. + thickness: f64, +} + +/// A live line's own frame; `None` for another live shape or a degenerate or non-finite line. +fn line_frame(live: &LiveShape) -> Option { + let (from, to, thickness) = match live { + LiveShape::Line { from, to, weight } => (*from, *to, *weight), + LiveShape::ArrowLine { from, to, weight, start, end, width, .. } => (*from, *to, if *start || *end { weight.max(*width) } else { *weight }), + _ => return None, + }; + let (dx, dy) = (to[0] - from[0], to[1] - from[1]); + let length = dx.hypot(dy); + if !length.is_finite() || length <= 1e-12 || !thickness.is_finite() || !from.iter().all(|v| v.is_finite()) { + return None; + } + let u = [dx / length, dy / length]; + Some(LineFrame { from, u, n: [-u[1], u[0]], length, thickness }) +} + +/// The size of a live line in its own rotated frame, as the Line tool's W and H fields show it +/// (#13250): `(length, thickness)`, the thickness being the weight, or the arrowhead width when an +/// arrowhead is on and wider. `None` for another live shape or a degenerate line. +pub fn line_frame_size(live: &LiveShape) -> Option<(f64, f64)> { + line_frame(live).map(|f| (f.length, f.thickness)) +} + +/// The transform that resizes a live line in its own rotated frame to `new_length` (W) by +/// `new_thickness` (H), for `shape.edit {"transform": m}` (#13250; the Properties Transform of a +/// line, #13265, builds on it). Along the line it scales about the start, so the start stays put +/// and the angle is kept; across it, it scales about the edge of the rotated box on the start's +/// side opposite the normal, `from - (thickness / 2) * n` with `n = (-u.y, u.x)`: the measured +/// reference moves the start of a 15 px thick line from 400,300 to 398.88,302.24 for H 20. +/// [`transform_shape`] keeps the line live under it and scales the weight and arrowhead width by +/// the thickness factor and the arrowhead length by the length factor. +/// +/// `None` (no edit) for another live shape, a degenerate line, or a size that is not finite and +/// positive. Never panics. +pub fn line_frame_scale(live: &LiveShape, new_length: f64, new_thickness: f64) -> Option { + if !new_length.is_finite() || !new_thickness.is_finite() || new_length <= 0.0 || new_thickness <= 0.0 { + return None; + } + let LineFrame { from, u, n, length, thickness } = line_frame(live)?; + if thickness <= 1e-12 { + return None; + } + let (sa, sp) = (new_length / length, new_thickness / thickness); + if !sa.is_finite() || !sp.is_finite() { + return None; + } + // M = I + (sa - 1) u u^T + (sp - 1) n n^T, about the pivot P: x' = M x + (P - M P). + let (ka, kp) = (sa - 1.0, sp - 1.0); + let a = 1.0 + ka * u[0] * u[0] + kp * n[0] * n[0]; + let b = ka * u[0] * u[1] + kp * n[0] * n[1]; + let d = 1.0 + ka * u[1] * u[1] + kp * n[1] * n[1]; + let pivot = [from[0] - thickness / 2.0 * n[0], from[1] - thickness / 2.0 * n[1]]; + let e = pivot[0] - (a * pivot[0] + b * pivot[1]); + let f = pivot[1] - (b * pivot[0] + d * pivot[1]); + let m = [a, b, b, d, e, f]; + m.iter().all(|v| v.is_finite()).then_some(Affine { m }) +} + +/// Whether `m` scales a live line only along and across itself (a non-trivial [`line_frame_scale`]): +/// its direction and normal map onto themselves with positive factors, not both 1. +fn is_line_frame_scale(live: &LiveShape, m: &[f64; 6]) -> bool { + let Some(LineFrame { u, n, .. }) = line_frame(live) else { return false }; + let [a, b, c, d, _, _] = *m; + let map = |v: [f64; 2]| [a * v[0] + c * v[1], b * v[0] + d * v[1]]; + let factor = |v: [f64; 2]| { + let w = map(v); + let along = w[0] * v[0] + w[1] * v[1]; + let across = w[0] * -v[1] + w[1] * v[0]; + (along.is_finite() && along > 1e-12 && across.abs() <= 1e-9 * along.max(1.0)).then_some(along) + }; + match (factor(u), factor(n)) { + (Some(sa), Some(sp)) => (sa - 1.0).abs() > 1e-12 || (sp - 1.0).abs() > 1e-12, + _ => false, + } +} + /// Applies an affine transform to a shape's path, keeping the live shape when the transform /// is a translation plus axis-aligned scale (otherwise the shape stops being parametric). pub fn transform_shape(sh: &mut ShapeLayer, a: &Affine) { @@ -317,6 +406,11 @@ pub fn transform_shape(sh: &mut ShapeLayer, a: &Affine) { } }) } + // A plain line under the same transforms (the W and H of a diagonal line, #13250). + (Some(LiveShape::Line { from, to, weight }), false) => arrow_axis_scales(a, from, to).map(|(_, perpendicular_scale)| { + let pt = |p: [f64; 2]| [m0 * p[0] + m2 * p[1] + tx, m1 * p[0] + m3 * p[1] + ty]; + LiveShape::Line { from: pt(from), to: pt(to), weight: weight * perpendicular_scale } + }), _ => None, }; // Keep the exact transformed outline. Remove live arrow parameters @@ -575,7 +669,9 @@ pub(super) fn path_to_shape(s: &mut Session, p: &Value) -> Result { /// End and Width; Start, Length and Concavity follow the same pattern. Rounding a live triangle /// alone is "Change Rounded Triangle" (#13354); a three-sided Polygon is not a Triangle and keeps /// "Edit Shape" until the Polygon naming issue lands. Any other edit, several keys at once, or -/// these keys sent to another shape stay "Edit Shape". +/// these keys sent to another shape stay "Edit Shape". A lone `transform` of a line that only scales +/// it along and across itself (the options bar's W and H, [`line_frame_scale`]) is "Scale Paths" +/// (#13250). fn edit_history_name(s: &Session, id: LayerId, p: &Value) -> &'static str { const EDIT: &str = "Edit Shape"; let live = s.active().and_then(|st| st.doc.layer(id)).and_then(|l| match &l.content { @@ -592,6 +688,8 @@ fn edit_history_name(s: &Session, id: LayerId, p: &Value) -> &'static str { (Some("arrowLength"), None) if line => "Change Arrowhead Length", (Some("arrowConcavity"), None) if line => "Change Arrowhead Concavity", (Some("cornerRadius"), None) if matches!(live, Some(LiveShape::Triangle { .. })) => "Change Rounded Triangle", + // The options bar's W and H of a line (#13250): a resize in the line's own frame. + (Some("transform"), None) if live.zip(nums::<6>(p, "transform")).is_some_and(|(l, m)| is_line_frame_scale(l, &m)) => "Scale Paths", _ => EDIT, } } diff --git a/crates/engine-core/src/cmd/vector_cmds/vector_mask.rs b/crates/engine-core/src/cmd/vector_cmds/vector_mask.rs index 34abf1eab0..a03de7ff50 100644 --- a/crates/engine-core/src/cmd/vector_cmds/vector_mask.rs +++ b/crates/engine-core/src/cmd/vector_cmds/vector_mask.rs @@ -58,6 +58,11 @@ pub(super) fn vector_mask_add(s: &mut Session, p: &Value, from_path: bool) -> Re } pub(super) fn vector_mask_edit(s: &mut Session, p: &Value) -> Result { + edit_vector_mask(s, p, "Edit Vector Mask") +} + +/// `layer.vectorMask.edit` with `p`, its history step named `label`. +fn edit_vector_mask(s: &mut Session, p: &Value, label: &str) -> Result { const CMD: &str = "layer.vectorMask.edit"; let id = layer_id(s, p)?; let path = p.get("path").map(parse_path).transpose().map_err(|e| bad(CMD, e))?; @@ -100,7 +105,7 @@ pub(super) fn vector_mask_edit(s: &mut Session, p: &Value) -> Result { })?; return vector_mask_info(s, id); } - s.edit("Edit Vector Mask", |doc, _| { + s.edit(label, |doc, _| { let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; let vm = l.vector_mask.as_mut().ok_or_else(|| EngineError::Other("layer has no vector mask".into()))?; if let Some(pth) = path { @@ -194,6 +199,15 @@ pub(super) fn toggle_vector_mask(s: &mut Session, p: &Value, key: &str) -> Resul let vm = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?.vector_mask.as_ref().ok_or_else(|| EngineError::Other("layer has no vector mask".into()))?; if key == "enabled" { vm.enabled } else { vm.linked } }; + // A call that says the direction (the Layers panel's ⇧-click and chain) is named by it, as in Photoshop + // (#16786); a plain toggle (Layer › Vector Mask) keeps its name. + let label = match (key, p.get(key).and_then(Value::as_bool)) { + ("enabled", Some(true)) => "Enable Vector Mask", + ("enabled", Some(false)) => "Disable Vector Mask", + (_, Some(true)) => "Link Vector Mask", + (_, Some(false)) => "Unlink Vector Mask", + (_, None) => "Edit Vector Mask", + }; let v = p.get(key).and_then(Value::as_bool).unwrap_or(!cur); - vector_mask_edit(s, &json!({ "layer": id.0, key: v })) + edit_vector_mask(s, &json!({ "layer": id.0, key: v }), label) } diff --git a/crates/engine-core/src/cmd/web_cmds/quick.rs b/crates/engine-core/src/cmd/web_cmds/quick.rs index 66b4b4dc9c..befb25a554 100644 --- a/crates/engine-core/src/cmd/web_cmds/quick.rs +++ b/crates/engine-core/src/cmd/web_cmds/quick.rs @@ -119,6 +119,10 @@ pub(super) fn quick_export(s: &mut Session, p: &Value) -> Result { // Keeping quality absent preserves the historical lossless Quick Export behavior. let st = WebSettings::from_params(&Value::Object(o.clone()), cmd)?; let (mut wdoc, _, _) = web_document(&doc, &json!({}), &st)?; + if !st.convert_to_srgb && doc.icc_profile.is_none() && doc.mode == photocraft_doc::ColorMode::Rgb { + // The regular WebP writer embeds ICC by default; do not let it guess sRGB. + wdoc.icc_profile = Some(crate::color_cmds::export_working_profile(s, doc.mode)?.to_bytes()); + } // The regular exporter embeds the document's XMP and EXIF as they are: give it only // what the metadata choice keeps, as the Save for Web formats get. wdoc.metadata.xmp = web_xmp(&doc, st.metadata).map(std::sync::Arc::from); diff --git a/crates/engine-core/src/cmd/web_cmds/save_web.rs b/crates/engine-core/src/cmd/web_cmds/save_web.rs index a6478b76ea..2a4b305c73 100644 --- a/crates/engine-core/src/cmd/web_cmds/save_web.rs +++ b/crates/engine-core/src/cmd/web_cmds/save_web.rs @@ -227,16 +227,28 @@ fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u let st = WebSettings::from_params(p, cmd)?; // So are the slices: committing a floating move doesn't change them. let pick = slice_pick(p, cmd, &s.active().ok_or(EngineError::NoDocument)?.doc)?; + // A refused implicit profile read must also leave a directly called platform export's move floating. + let working_profile = { + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + if st.embed_icc && !st.convert_to_srgb && doc.icc_profile.is_none() && doc.mode == photocraft_doc::ColorMode::Rgb { + Some(crate::color_cmds::export_working_profile(s, doc.mode)?) + } else { + None + } + }; // Direct platform calls must export the moved selection as it appears on the canvas, // just as Session::execute does before dispatching the native command. crate::float_cmds::before_command(s, cmd)?; - let d = s.active().ok_or(EngineError::NoDocument)?; - let doc = d.doc.clone(); + let mut doc = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); + if let Some(profile) = working_profile { + // Tag the post-move copy, never the open document. + std::sync::Arc::make_mut(&mut doc).icc_profile = Some(profile.to_bytes()); + } let (wdoc, sx, sy) = web_document(&doc, p, &st)?; let buf = photocraft_compose::flatten(&wdoc); let bw = wdoc.size.width as usize; - // An untagged document is treated as sRGB (see [`web_document`]); with Embed Color Profile - // on, the file says so, as Photoshop's does (#9325). + // Copies that retain the working space are tagged above. Keep the default sRGB tag for + // the remaining untagged web output (#9325). let srgb = (st.embed_icc && wdoc.icc_profile.is_none()).then(|| craft_cms::Builtin::Srgb.profile().to_bytes().to_vec()); let icc = wdoc.icc_profile.as_deref().map(|v| v.as_slice()).or(srgb.as_deref()); let xmp = web_xmp(&doc, st.metadata); diff --git a/crates/engine-core/src/cmd/web_cmds/tests.rs b/crates/engine-core/src/cmd/web_cmds/tests.rs index 01b1e9a78d..6ed5a39ec7 100644 --- a/crates/engine-core/src/cmd/web_cmds/tests.rs +++ b/crates/engine-core/src/cmd/web_cmds/tests.rs @@ -1,4 +1,5 @@ use super::*; +use crate::color_cmds::ColorExt; use photocraft_doc::{Layer, LayerContent}; fn tmp(name: &str) -> String { @@ -1616,3 +1617,127 @@ fn a_whole_image_path_with_slice_numbers_is_refused() { s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "path": whole, "numbers": [1]})).unwrap(); assert_eq!(decode(&whole).dimensions(), (64, 48)); } + +/// #17199: preserving document colours embeds their working interpretation; explicitly +/// converting for the web still names sRGB, and disabling embedding still omits ICC. +#[test] +fn save_for_web_embeds_the_working_rgb_only_when_preserving_document_colours() { + let mut s = session(8); + s.execute("edit.assignProfile", json!({"profile": "none"})).unwrap(); + s.execute("edit.colorSettings", json!({"workingRgb": "prophoto-compat"})).unwrap(); + let expected = s.color().working(photocraft_color::ColorMode::Rgb).to_bytes(); + assert_ne!(expected, craft_cms::Builtin::Srgb.profile().to_bytes()); + let original = s.active().unwrap().doc.clone(); + let samples = photocraft_compose::flatten(&original).px.to_vec(); + let dir = tmp("working-profile-17199"); + let preserved = format!("{dir}/preserved.png"); + s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "convertToSrgb": false, "embedIcc": true, "path": preserved})).unwrap(); + let preserved = decode(&preserved); + assert_eq!(preserved.icc.as_deref(), Some(expected.as_slice())); + let off = format!("{dir}/off.png"); + s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "convertToSrgb": false, "embedIcc": false, "path": off})).unwrap(); + let off = decode(&off); + assert!(off.icc.is_none()); + assert_eq!(off.data(), preserved.data(), "embedding describes the same samples"); + let converted = format!("{dir}/srgb.png"); + s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "convertToSrgb": true, "embedIcc": true, "path": converted})).unwrap(); + assert_eq!( + decode(&converted).icc.as_deref(), + Some(craft_cms::Builtin::Srgb.profile().to_bytes().as_slice()), + "an explicit web conversion keeps its sRGB destination tag" + ); + assert_eq!(s.active().unwrap().doc.icc_profile, original.icc_profile); + assert_eq!(photocraft_compose::flatten(&s.active().unwrap().doc).px.to_vec(), samples); + // An export may be authorized while a stored working-profile path is not. The inherited + // job gate must run before resolving that path, including APIs without Session::execute. + fn deny_profile_path(id: &str, params: &Value) -> crate::Result<()> { + if id == "edit.profileInfo" && params.get("profile").and_then(Value::as_str).is_some_and(|p| p.ends_with("blocked-working.icc")) { + return Err(EngineError::Other("denied working ICC read 17199".into())); + } + Ok(()) + } + let profile_dir = tempfile::tempdir().unwrap(); + let profile_path = profile_dir.path().join("blocked-working.icc"); + std::fs::write(&profile_path, expected.as_slice()).unwrap(); + s.execute("edit.colorSettings", json!({"workingRgb": profile_path.to_string_lossy()})).unwrap(); + let _authorization = crate::jobs::render_authorization_scope(Some(deny_profile_path)); + + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 2, "height": 2})).unwrap(); + s.execute("select.float", json!({"dx": 2})).unwrap(); + assert!(crate::float_cmds::floating(s.active().unwrap()).is_some()); + let document = s.active().unwrap().doc.clone(); + let revision = s.active().unwrap().revision; + let history = s.active().unwrap().history.entries(); + + let blocked = format!("{dir}/blocked.png"); + let error = s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "convertToSrgb": false, "embedIcc": true, "path": blocked})).unwrap_err(); + assert!(error.to_string().contains("denied working ICC read 17199")); + assert!(!std::path::Path::new(&blocked).exists()); + assert!(crate::float_cmds::floating(s.active().unwrap()).is_some(), "a denied profile read leaves the move floating"); + assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &document)); + assert_eq!(s.active().unwrap().revision, revision); + assert_eq!(s.active().unwrap().history.entries(), history, "no History step is added"); + + let mut writes = 0; + let error = save_for_web_with_writer(&mut s, &json!({"format": "png24", "convertToSrgb": false, "embedIcc": true, "path": blocked}), &mut |_, _| { + writes += 1; + Ok(()) + }) + .unwrap_err(); + assert!(error.to_string().contains("denied working ICC read 17199")); + assert_eq!(writes, 0); + assert!(crate::float_cmds::floating(s.active().unwrap()).is_some(), "a denied profile read leaves the move floating"); + assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &document)); + assert_eq!(s.active().unwrap().revision, revision); + assert_eq!(s.active().unwrap().history.entries(), history, "no History step is added"); +} + +/// #17199: Quick WebP's regular encoder embeds by default, so a non-converting export +/// needs the same working-space interpretation even though Quick Export has no ICC toggle. +#[test] +fn quick_webp_without_conversion_embeds_the_untagged_working_rgb() { + let mut s = session(8); + s.execute("edit.assignProfile", json!({"profile": "none"})).unwrap(); + s.execute("edit.colorSettings", json!({"workingRgb": "prophoto-compat"})).unwrap(); + let expected = s.color().working(photocraft_color::ColorMode::Rgb).to_bytes(); + assert_ne!(expected, craft_cms::Builtin::Srgb.profile().to_bytes()); + let original = s.active().unwrap().doc.clone(); + let samples = photocraft_compose::flatten(&original).px.to_vec(); + s.execute("file.export.exportPreferences", json!({"quickExportFormat": "png", "convertToSrgb": false, "webpLossless": true, "metadata": "none"})).unwrap(); + let path = format!("{}/working.webp", tmp("quick-working-profile-17199")); + s.execute("file.export.quickExport", json!({"path": path})).unwrap(); + assert_eq!(decode(&path).icc.as_deref(), Some(expected.as_slice())); + assert_eq!(s.active().unwrap().doc.icc_profile, original.icc_profile); + assert_eq!(photocraft_compose::flatten(&s.active().unwrap().doc).px.to_vec(), samples); + s.execute("prefs.reset", json!({"path": "export"})).unwrap(); + // An export may be authorized while a stored working-profile path is not. The inherited + // job gate must run before resolving that path, including APIs without Session::execute. + fn deny_profile_path(id: &str, params: &Value) -> crate::Result<()> { + if id == "edit.profileInfo" && params.get("profile").and_then(Value::as_str).is_some_and(|p| p.ends_with("blocked-working.icc")) { + return Err(EngineError::Other("denied working ICC read 17199".into())); + } + Ok(()) + } + let profile_dir = tempfile::tempdir().unwrap(); + let profile_path = profile_dir.path().join("blocked-working.icc"); + std::fs::write(&profile_path, expected.as_slice()).unwrap(); + s.execute("edit.colorSettings", json!({"workingRgb": profile_path.to_string_lossy()})).unwrap(); + let _authorization = crate::jobs::render_authorization_scope(Some(deny_profile_path)); + + s.execute("file.export.exportPreferences", json!({"quickExportFormat": "png", "convertToSrgb": false, "webpLossless": true})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 2, "height": 2})).unwrap(); + s.execute("select.float", json!({"dx": 2})).unwrap(); + assert!(crate::float_cmds::floating(s.active().unwrap()).is_some()); + let document = s.active().unwrap().doc.clone(); + let revision = s.active().unwrap().revision; + let history = s.active().unwrap().history.entries(); + + let blocked = format!("{}/blocked.webp", tmp("quick-blocked-profile-17199")); + let error = s.execute("file.export.quickExport", json!({"path": blocked})).unwrap_err(); + assert!(error.to_string().contains("denied working ICC read 17199")); + assert!(!std::path::Path::new(&blocked).exists()); + assert!(crate::float_cmds::floating(s.active().unwrap()).is_some(), "a denied profile read leaves the move floating"); + assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &document)); + assert_eq!(s.active().unwrap().revision, revision); + assert_eq!(s.active().unwrap().history.entries(), history, "no History step is added"); +} diff --git a/crates/engine-core/src/doc_state.rs b/crates/engine-core/src/doc_state.rs index 5dcd43213f..fdb9f452f8 100644 --- a/crates/engine-core/src/doc_state.rs +++ b/crates/engine-core/src/doc_state.rs @@ -31,6 +31,9 @@ pub struct DocState { pub coalesce: Option, /// Channels panel: targeted channel and eye toggles (view state, not history). pub channel_view: channel_cmds::ChannelView, + /// The channel views undo brings back, by the step they belong to: the ids of the history + /// states New Channel or Calculations started from and made (#14683). View state, not history. + pub(crate) undo_channel_views: Vec<(u64, u64, channel_cmds::ChannelView)>, /// Select › Isolate Layers: the Layers panel lists only these layers (empty = off; view state). pub isolated_layers: Vec, /// Painting symmetry preset or sampled path (tool state, not document pixels). @@ -144,6 +147,7 @@ impl DocState { damage_log: Default::default(), coalesce: None, channel_view, + undo_channel_views: Vec::new(), isolated_layers: Vec::new(), symmetry: None, fx_collapsed: Vec::new(), diff --git a/crates/engine-core/src/install.rs b/crates/engine-core/src/install.rs index 44d6a4f9e7..70b6af93b7 100644 --- a/crates/engine-core/src/install.rs +++ b/crates/engine-core/src/install.rs @@ -188,6 +188,7 @@ pub fn register(install: &mut Install) { // files hooks.request_params.push(crate::file_cmds::batch_open_params); + hooks.check_params.push(crate::color_cmds::check_export_working_profile); hooks.after_command.push(|s, id, _| crate::automate_cmds::after_command(s, id)); hooks.step_recorded.push(crate::actions_cmds::note_step_origin); hooks.flush_recording.push(crate::actions_cmds::flush_recording); diff --git a/crates/engine-core/src/layer_style.rs b/crates/engine-core/src/layer_style.rs index 9159a5a9fe..ceb2c8b127 100644 --- a/crates/engine-core/src/layer_style.rs +++ b/crates/engine-core/src/layer_style.rs @@ -164,7 +164,9 @@ pub fn effect_defaults(kind: &str) -> Value { "stroke" => json!({"size": 1, "position": "inside", "blend": "Normal", "opacity": 100, "overprint": false, "color": "#000000"}), "colorOverlay" => json!({"blend": "Normal", "color": "#ff0000", "opacity": 100}), "gradientOverlay" => { - json!({"blend": "Normal", "opacity": 100, "from": "#000000", "to": "#ffffff", "reverse": false, "style": "linear", "angle": 90, "scale": 100, "method": "custom"}) + // The reference application's "Gray, White" with the Smooth method (#14900). The page + // edits the stop list; From/To name the same ends for callers that read them. + json!({"blend": "Normal", "opacity": 100, "from": "#d7d7d7", "to": "#ffffff", "stops": [[0, "#d7d7d7"], [1, "#ffffff"]], "reverse": false, "style": "linear", "angle": 90, "scale": 100, "method": "smooth", "smoothness": 100}) } "patternOverlay" => json!({"blend": "Normal", "opacity": 100, "pattern": "", "angle": 0, "scale": 100, "link": true}), "bevelEmboss" => { @@ -553,6 +555,12 @@ pub fn contour_to_shc_all(list: &[&Contour]) -> Result> { craft_psd::shc::write(&file).map_err(|e| EngineError::Other(format!("can't write the contour: {e}"))) } +/// A Gradient Overlay with `Gradient::default()` (black to white, straight stops) and no recorded +/// method: what a command that names its own colours or stops starts from. +fn blank_gradient_overlay() -> Effect { + Effect::GradientOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), gradient: Gradient::default(), dither: false, interpolation: None } +} + /// An effect of `kind` with its factory settings (before params are applied). fn fresh_effect(kind: &str) -> Option { let shadow = |inner: bool| Shadow { @@ -598,7 +606,10 @@ fn fresh_effect(kind: &str) -> Option { }), "colorOverlay" => Effect::ColorOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), color: Color::rgb(1.0, 0.0, 0.0) }, "gradientOverlay" => { - Effect::GradientOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), gradient: Gradient::default(), dither: false, interpolation: None } + // The factory values carry the recorded Smooth method, so build them like the page does. + let mut fx = blank_gradient_overlay(); + overlay_effect(&mut fx, &effect_defaults(kind)); + fx } "patternOverlay" => Effect::PatternOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), @@ -974,7 +985,10 @@ pub fn overlay_effect(fx: &mut Effect, p: &Value) { /// spread, range in percent; sizes in px; angles in degrees). pub fn effect_from_params(kind: &str, p: &Value) -> Option { crate::commands::check_f32_values("layer.layerStyle", p).ok()?; - let mut fx = fresh_effect(kind)?; + // A Gradient Overlay given its own colours or stops keeps today's straight stops unless the + // params pick a method; only the factory one (#14900) starts from the Smooth grey to white. + let mut fx = + if kind == "gradientOverlay" && ["from", "to", "stops"].iter().any(|k| p.get(k).is_some()) { blank_gradient_overlay() } else { fresh_effect(kind)? }; overlay_effect(&mut fx, p); Some(fx) } @@ -1320,6 +1334,8 @@ fn delete_effect(s: &mut Session, p: &Value, effect: &Value) -> Result { Ok(Value::Null) } +#[cfg(test)] +mod gradient_overlay_defaults_tests; #[cfg(test)] mod satin_defaults_tests; diff --git a/crates/engine-core/src/layer_style/gradient_overlay.rs b/crates/engine-core/src/layer_style/gradient_overlay.rs index 217f6fd70c..aa1a0ca88d 100644 --- a/crates/engine-core/src/layer_style/gradient_overlay.rs +++ b/crates/engine-core/src/layer_style/gradient_overlay.rs @@ -248,13 +248,18 @@ mod tests { } #[test] - fn reset_to_factory_defaults_removes_the_recorded_method() { + fn reset_to_factory_defaults_restores_the_factory_gradient_and_method() { let mut gradient = Gradient::default(); let mut source = None; - overlay(&mut gradient, &mut source, &json!({"method": "smooth", "from": "#ff0000"})); + overlay(&mut gradient, &mut source, &json!({"method": "classic", "from": "#ff0000"})); overlay(&mut gradient, &mut source, &super::super::effect_defaults("gradientOverlay")); - assert!(source.is_none()); - assert_eq!(gradient, Gradient::default()); + let Some(Effect::GradientOverlay { gradient: factory, interpolation: factory_source, .. }) = + super::super::effect_from_params("gradientOverlay", &json!({})) + else { + panic!("no factory overlay") + }; + assert_eq!(source, factory_source, "#14900: the factory overlay records Smooth grey 215 to white"); + assert_eq!(gradient, factory); } } diff --git a/crates/engine-core/src/layer_style/gradient_overlay_defaults_tests.rs b/crates/engine-core/src/layer_style/gradient_overlay_defaults_tests.rs new file mode 100644 index 0000000000..56b26fe2f4 --- /dev/null +++ b/crates/engine-core/src/layer_style/gradient_overlay_defaults_tests.rs @@ -0,0 +1,149 @@ +//! #14900: the Gradient Overlay page's factory values (Normal, 100 %, grey 215 to white, Method +//! Smooth, Smoothness 100 %, Linear, Angle 90, Scale 100) and the rule that an overlay already +//! stored keeps its own gradient and method. The measured column of the factory overlay sits +//! within 2 levels of the reference application's on the white test document. + +use super::*; +use crate::Session; +use photocraft_doc::GradientStyle; +use photocraft_doc::effects::GradientInterpolation; +use serde_json::json; + +const GREY_215: f32 = 215.0 / 255.0; + +/// The issue's test document: 400 x 300 px at 72 ppi, RGB 8 bit, a white Background and a pixel +/// layer with an orange (255,128,0) rectangle at x 100..299, y 75..224. +fn test_document() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 400, "height": 300, "resolution": 72, "background": "#ffffff"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + // Edit > Fill lives in photocraft-engine-paint, so the rectangle is written directly. + let id = s.active().unwrap().active_layer.unwrap(); + s.edit("orange", |doc, _| { + let surf = doc.layer_mut(id).unwrap().surface_mut().unwrap(); + let r = photocraft_geom::Rect::from_xywh(100, 75, 200, 150); + let px = photocraft_raster::from_rgba(&surf.format(), [1.0, 128.0 / 255.0, 0.0, 1.0]); + surf.write_region(r, &px.repeat(200 * 150)); + Ok(()) + }) + .unwrap(); + s +} + +fn session() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s +} + +/// The one effect the active layer carries. +fn only_effect(s: &Session) -> Effect { + let d = s.active().unwrap(); + let l = d.doc.layer(d.active_layer.unwrap()).unwrap(); + match l.effects.items.as_slice() { + [fx] => fx.clone(), + other => panic!("not one effect: {other:?}"), + } +} + +fn close(a: &Color, rgb: [f32; 3]) -> bool { + a.to_rgb().iter().zip(rgb).all(|(x, y)| (x - y).abs() < 1e-3) +} + +/// #14900: Layer > Layer Style > Gradient Overlay... seeds a new instance from `effect_defaults` +/// (the page reads its stop list, so the stops carry the colours as well as From/To). +#[test] +fn a_new_gradient_overlay_starts_at_the_factory_values() { + let d = effect_defaults("gradientOverlay"); + assert_eq!(d["blend"], json!("Normal"), "blend"); + assert_eq!(d["opacity"], json!(100), "opacity"); + assert_eq!(d["stops"], json!([[0, "#d7d7d7"], [1, "#ffffff"]]), "stops"); + assert_eq!((d["from"].as_str(), d["to"].as_str()), (Some("#d7d7d7"), Some("#ffffff")), "from / to"); + assert_eq!(d["method"], json!("smooth"), "method"); + assert_eq!(d["smoothness"], json!(100), "smoothness"); + assert_eq!(d["reverse"], json!(false), "reverse"); + assert_eq!(d["style"], json!("linear"), "style"); + assert_eq!(d["angle"], json!(90), "angle"); + assert_eq!(d["scale"], json!(100), "scale"); +} + +/// #14900: `layer.layerStyle.gradientOverlay` without colours or stops makes the factory overlay: +/// grey 215 to white with the Smooth method recorded, the rest at the page's values. +#[test] +fn a_gradient_overlay_command_without_colours_makes_the_factory_effect() { + let mut s = session(); + s.execute("layer.layerStyle.gradientOverlay", json!({})).unwrap(); + let Effect::GradientOverlay { common, gradient, dither, interpolation } = only_effect(&s) else { panic!("not a gradient overlay") }; + assert_eq!((common.blend, common.opacity), (BlendMode::Normal, 1.0)); + assert!(!dither, "dither"); + let Some(GradientInterpolation { method, smoothness, stops }) = interpolation else { panic!("no recorded method") }; + assert_eq!((method.as_str(), smoothness), ("smooth", 100.0)); + assert_eq!(stops.len(), 2, "source stops {stops:?}"); + assert!(stops[0].0 == 0.0 && close(&stops[0].1, [GREY_215; 3]), "first stop {:?}", stops[0]); + assert!(stops[1].0 == 1.0 && close(&stops[1].1, [1.0; 3]), "last stop {:?}", stops[1]); + assert!(close(&gradient.stops.first().unwrap().1, [GREY_215; 3]) && close(&gradient.stops.last().unwrap().1, [1.0; 3]), "baked ends"); + assert!(gradient.stops.len() > 2, "the Smooth curve is baked, not straight: {:?}", gradient.stops); + assert_eq!((gradient.style, gradient.angle, gradient.scale, gradient.reverse, gradient.align), (GradientStyle::Linear, 90.0, 1.0, false, true)); + // The dialog's OK on the factory values (its stop list, no From/To) builds the same effect. + let mut dialog = effect_defaults("gradientOverlay"); + dialog.as_object_mut().unwrap().retain(|k, _| k != "from" && k != "to"); + assert_eq!(effect_from_params("gradientOverlay", &json!({})), effect_from_params("gradientOverlay", &dialog)); +} + +/// #14900 measured: OK on the factory values over the white test document. Red channel at +/// x 200 down the rectangle; the reference application gives +/// `255 255 251 246 240 235 235 230 224 219 215 215`, each within 2 levels. Outside stays white. +#[test] +fn the_factory_gradient_overlay_paints_the_measured_column() { + let mut s = test_document(); + s.execute("layer.layerStyle.gradientOverlay", json!({})).unwrap(); + let d = s.active().unwrap(); + let px = photocraft_compose::render(&d.doc, d.doc.bounds()).into_px(); + let level = |x: usize, y: usize, c: usize| (px[y * 400 + x][c] * 255.0).round() as i32; + let want = [(75, 255), (76, 255), (94, 251), (112, 246), (131, 240), (149, 235), (150, 235), (168, 230), (187, 224), (205, 219), (223, 215), (224, 215)]; + let got: Vec = want.iter().map(|&(y, _)| level(200, y, 0)).collect(); + for (&(y, w), g) in want.iter().zip(&got) { + assert!((g - w).abs() <= 2, "red at (200, {y}): {g}, the reference gives {w}; column {got:?}"); + } + for (x, y) in [(200, 74), (200, 225), (99, 150), (300, 150)] { + assert_eq!([0, 1, 2].map(|c| level(x, y, c)), [255; 3], "outside the layer at ({x}, {y})"); + } +} + +/// #14900: Reset to Default reads the factory values through `layer.layerStyle.defaultFor` until a +/// Make Default stores other ones; the saved values keep winning. +#[test] +fn reset_to_default_restores_the_gradient_overlay_factory_values() { + let mut s = session(); + let d = s.execute("layer.layerStyle.defaultFor", json!({"kind": "gradientOverlay"})).unwrap(); + assert_eq!(d["user"], json!(false)); + assert_eq!(d["params"], effect_defaults("gradientOverlay")); + assert_eq!((d["params"]["method"].as_str(), d["params"]["stops"][0][1].as_str()), (Some("smooth"), Some("#d7d7d7"))); + s.execute("layer.layerStyle.makeDefault", json!({"kind": "gradientOverlay", "params": {"opacity": 40, "method": "linear"}})).unwrap(); + let saved = s.execute("layer.layerStyle.defaultFor", json!({"kind": "gradientOverlay"})).unwrap(); + assert_eq!(saved["user"], json!(true)); + assert_eq!((saved["params"]["opacity"].as_f64(), saved["params"]["method"].as_str()), (Some(40.0), Some("linear")), "a saved default still wins"); +} + +/// #14900: an overlay the document already carries (a PSD or `.pcraft` one, edited in the dialog) +/// keeps its gradient and method through `layer.layerStyle.replace`, and a command that names its +/// colours still gets those colours. +#[test] +fn a_stored_gradient_overlay_keeps_its_own_gradient_and_method() { + let mut s = session(); + let stored = Effect::GradientOverlay { + common: FxCommon::new(BlendMode::Multiply, 0.5), + gradient: Gradient { stops: vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (1.0, Color::rgb(0.0, 0.0, 1.0))], angle: 30.0, ..Gradient::default() }, + dither: true, + interpolation: None, + }; + let snapshot = serde_json::to_value(&stored).unwrap(); + s.execute("layer.layerStyle.replace", json!({"effects": [{"kind": "gradientOverlay", "params": {}, "fx": snapshot}]})).unwrap(); + assert_eq!(only_effect(&s), stored, "an edited effect list left the overlay alone"); + + s.execute("layer.layerStyle.gradientOverlay", json!({"from": "#ff0000", "to": "#0000ff"})).unwrap(); + let Effect::GradientOverlay { gradient, interpolation, .. } = only_effect(&s) else { panic!("not a gradient overlay") }; + assert_eq!(interpolation, None, "named colours keep today's straight stops"); + assert_eq!(gradient.stops, vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (1.0, Color::rgb(0.0, 0.0, 1.0))]); +} diff --git a/crates/engine-core/src/prefs/store.rs b/crates/engine-core/src/prefs/store.rs index f27efc0d6b..9ddb4e72b8 100644 --- a/crates/engine-core/src/prefs/store.rs +++ b/crates/engine-core/src/prefs/store.rs @@ -8,6 +8,7 @@ use super::{Deserialize, Map, Preferences, Serialize, Value}; pub struct PrefsStore { values: Preferences, rev: u64, + settings_rev: u64, catalog_rev: u64, section_revs: std::collections::BTreeMap, } @@ -16,8 +17,15 @@ impl PrefsStore { pub fn get(&self) -> &Preferences { &self.values } - /// Change preferences; bumps the revision. + /// Change preferences; bumps the revision and the settings revision. pub fn edit(&mut self, f: impl FnOnce(&mut Preferences) -> R) -> R { + self.settings_rev += 1; + self.remember(f) + } + /// Store what the app remembers of its own state between launches (the selected tool, its options, the colours): + /// bumps the revision, so frontends persist, but not the settings revision, because no view reads these back from + /// the preferences; they show the state itself. + pub fn remember(&mut self, f: impl FnOnce(&mut Preferences) -> R) -> R { let before = (&self.values.shortcuts, &self.values.alternate_shortcuts, &self.values.toolbar); let before = (before.0.clone(), before.1.clone(), before.2.clone()); let sections = self.values.sections.clone(); @@ -45,6 +53,10 @@ impl PrefsStore { pub fn rev(&self) -> u64 { self.rev } + /// Revision of the preferences views read: every [`edit`](Self::edit), not what the app [`remember`](Self::remember)s. + pub fn settings_rev(&self) -> u64 { + self.settings_rev + } } /// The preferences file format written by [`SavedPrefsExt::prefs_value`](crate::prefs::SavedPrefsExt::prefs_value). 2: Use Shift Key for Tool diff --git a/crates/engine-core/src/session/history.rs b/crates/engine-core/src/session/history.rs index 6d5662f098..b8ae73c4d6 100644 --- a/crates/engine-core/src/session/history.rs +++ b/crates/engine-core/src/session/history.rs @@ -25,6 +25,7 @@ impl Session { st.coalesce = None; // The step being undone: the layers whose visibility it changed get it back. let changed = st.history.current_visibility().to_vec(); + let left = st.history.row_id(st.history.past_len()); let doc = st.doc.clone(); match st.history.undo(doc) { // Undo Clear History: the list comes back, the document is the same one. Not an @@ -55,6 +56,7 @@ impl Session { let before = std::mem::replace(st.doc_mut(), d); let keep_clean = st.keeps_clean(&before); restore_target(st, layers); + channel_cmds::restore_view_after_undo(st, left); st.bump_revision(keep_clean); st.last_damage = damage; st.record_damage(); diff --git a/crates/engine-paint/src/cmd/redeye_cmds.rs b/crates/engine-paint/src/cmd/redeye_cmds.rs index ceaffa4fac..55dfde2944 100644 --- a/crates/engine-paint/src/cmd/redeye_cmds.rs +++ b/crates/engine-paint/src/cmd/redeye_cmds.rs @@ -249,18 +249,22 @@ fn red_eye(s: &mut Session, p: &Value) -> Result { let pupil = pupil_raw.clamp(1.0, 100.0); let darken = darken.clamp(0.0, 100.0); let id = if p.get("layer").is_some() { Some(crate::commands::layer_param(s, p)?) } else { s.active().and_then(|d| d.active_layer) }; + // The press point decides (#12576): a press outside the selection does nothing, not clipped, and + // like Photoshop it is silent (#13096): no pixels, no state, no message. Feathered (partly + // selected) and off-canvas presses were not measured and keep today's behaviour: any value above + // 0 counts as inside, and off-canvas presses are not checked. + if let (Some(&first), Some(d)) = (pts.first(), s.active()) + && d.doc.bounds().contains(first.0, first.1) + && d.doc.selection.as_ref().is_some_and(|m| m.sample_channel(first.0, first.1, 0) <= 0.0) + { + return Ok(json!({ "damage": [0, 0, 0, 0], "pixels": 0, "outsideSelection": true })); + } let (damage, total) = s.edit("Red Eye Removal Tool", |doc, active| { let canvas = doc.bounds(); let sel = doc.selection.clone(); let layer = id.or(*active); let (surf, lock) = crate::channel_cmds::target_surface(doc, layer, p)?; let Some(&first) = pts.first() else { return Err(EngineError::Other(MISS.into())) }; - // The press point decides (#12576): a press outside the selection is refused like a miss, - // not clipped. Feathered (partly selected) and off-canvas presses were not measured and keep - // today's behaviour: any value above 0 counts as inside, and off-canvas presses are not checked. - if canvas.contains(first.0, first.1) && sel.as_ref().is_some_and(|m| m.sample_channel(first.0, first.1, 0) <= 0.0) { - return Err(EngineError::Other(MISS.into())); - } // The Background always locks transparency, so only a click on a clear pixel counts. let on_locked_clear = lock && surf.rgba(first.0, first.1)[3] <= 1.0e-5; let mut total = 0u32; @@ -286,7 +290,7 @@ pub fn specs() -> Vec { label: "Red Eye", menu: &[], shortcut: None, - params: r#"{"x":px, "y":px} | {"points":[[x,y],…] (at most 64)},"pupilSize":1..100=50,"darken":0..100=50,"layer":id?=active,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i} → {"damage":[x,y,w,h], "pixels":n}"#, + params: r#"{"x":px, "y":px} | {"points":[[x,y],…] (at most 64)},"pupilSize":1..100=50,"darken":0..100=50,"layer":id?=active,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i} → {"damage":[x,y,w,h], "pixels":n, "outsideSelection":true?}"#, enabled, run: red_eye, journal: true, diff --git a/crates/engine-paint/src/cmd/redeye_history_state_tests.rs b/crates/engine-paint/src/cmd/redeye_history_state_tests.rs index 150a21802a..d188327a62 100644 --- a/crates/engine-paint/src/cmd/redeye_history_state_tests.rs +++ b/crates/engine-paint/src/cmd/redeye_history_state_tests.rs @@ -127,7 +127,13 @@ fn refused_clicks_add_no_state() { refused(&mut s, params, case); } s.execute("select.rect", json!({"x": 40, "y": 40, "width": 10, "height": 10})).unwrap(); - refused(&mut s, json!({"x": 8, "y": 8}), "a click outside the selection"); + // #13096: a click outside the selection does nothing silently: an Ok with no state. + let (n, _) = last(&s); + let before = pixels(&s); + let r = s.execute("paint.redEye", json!({"x": 8, "y": 8})).unwrap(); + assert_eq!((r["pixels"].as_u64(), r["outsideSelection"].as_bool()), (Some(0), Some(true)), "{r}"); + assert_eq!(last(&s).0, n, "a click outside the selection: no state"); + assert!(pixels(&s) == before, "a click outside the selection"); unchanged_state(&mut s, json!({"x": 44, "y": 44}), "a click inside the selection"); s.execute("select.deselect", json!({})).unwrap(); let id = s.active().unwrap().active_layer.unwrap(); diff --git a/crates/engine-paint/src/cmd/redeye_outside_selection_tests.rs b/crates/engine-paint/src/cmd/redeye_outside_selection_tests.rs index 1d9ca30efa..2aed130096 100644 --- a/crates/engine-paint/src/cmd/redeye_outside_selection_tests.rs +++ b/crates/engine-paint/src/cmd/redeye_outside_selection_tests.rs @@ -1,5 +1,6 @@ //! #12576: a Red Eye press outside the selection does nothing and adds no History state; a press //! inside it is clipped to the selection as before, and with no selection nothing changes. +//! #13096: the outside press is silent, an `Ok` that says so, not the miss error. use serde_json::{Value, json}; @@ -23,7 +24,7 @@ fn eyes() -> Session { /// The left half of eye B: x 450–499. fn select_left_half_of_eye_b(s: &mut Session) { - s.execute("select.rect", json!({"x": 450, "y": 0, "width": 50, "height": 600})).unwrap(); + s.execute("select.rect", json!({"x": 450, "y": 0, "width": 50, "height": 1000})).unwrap(); } /// History length, and the Background's pixels as one value per channel. @@ -53,10 +54,46 @@ fn a_press_outside_the_selection_changes_nothing_and_adds_no_state() { let (states, cols, r) = press(&mut s, params.clone()); assert_eq!(cols, None, "{params}: pixels changed"); assert_eq!(states, 0, "{params}: a history state was added"); - assert_eq!(r, Err(MISS.to_string()), "{params}"); + let r = r.unwrap_or_else(|e| panic!("{params}: an outside press is not an error: {e}")); + assert_eq!(r, json!({"damage": [0, 0, 0, 0], "pixels": 0, "outsideSelection": true}), "{params}"); } } +#[test] +fn an_outside_press_is_silent_at_every_depth() { + for depth in [8, 16, 32] { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 64, "height": 64, "mode": "rgb", "depth": depth})).unwrap(); + s.execute("edit.fill", json!({"color": "#d22828"})).unwrap(); + s.execute("select.rect", json!({"x": 40, "y": 40, "width": 10, "height": 10})).unwrap(); + let n = s.active().unwrap().history.past_len(); + let r = s.execute("paint.redEye", json!({"x": 8, "y": 8})).unwrap_or_else(|e| panic!("{depth} bit: {e}")); + assert_eq!(r["pixels"], 0, "{depth} bit"); + assert_eq!(r["outsideSelection"], true, "{depth} bit"); + assert_eq!(s.active().unwrap().history.past_len(), n, "{depth} bit: no state"); + } +} + +#[test] +fn a_miss_inside_the_selection_keeps_its_result() { + // On a dark blue patch inside the selection: the tool runs and leaves one unchanged state, as before. + let mut s = eyes(); + s.execute("select.rect", json!({"x": 450, "y": 0, "width": 50, "height": 100})).unwrap(); + s.execute("edit.fill", json!({"color": "#283c78"})).unwrap(); + select_left_half_of_eye_b(&mut s); + let (states, cols, r) = press(&mut s, json!({"x": 475, "y": 40, "pupilSize": 1})); + let r = r.unwrap(); + assert_eq!((r["pixels"].as_u64(), r.get("outsideSelection")), (Some(0), None), "{r}"); + assert_eq!((states, cols), (1, None)); + // On a clear pixel under Lock transparent pixels inside the selection: still the miss error. + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("layer.lockLayers", json!({"transparency": true})).unwrap(); + let n = s.active().unwrap().history.past_len(); + let r = s.execute("paint.redEye", json!({"x": 475, "y": 40, "pupilSize": 1})).map_err(|e| e.to_string()); + assert_eq!(r, Err(MISS.to_string())); + assert_eq!(s.active().unwrap().history.past_len(), n); +} + #[test] fn a_press_inside_the_selection_is_clipped_and_adds_one_state() { // A batch whose first point is inside runs, and x 499.5 is still on the last selected column. diff --git a/crates/engine-paint/src/cmd/retouch_cmds.rs b/crates/engine-paint/src/cmd/retouch_cmds.rs index 6ecb8398f4..767f0547db 100644 --- a/crates/engine-paint/src/cmd/retouch_cmds.rs +++ b/crates/engine-paint/src/cmd/retouch_cmds.rs @@ -17,7 +17,7 @@ use photocraft_algo::retouch::{ToneRange, dodge_burn, local_blur, local_sharpen, use photocraft_color::{BlendMode, PixelFormat, SampleType}; use photocraft_doc::{Document, LayerContent, LayerId}; use photocraft_geom::Rect; -use photocraft_paint::retouch::{Footprint, Region, Smudge, alpha_index, apply_coverage, apply_dab_stroke}; +use photocraft_paint::retouch::{Footprint, Region, Smudge, alpha_index, apply_coverage, apply_dab_stroke, restore_coverage}; use photocraft_paint::{BrushSettings, Stroke, StrokePoint}; use photocraft_raster::{Surface, from_rgba_into, to_rgba}; use rayon::prelude::*; diff --git a/crates/engine-paint/src/cmd/retouch_cmds/burn_32bit_linear_tests.rs b/crates/engine-paint/src/cmd/retouch_cmds/burn_32bit_linear_tests.rs new file mode 100644 index 0000000000..23fa4d1d03 --- /dev/null +++ b/crates/engine-paint/src/cmd/retouch_cmds/burn_32bit_linear_tests.rs @@ -0,0 +1,188 @@ +//! Burn in a 32-bit document tones the linear values it holds, with the reference's curve +//! (#12674); 8- and 16-bit documents keep their results. + +use crate::Session; +use photocraft_algo::retouch::{ToneRange, dodge_burn}; +use photocraft_color::convert::linear_to_srgb; +use serde_json::{Value, json}; + +/// The reference's test colours (8-bit RGB): grey 32, 128 and 224, red, skin and pastel. +const PATCHES: [[u8; 3]; 6] = [[32, 32, 32], [128, 128, 128], [224, 224, 224], [200, 40, 40], [220, 170, 140], [180, 200, 230]]; +const SIDE: i32 = 60; + +/// An 8-bit RGB document of `PATCHES` side by side, converted to `depth` bits. +fn patches(depth: u32) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": SIDE * PATCHES.len() as i32, "height": SIDE, "depth": 8, "mode": "rgb"})).unwrap(); + s.edit("patches", |doc, active| { + let b = doc.bounds(); + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let fmt = surf.format(); + let mut data = Vec::new(); + for _ in b.y0..b.y1 { + for x in b.x0..b.x1 { + let c = PATCHES[(x / SIDE) as usize].map(|v| f32::from(v) / 255.0); + data.extend(photocraft_raster::from_rgba(&fmt, [c[0], c[1], c[2], 1.0])); + } + } + surf.write_region(b, &data); + Ok(()) + }) + .unwrap(); + if depth != 8 { + s.execute(&format!("image.mode.bits{depth}"), json!({})).unwrap(); + } + s +} + +fn rgb(s: &Session, x: i32, y: i32) -> [f32; 3] { + let d = s.active().unwrap(); + let p = d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y); + [p[0], p[1], p[2]] +} + +/// One default Burn click (Midtones, Protect Tones, 50 %) with a hard 40 px tip on each patch's +/// centre; the stored values there. +fn burn_each(s: &mut Session, extra: Value) -> Vec<[f32; 3]> { + (0..PATCHES.len() as i32) + .map(|i| { + let (x, y) = (i * SIDE + SIDE / 2, SIDE / 2); + let mut p = json!({"points": [[x, y]], "size": 40, "hardness": 100}); + if let (Some(p), Some(e)) = (p.as_object_mut(), extra.as_object()) { + p.extend(e.clone()); + } + s.execute("paint.burn", p).unwrap(); + rgb(s, x, y) + }) + .collect() +} + +/// A 32-bit document's linear values as 8-bit RGB, as the reference reads them. +fn as_8bit(c: [f32; 3]) -> [i32; 3] { + c.map(|v| (linear_to_srgb(v).clamp(0.0, 1.0) * 255.0).round() as i32) +} + +#[test] +fn burn_tones_linear_values_in_32_bit() { + // Measured in the reference: one default click in a 32-bit RGB document, read as 8-bit. + let expected = [[32, 32, 32], [122, 122, 122], [217, 217, 217], [189, 40, 40], [212, 162, 132], [168, 192, 225]]; + let mut s = patches(32); + let got: Vec<_> = burn_each(&mut s, json!({})).into_iter().map(as_8bit).collect(); + for ((g, e), p) in got.iter().zip(expected).zip(PATCHES) { + assert!(g.iter().zip(e).all(|(g, e)| (g - e).abs() <= 2), "32-bit Burn of {p:?}: got {g:?}, expected {e:?} (+-2); all: {got:?}"); + } +} + +#[test] +fn burn_keeps_8_and_16_bit_results() { + // Pinned from main 406ac677e1: this change only adds the 32-bit path. + let mut s = patches(8); + let got: Vec<_> = burn_each(&mut s, json!({})).into_iter().map(|c| c.map(|v| (v * 255.0).round() as u16)).collect(); + assert_eq!(got, [[23, 23, 23], [91, 91, 91], [218, 218, 218], [125, 25, 25], [192, 148, 122], [165, 183, 211]]); + let mut s = patches(16); + let got: Vec<_> = burn_each(&mut s, json!({})).into_iter().map(|c| c.map(|v| (v * 65535.0).round() as u16)).collect(); + assert_eq!(got, [[5893, 5893, 5893], [23307, 23307, 23307], [56025, 56025, 56025], [32222, 6444, 6444], [49291, 38089, 31367], [42377, 47085, 54148]]); +} + +/// Fill the first patch with light above white (4.0, 1.5, 0.2, linear). +fn above_white(s: &mut Session) { + s.edit("bright", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let r = photocraft_geom::Rect::new(0, 0, SIDE, SIDE); + let px = photocraft_raster::from_rgba(&surf.format(), [4.0, 1.5, 0.2, 1.0]); + surf.write_region(r, &px.repeat((SIDE * SIDE) as usize)); + Ok(()) + }) + .unwrap(); +} + +#[test] +fn burn_keeps_light_above_white_in_32_bit() { + let mut s = patches(32); + above_white(&mut s); + let c = burn_each(&mut s, json!({}))[0]; + assert_eq!([c[0], c[1]], [4.0, 1.5], "light above white must stay as it was: {c:?}"); + assert!(c[2] < 0.2, "the in-range channel is still burned: {c:?}"); +} + +#[test] +fn burn_keeps_todays_curve_at_unmeasured_exposures_in_32_bit() { + // Only 50 % was measured in 32-bit; other exposures keep the gamma curve with Protect Tones' + // luma scaling, run on the stored values. + for exposure in [25, 100] { + let mut s = patches(32); + let before: Vec<_> = (0..PATCHES.len() as i32).map(|i| rgb(&s, i * SIDE + SIDE / 2, SIDE / 2)).collect(); + let got = burn_each(&mut s, json!({"exposure": exposure})); + for (g, o) in got.iter().zip(before) { + let e = dodge_burn(o, exposure as f32 / 100.0, ToneRange::Midtones, true, true); + assert!(g.iter().zip(e).all(|(g, e)| (g - e).abs() < 1e-5), "{exposure} % Burn of {o:?}: got {g:?}, today's curve gives {e:?}"); + } + } +} + +#[test] +fn burn_keeps_light_above_white_with_unmeasured_settings_in_32_bit() { + // The settings that keep today's curve must not clip light above white either; Highlights + // darkens it, but not down to 1.0. + for extra in [json!({"exposure": 100}), json!({"range": "shadows"}), json!({"range": "highlights"}), json!({"protectTones": false})] { + let mut s = patches(32); + above_white(&mut s); + let c = burn_each(&mut s, extra.clone())[0]; + assert!(c[0] > 1.0, "Burn with {extra} clipped light above white: {c:?}"); + } + let mut s = crate::session(); + s.execute("file.new", json!({"width": SIDE, "height": SIDE, "depth": 32, "mode": "gray"})).unwrap(); + s.edit("bright", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let px = photocraft_raster::from_rgba(&surf.format(), [2.0, 2.0, 2.0, 1.0]); + surf.write_region(photocraft_geom::Rect::new(0, 0, SIDE, SIDE), &px.repeat((SIDE * SIDE) as usize)); + Ok(()) + }) + .unwrap(); + let before = rgb(&s, SIDE / 2, SIDE / 2)[0]; + assert!(before > 1.0, "{before}"); + s.execute("paint.burn", json!({"points": [[SIDE / 2, SIDE / 2]], "size": 40, "hardness": 100})).unwrap(); + let after = rgb(&s, SIDE / 2, SIDE / 2)[0]; + assert!(after > 1.0, "32-bit Grayscale Burn clipped {before} to {after}"); +} + +#[test] +fn burn_keeps_light_above_white_when_luma_is_not_positive_in_32_bit() { + // A channel above white next to a negative one: luma <= 0, so Protect Tones can't scale the + // colour by luma. It takes the per-channel curve instead and keeps the light above white. + for exposure in [25, 100] { + for o in [[1.2f32, -0.7, 0.2], [1.01, -0.52, 0.02]] { + let mut s = patches(32); + s.edit("bright", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let px = photocraft_raster::from_rgba(&surf.format(), [o[0], o[1], o[2], 1.0]); + surf.write_region(photocraft_geom::Rect::new(0, 0, SIDE, SIDE), &px.repeat((SIDE * SIDE) as usize)); + Ok(()) + }) + .unwrap(); + assert_eq!(rgb(&s, SIDE / 2, SIDE / 2), o); + let c = burn_each(&mut s, json!({"exposure": exposure}))[0]; + assert!(c[0] > 1.0, "{exposure} % Burn of {o:?} clipped light above white: {c:?}"); + let e = dodge_burn(o, exposure as f32 / 100.0, ToneRange::Midtones, true, false); + assert!(c.iter().zip(e).all(|(c, e)| (c - e).abs() < 1e-5), "{exposure} % Burn of {o:?}: got {c:?}, the per-channel curve gives {e:?}"); + } + } +} + +#[test] +fn burn_keeps_tones_in_order_in_32_bit() { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 256, "height": 8, "depth": 32, "mode": "rgb"})).unwrap(); + s.edit("ramp", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let fmt = surf.format(); + let data: Vec = (0..8).flat_map(|_| (0..256).flat_map(|x| photocraft_raster::from_rgba(&fmt, [x as f32 / 255.0; 4]))).collect(); + surf.write_region(photocraft_geom::Rect::new(0, 0, 256, 8), &data); + Ok(()) + }) + .unwrap(); + s.execute("paint.burn", json!({"points": [[-20, 4], [276, 4]], "size": 40, "hardness": 100})).unwrap(); + let row: Vec = (0..256).map(|x| rgb(&s, x, 4)[0]).collect(); + assert!(row.windows(2).all(|w| w[1] >= w[0]), "{row:?}"); + assert!(row.iter().all(|v| (0.0..=1.0).contains(v)) && row[0] == 0.0 && row[255] == 1.0, "{row:?}"); +} diff --git a/crates/engine-paint/src/cmd/retouch_cmds/burn_grayscale_tests.rs b/crates/engine-paint/src/cmd/retouch_cmds/burn_grayscale_tests.rs new file mode 100644 index 0000000000..71b7ec79b5 --- /dev/null +++ b/crates/engine-paint/src/cmd/retouch_cmds/burn_grayscale_tests.rs @@ -0,0 +1,224 @@ +//! Burn in an 8-bit Grayscale document and on a layer mask uses the reference's single-channel +//! curve (#12675); RGB documents and the cases the reference wasn't measured in keep the RGB +//! curve. The helpers are shared with `dodge_grayscale_tests`. + +use super::LiveDab; +use crate::Session; +use photocraft_algo::retouch::{ToneRange, dodge_burn, single_channel_midtones}; +use photocraft_raster::Surface; +use serde_json::{Value, json}; + +/// The greys the reference was measured on. +pub(super) const GREYS: [u8; 6] = [32, 105, 128, 180, 197, 224]; +const SIDE: i32 = 60; + +/// Fill `surf` with the `GREYS` bands, side by side. +fn bands(surf: &mut Surface, b: photocraft_geom::Rect) { + let fmt = surf.format(); + let mut data = Vec::new(); + for _ in b.y0..b.y1 { + for x in b.x0..b.x1 { + let v = f32::from(GREYS[(x / SIDE) as usize]) / 255.0; + data.extend(photocraft_raster::from_rgba(&fmt, [v, v, v, 1.0])); + } + } + surf.write_region(b, &data); +} + +/// A `mode` (`"gray"` or `"rgb"`) document of `depth` bits whose layer holds the `GREYS` bands. +pub(super) fn doc(mode: &str, depth: u32) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": SIDE * GREYS.len() as i32, "height": SIDE, "depth": depth, "mode": mode, "background": "white"})).unwrap(); + s.edit("bands", |doc, active| { + let b = doc.bounds(); + bands(doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(), b); + Ok(()) + }) + .unwrap(); + s +} + +/// The reference's mask setup in a `depth`-bit RGB document: a white pixel layer over a black one, +/// with a layer mask holding the `GREYS` bands. +pub(super) fn masked(depth: u32) -> Session { + let mut s = crate::session(); + s.execute( + "file.new", + json!({"width": SIDE * GREYS.len() as i32, "height": SIDE, "depth": depth, "background": "backgroundColor", "backgroundColor": [0.0, 0.0, 0.0]}), + ) + .unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.edit("bands", |doc, active| { + let b = doc.bounds(); + let layer = doc.layer_mut(active.unwrap()).unwrap(); + let surf = layer.surface_mut().unwrap(); + let white = photocraft_raster::from_rgba(&surf.format(), [1.0; 4]); + surf.write_region(b, &white.repeat((b.width() * b.height()) as usize)); + bands(&mut layer.mask.as_mut().unwrap().surface, b); + Ok(()) + }) + .unwrap(); + s +} + +/// The stored value (0..255) the target of `extra` holds at `(x, y)`. +fn read(s: &Session, extra: &Value, x: i32, y: i32) -> f32 { + let d = s.active().unwrap(); + let surf = match extra.get("target") { + Some(Value::String(t)) if t == "mask" => &d.doc.layer(d.active_layer.unwrap()).unwrap().mask.as_ref().unwrap().surface, + Some(Value::String(t)) if t == "quickMask" => &d.doc.quick_mask.as_ref().unwrap().surface, + Some(Value::Object(_)) => &d.doc.channels[0].surface, + _ => d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap(), + }; + surf.rgba(x, y)[0] * 255.0 +} + +/// One `cmd` click (40 px, hardness 100, plus `extra`) on each band's centre; the values there. +pub(super) fn click_each(s: &mut Session, cmd: &str, extra: &Value) -> Vec { + (0..GREYS.len() as i32) + .map(|i| { + let (x, y) = (i * SIDE + SIDE / 2, SIDE / 2); + let mut p = json!({"points": [[x, y]], "size": 40, "hardness": 100}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + s.execute(cmd, p).unwrap(); + read(s, extra, x, y) + }) + .collect() +} + +pub(super) fn assert_near(got: &[f32], want: &[f32], tol: f32, what: &str) { + assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() <= tol), "{what}: got {got:?}, expected {want:?} (±{tol})"); +} + +/// Today's RGB curve for the `GREYS`, as 0..255. +pub(super) fn rgb_curve(e: f32, range: ToneRange, burn: bool, protect: bool) -> Vec { + GREYS.iter().map(|&g| dodge_burn([f32::from(g) / 255.0; 3], e, range, burn, protect)[0] * 255.0).collect() +} + +/// The cases the reference wasn't measured in keep the RGB curve: 16- and 32-bit Grayscale, a +/// mask in a 16- or 32-bit document, the other ranges and exposures, Protect Tones off, an alpha +/// channel and the Quick Mask. +pub(super) fn keeps_rgb_curve_where_not_measured(cmd: &str, burn: bool) { + let mid = |e, protect| rgb_curve(e, ToneRange::Midtones, burn, protect); + for depth in [16, 32] { + let tol = if depth == 16 { 0.05 } else { 0.01 }; + assert_near(&click_each(&mut doc("gray", depth), cmd, &json!({})), &mid(0.5, true), tol, &format!("{cmd} gray {depth}-bit")); + assert_near(&click_each(&mut masked(depth), cmd, &json!({"target": "mask"})), &mid(0.5, true), tol, &format!("{cmd} mask {depth}-bit")); + } + let cases = [ + (json!({"range": "shadows"}), rgb_curve(0.5, ToneRange::Shadows, burn, true)), + (json!({"range": "highlights"}), rgb_curve(0.5, ToneRange::Highlights, burn, true)), + (json!({"exposure": 100}), mid(1.0, true)), + (json!({"exposure": 49}), mid(0.49, true)), + (json!({"protectTones": false}), mid(0.5, false)), + ]; + for (extra, want) in cases { + // A rounding step: the 8-bit document stores whole levels. + let want: Vec = want.iter().map(|v| v.round()).collect(); + assert_near(&click_each(&mut doc("gray", 8), cmd, &extra), &want, 0.51, &format!("{cmd} gray 8-bit {extra}")); + } + let want: Vec = mid(0.5, true).iter().map(|v| v.round()).collect(); + let mut s = doc("gray", 8); + s.execute("channel.new", json!({})).unwrap(); + s.edit("bands", |doc, _| { + let b = doc.bounds(); + bands(&mut doc.channels[0].surface, b); + Ok(()) + }) + .unwrap(); + assert_near(&click_each(&mut s, cmd, &json!({"target": {"channel": 0}})), &want, 0.51, &format!("{cmd} alpha channel")); + let mut s = doc("gray", 8); + s.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap(); + s.edit("bands", |doc, _| { + let b = doc.bounds(); + bands(&mut doc.quick_mask.as_mut().unwrap().surface, b); + Ok(()) + }) + .unwrap(); + assert_near(&click_each(&mut s, cmd, &json!({"target": "quickMask"})), &want, 0.51, &format!("{cmd} Quick Mask")); +} + +/// The live stroke shows the same single-channel result its commit lays down, on a short drag +/// across the grey 128 band (the stroke's last dab shows on release, so the start is compared). +pub(super) fn live_matches_commit(cmd: &str) { + let mut s = doc("gray", 8); + s.tools.brush.smoothing.enabled = false; + let (x, y) = (2 * SIDE + 15, SIDE / 2); + let all = [[x, y], [x + 10, y], [x + 20, y]]; + let opts = |p: &[[i32; 2]]| json!({"points": p, "size": 20, "hardness": 100}); + let mut live = LiveDab::begin(&s, cmd, &opts(&all[..1])).unwrap(); + live.push(&all[1..].iter().map(|q| photocraft_paint::StrokePoint::new(f64::from(q[0]), f64::from(q[1]), 1.0)).collect::>()).unwrap(); + let id = s.active().unwrap().active_layer.unwrap(); + let shown = live.doc.layer(id).unwrap().surface().unwrap().rgba(x, y)[0] * 255.0; + s.execute(cmd, opts(&all)).unwrap(); + let committed = read(&s, &json!({}), x, y); + assert_ne!(committed, 128.0, "{cmd}: the stroke toned the band"); + assert_eq!(shown, committed, "{cmd}: live against commit"); +} + +/// The single-channel curve keeps black and white, keeps tones in order and passes values outside +/// 0..1 through. +pub(super) fn curve_is_monotone_and_bounded(burn: bool) { + let mut last = 0.0f32; + for i in 0..=10_000 { + let v = i as f32 / 10_000.0; + let o = single_channel_midtones(v, burn); + assert!(o.is_finite() && o >= last - 1e-6 && (0.0..=1.0).contains(&o), "burn={burn}: {v} → {o} after {last}"); + assert!(if burn { o <= v } else { o >= v }, "burn={burn}: {v} → {o}"); + last = o; + } + assert_eq!(single_channel_midtones(0.0, burn), 0.0); + assert_eq!(single_channel_midtones(1.0, burn), 1.0); + for v in [-0.5, 1.5, 4.0, f32::NAN] { + let o = single_channel_midtones(v, burn); + assert!(o == v || (v.is_nan() && o.is_nan()), "burn={burn}: {v} → {o}"); + } +} + +/// Measured in the reference: one default Burn click in an 8-bit Grayscale document. +const REFERENCE: [f32; 6] = [25.0, 92.0, 115.0, 170.0, 188.0, 219.0]; + +#[test] +fn burn_in_8_bit_grayscale_matches_the_reference() { + let got = click_each(&mut doc("gray", 8), "paint.burn", &json!({})); + assert_near(&got, &REFERENCE, 2.0, "Burn, 8-bit Grayscale"); +} + +#[test] +fn burn_on_a_layer_mask_matches_grayscale() { + let mut s = masked(8); + let before = s.active().unwrap().history.past_len(); + let got = click_each(&mut s, "paint.burn", &json!({"target": "mask"})); + assert_near(&got, &REFERENCE, 2.0, "Burn, layer mask"); + let h = &s.active().unwrap().history; + assert_eq!((h.past_len(), h.undo_label()), (before + GREYS.len(), Some("Burn Tool"))); +} + +#[test] +fn burn_keeps_rgb_results() { + // Pinned from main d5582062a0: neutral greys and a colour in an 8-bit RGB document. + let got = click_each(&mut doc("rgb", 8), "paint.burn", &json!({})); + assert_near(&got, &[23.0, 69.0, 91.0, 156.0, 180.0, 218.0], 0.0, "Burn, RGB greys"); + let mut s = crate::session(); + s.execute("file.new", json!({"width": 60, "height": 60, "background": "backgroundColor", "backgroundColor": [0.7843137, 0.15686275, 0.15686275]})).unwrap(); + s.execute("paint.burn", json!({"points": [[30, 30]], "size": 40, "hardness": 100})).unwrap(); + let d = s.active().unwrap(); + let px = d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().rgba(30, 30); + assert_eq!([px[0], px[1], px[2]].map(|v| (v * 255.0).round()), [125.0, 25.0, 25.0]); +} + +#[test] +fn burn_keeps_the_rgb_curve_where_the_reference_was_not_measured() { + keeps_rgb_curve_where_not_measured("paint.burn", true); +} + +#[test] +fn live_burn_in_grayscale_matches_the_commit() { + live_matches_commit("paint.burn"); +} + +#[test] +fn single_channel_burn_curve_is_monotone_and_bounded() { + curve_is_monotone_and_bounded(true); +} diff --git a/crates/engine-paint/src/cmd/retouch_cmds/clone.rs b/crates/engine-paint/src/cmd/retouch_cmds/clone.rs index 201990dfc2..4e8781e021 100644 --- a/crates/engine-paint/src/cmd/retouch_cmds/clone.rs +++ b/crates/engine-paint/src/cmd/retouch_cmds/clone.rs @@ -4,7 +4,7 @@ use super::sampling::{SampleLayers, sample_layers}; use super::{ BlendMode, BrushSettings, Document, EngineError, LayerId, PixelFormat, Rect, Region, Result, SampleType, Session, Stroke, StrokePoint, Surface, Value, alpha_index, apply_coverage, bad, coverage, damage_json, flag, has_pixel_layer, json, parse_blend, parse_brush, pattern_stamp, periodic, point, - reject_huge_stroke, run_stroke, to_rgba, + reject_huge_stroke, restore_coverage, run_stroke, to_rgba, }; /// Where a clone stroke samples: `offset` / `source` params, else the active Clone Source slot, @@ -517,10 +517,14 @@ impl LiveRetouch { // The Pattern Stamp's Behind goes beneath the pixels, as its commit lays it. let behind = matches!(self.paint, LivePaint::Pattern { behind: true, .. }); let clone = matches!(self.paint, LivePaint::Clone { .. }); + let history = matches!(self.paint, LivePaint::History(_)); let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.id, &self.params)?; surf.write_region(r, &self.pre_surf.read_region(r)); let damage = if clone { apply_clone_coverage(surf, r, cov, self.opacity, self.sel.as_ref(), self.lock, &paint, self.mode) + } else if history { + // As the commit paints it (`heal::history_brush`): the source state replaces the pixels. + restore_coverage(surf, r, cov, self.opacity, self.sel.as_ref(), self.lock, &paint, self.mode) } else { pattern_stamp::lay_coverage(surf, r, cov, self.opacity, self.sel.as_ref(), self.lock, &paint, self.mode, behind) }; diff --git a/crates/engine-paint/src/cmd/retouch_cmds/dab.rs b/crates/engine-paint/src/cmd/retouch_cmds/dab.rs index 11dc337871..4ee3ca8f1d 100644 --- a/crates/engine-paint/src/cmd/retouch_cmds/dab.rs +++ b/crates/engine-paint/src/cmd/retouch_cmds/dab.rs @@ -4,7 +4,7 @@ use super::{ Region, Result, Session, Smudge, Stroke, StrokePoint, Surface, ToneRange, Value, alpha_index, apply_dab_stroke, bad, damage_json, dodge_burn, flag, from_rgba_into, has_pixel_layer, json, local_blur, local_sharpen, num, parse_blend, parse_brush, run_stroke, sponge, string, to_rgba, }; -use photocraft_algo::retouch::sponge_rgb; +use photocraft_algo::retouch::{luma, single_channel_midtones, sponge_rgb, tone_curve}; use photocraft_color::{ColorMode, SampleType}; // --------------------------------------------------------------------------------------------- @@ -185,6 +185,51 @@ fn tone_stroke(fmt: PixelFormat, toned: impl Fn([f32; 3]) -> [f32; 3] + Send + ' }) } +/// Strength of [`linear_midtones`] per unit of Exposure. +const LINEAR_MIDTONES_STRENGTH: f32 = 1.34; + +/// The Midtones Dodge (`burn = false`) or Burn curve for one linear value of a 32-bit document at +/// exposure `e` (0..1): `v ± 1.34·e·v²·(1 − v)^1.5`, each channel on its own. It is fitted to the +/// reference's 32-bit results (#12687, #12674), which tone the stored linear values: much gentler on the +/// mid tones than the 8-bit curve on gamma-encoded values, and the shadows are left alone. Black +/// and white stay put, values outside 0..1 (light above white) are kept as they are, and tones +/// stay in order at every exposure. +#[inline] +fn linear_midtones(v: f32, e: f32, burn: bool) -> f32 { + if !(v > 0.0 && v < 1.0) { + return v; + } + let d = LINEAR_MIDTONES_STRENGTH * e.clamp(0.0, 1.0) * v * v * (1.0 - v).powf(1.5); + if burn { v - d } else { v + d } +} + +/// The Grayscale and layer-mask reference was measured at Exposure 50 % only (#12675, #12689); +/// other exposures keep the RGB curve. +const MEASURED_SINGLE_CHANNEL_EXPOSURE: f32 = 0.5; + +/// The 32-bit reference was measured at Exposure 50 % only (#12687, #12674); other exposures keep the +/// gamma curve. +const MEASURED_LINEAR_EXPOSURE: f32 = 0.5; + +/// Dodge or Burn of a 32-bit colour with the curve the other bit depths use, except that light above +/// white isn't clipped: Protect Tones scales such a colour to its new luma without gamut +/// compression, which would pull it back to 1.0 (#12687, #12674). Such a colour whose luma isn't +/// positive (a negative channel outweighs it) can't be scaled by luma, so it takes the per-channel +/// curve, as with Protect Tones off, which keeps light above white too. Other colours get today's +/// result. +#[inline] +fn dodge_burn_float(c: [f32; 3], e: f32, range: ToneRange, burn: bool, protect: bool) -> [f32; 3] { + if protect && c.iter().any(|&v| v > 1.0) { + let l = luma(c); + if l > 1e-6 { + let nl = tone_curve(l, e, range, burn); + return c.map(|v| v * nl / l); + } + return dodge_burn(c, e, range, burn, false); + } + dodge_burn(c, e, range, burn, protect) +} + fn tone_range(p: &Value, cmd: &str) -> Result { match string(p, "range", "midtones") { "shadows" => Ok(ToneRange::Shadows), @@ -198,7 +243,7 @@ fn tone_range(p: &Value, cmd: &str) -> Result { /// turned into its per-dab effect, for the commit and the live preview alike. #[derive(Clone, Debug, PartialEq)] pub(super) enum DabTool { - Tone { burn: bool, range: ToneRange, exposure: f32, protect: bool }, + Tone { burn: bool, range: ToneRange, exposure: f32, protect: bool, single: bool }, Sponge { saturate: bool, vibrance: bool }, Focus { sharpen: bool, strength: f32, protect: bool, sigma: f32 }, Smudge { strength: f32, finger: Option<[f32; 4]>, max_size: f32, mode: BlendMode }, @@ -260,6 +305,10 @@ impl DabTool { range: tone_range(p, cmd)?, exposure: num(p, "exposure", 50.0).clamp(1.0, 100.0) / 100.0, protect: flag(p, "protectTones", true), + // The layer's pixels or its layer mask: there a Grayscale surface takes the + // reference's single-channel curve. An alpha channel, the Quick Mask and a + // filter mask weren't measured. + single: matches!(crate::channel_cmds::target_of(p), crate::channel_cmds::Target::Pixels | crate::channel_cmds::Target::Mask), }; (tool, if burn { "Burn Tool" } else { "Dodge Tool" }) } @@ -305,7 +354,27 @@ impl DabTool { pub(super) fn effect(&self, fmt: PixelFormat, spacing: f32) -> DabEffect { let sp = spacing; match self.clone() { - Self::Tone { burn, range, exposure, protect } => tone_stroke(fmt, move |c| dodge_burn(c, exposure, range, burn, protect)), + // An 8-bit Grayscale document or layer mask has its own default curve in the reference + // (#12675, #12689). Other depths, ranges, exposures, Protect Tones off and the other + // single-channel targets weren't measured and keep the RGB curve. + Self::Tone { burn, range: ToneRange::Midtones, exposure, protect: true, single: true } + if fmt.mode == ColorMode::Grayscale && fmt.sample == SampleType::U8 && (exposure - MEASURED_SINGLE_CHANNEL_EXPOSURE).abs() < 1e-4 => + { + tone_stroke(fmt, move |c| c.map(|v| single_channel_midtones(v, burn))) + } + // A 32-bit RGB document holds linear values, which the reference's default Dodge and Burn + // tone with their own curve. Grayscale, the other ranges, Protect Tones off and the other + // exposures weren't measured there and keep the gamma curve, without clipping light + // above white. + Self::Tone { burn, range: ToneRange::Midtones, exposure, protect: true, .. } + if fmt.sample == SampleType::F32 && fmt.mode == ColorMode::Rgb && (exposure - MEASURED_LINEAR_EXPOSURE).abs() < 1e-4 => + { + tone_stroke(fmt, move |c| c.map(|v| linear_midtones(v, exposure, burn))) + } + Self::Tone { burn, range, exposure, protect, .. } if fmt.sample == SampleType::F32 => { + tone_stroke(fmt, move |c| dodge_burn_float(c, exposure, range, burn, protect)) + } + Self::Tone { burn, range, exposure, protect, .. } => tone_stroke(fmt, move |c| dodge_burn(c, exposure, range, burn, protect)), // Flow is already in the dab's coverage. The reference RGB response applies to integer // RGB surfaces, including 16-bit. Float RGB and the other models use the legacy curve. Self::Sponge { saturate, vibrance } if fmt.mode == ColorMode::Rgb && fmt.sample != SampleType::F32 => { @@ -828,3 +897,19 @@ mod smudge_refuses_indexed_tests; #[cfg(test)] #[path = "smudge_mode_tests.rs"] mod smudge_mode_tests; + +#[cfg(test)] +#[path = "burn_grayscale_tests.rs"] +mod burn_grayscale_tests; + +#[cfg(test)] +#[path = "dodge_grayscale_tests.rs"] +mod dodge_grayscale_tests; + +#[cfg(test)] +#[path = "dodge_32bit_linear_tests.rs"] +mod dodge_32bit_linear_tests; + +#[cfg(test)] +#[path = "burn_32bit_linear_tests.rs"] +mod burn_32bit_linear_tests; diff --git a/crates/engine-paint/src/cmd/retouch_cmds/dodge_32bit_linear_tests.rs b/crates/engine-paint/src/cmd/retouch_cmds/dodge_32bit_linear_tests.rs new file mode 100644 index 0000000000..dd8535b397 --- /dev/null +++ b/crates/engine-paint/src/cmd/retouch_cmds/dodge_32bit_linear_tests.rs @@ -0,0 +1,187 @@ +//! Dodge in a 32-bit document tones the linear values it holds, with the reference's curve +//! (#12687); 8- and 16-bit documents keep their results. + +use crate::Session; +use photocraft_algo::retouch::{ToneRange, dodge_burn}; +use photocraft_color::convert::linear_to_srgb; +use serde_json::{Value, json}; + +/// The reference's test colours (8-bit RGB): grey 32, 128 and 224, red, skin and pastel. +const PATCHES: [[u8; 3]; 6] = [[32, 32, 32], [128, 128, 128], [224, 224, 224], [200, 40, 40], [220, 170, 140], [180, 200, 230]]; +const SIDE: i32 = 60; + +/// An 8-bit RGB document of `PATCHES` side by side, converted to `depth` bits. +fn patches(depth: u32) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": SIDE * PATCHES.len() as i32, "height": SIDE, "depth": 8, "mode": "rgb"})).unwrap(); + s.edit("patches", |doc, active| { + let b = doc.bounds(); + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let fmt = surf.format(); + let mut data = Vec::new(); + for _ in b.y0..b.y1 { + for x in b.x0..b.x1 { + let c = PATCHES[(x / SIDE) as usize].map(|v| f32::from(v) / 255.0); + data.extend(photocraft_raster::from_rgba(&fmt, [c[0], c[1], c[2], 1.0])); + } + } + surf.write_region(b, &data); + Ok(()) + }) + .unwrap(); + if depth != 8 { + s.execute(&format!("image.mode.bits{depth}"), json!({})).unwrap(); + } + s +} + +fn rgb(s: &Session, x: i32, y: i32) -> [f32; 3] { + let d = s.active().unwrap(); + let p = d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y); + [p[0], p[1], p[2]] +} + +/// One default Dodge click (Midtones, Protect Tones, 50 %) with a hard 40 px tip on each patch's +/// centre; the stored values there. +fn dodge_each(s: &mut Session, extra: Value) -> Vec<[f32; 3]> { + (0..PATCHES.len() as i32) + .map(|i| { + let (x, y) = (i * SIDE + SIDE / 2, SIDE / 2); + let mut p = json!({"points": [[x, y]], "size": 40, "hardness": 100}); + if let (Some(p), Some(e)) = (p.as_object_mut(), extra.as_object()) { + p.extend(e.clone()); + } + s.execute("paint.dodge", p).unwrap(); + rgb(s, x, y) + }) + .collect() +} + +/// A 32-bit document's linear values as 8-bit RGB, as the reference reads them. +fn as_8bit(c: [f32; 3]) -> [i32; 3] { + c.map(|v| (linear_to_srgb(v).clamp(0.0, 1.0) * 255.0).round() as i32) +} + +#[test] +fn dodge_tones_linear_values_in_32_bit() { + // Measured in the reference: one default click in a 32-bit RGB document, read as 8-bit. + let expected = [[32, 32, 32], [134, 134, 134], [230, 230, 230], [210, 40, 40], [227, 177, 147], [191, 209, 235]]; + let mut s = patches(32); + let got: Vec<_> = dodge_each(&mut s, json!({})).into_iter().map(as_8bit).collect(); + for ((g, e), p) in got.iter().zip(expected).zip(PATCHES) { + assert!(g.iter().zip(e).all(|(g, e)| (g - e).abs() <= 2), "32-bit Dodge of {p:?}: got {g:?}, expected {e:?} (+-2); all: {got:?}"); + } +} + +#[test] +fn dodge_keeps_8_and_16_bit_results() { + // Pinned from main 406ac677e1: this change only adds the 32-bit path. + let mut s = patches(8); + let got: Vec<_> = dodge_each(&mut s, json!({})).into_iter().map(|c| c.map(|v| (v * 255.0).round() as u16)).collect(); + assert_eq!(got, [[46, 46, 46], [161, 161, 161], [228, 228, 228], [255, 65, 65], [242, 187, 154], [191, 212, 244]]); + let mut s = patches(16); + let got: Vec<_> = dodge_each(&mut s, json!({})).into_iter().map(|c| c.map(|v| (v * 65535.0).round() as u16)).collect(); + assert_eq!(got, [[11825, 11825, 11825], [41392, 41392, 41392], [58654, 58654, 58654], [65535, 16658, 16658], [62104, 47989, 39521], [49139, 54599, 62789]]); +} + +/// Fill the first patch with light above white (4.0, 1.5, 0.2, linear). +fn above_white(s: &mut Session) { + s.edit("bright", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let r = photocraft_geom::Rect::new(0, 0, SIDE, SIDE); + let px = photocraft_raster::from_rgba(&surf.format(), [4.0, 1.5, 0.2, 1.0]); + surf.write_region(r, &px.repeat((SIDE * SIDE) as usize)); + Ok(()) + }) + .unwrap(); +} + +#[test] +fn dodge_keeps_light_above_white_in_32_bit() { + let mut s = patches(32); + above_white(&mut s); + let c = dodge_each(&mut s, json!({}))[0]; + assert_eq!([c[0], c[1]], [4.0, 1.5], "light above white must stay as it was: {c:?}"); + assert!(c[2] > 0.2, "the in-range channel is still dodged: {c:?}"); +} + +#[test] +fn dodge_keeps_todays_curve_at_unmeasured_exposures_in_32_bit() { + // Only 50 % was measured in 32-bit; other exposures keep the gamma curve with Protect Tones' + // luma scaling, run on the stored values. + for exposure in [25, 100] { + let mut s = patches(32); + let before: Vec<_> = (0..PATCHES.len() as i32).map(|i| rgb(&s, i * SIDE + SIDE / 2, SIDE / 2)).collect(); + let got = dodge_each(&mut s, json!({"exposure": exposure})); + for (g, o) in got.iter().zip(before) { + let e = dodge_burn(o, exposure as f32 / 100.0, ToneRange::Midtones, false, true); + assert!(g.iter().zip(e).all(|(g, e)| (g - e).abs() < 1e-5), "{exposure} % Dodge of {o:?}: got {g:?}, today's curve gives {e:?}"); + } + } +} + +#[test] +fn dodge_keeps_light_above_white_with_unmeasured_settings_in_32_bit() { + // The settings that keep today's curve must not clip light above white either. + for extra in [json!({"exposure": 100}), json!({"range": "shadows"}), json!({"range": "highlights"}), json!({"protectTones": false})] { + let mut s = patches(32); + above_white(&mut s); + let c = dodge_each(&mut s, extra.clone())[0]; + assert!(c[0] >= 4.0 && c[1] >= 1.5, "Dodge with {extra} clipped light above white: {c:?}"); + } + let mut s = crate::session(); + s.execute("file.new", json!({"width": SIDE, "height": SIDE, "depth": 32, "mode": "gray"})).unwrap(); + s.edit("bright", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let px = photocraft_raster::from_rgba(&surf.format(), [2.0, 2.0, 2.0, 1.0]); + surf.write_region(photocraft_geom::Rect::new(0, 0, SIDE, SIDE), &px.repeat((SIDE * SIDE) as usize)); + Ok(()) + }) + .unwrap(); + let before = rgb(&s, SIDE / 2, SIDE / 2)[0]; + assert!(before > 1.0, "{before}"); + s.execute("paint.dodge", json!({"points": [[SIDE / 2, SIDE / 2]], "size": 40, "hardness": 100})).unwrap(); + let after = rgb(&s, SIDE / 2, SIDE / 2)[0]; + assert!(after >= before, "32-bit Grayscale Dodge clipped {before} to {after}"); +} + +#[test] +fn dodge_keeps_light_above_white_when_luma_is_not_positive_in_32_bit() { + // A channel above white next to a negative one: luma <= 0, so Protect Tones can't scale the + // colour by luma. It takes the per-channel curve instead and keeps the light above white. + for exposure in [25, 100] { + for o in [[1.2f32, -0.7, 0.2], [1.01, -0.52, 0.02]] { + let mut s = patches(32); + s.edit("bright", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let px = photocraft_raster::from_rgba(&surf.format(), [o[0], o[1], o[2], 1.0]); + surf.write_region(photocraft_geom::Rect::new(0, 0, SIDE, SIDE), &px.repeat((SIDE * SIDE) as usize)); + Ok(()) + }) + .unwrap(); + assert_eq!(rgb(&s, SIDE / 2, SIDE / 2), o); + let c = dodge_each(&mut s, json!({"exposure": exposure}))[0]; + assert!(c[0] >= o[0], "{exposure} % Dodge of {o:?} clipped light above white: {c:?}"); + let e = dodge_burn(o, exposure as f32 / 100.0, ToneRange::Midtones, false, false); + assert!(c.iter().zip(e).all(|(c, e)| (c - e).abs() < 1e-5), "{exposure} % Dodge of {o:?}: got {c:?}, the per-channel curve gives {e:?}"); + } + } +} + +#[test] +fn dodge_keeps_tones_in_order_in_32_bit() { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 256, "height": 8, "depth": 32, "mode": "rgb"})).unwrap(); + s.edit("ramp", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let fmt = surf.format(); + let data: Vec = (0..8).flat_map(|_| (0..256).flat_map(|x| photocraft_raster::from_rgba(&fmt, [x as f32 / 255.0; 4]))).collect(); + surf.write_region(photocraft_geom::Rect::new(0, 0, 256, 8), &data); + Ok(()) + }) + .unwrap(); + s.execute("paint.dodge", json!({"points": [[-20, 4], [276, 4]], "size": 40, "hardness": 100})).unwrap(); + let row: Vec = (0..256).map(|x| rgb(&s, x, 4)[0]).collect(); + assert!(row.windows(2).all(|w| w[1] >= w[0]), "{row:?}"); + assert!(row.iter().all(|v| (0.0..=1.0).contains(v)) && row[0] == 0.0 && row[255] == 1.0, "{row:?}"); +} diff --git a/crates/engine-paint/src/cmd/retouch_cmds/dodge_grayscale_tests.rs b/crates/engine-paint/src/cmd/retouch_cmds/dodge_grayscale_tests.rs new file mode 100644 index 0000000000..d545e26b48 --- /dev/null +++ b/crates/engine-paint/src/cmd/retouch_cmds/dodge_grayscale_tests.rs @@ -0,0 +1,61 @@ +//! Dodge in an 8-bit Grayscale document and on a layer mask uses the reference's single-channel +//! curve (#12689); RGB documents and the cases the reference wasn't measured in keep the RGB +//! curve. The helpers live in `burn_grayscale_tests`. + +use super::burn_grayscale_tests::{ + GREYS, assert_near, click_each, curve_is_monotone_and_bounded, doc, keeps_rgb_curve_where_not_measured, live_matches_commit, masked, +}; +use serde_json::json; + +/// Measured in the reference: one default Dodge click in an 8-bit Grayscale document. +const REFERENCE: [f32; 6] = [46.0, 117.0, 138.0, 187.0, 202.0, 227.0]; + +#[test] +fn dodge_in_8_bit_grayscale_matches_the_reference() { + let got = click_each(&mut doc("gray", 8), "paint.dodge", &json!({})); + assert_near(&got, &REFERENCE, 2.0, "Dodge, 8-bit Grayscale"); +} + +#[test] +fn dodge_on_a_layer_mask_matches_grayscale() { + let mut s = masked(8); + let before = s.active().unwrap().history.past_len(); + let got = click_each(&mut s, "paint.dodge", &json!({"target": "mask"})); + assert_near(&got, &REFERENCE, 2.0, "Dodge, layer mask"); + let h = &s.active().unwrap().history; + assert_eq!((h.past_len(), h.undo_label()), (before + GREYS.len(), Some("Dodge Tool"))); +} + +#[test] +fn dodge_on_an_adjustment_layers_white_mask_keeps_it_white() { + let mut s = doc("gray", 8); + s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap(); + let before = s.active().unwrap().history.past_len(); + s.execute("paint.dodge", json!({"points": [[30, 30]], "size": 40, "hardness": 100, "target": "mask"})).unwrap(); + let d = s.active().unwrap(); + let mask = &d.doc.layer(d.active_layer.unwrap()).unwrap().mask.as_ref().unwrap().surface; + assert_eq!(mask.rgba(30, 30)[0], 1.0); + assert_eq!((d.history.past_len(), d.history.undo_label()), (before + 1, Some("Dodge Tool"))); +} + +#[test] +fn dodge_keeps_rgb_results() { + // Pinned from main d5582062a0: neutral greys and a colour in an 8-bit RGB document. + let got = click_each(&mut doc("rgb", 8), "paint.dodge", &json!({})); + assert_near(&got, &[46.0, 140.0, 161.0, 198.0, 209.0, 228.0], 0.0, "Dodge, RGB greys"); +} + +#[test] +fn dodge_keeps_the_rgb_curve_where_the_reference_was_not_measured() { + keeps_rgb_curve_where_not_measured("paint.dodge", false); +} + +#[test] +fn live_dodge_in_grayscale_matches_the_commit() { + live_matches_commit("paint.dodge"); +} + +#[test] +fn single_channel_dodge_curve_is_monotone_and_bounded() { + curve_is_monotone_and_bounded(false); +} diff --git a/crates/engine-paint/src/cmd/retouch_cmds/heal.rs b/crates/engine-paint/src/cmd/retouch_cmds/heal.rs index db5a0e3fe7..4c1c2f4bc3 100644 --- a/crates/engine-paint/src/cmd/retouch_cmds/heal.rs +++ b/crates/engine-paint/src/cmd/retouch_cmds/heal.rs @@ -3,7 +3,7 @@ use super::periodic; use super::sampling::{SampleLayers, composite_region, sample_all_layers, sample_layers}; use super::{ BlendMode, CompleteParams, Document, EngineError, LayerId, PixelFormat, Rect, Region, Result, Session, Stroke, Surface, Value, apply_coverage, bad, - coverage, damage_json, flag, inpaint, json, parse_brush, poisson, reject_huge_stroke, run_stroke, string, + coverage, damage_json, flag, inpaint, json, parse_brush, poisson, reject_huge_stroke, restore_coverage, run_stroke, string, }; /// Grow a stroke's coverage map by `m` pixels of zero coverage (a Dirichlet boundary for the solve). @@ -183,7 +183,7 @@ pub(super) fn history_brush(s: &mut Session, p: &Value) -> Result { let src = if src_surface.format() == fmt { src_surface } else { src_surface.convert(fmt) }; let (bounds, cov) = coverage(CMD, &stroke)?; let paint = Region::read(&src, bounds); - Ok(apply_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode)) + Ok(restore_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode)) })?; let mut r = json!({ "damage": damage_json(dmg) }); if from_live { @@ -326,6 +326,10 @@ pub(super) fn spot_healing(s: &mut Session, p: &Value) -> Result { #[path = "heal_indexed_tests.rs"] mod heal_indexed_tests; +#[cfg(test)] +#[path = "history_brush_transparency_tests.rs"] +mod history_brush_transparency_tests; + #[cfg(test)] #[path = "heal_replace_tests.rs"] mod heal_replace_tests; diff --git a/crates/engine-paint/src/cmd/retouch_cmds/history_brush_transparency_tests.rs b/crates/engine-paint/src/cmd/retouch_cmds/history_brush_transparency_tests.rs new file mode 100644 index 0000000000..f87ca40405 --- /dev/null +++ b/crates/engine-paint/src/cmd/retouch_cmds/history_brush_transparency_tests.rs @@ -0,0 +1,107 @@ +//! #14701: the History Brush in Normal mode restores the source state's pixels, transparency +//! included, instead of laying them over what is there now. Painting a moved subject's new place +//! from the state before the move clears it again (no "ghost" double image), at the stroke's +//! opacity, and the live stroke shows what the commit paints. Other modes still composite. + +use serde_json::json; + +use super::*; + +const W: i32 = 48; +const H: i32 = 16; +const RED: [f32; 4] = [0.8, 0.1, 0.1, 1.0]; + +/// A `depth` RGB document with a layer over the Background holding a red subject on its left +/// half (History row 2), then the subject moved to the right half (row 3, the current state). +fn moved(depth: u64) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": W, "height": H, "depth": depth, "mode": "rgb"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + for left in [true, false] { + s.edit("setup", |doc, active| { + let b = doc.bounds(); + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let fmt = surf.format(); + let data: Vec = (b.y0..b.y1) + .flat_map(|y| (b.x0..b.x1).map(move |x| (x, y))) + .flat_map(|(x, _)| photocraft_raster::from_rgba(&fmt, if (x < W / 2) == left { RED } else { [0.0; 4] })) + .collect(); + surf.write_region(b, &data); + Ok(()) + }) + .unwrap(); + } + s +} + +/// A stroke across the whole layer from History row 2 (the subject still on the left). +fn stroke(extra: Value) -> Value { + let mut p = json!({"points": [[0, 8], [W, 8]], "size": 40, "hardness": 100, "state": 2}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) { + p.extend(extra.clone()); + } + p +} + +fn layer_rgba(doc: &Document, s: &Session, x: i32, y: i32) -> [f32; 4] { + doc.layer(s.active().unwrap().active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y) +} + +fn close(a: [f32; 4], b: [f32; 4], tol: f32) -> bool { + a.iter().zip(b).all(|(a, b)| (a - b).abs() <= tol) +} + +#[test] +fn history_brush_restores_transparency_from_the_source_state() { + for depth in [8u64, 16, 32] { + let mut s = moved(depth); + s.execute("paint.historyBrush", stroke(json!({}))).unwrap(); + let doc = s.active().unwrap().doc.clone(); + let (left, right) = (layer_rgba(&doc, &s, 8, 8), layer_rgba(&doc, &s, 40, 8)); + assert!(close(left, RED, 0.01), "depth {depth}: the subject comes back on the left: {left:?}"); + assert!(right[3] < 0.01, "depth {depth}: the moved subject is cleared, no ghost: {right:?}"); + } +} + +#[test] +fn history_brush_restores_transparency_at_the_stroke_opacity() { + for depth in [8u64, 16, 32] { + let mut s = moved(depth); + s.execute("paint.historyBrush", stroke(json!({"opacity": 50}))).unwrap(); + let doc = s.active().unwrap().doc.clone(); + let (left, right) = (layer_rgba(&doc, &s, 8, 8), layer_rgba(&doc, &s, 40, 8)); + assert!((left[3] - 0.5).abs() < 0.01 && close([left[0], left[1], left[2], 1.0], RED, 0.01), "depth {depth}: half the subject back: {left:?}"); + assert!((right[3] - 0.5).abs() < 0.01 && close([right[0], right[1], right[2], 1.0], RED, 0.01), "depth {depth}: half cleared: {right:?}"); + } +} + +#[test] +fn live_history_brush_shows_the_restored_transparency() { + for depth in [8u64, 32] { + let s = moved(depth); + let live = super::super::LiveRetouch::begin(&s, "paint.historyBrush", &stroke(json!({}))).unwrap(); + let (left, right) = (layer_rgba(&live.doc, &s, 8, 8), layer_rgba(&live.doc, &s, 40, 8)); + assert!(close(left, RED, 0.01), "depth {depth}: {left:?}"); + assert!(right[3] < 0.01, "depth {depth}: the live stroke clears the moved subject: {right:?}"); + } +} + +#[test] +fn other_modes_and_locked_transparency_keep_compositing() { + // Multiply of a transparent source changes nothing: the moved subject stays. + let mut s = moved(8); + s.execute("paint.historyBrush", stroke(json!({"mode": "multiply"}))).unwrap(); + let doc = s.active().unwrap().doc.clone(); + assert!(close(layer_rgba(&doc, &s, 40, 8), RED, 0.01)); + // Locked transparency keeps the layer's alpha: nothing to clear, nothing to restore. + let mut s = moved(8); + s.edit("lock", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().locks.transparency = true; + Ok(()) + }) + .unwrap(); + s.execute("paint.historyBrush", stroke(json!({}))).unwrap(); + let doc = s.active().unwrap().doc.clone(); + assert!(close(layer_rgba(&doc, &s, 40, 8), RED, 0.01)); + assert!(layer_rgba(&doc, &s, 8, 8)[3] < 0.01); +} diff --git a/crates/engine/tests/it/layers_thumbnail_history_names.rs b/crates/engine/tests/it/layers_thumbnail_history_names.rs new file mode 100644 index 0000000000..948f51158d --- /dev/null +++ b/crates/engine/tests/it/layers_thumbnail_history_names.rs @@ -0,0 +1,110 @@ +//! History names of the Layers panel's thumbnail gestures (#16786), run with the params the panel sends, and the +//! Layer and Select menus' calls of the same commands, which keep their names. + +use photocraft_engine::Session; +use serde_json::{Value, json}; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 30})).unwrap(); + s +} + +fn active(s: &Session) -> u64 { + s.active().unwrap().active_layer.unwrap().0 +} + +/// A new pixel layer filled with red, active. +fn pixel_layer(s: &mut Session) -> u64 { + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + active(s) +} + +/// The name of the one history state `cmd` with `params` adds. +fn step(s: &mut Session, cmd: &str, params: Value) -> String { + let before = s.active().unwrap().history.entries().len(); + s.execute(cmd, params.clone()).unwrap_or_else(|e| panic!("{cmd} {params}: {e}")); + let after = s.active().unwrap().history.entries(); + assert_eq!(after.len(), before + 1, "{cmd} {params} adds one state: {after:?}"); + after[before].clone() +} + +/// ⌘-click (with ⇧ / ⌥ too) on a pixel, type, smart object or adjustment thumbnail, Select Pixels and ⌘-click on a +/// layer mask are `Load Selection`; on a shape thumbnail or a vector mask, `Selection Change`. +#[test] +fn thumbnail_loads_are_named_as_their_kind() { + let mut s = session(); + let pixel = pixel_layer(&mut s); + pixel_layer(&mut s); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let smart = active(&s); + let typ = s.execute("type.create", json!({"text": "A", "x": 5, "y": 20})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap(); + let adjustment = active(&s); + for layer in [pixel, smart, typ, adjustment] { + for operation in ["new", "add", "subtract", "intersect"] { + let params = json!({"channel": "transparency", "layer": layer, "operation": operation}); + assert_eq!(step(&mut s, "select.loadSelection", params), "Load Selection", "layer {layer}, {operation}"); + } + } + s.execute("layer.layerMask.revealAll", json!({"layer": pixel})).unwrap(); + assert_eq!(step(&mut s, "select.loadSelection", json!({"channel": "mask", "layer": pixel, "operation": "new"})), "Load Selection"); + + let shape = s.execute("shape.create", json!({"kind": "rect", "rect": [2, 2, 20, 20]})).unwrap()["layer"].as_u64().unwrap(); + let params = json!({"channel": "transparency", "layer": shape, "operation": "new"}); + assert_eq!(step(&mut s, "select.loadSelection", params), "Selection Change", "shape thumbnail"); + s.execute("layer.vectorMask.revealAll", json!({"layer": pixel})).unwrap(); + let params = json!({"channel": "vectorMask", "layer": pixel, "operation": "add"}); + assert_eq!(step(&mut s, "select.loadSelection", params), "Selection Change", "vector mask"); +} + +/// Select › Load Selection names no layer, and keeps its names. +#[test] +fn the_menu_load_keeps_its_names() { + let mut s = session(); + let layer = pixel_layer(&mut s); + s.execute("layer.layerMask.revealAll", json!({"layer": layer})).unwrap(); + assert_eq!(step(&mut s, "select.loadSelection", json!({"channel": "transparency"})), "Load Transparency"); + assert_eq!(step(&mut s, "select.loadSelection", json!({"channel": "mask"})), "Load Layer Mask"); +} + +/// ⇧-click on a mask and the chain say which way they went; the Layer menu's plain toggles keep their names. +#[test] +fn mask_toggles_and_chains_name_their_direction() { + let mut s = session(); + let layer = pixel_layer(&mut s); + s.execute("layer.layerMask.revealAll", json!({"layer": layer})).unwrap(); + s.execute("layer.vectorMask.revealAll", json!({"layer": layer})).unwrap(); + let cases = [ + ("layer.layerMask.enabled", "enabled", ["Disable Layer Mask", "Enable Layer Mask"], "Enable/Disable Layer Mask"), + ("layer.layerMask.linked", "linked", ["Unlink Mask", "Link Mask"], "Link/Unlink Layer Mask"), + ("layer.vectorMask.enabled", "enabled", ["Disable Vector Mask", "Enable Vector Mask"], "Edit Vector Mask"), + ("layer.vectorMask.linked", "linked", ["Unlink Vector Mask", "Link Vector Mask"], "Edit Vector Mask"), + ]; + for (cmd, key, [off, on], toggle) in cases { + assert_eq!(step(&mut s, cmd, json!({"layer": layer, key: false})), off); + assert_eq!(step(&mut s, cmd, json!({"layer": layer, key: true})), on); + assert_eq!(step(&mut s, cmd, json!({})), toggle, "{cmd} from the menu"); + } +} + +/// Dragging a layer mask onto another layer, or ⌥-dragging a copy there, is one `Add Layer Mask` state, and one undo +/// puts both layers back. +#[test] +fn a_mask_drop_is_one_add_layer_mask_state() { + for copy in [false, true] { + let mut s = session(); + let from = pixel_layer(&mut s); + let to = pixel_layer(&mut s); + s.execute("layer.layerMask.revealAll", json!({"layer": from})).unwrap(); + let before = s.active().unwrap().doc.clone(); + assert_eq!(step(&mut s, "layer.layerMask.moveTo", json!({"layer": from, "to": to, "copy": copy})), "Add Layer Mask", "copy {copy}"); + s.execute("edit.undo", json!({})).unwrap(); + let doc = &s.active().unwrap().doc; + for id in [from, to] { + let has_mask = |d: &photocraft_doc::Document| d.layer(photocraft_doc::LayerId(id)).unwrap().mask.is_some(); + assert_eq!(has_mask(doc), has_mask(&before), "copy {copy}: one undo restores layer {id}"); + } + } +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 69b4cb0840..eac618e76d 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -92,6 +92,7 @@ mod layer_delete_last; mod layer_mask_depth; mod layer_props_several; mod layer_range_panel_order; +mod layers_thumbnail_history_names; mod live_dab_matches_replay; mod live_line_transform; mod magnetic_lasso_composite; diff --git a/crates/engine/tests/it/paint_in_layer_copy_cmds.rs b/crates/engine/tests/it/paint_in_layer_copy_cmds.rs index cbd947ce58..62fc8f1b65 100644 --- a/crates/engine/tests/it/paint_in_layer_copy_cmds.rs +++ b/crates/engine/tests/it/paint_in_layer_copy_cmds.rs @@ -232,7 +232,7 @@ fn duplicate_to_a_new_document_keeps_size_pixels_and_place_at_every_depth() { assert_eq!(*src, source_before, "the source is untouched"); assert_eq!(dst.size, src.size, "same canvas, as Photoshop"); assert_eq!((dst.mode, dst.depth, dst.resolution_dpi), (src.mode, src.depth, src.resolution_dpi)); - assert_eq!(dst.name, format!("{} copy", src.name)); + assert_eq!(dst.name, "Untitled-1"); let layers = r["layers"].as_array().unwrap(); assert_eq!(layers.len(), 1); let id = LayerId(layers[0].as_u64().unwrap()); diff --git a/crates/gpu/src/fx/builders.rs b/crates/gpu/src/fx/builders.rs index ff48eae03a..6b51c79211 100644 --- a/crates/gpu/src/fx/builders.rs +++ b/crates/gpu/src/fx/builders.rs @@ -22,16 +22,16 @@ impl B { // `× shape` step below would then remove the whole shadow, exactly as on the CPU. Both // compositors expand the inverted shape by the ¼–½–¼ taps instead // (`photocraft_compose::effects::size_one_kernel`, the kernel `shadow_map` applies). - // #14934: an Anti-aliased Inner Shadow takes the CPU's sub-pixel source offset, on the - // CPU's gate only (`fx::aa_shift`: the inner branch, the Gaussian contour, and a Size and - // Choke that leave the map a shift plus a blur that is not the identity). A Drop Shadow - // keeps today's map (#14881). At a Choke that dilates the CPU recomputes its dilation - // distance on the offset map while this builder shifts the whole-pixel field of the - // unshifted shape, and at a blur of width 1 the offset would be the whole map: both - // neighbours take no offset here — which covers the Size 1 case above —, which is what - // keeps them equal on both compositors - // (`anti_aliased_inner_shadow_gated_neighbours_match_the_cpu`). - let aa = fx::aa_shift(inner && s.anti_alias, &s.contour, s.size, s.spread); + // #14934 / #14881: an Anti-aliased Inner or Drop Shadow takes the CPU's sub-pixel source + // offset, on the CPU's gate only (`fx::aa_shift`: the Gaussian contour, and a Size and + // Choke / Spread that leave the map a shift plus a blur that is not the identity). At a + // Choke or Spread that dilates the CPU recomputes its dilation distance on the offset map + // while this builder shifts the whole-pixel field of the unshifted shape, and at a blur of + // width 1 the offset would be the whole map: both neighbours take no offset here — which + // covers the Size 1 case above —, which is what keeps them equal on both compositors + // (`anti_aliased_inner_shadow_gated_neighbours_match_the_cpu`, + // `anti_aliased_drop_shadow_gated_neighbours_match_the_cpu`). + let aa = fx::aa_shift(s.anti_alias, &s.contour, s.size, s.spread); let src = self.shift(In::Shape, dx + aa, dy + aa, if inner { 1.0 } else { 0.0 }, inner); let m = if inner && s.size == 1.0 && s.spread == 0.0 { self.conv(src, fx::size_one_kernel()) diff --git a/crates/gpu/src/fx/tests.rs b/crates/gpu/src/fx/tests.rs index a8d3667e63..897f6a58cf 100644 --- a/crates/gpu/src/fx/tests.rs +++ b/crates/gpu/src/fx/tests.rs @@ -427,11 +427,74 @@ fn anti_aliased_inner_shadow_shifts_the_map_stage() { // Unmeasured cases keep today's stage: the contour gate is the CPU's. let linear = program(&Effect::InnerShadow(shadow(true, Contour::Linear)), &light, false); assert_eq!(shift_stages(&linear)[0].p0, [0.0, 0.0, 1.0, 1.0], "a Linear inner shadow still ignores Anti-aliased (#14934 leaves that contour unmeasured)"); - // A Drop Shadow (its own item is #14881) keeps its whole-pixel program either way. - let drop_on = program(&Effect::DropShadow(shadow(true, gaussian.clone())), &light, false); + // A Drop Shadow without Anti-aliased keeps its whole-pixel program: no shift at Distance 0. let drop_off = program(&Effect::DropShadow(shadow(false, gaussian)), &light, false); - assert_eq!(shift_stages(&drop_on).len(), 0, "a Drop Shadow at Distance 0 takes no shift stage"); - assert_eq!(drop_on.key, drop_off.key, "the Drop Shadow still ignores Anti-aliased (#14881 is its own item)"); + assert_eq!(shift_stages(&drop_off).len(), 0, "a Drop Shadow at Distance 0 without Anti-aliased takes no shift stage"); +} + +/// #14881: the GPU's Drop Shadow program takes the same sub-pixel source offset as the CPU's +/// `shadow_map`, on the same gate as the Inner Shadow: the Gaussian contour and a Size and Spread +/// whose map is a shift plus a blur wider than the identity. At Distance 0 the flag off builds no +/// shift stage at all; the flag on adds one carrying the offset (no invert, empty outside). +#[test] +fn anti_aliased_drop_shadow_shifts_the_map_stage() { + use photocraft_doc::{Contour, FxCommon, Shadow}; + let pts: [(f32, f32); 11] = [ + (0.0, 0.0), + (0.117, 0.023), + (0.172, 0.055), + (0.234, 0.117), + (0.305, 0.234), + (0.383, 0.414), + (0.523, 0.688), + (0.617, 0.812), + (0.703, 0.891), + (0.805, 0.953), + (1.0, 1.0), + ]; + let gaussian = || Contour::Custom { + name: "Gaussian".into(), + points: pts.iter().map(|(input, output)| photocraft_doc::adjust::CurvePoint { input: *input, output: *output }).collect(), + corners: (0..pts.len()).map(|i| i > 0 && i < pts.len() - 1).collect(), + }; + let shadow = |size: f32, spread: f32, distance: f32, contour: Contour, anti_aliased: bool| Shadow { + common: FxCommon::new(BlendMode::Multiply, 1.0), + color: photocraft_color::Color::BLACK, + angle: 0.0, + use_global_light: false, + distance, + spread, + size, + contour, + anti_alias: anti_aliased, + noise: 0.0, + knocks_out: false, + }; + let shifts = |s: Shadow| -> (Vec<[f32; 4]>, u64) { + let p = program(&Effect::DropShadow(s), &GlobalLight::default(), false); + (p.stages.iter().filter(|s| s.kernel == Kernel::MShift).map(|s| s.p0).collect(), p.key) + }; + let aa = photocraft_compose::effects::aa_shift(true, &gaussian(), 10.0, 0.0); + assert_eq!(aa, -1.0 / 3.0, "the CPU offset the GPU has to copy at the measured Size 10, Spread 0"); + let off = shifts(shadow(10.0, 0.0, 0.0, gaussian(), false)); + let on = shifts(shadow(10.0, 0.0, 0.0, gaussian(), true)); + assert!(off.0.is_empty(), "a Drop Shadow at Distance 0 without Anti-aliased takes no shift stage: {:?}", off.0); + assert_eq!(on.0, vec![[aa, aa, 0.0, 0.0]], "the Anti-aliased drop shadow must shift its source by the CPU's offset"); + assert_ne!(on.1, off.1, "the flag has to invalidate the cached program"); + // Distance 5 at angle 0: the whole-pixel light offset (-5, 0) plus the third of a pixel. + let far = shifts(shadow(10.0, 0.0, 5.0, gaussian(), true)); + assert_eq!(far.0, vec![[-5.0 + aa, aa, 0.0, 0.0]], "Distance 5 carries the light offset plus the sub-pixel offset"); + // The gate: other contours, the identity blur and a Spread that dilates keep today's program. + for (s, what) in [ + (shadow(10.0, 0.0, 0.0, Contour::Linear, true), "a Linear contour"), + (shadow(1.0, 0.0, 0.0, gaussian(), true), "Size 1"), + (shadow(2.0, 0.5, 0.0, gaussian(), true), "Size 2 Spread 50 %"), + (shadow(10.0, 0.5, 5.0, gaussian(), true), "Size 10 Spread 50 % at Distance 5"), + ] { + let mut flag_off = s.clone(); + flag_off.anti_alias = false; + assert_eq!(shifts(s), shifts(flag_off), "the {what} drop shadow program moved with Anti-aliased"); + } } /// #14934 review: the GPU's gate is the CPU's rule, including its two degenerate neighbours. At diff --git a/crates/gpu/tests/it/parity.rs b/crates/gpu/tests/it/parity.rs index d3ffa24f21..1843c30e8b 100644 --- a/crates/gpu/tests/it/parity.rs +++ b/crates/gpu/tests/it/parity.rs @@ -3811,3 +3811,79 @@ fn anti_aliased_inner_shadow_gated_neighbours_match_the_cpu() { .unwrap_or_else(|e| panic!("{e}")); } } + +// --------------------------------------------------------------------------------------------- +// #14881: the Drop Shadow's Anti-aliased checkbox has to reach the GPU map program too. + +/// The #14881 test document: the #14934 canvas and orange rectangle under a black Multiply Drop +/// Shadow (Global Light 120 / 30, Noise 0, Contour Gaussian) with Size, Spread, Distance and +/// Anti-aliased as given. +fn drop_shadow_doc(size: f32, spread: f32, distance: f32, anti_aliased: bool) -> Document { + let mut d = inner_shadow_doc(size, spread, distance, anti_aliased); + if let Some(px) = d.layers.get_mut(1) { + px.effects.items = vec![Effect::DropShadow(Shadow { + common: FxCommon::new(BlendMode::Multiply, 1.0), + color: Color::BLACK, + angle: 120.0, + use_global_light: true, + distance, + spread, + size, + contour: gaussian_contour(), + anti_alias: anti_aliased, + noise: 0.0, + knocks_out: false, + })]; + } + d +} + +/// The nine R levels outwards from each of the issue's four edges of a 400 x 300 flatten. +fn drop_shadow_ramps(px: &[[f32; 4]]) -> [Vec; 4] { + let r = |x: i32, y: i32| px[(y * 400 + x) as usize][0] * 255.0; + let line = |first: (i32, i32), step: (i32, i32)| (0..9).map(|k| r(first.0 + k * step.0, first.1 + k * step.1)).collect(); + [line((200, 74), (0, -1)), line((99, 150), (-1, 0)), line((200, 225), (0, 1)), line((300, 150), (1, 0))] +} + +/// Done when (#14881): CPU and GPU agree with Anti-aliased on and off (whole-texture and paged +/// 256 px compositors), and the GPU's own ramps land on the measured profiles within 3 levels: +/// 98 147 191 223 241 249 252 254 255 at the top and left, 130 177 214 236 247 252 254 254 255 at +/// the bottom and right, while the flag off keeps the measured 114 163 205 231 244 251 253 254 255. +#[test] +fn anti_aliased_drop_shadow_matches_the_cpu_ramps() { + let Some(mut g) = gpu() else { return }; + let gpu_on = check_full(&mut g, &drop_shadow_doc(10.0, 0.0, 0.0, true), "#14881 drop shadow, Anti-aliased").whole; + let gpu_off = check_full(&mut g, &drop_shadow_doc(10.0, 0.0, 0.0, false), "#14881 drop shadow, Anti-aliased off").whole; + let tl: &[f32] = &[98.0, 147.0, 191.0, 223.0, 241.0, 249.0, 252.0, 254.0, 255.0]; + let br: &[f32] = &[130.0, 177.0, 214.0, 236.0, 247.0, 252.0, 254.0, 254.0, 255.0]; + let plain: &[f32] = &[114.0, 163.0, 205.0, 231.0, 244.0, 251.0, 253.0, 254.0, 255.0]; + for (px, wants, what) in [(&gpu_on, [tl, tl, br, br], "on"), (&gpu_off, [plain; 4], "off")] { + for ((side, got), want) in ["top", "left", "bottom", "right"].iter().zip(drop_shadow_ramps(px)).zip(wants) { + for (d, (got, want)) in got.iter().zip(want).enumerate() { + assert!((got - want).abs() <= 3.0, "GPU {side} edge, Anti-aliased {what}, {d} px out: {got:.1} vs measured {want}"); + } + } + } +} + +/// The gate's neighbours (#14881): Size 1, Size 2 at Spread 50 % and every Spread that dilates +/// take no offset, Size 2 / Spread 4 % / Distance 5 at Spread 0 take it; both compositors must +/// agree on each, plain and paged. +#[test] +fn anti_aliased_drop_shadow_gated_neighbours_match_the_cpu() { + let Some(mut g) = gpu() else { return }; + let around = Rect::new(80, 55, 320, 245); + for (size, spread, distance, what) in [ + (10.0, 0.5, 0.0, "Size 10 Spread 50 %"), + (10.0, 0.05, 0.0, "Size 10 Spread 5 %"), + (2.0, 0.5, 0.0, "Size 2 Spread 50 %"), + (1.0, 0.0, 0.0, "Size 1"), + (2.0, 0.0, 0.0, "Size 2 Spread 0 (offset on)"), + (10.0, 0.04, 0.0, "Size 10 Spread 4 % (dilates nothing, offset on)"), + (10.0, 0.0, 5.0, "Size 10 Spread 0 at Distance 5 (offset on)"), + (10.0, 0.5, 5.0, "Size 10 Spread 50 % at Distance 5 (gated)"), + ] { + diff_rect(&mut g, &drop_shadow_doc(size, spread, distance, true), around, &format!("#14881 drop shadow, {what}, Anti-aliased")) + .unwrap_or_else(|e| panic!("{e}")); + } +} diff --git a/crates/ipp/Cargo.toml b/crates/ipp/Cargo.toml index b8d05afdaf..94d8bf6793 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 = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } +craft-ipp = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } [lints] workspace = true diff --git a/crates/paint/src/brush_noise_strength_tests.rs b/crates/paint/src/brush_noise_strength_tests.rs new file mode 100644 index 0000000000..1d4e007eb1 --- /dev/null +++ b/crates/paint/src/brush_noise_strength_tests.rs @@ -0,0 +1,66 @@ +//! #17317: own 60 px strokes on an 800x400 logical frame, sampled without 8-bit quantization. + +use photocraft_color::PixelFormat; +use photocraft_raster::Surface; + +use crate::{BrushSettings, StrokePoint, render_stroke}; + +fn paint(noise: bool, hardness: f32, seed: u64) -> Surface { + let brush = BrushSettings { size: 60.0, hardness, noise, seed, ..BrushSettings::default() }; + let mut surface = Surface::new(PixelFormat::RGBA32F); + render_stroke(&mut surface, &brush, &[StrokePoint::new(100.0, 100.0, 1.0), StrokePoint::new(400.0, 100.0, 1.0)], None, false, 1.0); + surface +} + +#[test] +fn soft_noise_is_light_and_mean_neutral_over_the_complete_stroke_rectangle() { + let plain = paint(false, 0.0, 17317); + let noisy = paint(true, 0.0, 17317); + let (mut sum, mut squares, mut count) = (0.0, 0.0, 0usize); + // Fixed complete soft-tip support rectangle: 51.792 px reach plus pixel sampling, + // around the whole100..400 stroke. Include every pixel, not only favourable alpha bins. + for y in 48..152 { + for x in 48..452 { + let delta = 255.0 * f64::from(plain.rgba(x, y)[3] - noisy.rgba(x, y)[3]); + sum += delta; + squares += delta * delta; + count += 1; + } + } + let mean = sum / count as f64; + let deviation = (squares / count as f64 - mean * mean).max(0.0).sqrt(); + assert!(mean.abs() <= 2.0, "Noise minus plain mean {mean}"); + assert!((10.0..=20.0).contains(&deviation), "Noise minus plain std {deviation}"); +} + +#[test] +fn noise_leaves_the_hard_interior_and_the_empty_frame_unchanged() { + let plain = paint(false, 1.0, 17317); + let noisy = paint(true, 1.0, 17317); + for y in 80..120 { + for x in 100..400 { + assert_eq!(noisy.rgba(x, y), plain.rgba(x, y), "hard interior {x},{y}"); + } + } + for (x, y) in [(0, 0), (100, 40), (400, 160), (799, 399)] { + assert_eq!(noisy.rgba(x, y), plain.rgba(x, y)); + } +} + +#[test] +fn noise_replays_its_seed_and_different_seeds_get_different_grain() { + let first = paint(true, 0.0, 1); + let replay = paint(true, 0.0, 1); + let other = paint(true, 0.0, 2); + let plain_first = paint(false, 0.0, 1); + let plain_other = paint(false, 0.0, 2); + let mut changed = false; + for y in 48..152 { + for x in 48..452 { + assert_eq!(first.rgba(x, y), replay.rgba(x, y)); + assert_eq!(plain_first.rgba(x, y), plain_other.rgba(x, y), "Noise off stays seed-independent"); + changed |= first.rgba(x, y) != other.rgba(x, y); + } + } + assert!(changed, "different seeds must change the grain"); +} diff --git a/crates/paint/src/brush_size_fade_end_tests.rs b/crates/paint/src/brush_size_fade_end_tests.rs new file mode 100644 index 0000000000..f36e1331a2 --- /dev/null +++ b/crates/paint/src/brush_size_fade_end_tests.rs @@ -0,0 +1,64 @@ +//! #17312: own synthetic strokes must not leave the old radius-floor dots after Size Fade. + +use photocraft_color::PixelFormat; +use photocraft_raster::Surface; + +use crate::{BrushSettings, Control, Dynamic, Stroke, StrokePoint, dabs, render_stroke}; + +fn brush(steps: u32, minimum: f32) -> BrushSettings { + let mut brush = BrushSettings { size: 30.0, spacing: 1.5, seed: 17312, ..BrushSettings::default() }; + brush.shape_dynamics.enabled = true; + brush.shape_dynamics.size = Dynamic { control: Control::Fade, fade_steps: steps, minimum, ..Dynamic::default() }; + brush +} + +fn points() -> Vec { + vec![StrokePoint::new(100.0, 100.0, 1.0), StrokePoint::new(700.0, 100.0, 1.0)] +} + +#[test] +fn zero_minimum_size_fade_ends_after_the_last_nonzero_dab() { + for count in [5, 10] { + let brush = brush(count, 0.0); + let steps = dabs(&Stroke { brush: brush.clone(), points: points() }); + assert_eq!(steps.len(), count as usize); + for (index, dab) in steps.iter().enumerate() { + let diameter = 30.0 * (1.0 - index as f32 / count as f32); + assert!((dab.radius * 2.0 - diameter).abs() < 1e-4); + } + let mut surface = Surface::new(PixelFormat::RGBA32F); + render_stroke(&mut surface, &brush, &points(), None, false, 1.0); + let last = steps.last().unwrap(); + assert!(surface.rgba(last.center.x.round() as i32, 100)[3] > 0.0); + // This independent fix retains the baseline pitch; #17311 changes its spacing. + // Pixels beyond the last nonzero dab must stay clear, wherever that dab is placed. + let tail_start = (last.center.x + f64::from(last.radius) + 4.0).ceil() as i32; + for x in tail_start..=700 { + for y in 75..=125 { + assert_eq!(surface.rgba(x, y)[3], 0.0, "unexpected tail at {x},{y}, Fade{count}"); + } + } + } +} + +#[test] +fn a_positive_minimum_keeps_painting_past_the_fade() { + let steps = dabs(&Stroke { brush: brush(10, 0.3), points: points() }); + assert!(steps.len() > 10); + assert!(steps.last().unwrap().center.x > 680.0); + assert!(steps.iter().skip(10).all(|dab| (dab.radius - 4.5).abs() < 1e-4)); +} + +#[test] +fn zero_pressure_and_roundness_fade_keep_their_existing_floors() { + let pressure = BrushSettings { size: 30.0, pressure_size: true, ..BrushSettings::default() }; + let steps = dabs(&Stroke { brush: pressure, points: vec![StrokePoint::new(0.0, 0.0, 0.0), StrokePoint::new(10.0, 0.0, 0.0)] }); + assert!(!steps.is_empty()); + assert!(steps.iter().all(|dab| dab.radius == 0.5)); + let mut roundness = brush(10, 0.0); + roundness.shape_dynamics.roundness = roundness.shape_dynamics.size; + roundness.shape_dynamics.size.control = Control::Off; + let steps = dabs(&Stroke { brush: roundness, points: points() }); + assert!(steps.len() > 10); + assert!(steps.iter().skip(10).all(|dab| dab.radius == 15.0 && dab.roundness == 0.01)); +} diff --git a/crates/paint/src/brush_tests.rs b/crates/paint/src/brush_tests.rs index 558b3436de..586c881ac9 100644 --- a/crates/paint/src/brush_tests.rs +++ b/crates/paint/src/brush_tests.rs @@ -855,20 +855,23 @@ fn wet_edges_and_noise() { let hb = BrushSettings { hardness: 1.0, ..b }; let d = paint(&hb, &[StrokePoint::new(50.0, 50.0, 1.0)], 100, 100); assert!(d.rgba(50 + 18, 50)[3] > d.rgba(50, 50)[3] + 0.2); - // Noise: soft tip coverage becomes grainy (more pixels near 0/1). + // Noise: soft coverage gets a light grain, not the old near-binary dither. let soft = BrushSettings { size: 40.0, hardness: 0.0, ..brush() }; let a = paint(&soft, &[StrokePoint::new(50.0, 50.0, 1.0)], 100, 100); let n = paint(&BrushSettings { noise: true, ..soft }, &[StrokePoint::new(50.0, 50.0, 1.0)], 100, 100); - let extreme = |s: &Surface| { - (30..70) - .flat_map(|y| (30..70).map(move |x| (x, y))) - .filter(|&(x, y)| { - let v = s.rgba(x, y)[3]; - !(0.15..=0.85).contains(&v) - }) - .count() - }; - assert!(extreme(&n) > extreme(&a) + 100, "{} vs {}", extreme(&n), extreme(&a)); + let (mut sum, mut squares, mut count) = (0.0, 0.0, 0usize); + for y in 30..70 { + for x in 30..70 { + let delta = 255.0 * f64::from(a.rgba(x, y)[3] - n.rgba(x, y)[3]); + sum += delta; + squares += delta * delta; + count += 1; + } + } + let mean = sum / count as f64; + let deviation = (squares / count as f64 - mean * mean).max(0.0).sqrt(); + assert!(mean.abs() <= 2.0, "Noise mean {mean}"); + assert!((10.0..=20.0).contains(&deviation), "Noise std {deviation}"); } #[test] diff --git a/crates/paint/src/dynamics.rs b/crates/paint/src/dynamics.rs index 0428ea9edd..eef51d7160 100644 --- a/crates/paint/src/dynamics.rs +++ b/crates/paint/src/dynamics.rs @@ -642,6 +642,10 @@ impl DabBuilder { 1 }; let base_d = base_diameter(b, s); + // A zero Size Fade ends the stroke; pressure, jitter and other fades keep their floors. + if sd.enabled && sd.size.control == Control::Fade && sd.size.minimum <= 0.0 && base_d <= 0.0 { + return; + } for _ in 0..count { let i = self.next_index; self.next_index += 1; diff --git a/crates/paint/src/lib.rs b/crates/paint/src/lib.rs index d82132f3c6..aafc93138b 100644 --- a/crates/paint/src/lib.rs +++ b/crates/paint/src/lib.rs @@ -417,3 +417,9 @@ mod mixer_load_supply_tests; #[cfg(test)] mod smoothing_catch_up_default_tests; + +#[cfg(test)] +mod brush_noise_strength_tests; + +#[cfg(test)] +mod brush_size_fade_end_tests; diff --git a/crates/paint/src/render.rs b/crates/paint/src/render.rs index 7b1ca43f96..f0c51fa970 100644 --- a/crates/paint/src/render.rs +++ b/crates/paint/src/render.rs @@ -1672,9 +1672,10 @@ impl GeneralTip<'_> { continue; } if noise && val < 1.0 { - let n = hash2(x, y, NOISE_SALT); + let n = hash2(x, y, NOISE_SALT ^ b.seed); let hard = if n < val { 1.0 } else { 0.0 }; - val += (hard - val) * 0.7; + // A light unbiased grain, rather than near-binary dither. Solid pixels skip this. + val += (hard - val) * 0.15; } if tex_tip { val = texture_combine(b.texture.mode, val, ctx.texture_at(x, y), d.depth); diff --git a/crates/paint/src/render/reference.rs b/crates/paint/src/render/reference.rs index 2a3a87f8f7..2f24640e1f 100644 --- a/crates/paint/src/render/reference.rs +++ b/crates/paint/src/render/reference.rs @@ -110,9 +110,9 @@ impl BrushContext { continue; } if noise && val < 1.0 { - let n = hash2(x, y, NOISE_SALT); + let n = hash2(x, y, NOISE_SALT ^ b.seed); let hard = if n < val { 1.0 } else { 0.0 }; - val += (hard - val) * 0.7; + val += (hard - val) * 0.15; } if tex_tip { val = mask_combine(b.texture.mode, val, self.texture_at(x, y), d.depth); diff --git a/crates/paint/src/retouch.rs b/crates/paint/src/retouch.rs index 9ab36bf2de..3735864912 100644 --- a/crates/paint/src/retouch.rs +++ b/crates/paint/src/retouch.rs @@ -202,6 +202,39 @@ pub fn apply_coverage( lock_transparency: bool, paint: &Region, blend: BlendMode, +) -> Rect { + composite_coverage(target, rect, cov, opacity, selection, lock_transparency, paint, blend, false) +} + +/// [`apply_coverage`] for the History Brush (#14701): in Normal mode the paint image *replaces* +/// the pixels at the per-pixel weight (a premultiplied mix, alpha included), so a transparent +/// source pixel clears what is there instead of leaving it under the restored pixels. Other +/// modes, locked transparency and targets without alpha composite as [`apply_coverage`] does. +#[allow(clippy::too_many_arguments)] +pub fn restore_coverage( + target: &mut Surface, + rect: Rect, + cov: &[f32], + opacity: f32, + selection: Option<&Surface>, + lock_transparency: bool, + paint: &Region, + blend: BlendMode, +) -> Rect { + composite_coverage(target, rect, cov, opacity, selection, lock_transparency, paint, blend, true) +} + +#[allow(clippy::too_many_arguments)] +fn composite_coverage( + target: &mut Surface, + rect: Rect, + cov: &[f32], + opacity: f32, + selection: Option<&Surface>, + lock_transparency: bool, + paint: &Region, + blend: BlendMode, + replace: bool, ) -> Rect { if rect.is_empty() { return Rect::EMPTY; @@ -237,7 +270,10 @@ pub fn apply_coverage( } let src = paint.px(x, y); if blend == BlendMode::Normal { - over_native(&fmt, px, src, k, lock_transparency); + match a { + Some(a) if replace && !lock_transparency => mix_premultiplied(px, src, a, k), + _ => over_native(&fmt, px, src, k, lock_transparency), + } } else { // A transparent source cannot paint. Skip it before an RGB round trip changes // untouched native CMYK/Lab values; Normal handles zero weight in over_native. @@ -366,12 +402,14 @@ pub fn mix_back(target: &mut Surface, orig: &Region, work: &Region, rect: Rect, #[inline] pub fn mix_premultiplied(dst: &mut [f32], src: &[f32], a: usize, k: f32) { let (Some(&da), Some(&sa)) = (dst.get(a), src.get(a)) else { return }; - let oa = da + (sa - da) * k; + // Weighted, not `d + (s - d) * k`: at k = 1 the destination drops out exactly, even for + // large 32-bit values (or a tiny alpha next to 1) where the difference would round away the source. + let oa = da * (1.0 - k) + sa * k; for (c, (d, s)) in dst.iter_mut().zip(src).enumerate() { if c == a { continue; } - *d = if oa > 1e-6 { (*d * da + (*s * sa - *d * da) * k) / oa } else { *d + (*s - *d) * k }; + *d = if oa > 0.0 { (*d * da * (1.0 - k) + *s * sa * k) / oa } else { *d * (1.0 - k) + *s * k }; } if let Some(d) = dst.get_mut(a) { *d = oa; @@ -992,6 +1030,28 @@ mod tests { assert_eq!(d, [0.5, 0.5]); } + #[test] + fn premultiplied_mix_at_full_weight_keeps_the_source_exactly() { + let mut d = [67_108_864.0, 0.0, 0.0, 1.0]; + mix_premultiplied(&mut d, &[1.0, 0.0, 0.0, 1.0], 3, 1.0); + assert_eq!(d, [1.0, 0.0, 0.0, 1.0]); + } + + #[test] + fn premultiplied_mix_keeps_colour_at_tiny_alpha() { + // Half of a barely-there 32-bit red over transparent black is still that red, not half of it. + let mut d = [0.0, 0.0, 0.0, 0.0]; + mix_premultiplied(&mut d, &[1.0e6, 0.0, 0.0, 5.0e-7], 3, 0.5); + assert_eq!(d, [1.0e6, 0.0, 0.0, 2.5e-7]); + } + + #[test] + fn premultiplied_mix_at_full_weight_keeps_a_tiny_source_alpha() { + let mut d = [0.0, 0.0, 0.0, 1.0]; + mix_premultiplied(&mut d, &[1.0, 0.0, 0.0, 1.0e-8], 3, 1.0); + assert_eq!(d, [1.0, 0.0, 0.0, 1.0e-8]); + } + #[test] fn footprint_stays_inside_the_tips_reach() { let radius = 10.5f32; diff --git a/crates/text/build.rs b/crates/text/build.rs index 3cc6867ace..f97382430a 100644 --- a/crates/text/build.rs +++ b/crates/text/build.rs @@ -44,7 +44,8 @@ fn main() { /// Deflate the bundled fonts into `OUT_DIR/fonts/` (`fonts::BUNDLED` includes them). fn deflate_bundled_fonts() { use std::io::Write as _; - let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts"); + // Read at run time: a compiled build script is shared by worktrees with the same unit hash. + let src = PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap_or_default()).join("../../assets/fonts"); let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join("fonts"); let result = (|| -> std::io::Result<()> { std::fs::create_dir_all(&out)?; diff --git a/crates/ui-egui/src/alt_click_tests.rs b/crates/ui-egui/src/alt_click_tests.rs index f5055e476d..73f254b34e 100644 --- a/crates/ui-egui/src/alt_click_tests.rs +++ b/crates/ui-egui/src/alt_click_tests.rs @@ -14,7 +14,7 @@ use craft::keymap::Mods; pub(crate) fn harness(app: Box) -> Harness<'static, Box> { let mut h = Harness::builder().with_context(app.ctx().clone()).with_size(vec2(900.0, 600.0)).build_app( |ui, app: &mut PhotocraftApp| { - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); }, app, ); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 613fa6884c..8f07325142 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -116,7 +116,6 @@ impl PhotocraftApp { adjust_open: None, adjust_session: None, properties_hidden: 0, - properties_tracked: false, dialog_dropper: None, layer_style_child: None, color_targets: HashMap::new(), @@ -135,6 +134,7 @@ impl PhotocraftApp { #[cfg(not(target_arch = "wasm32"))] filter_preview_worker: Default::default(), redraws: Default::default(), + redraw_landed: 0, kept: Default::default(), color_range: None, adjust_preview: None, diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 4c16e24817..312bae9034 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -87,7 +87,6 @@ impl PhotocraftApp { if let Some(r) = preset_files_ui::open(self, name, bytes) { return r.map(|()| Vec::new()); } - let name = &self.open_name(name); // Decoded on a worker: a tab with progress appears now, the document when it's ready // (warnings are shown then). if self.background_jobs { @@ -122,6 +121,12 @@ impl PhotocraftApp { let (doc, warnings) = import(name, bytes, &opts)?; (doc, warnings, false) }; + // Decode under the source name; only a successfully opened template becomes untitled. + let opened_name = self.open_name(name); + if opened_name != name { + doc.name = opened_name.clone(); + } + let name = &opened_name; // Preferences › Raw Defaults › Resolution, as the engine's open applies it. photocraft_engine::file_cmds::raw_defaults(&self.session, &warnings, &mut doc); // Edit › Color Settings policies apply on open; Ask When Opening holds the file back diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index e15fcfeaac..ec74d98a39 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -154,8 +154,6 @@ impl PhotocraftApp { // A pass whose input carries an injected step acts for the automation client. self.automation_input = WindowHost::of(&ctx).injected_pass(); self.hover_layer = None; - // The contextual task bar reports itself again if this frame draws it (#10890). - self.ui.task_bar_shown = None; i18n::set_current(i18n::Lang::from_pref(&self.session.prefs().interface.language)); let t0 = gpu_canvas::now_ms(); self.perf.stage.ui_start(t0, frame.info().cpu_usage); @@ -231,10 +229,12 @@ impl PhotocraftApp { AppShell::new(WindowKey::main()) .window_title(window_title) .screen_mode(Bind::bound(&mut mode)) - .title_bar_if(menu_bar, |ui, _cx, app| panels::region_versions::show_title_bar(app, ui)) - .options_bar(options_bar && !home, |ui, _cx, app| panels::region_versions::show_options_bar(app, ui)) - .status(status_bar && !home, |ui, _cx, app| panels::status_bar(app, ui)) + .title_bar_if(menu_bar, |app| Some(panels::region_versions::title_bar(app)), |ui, _cx, app| panels::title_bar(app, ui)) + .options_bar(options_bar && !home, |app| Some(panels::region_versions::options_bar(app)), |ui, _cx, app| panels::options_bar(app, ui)) + .status(status_bar && !home, |app| Some(panels::region_versions::status_bar(app)), |ui, _cx, app| panels::status_bar(app, ui)) .body(|ui, cx, app| { + // The body runs every pass; the dock's columns and the document area replay while their versions hold. + canvas::document_area::each_pass(app, ui.ctx()); if home { canvas::document_area(app, ui); } else { diff --git a/crates/ui-egui/src/app/prefs.rs b/crates/ui-egui/src/app/prefs.rs index ef4e331070..cbc926f374 100644 --- a/crates/ui-egui/src/app/prefs.rs +++ b/crates/ui-egui/src/app/prefs.rs @@ -89,5 +89,7 @@ impl PhotocraftApp { // egui's own ⌘+ / ⌘- / ⌘0 scale the whole interface; PhotoCraft zooms the canvas instead // (shortcuts.rs), like Photoshop. ctx.options_mut(|o| o.zoom_with_keyboard = false); + // A pointer move that changes nothing under the pointer runs no frame (#17148). + craft::ui::runtime::pointer::gate_pointer_moves(ctx); } } diff --git a/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs b/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs index 1c339ff7cb..0bdeb32fc5 100644 --- a/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs +++ b/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs @@ -52,7 +52,7 @@ fn type_into(h: &mut Harness<'static, Box>, name: &str, text: &st #[test] fn options_bar_fields_that_alert_past_their_range() { type Read = fn(&PhotocraftApp) -> f32; - let o = |a: &PhotocraftApp| -> ToolOptions { a.ui.tool_options.clone() }; + let o = |a: &PhotocraftApp| -> ToolOptions { (*a.ui.tool_options).clone() }; let _ = o; // (tool, field, typed, kept, alerts) let rows: [(Tool, &str, &str, f32, bool, Read); 11] = [ diff --git a/crates/ui-egui/src/brush_picker_escape_tests.rs b/crates/ui-egui/src/brush_picker_escape_tests.rs index d841ee4cb2..dbe4ec4e9b 100644 --- a/crates/ui-egui/src/brush_picker_escape_tests.rs +++ b/crates/ui-egui/src/brush_picker_escape_tests.rs @@ -22,7 +22,7 @@ fn harness() -> Harness<'static, Box> { return; } // The canvas shows the picker itself (`canvas_tool_menu::run`); a second `show_at` would show it twice. - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); }, app, ); diff --git a/crates/ui-egui/src/brush_picker_memo_trials.rs b/crates/ui-egui/src/brush_picker_memo_trials.rs index fa2b0189c1..08bc761f9c 100644 --- a/crates/ui-egui/src/brush_picker_memo_trials.rs +++ b/crates/ui-egui/src/brush_picker_memo_trials.rs @@ -1,5 +1,5 @@ -//! The canvas Brush Preset picker runs only what changes: open with nothing changing, the whole picker replays, its -//! popover and the focused search field included, and none of its components runs; a Size drag runs the head and replays the list on every move; a preset rename or a new preset +//! The canvas Brush Preset picker runs only what changes: open with nothing changing, the whole picker replays (with the +//! document area around it), its popover and the focused search field included, and none of its components runs; a Size drag runs the head and replays the list on every move; a preset rename or a new preset //! builds the rows once, and the lists settle. use craft::ui::runtime::measure::{MemoRun, last_frame_derived_builds, last_frame_memo_runs, last_pass_memo_runs, last_pass_runs}; @@ -63,8 +63,10 @@ fn an_idle_open_picker_runs_no_component() { assert!(crate::brush_picker::opened_at(h.state()).is_some(), "the picker is open"); for frame in 0..3 { h.run_steps(1); - assert!(views(&h, "CanvasProps", MemoRun::Ran).is_empty(), "idle frame {frame} runs no picker"); - assert!(!views(&h, "CanvasProps", MemoRun::Replayed).is_empty(), "idle frame {frame} replays the picker"); + // The picker replays in its own view, or whole in the document area's view or the docked tree around it. + let holders = ["brush_picker::CanvasProps<", "region_versions::CanvasSlot<", "area::TreeView<"]; + assert!(holders.iter().all(|props| views(&h, props, MemoRun::Ran).is_empty()), "idle frame {frame} runs no picker"); + assert!(holders.iter().any(|props| !views(&h, props, MemoRun::Replayed).is_empty()), "idle frame {frame} replays the picker"); assert_eq!(chrome_runs(&h), 0, "idle frame {frame} runs none of the picker's components: {:?}", last_pass_runs(&h.ctx)); } assert!(h.query_all_by_role(Role::Slider).any(|n| n.accesskit_node().label().is_some_and(|label| label.starts_with("Size")))); diff --git a/crates/ui-egui/src/brush_resize_overlay_tests.rs b/crates/ui-egui/src/brush_resize_overlay_tests.rs index 16a746187c..932a6e97fd 100644 --- a/crates/ui-egui/src/brush_resize_overlay_tests.rs +++ b/crates/ui-egui/src/brush_resize_overlay_tests.rs @@ -15,7 +15,7 @@ fn harness() -> Harness<'static, Box> { app.sync_views(); let mut h = Harness::builder().with_context(app.ctx().clone()).with_size(vec2(900.0, 600.0)).build_app( |ui, app: &mut PhotocraftApp| { - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); }, app, ); diff --git a/crates/ui-egui/src/brush_settle_trials.rs b/crates/ui-egui/src/brush_settle_trials.rs index 43a83c247d..1074ca244b 100644 --- a/crates/ui-egui/src/brush_settle_trials.rs +++ b/crates/ui-egui/src/brush_settle_trials.rs @@ -8,16 +8,17 @@ use egui_kittest::Harness; use serde_json::json; use crate::PhotocraftApp; +use crate::chrome_settle_trials::{ShellSlot, slot_runs}; use crate::state::Tool; type H = Harness<'static, Box>; -/// How the memoized view whose props type is named `props` took part in the last pass. A view inside the options bar's -/// own view (`region_versions::OptionsSlot`) is not decided when that view replays: it replays with it. +/// How the memoized view whose props type is named `props` took part in the last pass. A view inside the options bar is +/// not decided when the shell's options slot replays: it replays with it. fn run_of(h: &H, props: &str) -> Option { let runs = last_pass_memo_runs(&h.ctx); let own = runs.iter().find(|(name, _, _)| name.contains(props)).map(|(_, _, run)| *run); - own.or_else(|| runs.iter().any(|(name, _, run)| name.contains("OptionsSlot<") && *run == MemoRun::Replayed).then_some(MemoRun::Replayed)) + own.or_else(|| (slot_runs(&runs, ShellSlot::Options) == (0, 1)).then_some(MemoRun::Replayed)) } #[test] diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index f2c04a7201..8261324fde 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -177,6 +177,10 @@ pub fn canvas_view( primary: bool, ) -> (View, craft::ui::canvas::CanvasOutput) { let ctx = ui.ctx().clone(); + // What the canvas shows follows the pointer (the tool's cursor, the rulers' marks, the Info panel and status bar + // readouts), so every pointer move over it runs a pass; elsewhere a move that changes nothing runs none (#17148). + let on_screen = ctx.layer_transform_to_global(ui.layer_id()).map_or(rect, |to_screen| to_screen * rect); + craft::ui::runtime::pointer::follows_pointer(&ctx, on_screen); let idx = host.idx; // The primary canvas keeps its view in `app.ui.views`: the pass starts from the stored view and stores the one it // ends with, unless something stored another view while the pass ran (a tool's commit that moved it), which then @@ -206,14 +210,6 @@ pub fn canvas_view( // A document switched while a button is down ends the gesture of the document it began on. tools::end_foreign_gesture(app, &ctx, doc.id.0); } - // Pen pressure/tilt for this frame's tool events (mouse = 1.0), unless Preferences › Tools › Use Tablet Pressure - // is off; the pen's eraser end selects the Eraser. - app.stylus.use_pressure = app.session.prefs().tools.use_tablet_pressure; - let curve = app.session.prefs().tools.pressure_curve.clone(); - app.stylus.set_pressure_curve(&curve); - crate::stylus::Stylus::sync_eraser_tool(app); - // A Properties Levels/Curves eyedropper left behind by a tool or layer switch is dropped. - crate::layer_picker::prune(app); let flip = app.ui.view.flip_horizontal; let pass = document_display::CanvasPass { ctx: &ctx, host, doc: &doc, output, rect, ppp, flip, aspect }; let shown = document_display::show(app, ui, &mut view, &pass); @@ -241,12 +237,18 @@ mod pattern_drag_tests; #[cfg(test)] mod tabs_tests; +#[cfg(test)] +mod canvas_settle_trials; + #[cfg(test)] mod doc_window_dialog_tests; #[cfg(test)] mod document_window_title_tests; +#[cfg(test)] +mod arrange_window_origin_tests; + #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/canvas/arrange_keeps_zoom_tests.rs b/crates/ui-egui/src/canvas/arrange_keeps_zoom_tests.rs new file mode 100644 index 0000000000..252422abf5 --- /dev/null +++ b/crates/ui-egui/src/canvas/arrange_keeps_zoom_tests.rs @@ -0,0 +1,105 @@ +//! #16885: Window › Arrange's n-up and Tile layouts keep each document's zoom and view centre instead of fitting every +//! document to its new pane. + +use egui_kittest::Harness; +use serde_json::json; + +use super::{PhotocraftApp, document_area}; + +type Area = Harness<'static, (Box, bool)>; + +/// Documents of different sizes, each larger than any pane, so fitting them would give each a zoom of its own below +/// 100 %. +const SIZES: [(u32, u32); 6] = [(1600, 1200), (1200, 1600), (2000, 900), (900, 900), (1400, 1000), (1000, 1400)]; + +/// The document area showing `count` documents, after their first passes placed their views. +fn area(count: usize) -> Area { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + for (i, (width, height)) in SIZES.iter().take(count).enumerate() { + app.run("file.new", json!({"width": width, "height": height, "name": format!("doc {i}")})).unwrap(); + } + app.sync_views(); + let mut h = Harness::builder().with_size(egui::vec2(900.0, 700.0)).with_context(app.ctx().clone()).build_ui_state( + |ui, (app, ready): &mut (Box, bool)| { + if *ready { + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| document_area(app, ui)); + } + }, + (app, false), + ); + h.state_mut().1 = true; + h.run_steps(4); + h +} + +fn set_zoom(h: &mut Area, doc: usize, zoom: f32) { + let view = &mut h.state_mut().0.ui.views[doc]; + view.zoom = zoom; + view.clear_pending(); +} + +fn arrange(h: &mut Area, layout: &str) { + let ctx = h.ctx.clone(); + crate::menus::invoke(&mut h.state_mut().0, &ctx, &format!("window.arrange.{layout}"), json!({})).unwrap(); + h.run_steps(4); +} + +/// Each view's zoom and the document point at its centre. +fn cameras(h: &Area) -> Vec<(f32, [f32; 2])> { + h.state().0.ui.views.iter().map(|view| (view.zoom, view.center)).collect() +} + +fn assert_kept(before: &[(f32, [f32; 2])], after: &[(f32, [f32; 2])], what: &str) { + assert_eq!(before.len(), after.len(), "{what}: every document keeps its view"); + for (d, ((zoom, center), (now, now_center))) in before.iter().zip(after).enumerate() { + assert!((zoom - now).abs() < 1e-4, "{what}: document {d} keeps its zoom {zoom}, not {now}"); + let moved = (center[0] - now_center[0]).hypot(center[1] - now_center[1]); + assert!(moved < 1e-2, "{what}: document {d} keeps its view centre {center:?}, not {now_center:?}"); + } +} + +#[test] +fn every_layout_keeps_each_document_at_100_percent_and_centred() { + let layouts = [ + "twoUpVertical", + "twoUpHorizontal", + "threeUpVertical", + "threeUpHorizontal", + "threeUpStacked", + "fourUp", + "sixUp", + "tile", + "tileAllVertically", + "tileAllHorizontally", + ]; + for layout in layouts { + let mut h = area(SIZES.len()); + for doc in 0..SIZES.len() { + set_zoom(&mut h, doc, 1.0); + } + h.run_steps(3); + let before = cameras(&h); + let active = h.state().0.session.active_index(); + arrange(&mut h, layout); + // Tile All Vertically / Horizontally dock as an arrangement only once the framework does (#16665); until then + // they float the documents, which never fitted them either. + if !layout.starts_with("tileAll") { + assert!(h.state().0.ui.document_windows.arrangement.is_some(), "{layout} arranges the document area"); + } + assert_kept(&before, &cameras(&h), layout); + assert_eq!(h.state().0.session.active_index(), active, "{layout} keeps the active document"); + } +} + +#[test] +fn a_zoomed_document_keeps_its_zoom_through_a_layout_and_back_to_tabs() { + let mut h = area(2); + set_zoom(&mut h, 0, 3.0); + h.run_steps(3); + let before = cameras(&h); + arrange(&mut h, "twoUpVertical"); + assert_kept(&before, &cameras(&h), "2-up Vertical"); + arrange(&mut h, "consolidateAllToTabs"); + assert!(h.state().0.ui.document_windows.arrangement.is_none(), "the tabs are back"); + assert_kept(&before, &cameras(&h), "Consolidate All to Tabs"); +} diff --git a/crates/ui-egui/src/canvas/arrange_window_origin_tests.rs b/crates/ui-egui/src/canvas/arrange_window_origin_tests.rs new file mode 100644 index 0000000000..f55fd61e61 --- /dev/null +++ b/crates/ui-egui/src/canvas/arrange_window_origin_tests.rs @@ -0,0 +1,281 @@ +//! #16883: Window › Arrange opens a floating document window over the app window's document area. The document +//! area is the app window's own rect, in the app window's own points; the place a window opens at is a rect on the +//! desktop. Every test here stands the app window away from the screen's origin, so the two differ, and builds the +//! expected places from the app's own geometry: the window's rect as the host reports it and the document area the +//! app drew in its last pass. + +use egui::{Context, Pos2, Rect, ViewportId, ViewportIdMap, ViewportInfo}; +use serde_json::json; + +use crate::PhotocraftApp; + +/// The app window as the host reports it: 1000 x 720 desktop points, its top-left far from the screen's origin, as +/// the reference measurement of #16883 had it (the app window at 816, 414). +fn app_window() -> Rect { + Rect::from_min_size(Pos2::new(760.0, 300.0), egui::vec2(1000.0, 720.0)) +} + +/// One pass in the order eframe runs them (`logic` before `ui`), with the app window reported at `window` on the +/// desktop, or with no rect reported at all when `window` is `None`, and `scale` pixels per point. +fn pass(app: &mut PhotocraftApp, ctx: &Context, window: Option, scale: f32) { + use eframe::App as _; + let local = Rect::from_min_size(Pos2::ZERO, window.unwrap_or_else(app_window).size()); + let mut viewports = ViewportIdMap::default(); + // egui needs the ROOT entry either way; without a rect the host has told the app nothing about where its window + // stands, which is the case before the first pass and on the fallback layer. + viewports.insert( + ViewportId::ROOT, + match window { + Some(window) => ViewportInfo { + inner_rect: Some(window), + outer_rect: Some(window), + focused: Some(true), + native_pixels_per_point: Some(scale), + minimized: Some(false), + ..Default::default() + }, + None => ViewportInfo { focused: Some(true), native_pixels_per_point: Some(scale), ..Default::default() }, + }, + ); + let mut input = egui::RawInput { viewport_id: ViewportId::ROOT, screen_rect: Some(local), viewports, focused: true, ..Default::default() }; + app.raw_input_hook(ctx, &mut input); + let mut frame = eframe::Frame::_new_kittest(); + let mut output = ctx.run_ui(input, |ui| { + app.logic(ui.ctx(), &mut frame); + app.ui(ui, &mut frame); + }); + output.textures_delta.clear(); +} + +/// The app with `documents` documents, its window standing at `window` on the desktop (nowhere reported when +/// `window` is `None`) at `scale`, through the passes that lay the document area out. Document windows open as OS +/// windows of their own, as the desktop integration runs them. +fn desktop(documents: usize, window: Option, scale: f32) -> (Box, Context) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + for i in 0..documents { + app.run("file.new", json!({ "width": 300 + 40 * i as u32, "height": 220, "name": format!("doc {i}") })).unwrap(); + } + app.sync_views(); + let ctx = app.ctx().clone(); + PhotocraftApp::setup_context(&ctx, Default::default()); + ctx.set_embed_viewports(false); + for _ in 0..3 { + pass(&mut app, &ctx, window, scale); + } + (app, ctx) +} + +/// Runs an Arrange command and returns the floating windows it left, in order. +fn arranged(app: &mut PhotocraftApp, ctx: &Context, command: &str, params: serde_json::Value) -> Result { + crate::menus::invoke(app, ctx, &format!("window.arrange.{command}"), params) +} + +/// The windows' rects on the desktop, in the order the app lists its floating windows. +fn placed(app: &PhotocraftApp) -> Vec { + app.ui.document_windows.floating.iter().map(|(_, rect)| *rect).collect() +} + +/// The document area where the app window stands: the rect the app drew its canvas in, moved from the app window's +/// own points into desktop points. +fn area_on_desktop(app: &PhotocraftApp, window: Rect) -> Rect { + Rect::from_min_size(app.last_canvas_rect.min + window.min.to_vec2(), app.last_canvas_rect.size()) +} + +/// The passes placed a document area of their own inside the app window: the tests compare against that rect, not a +/// literal one, so they read what the app really has. +fn assert_real_document_area(app: &PhotocraftApp, window: Rect) { + let canvas = app.last_canvas_rect; + assert!(canvas.is_positive(), "the passes laid out a document area: {canvas:?}"); + let local = Rect::from_min_size(Pos2::ZERO, window.size()); + assert!(local.contains(canvas.min) && local.contains(canvas.max), "the document area is in the app window's own points: {canvas:?} in {local:?}"); + assert!(canvas.width() < window.width() && canvas.height() < window.height(), "the document area is part of the window, not all of it: {canvas:?}"); +} + +#[test] +fn float_in_window_opens_its_window_over_the_document_area() { + let window = app_window(); + let (mut app, ctx) = desktop(1, Some(window), 1.0); + assert_real_document_area(&app, window); + let area = area_on_desktop(&app, window); + arranged(&mut app, &ctx, "floatInWindow", json!({})).expect("the active document floats"); + let windows = placed(&app); + let first = windows.last().copied().expect("one floating window"); + assert_eq!(windows.len(), 1, "one window for the one document"); + assert!((first.min - area.min).length() < 0.5, "the window opens at the document area's top-left on the desktop: {first:?}, the area is {area:?}"); + assert!(area.contains(first.min), "so its top-left lies over the document area: {first:?} in {area:?}"); + assert!((first.size() - area.size() * 0.5).length() < 0.5, "the window still takes half the document area: {first:?} of {area:?}"); + assert!( + (first.min - app.last_canvas_rect.min).length() > 100.0, + "the document area's own points are not a desktop place: {first:?} against the window's own {area:?}" + ); +} + +#[test] +fn float_all_in_windows_cascades_from_the_document_area() { + let window = app_window(); + let (mut app, ctx) = desktop(3, Some(window), 1.0); + assert_real_document_area(&app, window); + let area = area_on_desktop(&app, window); + arranged(&mut app, &ctx, "floatAllInWindows", json!({})).expect("every document gets a window"); + let windows = placed(&app); + assert_eq!(windows.len(), 3, "one window per document"); + assert!((windows[0].min - area.min).length() < 0.5, "the first window at the document area's top-left: {windows:?}, the area is {area:?}"); + for pair in windows.windows(2) { + let (before, next) = (pair[0], pair[1]); + assert!(next.min.x > before.min.x && next.min.y > before.min.y, "each next window steps down and across: {before:?} then {next:?}"); + assert!(area.contains(next.min), "and opens over the document area: {next:?} in {area:?}"); + } + assert!(windows.iter().all(|rect| (rect.size() - area.size() * 0.5).length() < 0.5), "every window takes half the document area: {windows:?}"); +} + +#[test] +fn new_window_for_document_opens_over_the_document_area() { + let window = app_window(); + let (mut app, ctx) = desktop(1, Some(window), 1.0); + let area = area_on_desktop(&app, window); + arranged(&mut app, &ctx, "newWindowForDocument", json!({})).expect("a second view opens"); + let windows = placed(&app); + assert_eq!(windows.len(), 1, "one new window"); + assert!((windows[0].min - area.min).length() < 0.5, "the second view opens at the document area's top-left: {windows:?}, the area is {area:?}"); + assert!(area.contains(windows[0].min), "so it lies over the document area: {windows:?} in {area:?}"); +} + +/// The point a torn-off tab was released at is a point of the app window; the window it opens stands on the desktop +/// under that same point. +#[test] +fn a_tab_dropped_off_the_strip_opens_its_window_where_it_was_dropped() { + let window = app_window(); + let (mut app, ctx) = desktop(2, Some(window), 1.0); + assert_real_document_area(&app, window); + let document = app.session.documents()[1].doc.id; + let dropped = app.last_canvas_rect.min + egui::vec2(30.0, 12.0); + arranged(&mut app, &ctx, "floatInWindow", json!({ "document": document.0, "position": [dropped.x, dropped.y] })).expect("the torn-off tab floats"); + let windows = placed(&app); + assert_eq!(windows.len(), 1, "the drop opened one window"); + let want = dropped + window.min.to_vec2(); + assert!((windows[0].min - want).length() < 0.5, "the window opens under the point the tab was dropped at: {:?}, want {want:?}", windows[0]); +} + +#[test] +fn cascade_moves_every_window_into_the_document_area() { + let window = app_window(); + let (mut app, ctx) = desktop(3, Some(window), 1.0); + let area = area_on_desktop(&app, window); + arranged(&mut app, &ctx, "floatAllInWindows", json!({})).expect("every document gets a window"); + // One window the user dragged off the document area: Cascade brings it back, as it did before. + let size = app.ui.document_windows.floating[0].1.size(); + app.ui.document_windows.floating[0].1 = Rect::from_min_size(Pos2::new(2400.0, 1800.0), size); + arranged(&mut app, &ctx, "cascade", json!({})).expect("cascade runs"); + let windows = placed(&app); + assert!((windows[0].min - area.min).length() < 0.5, "the cascade starts at the document area's top-left: {windows:?}, the area is {area:?}"); + assert!(windows.iter().all(|rect| area.contains(rect.min)), "and every window lands over the document area: {windows:?} in {area:?}"); +} + +/// The docked layouts work in the app window's own points: a floating window's desktop place must not move the +/// document area the app draws in. +#[test] +fn the_docked_layouts_keep_the_window_s_own_document_area() { + let window = app_window(); + let (mut app, ctx) = desktop(2, Some(window), 1.0); + assert_real_document_area(&app, window); + let canvas = app.last_canvas_rect; + arranged(&mut app, &ctx, "twoUpVertical", json!({})).expect("2-up Vertical arranges the panes"); + assert_eq!(app.last_canvas_rect, canvas, "the layout leaves the app window's own document rect alone"); + let panes = crate::canvas::arranged_cells(&app, app.last_canvas_rect).expect("two panes"); + assert_eq!(panes.len(), 2, "one pane per document"); + for (document, pane) in &panes { + assert!(canvas.contains(pane.min) && canvas.contains(pane.max), "pane {document} stays inside the window's own points: {pane:?} in {canvas:?}"); + } + arranged(&mut app, &ctx, "floatInWindow", json!({})).expect("the active document floats"); + let windows = placed(&app); + let first = windows.last().copied().expect("the floated window"); + assert!(area_on_desktop(&app, window).contains(first.min), "the floated window still opens over the document area: {first:?}"); + assert_eq!(app.last_canvas_rect, canvas, "and the document area did not move"); +} + +/// With no document open the app shows its empty desktop: no Arrange command opens a window there, and the desktop's +/// own layout is left as it is. +#[test] +fn an_empty_desktop_opens_no_window_and_keeps_its_layout() { + let window = app_window(); + let (mut app, ctx) = desktop(0, Some(window), 1.0); + let canvas = app.last_canvas_rect; + arranged(&mut app, &ctx, "floatInWindow", json!({})).expect("Float in Window over an empty desktop runs the framework arrangement"); + assert!(arranged(&mut app, &ctx, "floatInWindow", json!({ "position": [300.0, 200.0] })).is_err(), "a drop with no document behind it is refused"); + for command in ["floatAllInWindows", "newWindowForDocument", "cascade", "tile", "tileAllVertically"] { + let _ = arranged(&mut app, &ctx, command, json!({})); + } + assert!(app.ui.document_windows.floating.is_empty(), "no window opened over the empty desktop: {:?}", placed(&app)); + assert!(app.ui.document_windows.docked.is_empty(), "and no document group appeared"); + pass(&mut app, &ctx, Some(window), 1.0); + assert_eq!(app.last_canvas_rect, canvas, "the empty desktop keeps the layout it had"); +} + +/// Where the app window stands at the screen's origin its own points are desktop points: placement is what it was. +#[test] +fn a_window_at_the_screen_origin_places_where_it_always_did() { + let window = Rect::from_min_size(Pos2::ZERO, egui::vec2(1000.0, 720.0)); + let (mut app, ctx) = desktop(1, Some(window), 1.0); + assert_real_document_area(&app, window); + arranged(&mut app, &ctx, "floatInWindow", json!({})).expect("the active document floats"); + let first = placed(&app).pop().expect("one floating window"); + assert!((first.min - app.last_canvas_rect.min).length() < 0.5, "at the origin the window opens at the document area's own rect: {first:?}"); +} + +/// The desktop place is known once the host reports the app window's rect. Before that, and on the fallback layer +/// with no OS windows, the document area's own points are used as they are today. +#[test] +fn an_app_that_has_not_reported_its_place_keeps_todays_placement() { + let (mut app, ctx) = desktop(1, None, 1.0); + assert_real_document_area(&app, app_window()); + arranged(&mut app, &ctx, "floatInWindow", json!({})).expect("the active document floats"); + let first = placed(&app).pop().expect("one floating window"); + assert!((first.min - app.last_canvas_rect.min).length() < 0.5, "with no rect reported the window opens where the document area is: {first:?}"); +} + +/// Where the host opens no OS window (egui embeds the viewports, as in the web build), the document window shows on +/// the framework's fallback layer inside the app window: its rect stays one of the app window's own points, and the +/// app window's desktop place is not added. +#[test] +fn a_document_window_on_the_fallback_layer_keeps_the_app_window_s_own_points() { + let window = app_window(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({ "width": 300, "height": 220, "name": "fallback.png" })).unwrap(); + app.sync_views(); + let ctx = app.ctx().clone(); + PhotocraftApp::setup_context(&ctx, Default::default()); + assert!(!craft::ui::runtime::windows::WindowHost::of(&ctx).viewports_available(), "this host opens no OS window of its own"); + for _ in 0..3 { + pass(&mut app, &ctx, Some(window), 1.0); + } + assert_real_document_area(&app, window); + arranged(&mut app, &ctx, "floatInWindow", json!({})).expect("the active document floats"); + let first = placed(&app).pop().expect("one floating window"); + assert!( + (first.min - app.last_canvas_rect.min).length() < 0.5, + "the fallback layer keeps the app window's own points: {first:?} in {:?}", + app.last_canvas_rect + ); +} + +/// The rule is in points, the unit the app window's rect and the document area are both reported in: the same place +/// at 100 %, 125 % and 200 % display scale. +#[test] +fn the_document_area_rule_holds_at_100_125_and_200_percent_scale() { + let window = app_window(); + let mut places: Vec = Vec::new(); + for scale in [1.0_f32, 1.25, 2.0] { + let (mut app, ctx) = desktop(1, Some(window), scale); + let area = area_on_desktop(&app, window); + assert!((area.min.x - (app.last_canvas_rect.min.x + window.min.x)).abs() < 0.5, "the area maps at {scale}: {area:?}"); + arranged(&mut app, &ctx, "floatInWindow", json!({})).expect("the active document floats"); + let first = placed(&app).pop().expect("one floating window"); + assert!((first.min - area.min).length() < 0.5, "at {scale} the window opens at the document area's top-left: {first:?}, the area is {area:?}"); + assert!((first.size() - area.size() * 0.5).length() < 0.5, "at {scale} the window's size is the same in points: {first:?} of {area:?}"); + places.push(first); + } + assert_eq!(places.len(), 3, "one place per scale"); + for pair in places.windows(2) { + assert!((pair[0].min - pair[1].min).length() < 0.5, "the scale does not move the window's place in points: {pair:?}"); + } +} diff --git a/crates/ui-egui/src/canvas/background_redraw.rs b/crates/ui-egui/src/canvas/background_redraw.rs index d0ab02fec9..2728a14af3 100644 --- a/crates/ui-egui/src/canvas/background_redraw.rs +++ b/crates/ui-egui/src/canvas/background_redraw.rs @@ -355,11 +355,22 @@ pub(crate) fn restart(app: &mut PhotocraftApp, ctx: &egui::Context, gpu: &GpuCan /// Upload the blocks document `doc`'s redraw has finished since the last frame. When the last one /// lands, the redraw is recorded like the synchronous refresh it replaces (and explained once if /// it was slow). +/// Lands every running redraw's finished blocks: the document area's host work (`canvas::document_area`), run every +/// pass before the area's view, so blocks land while the view replays. +pub(crate) fn poll_all(app: &mut PhotocraftApp) { + let Some(gpu) = app.gpu.clone() else { return }; + let docs: Vec = app.redraws.keys().copied().collect(); + for doc in docs { + poll(app, &gpu, doc); + } +} + pub(crate) fn poll(app: &mut PhotocraftApp, gpu: &GpuCanvas, doc: DocId) { let gamma = text_gamma(app); let Some(r) = app.redraws.get_mut(&doc) else { return }; r.forget_if_gamma_changed(gamma); - loop { + let mut landed = 0; + let finished = loop { match r.rx.try_recv() { Ok(p) => { let b = r.blocks[p.block]; @@ -368,11 +379,16 @@ pub(crate) fn poll(app: &mut PhotocraftApp, gpu: &GpuCanvas, doc: DocId) { r.left -= 1; r.drawn += b.width() as u64 * b.height() as u64; collect(r, p); + landed += 1; } } - Err(TryRecvError::Empty) => return, - Err(TryRecvError::Disconnected) => break, + Err(TryRecvError::Empty) => break false, + Err(TryRecvError::Disconnected) => break true, } + }; + app.redraw_landed += landed; + if !finished { + return; } let Some(mut r) = app.redraws.remove(&doc) else { return }; if r.left > 0 { diff --git a/crates/ui-egui/src/canvas/canvas_settle_trials.rs b/crates/ui-egui/src/canvas/canvas_settle_trials.rs new file mode 100644 index 0000000000..b211e89862 --- /dev/null +++ b/crates/ui-egui/src/canvas/canvas_settle_trials.rs @@ -0,0 +1,123 @@ +//! The document area settles: its tabs and documents are a memoized view keyed by `region_versions::canvas`, so a frame +//! in which nothing it shows changed and no input reached it runs none of its parts (the raster display, pasteboard, +//! scroll bars and tab strip); each repaints its last run. What it shows runs it again: a document edit, a view command +//! queued for its next pass, a redraw block landed. + +use craft::ui::runtime::measure::{MemoRun, last_frame_memo_runs, last_pass_runs}; +use egui::{Event, vec2}; +use egui_kittest::Harness; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::panels::region_versions; + +type H = Harness<'static, Box>; + +/// The canvas's parts: the components a run of the document area shows for a settled document. +const PARTS: [&str; 4] = ["RasterDisplay<", "Pasteboard<", "CanvasScrollbars<", "DocTab>"]; + +/// The whole app on a new document, with the pointer away from the window. +fn harness() -> H { + let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_max_steps(64).with_step_dt(1.0 / 60.0).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); + PhotocraftApp::with_context(cc.egui_ctx.clone(), session, crate::Services::default()) + }); + h.run_steps(8); + h.event(Event::PointerGone); + h.run_steps(4); + h +} + +/// The document area's view in the last frame: (ran, replayed). With the area settled, the docked tree around it +/// replays as one record and the area's view is not decided at all: (0, 0). +fn area(h: &H) -> (usize, usize) { + let runs = last_frame_memo_runs(&h.ctx); + let count = |how| runs.iter().filter(|(ty, _, run)| ty.contains("region_versions::CanvasSlot<") && *run == how).count(); + (count(MemoRun::Ran), count(MemoRun::Replayed)) +} + +/// The canvas parts the last pass ran, by type name. +fn part_runs(h: &H) -> Vec<(&'static str, u32)> { + last_pass_runs(&h.ctx).into_iter().filter(|(ty, _)| PARTS.iter().any(|part| ty.contains(part))).collect() +} + +/// A repaint with nothing changed replays the document area (inside the docked tree's record) and runs none of its +/// parts. +#[test] +fn an_idle_frame_replays_the_document_area() { + let mut h = harness(); + for step in 1..=3 { + h.ctx.request_repaint(); + h.run_steps(1); + assert_eq!(area(&h).0, 0, "idle step {step}: the document area replays"); + assert_eq!(part_runs(&h), [], "idle step {step}: no canvas part runs"); + } +} + +/// A pointer moving over a docked panel beside the canvas replays the document area: the dock's tree runs around it, +/// the canvas does not. +#[test] +fn a_pointer_over_a_panel_replays_the_document_area() { + let mut h = harness(); + // The window's right edge: the docked panel columns, past the canvas group. + let canvas = h.state().last_canvas_rect; + let beside = egui::pos2(1440.0 - 20.0, canvas.center().y); + h.event(Event::PointerMoved(beside)); + h.run_steps(2); + for step in 1..=3 { + h.event(Event::PointerMoved(beside + vec2(0.0, step as f32))); + h.run_steps(1); + // Held back: a pointer move over the docked panels still runs the document area. Two reads in the canvas + // note the pointer on every run: craft-ui-canvas's `ToolHost::run` (`pointer::frame`, for the tools' hover + // position) and `Canvas::autoscroll` (`pointer::frame`, for a press or the pointer leaving during a middle-button + // run). Turn these on once neither notes the pointer while it is away from the canvas. + // assert_eq!(area(&h).0, 0, "hover step {step}: the document area replays"); + // assert_eq!(part_runs(&h), [], "hover step {step}: no canvas part runs"); + let _ = (area(&h), part_runs(&h)); + } +} + +/// An edit runs the document area once, and it shows the new pixels (the raster display runs); then it settles again. +#[test] +fn a_document_edit_runs_the_document_area() { + let mut h = harness(); + h.state_mut().run("edit.fill", json!({"color": "#808080"})).unwrap(); + h.run_steps(1); + assert!(area(&h).0 >= 1, "the edit runs the document area"); + assert!(part_runs(&h).iter().any(|(ty, _)| ty.contains("RasterDisplay<")), "the raster display shows the edit: {:?}", part_runs(&h)); + h.run_steps(3); + assert_eq!(area(&h).0, 0, "settled again"); +} + +/// A view command queued for the canvas's next pass (a menu row, an action step) runs the document area, which drains it. +#[test] +fn a_queued_view_command_runs_the_document_area() { + let mut h = harness(); + h.state_mut().ui.views[0].request(craft::ui::canvas::ViewCommands::ZoomIn); + h.run_steps(1); + assert!(area(&h).0 >= 1, "the queued command runs the document area"); + assert!(h.state().ui.views[0].pending.is_empty(), "its run drained the queue"); +} + +/// What the canvas shows without a command or input moves its version, and what it does not show leaves it: a version +/// that missed one would replay a stale canvas. +#[test] +fn what_the_canvas_shows_moves_its_version() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + let moved = |app: &mut PhotocraftApp, change: &dyn Fn(&mut PhotocraftApp)| { + let before = region_versions::canvas(app); + change(app); + region_versions::canvas(app) != before + }; + assert!(!moved(&mut app, &|_| {}), "the same state settles"); + assert!(moved(&mut app, &|app| app.ui.views[0].center[0] += 4.0), "a pan"); + assert!(moved(&mut app, &|app| app.ui.views[0].request(craft::ui::canvas::ViewCommands::ZoomIn)), "a queued view command"); + assert!(moved(&mut app, &|app| app.redraw_landed += 1), "a redraw block landed"); + assert!(moved(&mut app, &|app| app.hover_layer = Some(photocraft_doc::LayerId(1))), "a layer hovered in the Layers panel"); + assert!(moved(&mut app, &|app| app.live_adjust = Some((photocraft_doc::LayerId(1), json!({"brightness": 10})))), "an adjustment's live preview"); + assert!(moved(&mut app, &|app| app.ui.tool_options.fill_opacity = 50.0), "a tool option"); + assert!(!moved(&mut app, &|app| app.hover_doc = Some([3.0, 4.0])), "the pointer's document point, which the canvas does not draw"); +} diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu.rs b/crates/ui-egui/src/canvas/canvas_tool_menu.rs index ff45431f9a..810aec8d19 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu.rs @@ -691,6 +691,32 @@ pub const COUNT_MENU: &[Row] = &[ /// Right-click with the Content-Aware Move tool inside an active selection (#12194). pub const CAM_INSIDE_SELECTION_MENU: &[Row] = &[Some(("Color Range…", "select.colorRange")), Some(("Load Selection…", "select.loadSelection"))]; +/// The Patch tool's rows (#12122). Use Pattern stays greyed: the Patch tool has no pattern mode yet. +pub const PATCH_USE_PATTERN: &str = "canvasMenu.patch.usePattern"; +pub const PATCH_SOURCE: &str = "canvasMenu.patch.source"; +pub const PATCH_DESTINATION: &str = "canvasMenu.patch.destination"; + +/// Right-click with the Patch tool inside the active selection, in the reference application's +/// order (#12122). Outside it the Patch tool opens the Lasso's selection menu. +pub const PATCH_INSIDE_SELECTION_MENU: &[Row] = &[ + Some(("Use Pattern to Patch Selection", PATCH_USE_PATTERN)), + None, + Some(("Use Patch as Source", PATCH_SOURCE)), + Some(("Use Patch as Destination", PATCH_DESTINATION)), + None, + Some(("Color Range…", "select.colorRange")), + Some(("Load Selection…", "select.loadSelection")), +]; + +/// The options bar's Patch mode a row sets: `source` or `destination`. +fn patch_mode(command: &str) -> Option<&'static str> { + match command { + PATCH_SOURCE => Some("source"), + PATCH_DESTINATION => Some("destination"), + _ => None, + } +} + /// The selection menu as measured in the reference application with the Red Eye tool (#12577), /// the Object Selection tool (#12866) and the Horizontal Type tool away from text (#12042): no /// Distort or Perspective, and Delete and Fill Selection after the fills. @@ -1001,9 +1027,16 @@ fn sampler_menu(menu: &CanvasToolMenu) -> bool { menu.tool == Tool::ColorSampler && menu.kind == MenuKind::Tool } -/// Is `menu` the Content-Aware Move tool's menu opened inside the active selection (#12194)? +/// Do `tool`'s menu rows depend on whether the right-click is inside the selection: Content-Aware +/// Move (#12194) and Patch (#12122)? +fn splits_at_selection(tool: Tool) -> bool { + matches!(tool, Tool::ContentAwareMove | Tool::Patch) +} + +/// Is `menu` the Content-Aware Move (#12194) or Patch (#12122) tool's menu opened inside the +/// active selection? pub fn inside_selection(menu: &CanvasToolMenu) -> bool { - menu.tool == Tool::ContentAwareMove && menu.kind == MenuKind::Tool && menu.has_selection && menu.inside_selection + splits_at_selection(menu.tool) && menu.kind == MenuKind::Tool && menu.has_selection && menu.inside_selection } /// Content-Aware Move's canvas context menu requires an open document and leaves Bitmap, Duotone @@ -1068,6 +1101,8 @@ pub fn applies(tool: Tool) -> bool { // Sample Size and Copy Color (#11747). | Tool::Eyedropper | Tool::ContentAwareMove + // The patch rows inside the selection, the selection menu outside it (#12122). + | Tool::Patch // The layer or selection menu, where measured (#12577). | Tool::RedEye ) || path_menu(tool) @@ -1234,7 +1269,7 @@ pub fn rows(menu: &CanvasToolMenu) -> &'static [Row] { } else if menu.tool == Tool::Eyedropper { EYEDROPPER_MENU } else if inside_selection(menu) { - CAM_INSIDE_SELECTION_MENU + if menu.tool == Tool::Patch { PATCH_INSIDE_SELECTION_MENU } else { CAM_INSIDE_SELECTION_MENU } } else { selection_rows(menu.has_selection) } @@ -1497,8 +1532,12 @@ pub fn entry_enabled(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) if sampler_menu(menu) { return command == SAMPLER_DELETE && menu.sampler.is_some() && sampler_current(app, menu); } - // Inside the Content-Aware Move selection menu (#12194), Load Selection… stays greyed until a - // selection channel (non-spot alpha channel) has been saved. + // The Patch mode rows set the options bar's mode; Use Pattern waits for a pattern patch (#12122). + if menu.tool == Tool::Patch && (patch_mode(command).is_some() || command == PATCH_USE_PATTERN) { + return inside_selection(menu) && patch_mode(command).is_some(); + } + // Inside the Content-Aware Move (#12194) and Patch (#12122) selection menus, Load Selection… + // stays greyed until a selection channel (non-spot alpha channel) has been saved. if inside_selection(menu) && command == "select.loadSelection" { return app.session.active().is_some_and(|st| st.doc.channels.iter().any(|c| c.spot.is_none())) && crate::menus::is_enabled(app, command); } @@ -1716,7 +1755,7 @@ fn capture(app: &mut PhotocraftApp, menu: &mut CanvasToolMenu, doc: [f64; 2], po // measured configuration heads the menu with the entry (#12915). menu.point = point.filter(|(target, hit)| pen_point_allowed(app, *target, hit)).and_then(|(target, hit)| point_at(app, target, hit)); } - menu.inside_selection = menu.tool == Tool::ContentAwareMove && selected_at(app, doc); + menu.inside_selection = splits_at_selection(menu.tool) && selected_at(app, doc); if menu.tool == Tool::ColorSampler { menu.sampler = crate::analysis::sampler_at(app, doc); // PLAN: assumed name `analysis::sampler_at` (tools-w53) menu.sampler_at = menu.sampler.and_then(|i| Some((app.session.active_index()?, *app.session.active()?.color_samplers.get(i)?))); @@ -1772,6 +1811,11 @@ pub fn choose(app: &mut PhotocraftApp, ctx: &Context, command: &str) { app.run(&id, params).map(|_| ()) } MenuKind::Tool if is_eyedropper(&menu) => choose_eyedropper(app, ctx, &menu, command), + // A Patch mode row sets the options bar's Source / Destination choice (#12122). + MenuKind::Tool if patch_mode(command).is_some() => { + app.ui.tool_options.patch_mode = patch_mode(command).unwrap_or("source").into(); + Ok(()) + } // Photoshop's Make Work Path… asks for the tolerance first. MenuKind::Tool if command == "select.toWorkPath" => { pen_dialogs::open(app, command, ""); @@ -2038,6 +2082,9 @@ mod cam_menu_tests; #[cfg(test)] pub(crate) mod tests; +#[cfg(test)] +mod patch_menu_tests; + #[cfg(test)] #[path = "../task_bar_pasteboard_entry_tests.rs"] mod task_bar_pasteboard_entry_tests; diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu/patch_menu_tests.rs b/crates/ui-egui/src/canvas/canvas_tool_menu/patch_menu_tests.rs new file mode 100644 index 0000000000..e82ffa66ec --- /dev/null +++ b/crates/ui-egui/src/canvas/canvas_tool_menu/patch_menu_tests.rs @@ -0,0 +1,116 @@ +//! #12122: the Patch tool's canvas right-click opens the patch rows inside the selection, the +//! Lasso's selection menu outside it and the selection tools' no-selection menu without one. + +use egui::Modifiers; +use egui_kittest::Harness; +use serde_json::{Value, json}; + +use super::tests::{any_dialog, app, harness, open_here, pick, right_click, screen_of}; +use super::{NO_SELECTION_MENU, PATCH_DESTINATION, PATCH_SOURCE, PATCH_USE_PATTERN, SELECTION_MENU, available}; +use crate::PhotocraftApp; +use crate::state::Tool; + +/// A 32 × 32 document with the selection 4..20 square and `tool` selected. +fn selected(tool: Tool) -> Box { + let mut app = app(); + app.run("select.rect", json!({"x": 4, "y": 4, "width": 16, "height": 16})).unwrap(); + app.ui.tool = tool; + app +} + +/// Right-click document point `doc` with `tool`: the open menu's entries as `ui.inspect` lists them. +fn entries_at(h: &mut Harness<'static, Box>, tool: Tool, doc: [f32; 2]) -> Vec { + h.state_mut().ui.canvas_tool_menu = None; + h.state_mut().ui.tool = tool; + let at = screen_of(h.state(), doc); + right_click(h, at, Modifiers::NONE); + let inspected = crate::control::inspect(h.state(), &h.ctx); + assert_eq!(inspected["canvasToolMenu"]["tool"], json!(format!("{tool:?}")), "{tool:?} opens its menu at {doc:?}"); + inspected["canvasToolMenu"]["entries"].as_array().cloned().unwrap_or_default() +} + +/// The entries' labels, a separator as `None`. +fn shown(entries: &[Value]) -> Vec> { + entries.iter().map(|e| if e["separator"] == json!(true) { None } else { e["label"].as_str().map(String::from) }).collect() +} + +fn enabled(entries: &[Value], label: &str) -> bool { + entries.iter().find(|e| e["label"] == json!(label)).unwrap_or_else(|| panic!("{label} is listed"))["enabled"] == json!(true) +} + +#[test] +fn inside_the_selection_the_patch_rows_show_in_the_reference_order() { + let mut h = harness(selected(Tool::Patch)); + let entries = entries_at(&mut h, Tool::Patch, [12.0, 12.0]); + let want = [ + Some("Use Pattern to Patch Selection"), + None, + Some("Use Patch as Source"), + Some("Use Patch as Destination"), + None, + Some("Color Range…"), + Some("Load Selection…"), + ]; + assert_eq!(shown(&entries), want.map(|l| l.map(String::from))); + assert!(!enabled(&entries, "Use Pattern to Patch Selection"), "no pattern patch exists yet: greyed"); + assert!(enabled(&entries, "Use Patch as Source") && enabled(&entries, "Use Patch as Destination")); + assert!(enabled(&entries, "Color Range…")); + assert!(!enabled(&entries, "Load Selection…"), "no selection saved: greyed"); + + h.state_mut().run("select.saveSelection", json!({"name": "Alpha 1"})).unwrap(); + let entries = entries_at(&mut h, Tool::Patch, [12.0, 12.0]); + assert!(enabled(&entries, "Load Selection…"), "a saved selection makes Load Selection… live"); +} + +#[test] +fn outside_the_selection_the_patch_tool_opens_the_lassos_menu() { + let mut h = harness(selected(Tool::Patch)); + let lasso = entries_at(&mut h, Tool::Lasso, [26.0, 26.0]); + let patch = entries_at(&mut h, Tool::Patch, [26.0, 26.0]); + assert_eq!(shown(&patch), shown(&lasso)); + assert_eq!(patch.iter().map(|e| &e["enabled"]).collect::>(), lasso.iter().map(|e| &e["enabled"]).collect::>()); + assert_eq!(patch.len(), SELECTION_MENU.len(), "the selection menu, nothing added"); +} + +#[test] +fn without_a_selection_the_patch_tool_opens_the_no_selection_menu() { + let mut app = app(); + app.ui.tool = Tool::Patch; + let mut h = harness(app); + let entries = entries_at(&mut h, Tool::Patch, [12.0, 12.0]); + let want: Vec<_> = NO_SELECTION_MENU.iter().map(|row| row.map(|(label, _)| label.to_string())).collect(); + assert_eq!(shown(&entries), want); +} + +#[test] +fn the_mode_rows_set_the_options_bar_mode_and_nothing_else() { + let mut app = selected(Tool::Patch); + assert_eq!(app.ui.tool_options.patch_mode, "source"); + let journal = app.session.journal.len(); + for (row, mode) in [(PATCH_DESTINATION, "destination"), (PATCH_SOURCE, "source")] { + assert!(open_here(&mut app, Tool::Patch, [12.0, 12.0])); + pick(&mut app, row); + assert!(app.ui.canvas_tool_menu.is_none(), "choosing a row closes the menu"); + assert_eq!(app.ui.tool_options.patch_mode, mode); + } + assert_eq!(app.session.journal.len(), journal, "the mode rows run no command"); + assert_eq!(app.ui.tool, Tool::Patch); + + // Use Pattern is greyed, so choosing it does nothing. + assert!(open_here(&mut app, Tool::Patch, [12.0, 12.0])); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert!(!available(&app, &menu, PATCH_USE_PATTERN)); + // Outside the selection the mode rows aren't offered. + assert!(open_here(&mut app, Tool::Patch, [26.0, 26.0])); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert!(!available(&app, &menu, PATCH_DESTINATION)); +} + +#[test] +fn color_range_opens_its_dialog() { + let mut app = selected(Tool::Patch); + assert!(open_here(&mut app, Tool::Patch, [12.0, 12.0])); + pick(&mut app, "select.colorRange"); + assert!(app.ui.canvas_tool_menu.is_none()); + assert!(any_dialog(&app), "Color Range… opens the Color Range dialog"); +} diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu/rectangle_menu_tests.rs b/crates/ui-egui/src/canvas/canvas_tool_menu/rectangle_menu_tests.rs index 1b97c92f61..0074f48834 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu/rectangle_menu_tests.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu/rectangle_menu_tests.rs @@ -77,7 +77,7 @@ fn shape_layer_filled(tool: Tool, filled: bool) -> Box { app.ui.tool_options.shape_fill = filled; app.ui.tool_options.stroke_width = 2.0; let rect = craft::behavior::kurbo::Rect::new(40.0, 40.0, 120.0, 120.0); - let shape = if tool == Tool::Triangle { ShapeGeometry::Triangle { rect } } else { ShapeGeometry::Rect { rect, radii: [0.0; 4] } }; + let shape = if tool == Tool::Triangle { ShapeGeometry::Triangle { rect, corner_radius: 0.0 } } else { ShapeGeometry::Rect { rect, radii: [0.0; 4] } }; crate::vector_ui::create_geometry(&mut app, &shape, crate::vector_ui::kind_of(tool), None).unwrap(); let st = app.session.active().unwrap(); assert_eq!(st.doc.layer(st.active_layer.unwrap()).unwrap().content.kind_name(), "Shape", "{tool:?} made a shape layer"); diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs b/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs index 1ab124000f..b6ef02002e 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs @@ -98,7 +98,7 @@ pub(crate) fn harness(mut app: Box) -> Harness<'static, Box) -> Harness<'static, Box bool { /// Shape tools whose Alt Eyedropper also updates the tool's Fill. pub(super) fn shape_alt_sets_fill(tool: Tool) -> bool { - matches!(tool, Tool::Triangle | Tool::CustomShape | Tool::Rectangle | Tool::EllipseShape | Tool::Polygon) + matches!(tool, Tool::Triangle | Tool::CustomShape | Tool::Rectangle | Tool::EllipseShape | Tool::Polygon | Tool::Star) } -/// Whether an Alt or Shift+Alt press samples the foreground and Fill for the Triangle, Custom Shape, -/// Rectangle, Ellipse and Polygon tools (#13364, #15856, #13333, #13224, #13317). Sampling requires Shape mode, no active shape layer, and a sampleable pixel. -/// Control+Alt is excluded here, as in [`alt_samples`]. +/// Whether an Alt press samples the foreground and Fill for a shape tool. Sampling requires Shape +/// mode, no active shape layer, and a sampleable pixel. The Star keeps Shift+Alt for drawing a +/// constrained shape from the centre. Control+Alt is excluded, as in [`alt_samples`]. pub(crate) fn shape_alt_samples(app: &mut PhotocraftApp, mods: Mods, x: f64, y: f64) -> bool { mods.alt && !mods.ctrl + && (!mods.shift || app.ui.tool != Tool::Star) && shape_alt_sets_fill(app.ui.tool) && app.ui.tool_options.shape_mode == craft::draw::ui::VectorMode::Shape && crate::vector_ui::active_shape_path(app).is_none() @@ -122,9 +123,27 @@ pub(crate) fn alt_loads_mixer(tool: Tool, mods: craft::keymap::Mods) -> bool { mods.alt && !mods.ctrl && tool == Tool::MixerBrush } -/// Whether the Mixer Brush's target layer has Lock All on, so its cursor shows the not-allowed mark. -pub(crate) fn mixer_target_locked(app: &PhotocraftApp) -> bool { - app.session.active().and_then(|st| st.active_layer.and_then(|id| st.doc.layer(id))).is_some_and(|layer| layer.locks.all) +/// Whether the painting tool shows the not-allowed cursor for its current target. +pub(super) fn paint_cursor_blocked(app: &PhotocraftApp) -> bool { + use photocraft_doc::LayerContent; + + let tool = app.ui.tool; + if !matches!(tool, Tool::Brush | Tool::Eraser | Tool::PaintBucket | Tool::MixerBrush) { + return false; + } + let Some(state) = app.session.active() else { return false }; + let Some(path) = state.active_layer.and_then(|id| state.doc.layers.index().path(id)) else { return false }; + let Some(layer) = state.doc.layer_at(path) else { return false }; + if tool == Tool::MixerBrush { + // #11957 checks the active layer's own Lock All for the Mixer Brush. + return layer.locks.all; + } + let blocked = match &layer.content { + LayerContent::Raster(_) => state.doc.locks_at(path).all, + LayerContent::Text(_) => matches!(tool, Tool::Brush | Tool::PaintBucket), + _ => false, + }; + blocked && state.doc.shown_at(path) && crate::brush_refusal::pixels_target(&super::paint_target(app)) } #[cfg(test)] @@ -194,3 +213,7 @@ mod custom_shape_alt_eyedropper_tests; #[cfg(test)] #[path = "magic_eraser_cursor_tests.rs"] mod magic_eraser_cursor_tests; + +#[cfg(test)] +#[path = "locked_layer_cursor_tests.rs"] +mod locked_layer_cursor_tests; diff --git a/crates/ui-egui/src/canvas/document_area.rs b/crates/ui-egui/src/canvas/document_area.rs index ca933f7d4a..3bbcdf823a 100644 --- a/crates/ui-egui/src/canvas/document_area.rs +++ b/crates/ui-egui/src/canvas/document_area.rs @@ -22,7 +22,9 @@ use super::textures::retain_gpu_documents; use super::{PhotocraftApp, canvas_view}; /// The canvas panel with the tab strip and the document, or the Home screen; then drops layers dragged onto another -/// document (`layer_transfer`). +/// document (`layer_transfer`). The tabs and documents are a memoized view keyed by `region_versions::canvas`, and the +/// dock's column around the area replays with that version too: the app work every pass needs ([`each_pass`]) runs +/// outside both, before the window's body. pub fn document_area(app: &mut PhotocraftApp, ui: &mut egui::Ui) { // Files the OS drops on the main window outside the tab strip: the Home screen has no other target (#16588). let dropped = super::window_drop::take(ui, ui.max_rect()); @@ -31,10 +33,19 @@ pub fn document_area(app: &mut PhotocraftApp, ui: &mut egui::Ui) { app.dock_drop_rect = None; // It replaces the canvas too: a file dropped where the canvas was opens, not into the hidden document. app.drop_canvas_rect = None; + app.ui.task_bar_shown = None; } else { crate::distort_ui::drop_foreign(app, ui.ctx()); crate::layer_transfer::prepare(app, ui.ctx()); - documents(app, ui); + if app.home_screen_up() { + // The Home screen hides the tabs: a floating window dropped on it docks nowhere (#16415). + app.dock_drop_rect = None; + app.drop_canvas_rect = None; + app.ui.task_bar_shown = None; + start_screen(app, ui); + } else { + crate::panels::region_versions::show_canvas(app, ui, documents); + } crate::layer_transfer::finish(app, ui.ctx()); // The Shift+Alt+right-click HUD Color Picker (#6098), while its gesture is held. crate::color_hud::show(app, ui); @@ -44,6 +55,31 @@ pub fn document_area(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } } +/// The document area's work of every pass, which the window's body runs before the dock: the GPU canvas's documents +/// and their texture budget, a Content-Aware Scale step, the blocks background redraws landed, the tablet settings, and +/// what a tool switch or a layer switch leaves behind (a pending crop, a Properties eyedropper). A replayed view or dock +/// column runs none of its own code, so none of this lives in them. A Batch preview in place of the documents +/// ([`crate::jobs_ui::batch_preview`]) holds all of it back. +pub(crate) fn each_pass(app: &mut PhotocraftApp, ctx: &egui::Context) { + if crate::jobs_ui::batch_preview_key(app).is_some() { + return; + } + retain_gpu_documents(app); + publish_shown(app); + crate::cas_transform::tick(app, ctx); + crate::background_redraw::poll_all(app); + // Pen pressure/tilt for the tools' events (mouse = 1.0), unless Preferences › Tools › Use Tablet Pressure is off; + // the pen's eraser end selects the Eraser. + app.stylus.use_pressure = app.session.prefs().tools.use_tablet_pressure; + let curve = app.session.prefs().tools.pressure_curve.clone(); + app.stylus.set_pressure_curve(&curve); + crate::stylus::Stylus::sync_eraser_tool(app); + // A Properties Levels/Curves eyedropper left behind by a tool or layer switch is dropped. + crate::layer_picker::prune(app); + // A crop left pending when another tool was picked is applied or dropped. + crate::crop_ui::each_pass(app); +} + /// Where each pane of Window › Arrange's n-up or Tile arrangement is in `rect`, with the document it shows: pane `i` is /// docked group `i` of `app.ui.document_windows`, showing that group's shown document, in the rect `SplitViews` /// places it in with the dividers at `app.ui.split_at`. `None` with no arrangement or fewer than two docked groups: @@ -128,14 +164,13 @@ pub(crate) fn publish_shown(app: &PhotocraftApp) { } /// What the document area does after Window › Arrange changed the document windows (top-w15 calls it after -/// `arrange`). A new n-up or Tile arrangement starts from even panes and every document fits its new pane, as -/// production's layouts do; Tile is a pane per open document, floating windows docked first (the framework's -/// `arrange` consolidates before it splits). The other window commands and the Match commands leave the panes and -/// views alone. +/// `arrange`). A new n-up or Tile arrangement starts from even panes; every document keeps its zoom and view centre, +/// as the reference application's layouts do (#16885), so it shows centred in its new pane. Tile is a pane per open +/// document, floating windows docked first (the framework's `arrange` consolidates before it splits). The other window +/// commands and the Match commands leave the panes and views alone. pub(crate) fn apply_arranged(app: &mut PhotocraftApp, arranged: Arranged) { if arranged == Arranged::Windows && app.ui.document_windows.arrangement.is_some() { app.ui.split_at = SplitAt::default(); - app.ui.views.iter_mut().for_each(|view| view.place(craft::ui::canvas::ViewCommands::FitOnScreen)); } } @@ -146,19 +181,12 @@ const DOCK_BAND: f32 = 32.0; fn documents(app: &mut PhotocraftApp, ui: &mut egui::Ui) { // The web build's drop path reads where the canvas is (`file_open::target_at`); set again when one shows. app.drop_canvas_rect = None; + // A run that shows no canvas of the active document shows no crop task bar (`crop_task_bar::show` reports one). + app.ui.task_bar_shown = None; // A floating window's title bar docks on the tab strip (`tabs::strip` sets its rect); where no strip shows, on a // band of a tab's height at the top of the area, where the strip would be. let area = ui.max_rect(); app.dock_drop_rect = Some(Rect::from_min_size(area.min, egui::vec2(area.width(), DOCK_BAND.min(area.height())))); - retain_gpu_documents(app); - publish_shown(app); - crate::cas_transform::tick(app, ui.ctx()); - if app.home_screen_up() { - // The Home screen hides the tabs: a floating window dropped on it docks nowhere (#16415). - app.dock_drop_rect = None; - start_screen(app, ui); - return; - } // Files opening in the background (#210) have tabs before they have documents. let opening = !app.jobs.opens.is_empty(); // The tabs region and the document run one after the other inside `show`, each with the app to itself. @@ -279,3 +307,7 @@ fn arranged(app: &mut PhotocraftApp, ui: &mut egui::Ui, rect: Rect, active: usiz } true } + +#[cfg(test)] +#[path = "arrange_keeps_zoom_tests.rs"] +mod arrange_keeps_zoom_tests; diff --git a/crates/ui-egui/src/canvas/document_display.rs b/crates/ui-egui/src/canvas/document_display.rs index 81ee1515c3..2fcaa80868 100644 --- a/crates/ui-egui/src/canvas/document_display.rs +++ b/crates/ui-egui/src/canvas/document_display.rs @@ -35,6 +35,11 @@ impl View { .aspect(f64::from(aspect)) } + /// Takes `zoom` points per document unit, shown at `ppp` device pixels per point, and leaves the centre and rotation. + pub(crate) fn set_zoom(&mut self, zoom: f64, ppp: f32) { + self.zoom = (zoom * f64::from(ppp)) as f32; + } + /// Takes the zoom, centre and rotation of `view`, shown at `ppp` device pixels per point. pub(crate) fn set_from(&mut self, view: &CanvasView, ppp: f32) { self.zoom = (view.zoom * f64::from(ppp)) as f32; @@ -513,7 +518,7 @@ fn canvas_controls( crate::blur_pins::overlay(app, ui, rect); let doc = app.session.documents()[host.idx].doc.id; if let Some(shown) = crate::vector_ui::overlay::show_paths(app, ui, rect, doc) { - let mods = craft::ui::runtime::pointer::frame(ui.ctx()).mods; + let mods = craft::ui::runtime::pointer::mods(ui.ctx()); crate::direct_select::edits::apply(app, &shown.output, &shown.refs, app.ui.tool, mods); } crate::type_tool::canvas_controls(app, ui, rect); @@ -573,7 +578,6 @@ fn canvas_controls( } crate::frame_tool::task_bar::show(ui, app, bar_area); } - crate::crop_ui::each_pass(app); crate::vector_ui::shapes::show_preview(app, ui, rect, &space.view); crate::tools::brush_feedback::show(ui, app, rect, pointer); if shown != space.view { diff --git a/crates/ui-egui/src/canvas/eyedropper_tool.rs b/crates/ui-egui/src/canvas/eyedropper_tool.rs index 163bb26948..730d6afac1 100644 --- a/crates/ui-egui/src/canvas/eyedropper_tool.rs +++ b/crates/ui-egui/src/canvas/eyedropper_tool.rs @@ -25,6 +25,10 @@ use crate::PhotocraftApp; #[path = "../eyedropper_cmyk_tests.rs"] mod cmyk_tests; +#[cfg(test)] +#[path = "other_precise_cursor_tests.rs"] +mod other_precise_cursor_tests; + /// The gesture's flags, kept in `CanvasTools::eyedropper`. #[derive(Debug, Default)] pub(crate) struct EyedropperState { @@ -44,6 +48,8 @@ pub(crate) struct PcEyedropper<'a> { stand_in: bool, /// Runs as a shape tool's Alt stand-in: a pick also sets the tool's Fill. shape_fill: bool, + /// The named Eyedropper uses a target for the Precise Other Cursors preference. + precise_target: bool, } /// The Eyedropper tool, for `Tool::Eyedropper`. @@ -68,7 +74,7 @@ impl<'a> PcEyedropper<'a> { let precise = app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise; (app.ui.tool_options.eyedropper, Srgba::rgb(r, g, b), precise, shape_alt_sets_fill(app.ui.tool)) }); - // Preferences › Cursors › Other Cursors = Precise wants the plain crosshair, so no ring. + // The sampling ring is the colour preview while held, separate from the pointer. options.show_ring &= !precise; let native = std::rc::Rc::new(std::cell::Cell::new(None)); let sampled_native = native.clone(); @@ -81,7 +87,15 @@ impl<'a> PcEyedropper<'a> { }) .map(|c| Srgba::rgb(c[0], c[1], c[2])) }; - PcEyedropper { scope, state, inner: EyedropperTool::new(options, sample).foreground(foreground), native, stand_in, shape_fill: stand_in && shape_fill } + PcEyedropper { + scope, + state, + inner: EyedropperTool::new(options, sample).foreground(foreground), + native, + stand_in, + shape_fill: stand_in && shape_fill, + precise_target: precise && !stand_in, + } } /// Writes the newest pick to its swatch; as a shape tool's stand-in, also makes the tool's Fill @@ -176,8 +190,10 @@ impl CanvasTool for PcEyedropper<'_> { self.inner.paint(draw, cx); } - /// `EyedropperTool::cursor`: the pipette, the precise crosshair with Caps Lock or the preference. fn cursor(&self, cx: &ToolContext<'_>) -> Cursor { + if self.precise_target && cx.precise() { + return super::cursor_policy::sample_target(); + } self.inner.cursor(cx) } diff --git a/crates/ui-egui/src/canvas/filter_preview.rs b/crates/ui-egui/src/canvas/filter_preview.rs index 44eb6126b9..a704025cef 100644 --- a/crates/ui-egui/src/canvas/filter_preview.rs +++ b/crates/ui-egui/src/canvas/filter_preview.rs @@ -48,6 +48,18 @@ fn adjust_request(app: &PhotocraftApp) -> Option<(craft::ui::dialog::DialogId, S Some((open.id, cmd, params)) } +/// An open preview dialog's request: the dialog, its command and its parameters. +type PreviewRequest = (craft::ui::dialog::DialogId, String, String); + +/// What the canvas shows of an open filter or adjustment dialog's preview, for the document area's version +/// (`region_versions::canvas`): the request the dialog asks for (its fields change with no command) and the result +/// on screen, with whether OK's job is running. +pub(crate) fn canvas_key(app: &PhotocraftApp) -> (Option, Option<(usize, bool)>) { + let request = adjust_request(app).map(|(id, command, params)| (id, command, params.to_string())); + let shown = app.filter_preview.as_ref().map(|p| (p.result.as_ref().map_or(0, |doc| std::sync::Arc::as_ptr(doc) as usize), p.committing)); + (request, shown) +} + /// Live preview for an open filter dialog: run the filter on the proxy and upload it. With /// background jobs (the desktop app) it computes on one background worker /// (`filter_preview_worker`); otherwise (web, tests, `PHOTOCRAFT_INLINE_JOBS`) it keeps the @@ -184,7 +196,7 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e } } if app.filter_preview_worker.busy() { - ctx.request_repaint_after(std::time::Duration::from_millis(16)); + craft::ui::runtime::frame::request_repaint_after(ctx, std::time::Duration::from_millis(16).as_secs_f64()); } let preview = app.filter_preview.as_ref()?; // Keep the last preview during a drag, but never one from another source or dialog. It is diff --git a/crates/ui-egui/src/canvas/guide_select/tests.rs b/crates/ui-egui/src/canvas/guide_select/tests.rs index 1856da7fcd..07f8568725 100644 --- a/crates/ui-egui/src/canvas/guide_select/tests.rs +++ b/crates/ui-egui/src/canvas/guide_select/tests.rs @@ -82,7 +82,7 @@ fn harness(app: Box) -> AppHarness { if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { return; } - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); crate::dialogs::run(app, ui); }, app, diff --git a/crates/ui-egui/src/canvas/layer_pick_ui.rs b/crates/ui-egui/src/canvas/layer_pick_ui.rs index 1d04cdf17f..c623000b47 100644 --- a/crates/ui-egui/src/canvas/layer_pick_ui.rs +++ b/crates/ui-egui/src/canvas/layer_pick_ui.rs @@ -188,7 +188,7 @@ mod tests { if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { return; } - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); }, a, ); diff --git a/crates/ui-egui/src/canvas/live_frame_tests.rs b/crates/ui-egui/src/canvas/live_frame_tests.rs index 425f189988..d4492ac4ee 100644 --- a/crates/ui-egui/src/canvas/live_frame_tests.rs +++ b/crates/ui-egui/src/canvas/live_frame_tests.rs @@ -5,7 +5,7 @@ use egui::{PointerButton, Pos2, Rect, vec2}; use serde_json::json; use super::document_display::{CanvasHost, shown_camera}; -use super::{canvas_display, canvas_view, document_area}; +use super::{canvas_display, canvas_view, testing}; use crate::PhotocraftApp; use crate::state::{Tool, View}; @@ -23,7 +23,7 @@ fn live_brush_texture_includes_this_frames_press_and_moves() { if !ui.ctx().fonts(|fonts| fonts.families().contains(&egui::FontFamily::Name("medium".into()))) { return; } - egui::CentralPanel::default().show(ui, |ui| document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| testing::document_area(app, ui)); }, app, ); diff --git a/crates/ui-egui/src/canvas/locked_layer_cursor_tests.rs b/crates/ui-egui/src/canvas/locked_layer_cursor_tests.rs new file mode 100644 index 0000000000..664423ff9b --- /dev/null +++ b/crates/ui-egui/src/canvas/locked_layer_cursor_tests.rs @@ -0,0 +1,138 @@ +//! #16815: show the system cursor for painting tools on the blocked layer targets measured in the issue. + +use craft::behavior::{Cursor, CursorIcon}; +use egui::{Modifiers, PointerButton}; +use egui_kittest::Harness; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::dialogs::{alerts, rasterize_prompt::Rasterize}; +use crate::guide_cursor_tests::{harness, hover, screen}; +use crate::state::Tool; + +const IN_IMAGE: f32 = 100.0; +const ON_PASTEBOARD: f32 = -40.0; +const TOOLS: [Tool; 3] = [Tool::Brush, Tool::Eraser, Tool::PaintBucket]; +const BLOCKED: Option = Some(Cursor::System(CursorIcon::NotAllowed)); + +fn pixel_layer() -> Harness<'static, Box> { + let mut h = harness(Tool::Brush); + h.state_mut().run("layer.new.layer", json!({})).unwrap(); + h.state_mut().run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + h +} + +fn cursor_at(h: &mut Harness<'static, Box>, tool: Tool, x: f32, mods: Modifiers) -> Option { + h.state_mut().ui.tool = tool; + hover(h, x, 150.0, mods); + h.state().canvas_tools.last_response.as_ref().and_then(|response| response.cursor.clone()) +} + +fn image_cursor(h: &mut Harness<'static, Box>, tool: Tool) -> Option { + cursor_at(h, tool, IN_IMAGE, Modifiers::NONE) +} + +fn click_image(h: &mut Harness<'static, Box>) { + let pos = screen(h, IN_IMAGE, 150.0); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(2); + } +} + +#[test] +fn lock_all_shows_the_blocked_cursor_on_the_image_and_pasteboard() { + let mut h = pixel_layer(); + let normal = TOOLS.map(|tool| image_cursor(&mut h, tool)); + for (tool, cursor) in TOOLS.into_iter().zip(&normal) { + assert!(cursor.is_some() && *cursor != BLOCKED, "{tool:?} has a normal cursor before locking"); + } + let shift_bucket = cursor_at(&mut h, Tool::PaintBucket, ON_PASTEBOARD, Modifiers::SHIFT); + h.state_mut().run("layer.lockLayers", json!({"all": true})).unwrap(); + for tool in TOOLS { + for x in [IN_IMAGE, ON_PASTEBOARD] { + assert_eq!(cursor_at(&mut h, tool, x, Modifiers::NONE), BLOCKED, "{tool:?} at x={x}"); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::NotAllowed); + } + } + assert_eq!(cursor_at(&mut h, Tool::PaintBucket, ON_PASTEBOARD, Modifiers::SHIFT), shift_bucket, "Shift changes the pasteboard colour"); + h.state_mut().run("layer.lockLayers", json!({"all": false})).unwrap(); + assert_eq!(TOOLS.map(|tool| image_cursor(&mut h, tool)), normal); +} + +#[test] +fn a_type_layer_blocks_brush_and_bucket_and_their_clicks_still_ask_to_rasterize() { + for tool in [Tool::Brush, Tool::PaintBucket] { + let mut h = pixel_layer(); + h.state_mut().run("type.create", json!({"x": 40, "y": 60, "text": "Type"})).unwrap(); + let cursor = image_cursor(&mut h, tool); + let before = h.state().session.active().unwrap().history.past_len(); + click_image(&mut h); + assert!(alerts::prompt_tagged::(h.state()).is_some(), "{tool:?}: Rasterize prompt"); + assert_eq!(h.state().session.active().unwrap().history.past_len(), before, "{tool:?}"); + assert_eq!(cursor, BLOCKED, "{tool:?}"); + } + let mut h = pixel_layer(); + let eraser = image_cursor(&mut h, Tool::Eraser); + h.state_mut().run("type.create", json!({"x": 40, "y": 60, "text": "Type"})).unwrap(); + assert_eq!(image_cursor(&mut h, Tool::Eraser), eraser); +} + +#[test] +fn locked_pixel_clicks_keep_their_refusal_and_history() { + for tool in TOOLS { + let mut h = pixel_layer(); + h.state_mut().run("layer.lockLayers", json!({"all": true})).unwrap(); + image_cursor(&mut h, tool); + let before = h.state().session.active().unwrap().history.past_len(); + click_image(&mut h); + let app = h.state(); + let dialogs = app.framework.dialogs.open_dialogs(); + let alert = dialogs.iter().any(|dialog| { + dialog + .fields + .as_ref() + .and_then(|fields| fields.get("message")) + .and_then(|message| message.as_str()) + .is_some_and(|message| message.contains("layer is locked")) + }); + assert!(alert || (app.ui.status_error && app.ui.status.contains("locked")), "{tool:?}: {}", app.ui.status); + assert_eq!(app.session.active().unwrap().history.past_len(), before, "{tool:?}"); + } +} + +#[test] +fn hidden_layers_partial_locks_and_groups_keep_each_tools_normal_cursor() { + let mut h = pixel_layer(); + let normal = TOOLS.map(|tool| image_cursor(&mut h, tool)); + for lock in ["pixels", "transparency", "position"] { + h.state_mut().run("layer.lockLayers", json!({ (lock): true })).unwrap(); + assert_eq!(TOOLS.map(|tool| image_cursor(&mut h, tool)), normal, "{lock}"); + h.state_mut().run("layer.lockLayers", json!({ (lock): false })).unwrap(); + } + // Test hiding a fully locked layer, so the hidden and locked rules compete. + h.state_mut().run("layer.lockLayers", json!({"all": true})).unwrap(); + h.state_mut().run("layer.setProps", json!({"visible": false})).unwrap(); + assert_eq!(TOOLS.map(|tool| image_cursor(&mut h, tool)), normal, "hidden Lock All layer"); + + h.state_mut().run("layer.new.group", json!({})).unwrap(); + h.state_mut().run("layer.lockLayers", json!({"all": true})).unwrap(); + assert_eq!(TOOLS.map(|tool| image_cursor(&mut h, tool)), normal, "locked group itself"); +} + +#[test] +fn locked_layers_keep_nonpainting_cursors_and_the_stand_ins() { + let mut h = pixel_layer(); + let tools = [Tool::RectMarquee, Tool::Move, Tool::Pencil]; + let expected = tools.map(|tool| image_cursor(&mut h, tool)); + let eyedropper = image_cursor(&mut h, Tool::Eyedropper); + let quick_mask = image_cursor(&mut h, Tool::Brush); + h.state_mut().run("layer.lockLayers", json!({"all": true})).unwrap(); + assert_eq!(tools.map(|tool| image_cursor(&mut h, tool)), expected); + assert_eq!(image_cursor(&mut h, Tool::MixerBrush), BLOCKED); + assert_eq!(cursor_at(&mut h, Tool::Brush, IN_IMAGE, Modifiers::ALT), eyedropper); + assert_eq!(cursor_at(&mut h, Tool::Brush, IN_IMAGE, Modifiers::COMMAND), expected[1]); + + h.state_mut().run("select.editInQuickMaskMode", json!({"on": true})).unwrap(); + assert_eq!(image_cursor(&mut h, Tool::Brush), quick_mask); +} diff --git a/crates/ui-egui/src/canvas/other_precise_cursor_tests.rs b/crates/ui-egui/src/canvas/other_precise_cursor_tests.rs new file mode 100644 index 0000000000..7b052b6947 --- /dev/null +++ b/crates/ui-egui/src/canvas/other_precise_cursor_tests.rs @@ -0,0 +1,75 @@ +//! The Other Cursors preference changes the Eyedropper over the document canvas. + +use craft::behavior::{Cursor, IconId, PaintedCursor}; +use craft::ui::primitives::painted_image; +use craft::ui::runtime::{env::Env, windows::WindowHost}; +use egui::Modifiers; +use egui_kittest::Harness; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::guide_cursor_tests::{harness, hover}; +use crate::state::Tool; + +fn other_cursor(h: &mut Harness<'static, Box>, value: &str) { + h.state_mut().run("prefs.set", json!({"path": "cursors.other", "value": value})).unwrap(); +} + +fn pointer(h: &mut Harness<'static, Box>, mods: Modifiers) -> Cursor { + hover(h, 100.0, 150.0, mods); + h.state().canvas_tools.last_response.as_ref().and_then(|response| response.cursor.clone()).expect("the tool cursor over the canvas") +} + +#[test] +fn precise_eyedropper_draws_a_centred_target() { + let mut h = harness(Tool::Eyedropper); + WindowHost::of(&h.ctx).set_caps_lock(Some(false)); + other_cursor(&mut h, "precise"); + let cursor = pointer(&mut h, Modifiers::NONE); + let Cursor::Painted(painted @ PaintedCursor::Circle { centre: true, .. }) = cursor else { + panic!("Precise Eyedropper should show a circle and crosshair, got {cursor:?}"); + }; + let bitmap = painted_image(&Env::of_root(&h.ctx), &painted, 2.0).expect("the target has a cursor bitmap"); + assert_eq!(bitmap.hotspot, bitmap.size.map(|side| side / 2), "the hotspot is the bitmap's centre"); + + let width = usize::from(bitmap.size[0]); + let [cx, cy] = bitmap.hotspot.map(usize::from); + let mut light_on_black = false; + let mut dark_on_white = false; + for (i, &[r, g, b, a]) in bitmap.rgba.as_chunks::<4>().0.iter().enumerate() { + // Sample off both axes so the contrast check uses the ring, away from the centre cross. + if (i % width).abs_diff(cx) <= 2 || (i / width).abs_diff(cy) <= 2 { + continue; + } + let alpha = f32::from(a) / 255.0; + let lightest = f32::from(r.max(g).max(b)); + let darkest = f32::from(r.min(g).min(b)); + light_on_black |= darkest * alpha >= 100.0; + dark_on_white |= lightest * alpha + 255.0 * (1.0 - alpha) <= 145.0; + } + assert!(light_on_black && dark_on_white, "the ring has a visible stroke on black and on white"); +} + +#[test] +fn standard_eyedropper_and_unaffected_tools_keep_their_cursors() { + let mut h = harness(Tool::Eyedropper); + let window = WindowHost::of(&h.ctx); + window.set_caps_lock(Some(false)); + let standard = pointer(&mut h, Modifiers::NONE); + assert!(matches!(&standard, Cursor::Painted(PaintedCursor::Tool { icon, .. }) if *icon == IconId::new("eyedropper"))); + window.set_caps_lock(Some(true)); + assert_eq!(pointer(&mut h, Modifiers::NONE), Cursor::Painted(PaintedCursor::Crosshair), "Caps Lock alone still uses the crosshair"); + other_cursor(&mut h, "precise"); + assert_eq!(pointer(&mut h, Modifiers::NONE), standard, "Caps Lock still inverts the preference"); + window.set_caps_lock(Some(false)); + + for tool in [Tool::Move, Tool::Type, Tool::Hand, Tool::Zoom] { + h.state_mut().ui.tool = tool; + other_cursor(&mut h, "standard"); + let standard = pointer(&mut h, Modifiers::NONE); + other_cursor(&mut h, "precise"); + assert_eq!(pointer(&mut h, Modifiers::NONE), standard, "{tool:?} keeps its cursor"); + } + h.state_mut().ui.tool = Tool::Brush; + assert_eq!(pointer(&mut h, Modifiers::ALT), Cursor::Painted(PaintedCursor::Crosshair), "the Alt stand-in keeps its cursor"); +} diff --git a/crates/ui-egui/src/canvas/paint_mouse.rs b/crates/ui-egui/src/canvas/paint_mouse.rs index b1993d367e..9c95b46fb4 100644 --- a/crates/ui-egui/src/canvas/paint_mouse.rs +++ b/crates/ui-egui/src/canvas/paint_mouse.rs @@ -273,6 +273,10 @@ pub(crate) enum ContextPopup { /// menus come from the guides' own output and transform menus from the transform box. pub(crate) fn context_popup(app: &mut PhotocraftApp, tool: Tool, mods: Mods, doc: [f64; 2]) -> Option { use crate::canvas_tool_menu as menu; + // Puppet Warp's pin menu, opened earlier in the pass, takes the right-click (#16734). + if crate::puppet_ui::menu_open(app) { + return None; + } if crate::brush_mode_menu::opens_on(app, tool, mods, Some(doc)) { return Some(ContextPopup::Menu(MenuKind::BrushMode { plain: !crate::brush_mode_menu::is_gesture(tool, mods) })); } diff --git a/crates/ui-egui/src/canvas/paint_mouse/tests.rs b/crates/ui-egui/src/canvas/paint_mouse/tests.rs index 0bcf80cbfc..9efc28951e 100644 --- a/crates/ui-egui/src/canvas/paint_mouse/tests.rs +++ b/crates/ui-egui/src/canvas/paint_mouse/tests.rs @@ -25,7 +25,7 @@ pub(super) fn harness(prefs: Option<&str>) -> Harness<'static, Box bool { } } +fn bucket_targets_pasteboard(app: &PhotocraftApp, at: [f64; 2], mods: Mods) -> bool { + let plain_shift = mods.shift && !mods.alt && !mods.ctrl && !mods.cmd; + let Some(st) = app.session.active() else { return false }; + let (w, h) = (f64::from(st.doc.size.width), f64::from(st.doc.size.height)); + let (x, y) = (at[0], at[1]); + let outside = x.is_finite() && y.is_finite() && (x < 0.0 || y < 0.0 || x >= w || y >= h); + plain_shift && outside && st.doc.selection.is_none() +} + /// Paint Bucket ⇧-click on the pasteboard sets the pasteboard colour to the foreground colour, as /// in the reference application (#12534): the custom colour, and use it, as the pasteboard menu's /// Select Custom Color… does. It is a preference, so no history state and no document change. /// Only a plain ⇧ with no selection: other modifiers and an active selection were not measured and /// keep today's fill. True when it handled the click. pub(crate) fn bucket_pasteboard_click(app: &mut PhotocraftApp, at: [f64; 2], mods: Mods) -> bool { - let plain_shift = mods.shift && !mods.alt && !mods.ctrl && !mods.cmd; - let Some(st) = app.session.active() else { return false }; - let (w, h) = (f64::from(st.doc.size.width), f64::from(st.doc.size.height)); - let (x, y) = (at[0], at[1]); - let outside = x.is_finite() && y.is_finite() && (x < 0.0 || y < 0.0 || x >= w || y >= h); - if !plain_shift || !outside || st.doc.selection.is_some() { + if !bucket_targets_pasteboard(app, at, mods) { return false; } let [r, g, b, _] = app.session.tools.foreground; @@ -489,8 +493,10 @@ impl CanvasTool for PaintTool<'_> { if alt_loads_mixer(tool, cx.mods) && !cx.mods.cmd { return if cx.precise() { Cursor::Painted(PaintedCursor::Crosshair) } else { sample_target() }; } - // Over a layer it can't paint (Lock All), the Mixer Brush shows a no-entry sign (#11957). - if tool == Tool::MixerBrush && mixer_target_locked(app) { + let sets_pasteboard = tool == Tool::PaintBucket + && cx.mods.shift + && cx.pointer.as_ref().and_then(|pointer| doc_point(cx, pointer.pos)).is_some_and(|at| bucket_targets_pasteboard(app, at, cx.mods)); + if !sets_pasteboard && paint_cursor_blocked(app) { return Cursor::System(CursorIcon::NotAllowed); } // The Paint Bucket and the Magic Eraser act on a click: their own pointers, no brush tip. diff --git a/crates/ui-egui/src/canvas/paint_tool/tests.rs b/crates/ui-egui/src/canvas/paint_tool/tests.rs index 281651fb54..3a8685f6ad 100644 --- a/crates/ui-egui/src/canvas/paint_tool/tests.rs +++ b/crates/ui-egui/src/canvas/paint_tool/tests.rs @@ -52,7 +52,7 @@ fn harness(mut app: Box) -> Harness<'static, Box> if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { return; } - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); }, app, ); @@ -494,11 +494,12 @@ fn painting_a_group_is_refused_at_the_press_with_a_message() { let seen = errors(&app).len(); app.ui.tool = tool; tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, M); - // Brush, Classic gradient and Magic Eraser use the measured alerts (#11898, #12017, #12020). + // Brush, Classic gradient, Magic Eraser and Paint Bucket use the measured alerts (#11898, #12017, #12020, #12537). let want = match tool { Tool::Brush => "Could not use the brush tool because the pixels in a group cannot be edited without merging the group.".to_string(), Tool::MagicEraser => "Could not use the magic eraser because the pixels in a group cannot be edited without merging the group.".to_string(), Tool::Gradient => "Could not use the gradient tool because the pixels in a group cannot be edited without merging the group.".to_string(), + Tool::PaintBucket => "Could not use the paint bucket because the pixels in a group cannot be edited without merging the group.".to_string(), _ => format!("Could not use the {} because the target layer is a group.", tool.label()), }; assert_eq!(errors(&app)[seen..], [want], "{tool:?}"); diff --git a/crates/ui-egui/src/canvas/rulers/tests.rs b/crates/ui-egui/src/canvas/rulers/tests.rs index 0b5ecfce46..9782ad3106 100644 --- a/crates/ui-egui/src/canvas/rulers/tests.rs +++ b/crates/ui-egui/src/canvas/rulers/tests.rs @@ -25,7 +25,7 @@ fn harness_with_passes(size: [u32; 2], tool: Tool, second_pass: bool) -> AppHarn if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { return; } - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); if second_pass && ui.ctx().current_pass_index() == 0 { ui.ctx().request_discard("a second pass of the frame"); } diff --git a/crates/ui-egui/src/canvas/scroll_all_windows.rs b/crates/ui-egui/src/canvas/scroll_all_windows.rs index 2d77f4da00..50209b1495 100644 --- a/crates/ui-egui/src/canvas/scroll_all_windows.rs +++ b/crates/ui-egui/src/canvas/scroll_all_windows.rs @@ -281,7 +281,7 @@ mod tests { Hidden::Home => app.ui.chrome.home = Some(app.session.documents().len()), Hidden::Card => { let job = photocraft_engine::jobs::JobId(9); - app.jobs.opens.push(crate::jobs_ui::OpenTab { job, name: "opening.psd".into(), path: None, slot: None, order: None }); + app.jobs.opens.push(crate::jobs_ui::OpenTab { job, name: "opening.psd".into(), path: None, error_source: None, slot: None, order: None }); app.jobs.focus = Some(job); } } diff --git a/crates/ui-egui/src/canvas/snap_off_lines_tests.rs b/crates/ui-egui/src/canvas/snap_off_lines_tests.rs new file mode 100644 index 0000000000..af9d9cb6de --- /dev/null +++ b/crates/ui-egui/src/canvas/snap_off_lines_tests.rs @@ -0,0 +1,97 @@ +//! #16857: with View > Snap off and Smart Guides on, a Move-tool drag that lines an edge or centre up exactly with +//! another layer's still draws that smart guide, with no pull; Smart Guides off draws nothing, and Snap on keeps +//! snapping. + +use craft::behavior::Axis; +use craft::behavior::geometry::SnapLine; +use serde_json::json; + +use crate::canvas::{ToolEvent, tool_event, tool_event_response}; +use crate::state::Tool; +use crate::{PhotocraftApp, Services}; + +/// The epic's test document: 1000 x 800, white Background, A red (100,100)-(300,260), C green (400,100)-(500,200) +/// and B blue (600,400)-(750,520) on top and active; the Move tool without Auto-Select, the view fitted (the test +/// window is smaller than the document at 100 %; an exact coincidence does not depend on the zoom). +fn test_document(snap: bool, smart_guides: bool) -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({"width": 1000, "height": 800})).unwrap(); + app.sync_views(); + for (name, rect, color) in [("A", [100, 100, 200, 160], "#ff0000"), ("C", [400, 100, 100, 100], "#00ff00"), ("B", [600, 400, 150, 120], "#0000ff")] { + app.run("layer.new.layer", json!({"name": name})).unwrap(); + app.run("select.rect", json!({"x": rect[0], "y": rect[1], "width": rect[2], "height": rect[3]})).unwrap(); + app.run("edit.fill", json!({"color": color})).unwrap(); + } + app.run("select.deselect", json!({})).unwrap(); + app.ui.tool = Tool::Move; + app.ui.tool_options.move_auto_select = false; + app.ui.extras.snap = snap; + app.ui.view.show.smart_guides = smart_guides; + app +} + +/// B's bounds. +fn b_left(app: &PhotocraftApp) -> i32 { + let st = app.session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds().x0 +} + +/// Drags B from its centre (675, 460) by `dx` and returns the snap lines of the last move; B's left edge after the +/// release. +fn drag_b(app: &mut PhotocraftApp, dx: f64) -> (Vec, i32) { + let m = egui::Modifiers::NONE; + tool_event(app, ToolEvent::Down { x: 675.0, y: 460.0, pressure: 1.0 }, m); + tool_event(app, ToolEvent::Move { x: 675.0 + dx / 2.0, y: 460.0, pressure: 1.0 }, m); + let lines = tool_event_response(app, ToolEvent::Move { x: 675.0 + dx, y: 460.0, pressure: 1.0 }, m).snapped; + tool_event(app, ToolEvent::Up { x: 675.0 + dx, y: 460.0 }, m); + (lines, b_left(app)) +} + +fn vertical_at(lines: &[SnapLine], x: f64) -> bool { + lines.iter().any(|l| l.along == Axis::Y && l.position == x && l.kind.is_smart()) +} + +#[test] +fn snap_off_draws_a_smart_guide_where_an_edge_lines_up_exactly() { + let mut app = test_document(false, true); + let (lines, left) = drag_b(&mut app, -500.0); + assert_eq!(left, 100, "B's left edge on A's"); + assert!(vertical_at(&lines, 100.0), "x=100 (A's left) is drawn: {lines:?}"); +} + +#[test] +fn snap_off_draws_nothing_and_does_not_pull_four_pixels_away() { + let mut app = test_document(false, true); + let (lines, left) = drag_b(&mut app, -496.0); + assert_eq!(left, 104, "no pull with Snap off"); + assert!(!vertical_at(&lines, 100.0), "nothing for A's left 4 px away: {lines:?}"); +} + +#[test] +fn snap_off_and_smart_guides_off_draw_nothing() { + let mut app = test_document(false, false); + let (lines, left) = drag_b(&mut app, -500.0); + assert_eq!(left, 100); + assert!(lines.is_empty(), "{lines:?}"); +} + +#[test] +fn snap_off_ctrl_draws_nothing() { + let mut app = test_document(false, true); + let m = egui::Modifiers::NONE; + let ctrl = if cfg!(target_os = "macos") { egui::Modifiers::CTRL } else { egui::Modifiers::COMMAND }; + tool_event(&mut app, ToolEvent::Down { x: 675.0, y: 460.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Move { x: 425.0, y: 460.0, pressure: 1.0 }, ctrl); + let lines = tool_event_response(&mut app, ToolEvent::Move { x: 175.0, y: 460.0, pressure: 1.0 }, ctrl).snapped; + tool_event(&mut app, ToolEvent::Up { x: 175.0, y: 460.0 }, ctrl); + assert_eq!(b_left(&app), 100); + assert!(lines.is_empty(), "the suspend key hides the lines too: {lines:?}"); +} + +#[test] +fn snap_on_keeps_snapping_and_its_line() { + let mut app = test_document(true, true); + let (lines, left) = drag_b(&mut app, -496.0); + assert_eq!(left, 100, "Snap on pulls B's left onto A's"); + assert!(vertical_at(&lines, 100.0), "{lines:?}"); +} diff --git a/crates/ui-egui/src/canvas/snap_ui.rs b/crates/ui-egui/src/canvas/snap_ui.rs index 2fa083206f..8158c56b5a 100644 --- a/crates/ui-egui/src/canvas/snap_ui.rs +++ b/crates/ui-egui/src/canvas/snap_ui.rs @@ -42,7 +42,7 @@ pub(crate) struct SnapCache { /// tool that hands its press to the Move stand-in. Read before the press so the targets do not /// change at it. fn moves_as_move_tool(app: &PhotocraftApp) -> bool { - app.ui.tool == Tool::Move || (crate::canvas::tools::takes_command_stand_in(app.ui.tool) && craft::ui::runtime::pointer::frame(app.ctx()).mods.cmd) + app.ui.tool == Tool::Move || (crate::canvas::tools::takes_command_stand_in(app.ui.tool) && craft::ui::runtime::pointer::mods(app.ctx()).cmd) } /// The selected pixels move with the drag, so the selection is not a place to snap to (#6290). @@ -57,7 +57,7 @@ fn selection_moves(app: &PhotocraftApp) -> bool { /// group does not snap to its own layers' starting edges), the type layer being edited (a paragraph-box handle drag /// does not snap to the text it resizes, #6819), the layers of the open Free Transform and the shape layers the shape /// scale box or a corner widget is pressing. -fn moving_set(app: &PhotocraftApp) -> Vec { +pub(crate) fn moving_set(app: &PhotocraftApp) -> Vec { let mut set = Vec::new(); if moves_as_move_tool(app) && let Some(st) = app.session.active() diff --git a/crates/ui-egui/src/canvas/testing.rs b/crates/ui-egui/src/canvas/testing.rs index d5716b8bf3..fae446554e 100644 --- a/crates/ui-egui/src/canvas/testing.rs +++ b/crates/ui-egui/src/canvas/testing.rs @@ -121,7 +121,7 @@ fn run_frame(app: &mut PhotocraftApp) { frames.frame_without_input(os_input, |ui| { crate::shortcut_dispatch::record_view_commands(app); crate::shortcuts::handle(app, &ui.ctx().clone()); - egui::CentralPanel::default().show(ui, |ui| super::document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| document_area(app, ui)); crate::dialogs::run(app, ui); crate::shortcuts::escape_keys(app, &ui.ctx().clone()); }); @@ -266,6 +266,14 @@ pub(crate) fn modifiers(app: &mut PhotocraftApp, mods: Modifiers) { settle(app); } +/// The document area as the app's window runs it: first the area's work of every pass, which the window's body runs +/// before the dock (a pending crop left by a tool switch, the tablet settings, landed redraws), then the area. Every +/// harness that shows the area without the window shows it through this. +pub(crate) fn document_area(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + super::document_area::each_pass(app, ui.ctx()); + super::document_area(app, ui); +} + /// One pass with no input: what a tool change cancels, a document switch drops. pub(crate) fn frame(app: &mut PhotocraftApp) { run_frame(app); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index e2acefdd92..9c928ab231 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -919,7 +919,7 @@ fn torn_off_document_is_not_drawn_again_in_the_main_window() { let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(680.0, 480.0)).with_context(app.ctx().clone()).build_ui_state( |ui, (app, ready): &mut (Box, bool)| { if *ready { - egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| document_area(app, ui)); + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| testing::document_area(app, ui)); } }, (app, false), @@ -990,7 +990,7 @@ fn a_new_window_for_document_keeps_its_own_view() { let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 700.0)).with_context(app.ctx().clone()).build_ui_state( |ui, (app, ready): &mut (Box, bool)| { if *ready { - egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| document_area(app, ui)); + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| testing::document_area(app, ui)); extra_windows(app, ui); } }, @@ -1028,7 +1028,7 @@ fn a_tiled_document_follows_navigator_and_status_bar_zoom() { let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 700.0)).with_context(app.ctx().clone()).build_ui_state( |ui, (app, ready): &mut (Box, bool)| { if *ready { - egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| document_area(app, ui)); + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| testing::document_area(app, ui)); } }, (app, false), diff --git a/crates/ui-egui/src/canvas/textures.rs b/crates/ui-egui/src/canvas/textures.rs index 22a92e76be..1a850582d0 100644 --- a/crates/ui-egui/src/canvas/textures.rs +++ b/crates/ui-egui/src/canvas/textures.rs @@ -317,8 +317,6 @@ pub(super) fn ensure_gpu(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usiz app.navigator_gpu.remove(&id); } let size = [doc.size.width, doc.size.height]; - // A full CPU redraw running in the background: show the blocks it has finished. - crate::background_redraw::poll(app, &gpu, id); let cache = app.canvases.entry((id, GPU_OUTPUT)).or_default(); let present = cache.on_gpu && gpu.has(id.0, size); let current = cache.revision == revision && cache.preview_key == preview_key; diff --git a/crates/ui-egui/src/canvas/tools/mod.rs b/crates/ui-egui/src/canvas/tools/mod.rs index c8bd3e62de..7d8c6ba2ec 100644 --- a/crates/ui-egui/src/canvas/tools/mod.rs +++ b/crates/ui-egui/src/canvas/tools/mod.rs @@ -722,7 +722,7 @@ pub(crate) fn run(app: &mut PhotocraftApp, ui: &egui::Ui, host: CanvasHost, out: response.view = Some(view); } } - ctx.request_repaint(); + craft::ui::runtime::frame::request_repaint(&ctx); } match response.gesture { Some(GesturePhase::Begin) => tools.gesture_on = app.session.documents().get(host.idx).map(|state| (state.doc.id.0, host)), diff --git a/crates/ui-egui/src/canvas/tools/move_tool.rs b/crates/ui-egui/src/canvas/tools/move_tool.rs index 80c634d381..6c49cb207c 100644 --- a/crates/ui-egui/src/canvas/tools/move_tool.rs +++ b/crates/ui-egui/src/canvas/tools/move_tool.rs @@ -11,7 +11,7 @@ use super::{FamilyTool, ToolScope}; use crate::PhotocraftApp; use crate::canvas::document_display::CanvasHost; use crate::state::Tool; -use craft::behavior::geometry::{ConstrainStyle, Directions, MoveGesture}; +use craft::behavior::geometry::{ConstrainStyle, Directions, MoveGesture, SnapKinds}; use craft::behavior::kurbo::{self, Point}; use craft::behavior::{CancelReason, Cursor, CursorIcon, PaintedCursor, PointerGlyph}; use craft::keymap::{Chord, Key, Mods}; @@ -267,6 +267,24 @@ fn press_at(app: &mut PhotocraftApp, p: [f64; 2], mods: Mods, style: ConstrainSt (ToolAction::Claimed, Some(run)) } +/// How far apart two coordinates may be and still line up exactly: the moved box sits on whole pixels. +const EXACT: f64 = 1e-6; + +/// With View › Snap off and Smart Guides on, the smart guides of the edges and centres of `moved` (the box at the +/// offset the drag commits) that line up exactly with another layer's, as in the reference application: nothing +/// pulls, the line only marks the coincidence (#16857). Snap on draws its lines through `snap_rect`; Smart Guides off +/// or the suspend key held draws none. +fn exact_lines(app: &PhotocraftApp, cx: &mut ToolContext<'_>, moved: kurbo::Rect, mods: Mods) { + let Some(idx) = app.session.active_index() else { return }; + let options = crate::canvas::snap_ui::snap(app, idx).options(); + if options.on || !options.smart_guides || craft::ui::canvas::snap_suspended(mods, craft::keymap::Platform::current(), options.suspend, false) { + return; + } + let targets = crate::canvas::snap_ui::targets(app, idx, &crate::canvas::snap_ui::moving_set(app)); + let (_, lines) = targets.snap_rect_of(moved, EXACT, SnapKinds::ALL); + cx.add_snapped(lines); +} + /// The drag to `pointer`: the ⇧ lock, the snap of the moving box, the ⌥ duplicate and, while the button is down /// (`readout`), the readout; the release applies its last sample without one. /// A pass applies only its own pointer sample, so a second pass of a frame moves the offset to @@ -293,6 +311,10 @@ fn follow(run: &mut Run, app: &mut PhotocraftApp, pointer: &ToolPointer, cx: &mu run.offset = (dx, dy); run.delta = [f64::from(dx), f64::from(dy)]; run.moved = true; + if let Some(b) = run.box_rect { + let moved = kurbo::Rect::new(b[0], b[1], b[2], b[3]) + kurbo::Vec2::new(run.delta[0], run.delta[1]); + exact_lines(app, cx, moved, pointer.mods); + } if readout { let x_arrow = if dx < 0 { "←" } else { "→" }; let y_arrow = if dy < 0 { "↑" } else { "↓" }; @@ -466,3 +488,6 @@ impl CanvasTool for MoveRun<'_> { #[cfg(test)] #[path = "move_cursor_cross_tests.rs"] mod move_cursor_cross_tests; +#[cfg(test)] +#[path = "../snap_off_lines_tests.rs"] +mod snap_off_lines_tests; diff --git a/crates/ui-egui/src/canvas/viewport_pages.rs b/crates/ui-egui/src/canvas/viewport_pages.rs index 86860233fc..96084cbaf2 100644 --- a/crates/ui-egui/src/canvas/viewport_pages.rs +++ b/crates/ui-egui/src/canvas/viewport_pages.rs @@ -723,7 +723,7 @@ pub(super) fn show(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize, vie } stream.stats.limit = limit; if stream.busy() { - ctx.request_repaint_after(std::time::Duration::from_millis(16)); + craft::ui::runtime::frame::request_repaint_after(ctx, std::time::Duration::from_millis(16).as_secs_f64()); } true } diff --git a/crates/ui-egui/src/caps_lock_tests.rs b/crates/ui-egui/src/caps_lock_tests.rs index c7826048ee..4e1a40f6c5 100644 --- a/crates/ui-egui/src/caps_lock_tests.rs +++ b/crates/ui-egui/src/caps_lock_tests.rs @@ -28,7 +28,7 @@ fn capslock_harness() -> Harness<'static, Box> { if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { return; } - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); }, app, ); diff --git a/crates/ui-egui/src/chrome_settle_trials.rs b/crates/ui-egui/src/chrome_settle_trials.rs index 83b4a8dd81..0e69330e7f 100644 --- a/crates/ui-egui/src/chrome_settle_trials.rs +++ b/crates/ui-egui/src/chrome_settle_trials.rs @@ -53,13 +53,42 @@ fn chrome_views(h: &H) -> Vec<(&'static str, MemoRun)> { last_frame_memo_runs(&h.ctx).into_iter().filter(|(name, _, _)| CHROME.iter().any(|c| name.contains(c))).map(|(name, _, run)| (name, run)).collect() } +/// The shell's slots of the harness's window, in the order the shell shows them (`AppShell`): the title bar, the +/// options bar, the status bar. +#[derive(Clone, Copy, Debug)] +pub(crate) enum ShellSlot { + Title, + Options, + Status, +} + +/// How the shell's view of `slot` took part in `runs`: `(ran, replayed)`. The shell's slot views share one props type, +/// so they are told apart by id, in the order the shell decides them in every pass, which is the order it shows its +/// slots in. +pub(crate) fn slot_runs(runs: &[(&'static str, egui::Id, MemoRun)], slot: ShellSlot) -> (usize, usize) { + let mut ids: Vec = Vec::new(); + for (name, id, _) in runs { + if name.contains("app_shell::SlotView<") && !ids.contains(id) { + ids.push(*id); + } + } + let Some(&id) = ids.get(slot as usize) else { return (0, 0) }; + let count = |how: MemoRun| runs.iter().filter(|(_, of, run)| *of == id && *run == how).count(); + (count(MemoRun::Ran), count(MemoRun::Replayed)) +} + +/// How the shell's view of `slot` took part in the last frame: `(ran, replayed)`. +fn slot_views(h: &H, slot: ShellSlot) -> (usize, usize) { + slot_runs(&last_frame_memo_runs(&h.ctx), slot) +} + /// The panel tab strips the last pass ran. fn tab_strip_runs(h: &H) -> Vec<(&'static str, u32)> { last_pass_runs(&h.ctx).into_iter().filter(|(ty, _)| ty.contains("TabStrip<'_, craft_ui_panels::docking::PanelKey>")).collect() } -/// A hover over the canvas replays the dock's tab rows and column bars and the menu bar (memoized views) and runs no -/// panel tab strip. +/// A hover over the canvas replays the dock's tab rows and column bars (in the columns' views, which replay whole) and +/// the menu bar (memoized views) and runs no panel tab strip. #[test] fn a_hover_over_the_canvas_replays_the_dock_chrome_and_the_menu_bar() { let mut h = harness(); @@ -68,11 +97,14 @@ fn a_hover_over_the_canvas_replays_the_dock_chrome_and_the_menu_bar() { for step in 1..=3 { h.event(Event::PointerMoved(at + vec2(step as f32, 0.0))); h.run_steps(1); - // The menu bar sits in the title bar's own view: while that replays, the menu bar replays with it. - let title_replayed = views(&h, "TitleSlot<", MemoRun::Replayed) == 1; + // The menu bar sits in the title slot's view: while that replays, the menu bar replays with it. + let title_replayed = slot_views(&h, ShellSlot::Title).1 == 1; + let columns = (views_ran(&h, "area::ColumnView<"), views(&h, "area::ColumnView<", MemoRun::Replayed)); + assert!(columns.0 == 0 && columns.1 >= 1, "hover step {step}: the dock's columns replay: {columns:?}"); let views = chrome_views(&h); for kind in ["TabRow", "dock_column::bar::BarProps", "menu::bar::BarProps"] { - let shown = views.iter().any(|(name, _)| name.contains(kind)) || (kind == "menu::bar::BarProps" && title_replayed); + let replayed_with = if kind == "menu::bar::BarProps" { title_replayed } else { columns.1 >= 1 }; + let shown = views.iter().any(|(name, _)| name.contains(kind)) || replayed_with; assert!(shown, "hover step {step}: the chrome shows a {kind} view: {views:?}"); } let ran: Vec<_> = views.iter().filter(|(_, run)| *run != MemoRun::Replayed).collect(); @@ -81,8 +113,9 @@ fn a_hover_over_the_canvas_replays_the_dock_chrome_and_the_menu_bar() { } } -/// A hover over the canvas replays the title bar, the options bar, the status bar (its own view) and every panel body: the -/// panels read the modifiers, not the pointer frame (storytold/craft-libs#2812), so a pointer move runs none of them. +/// A hover over the canvas replays the title bar, the options bar, the status bar (its own view) and every panel body +/// (in the columns' views, which replay whole): the panels read the modifiers, not the pointer frame +/// (storytold/craft-libs#2812), so a pointer move runs none of them. #[test] fn a_hover_over_the_canvas_replays_the_bars_and_the_panel_bodies() { let mut h = harness(); @@ -90,16 +123,20 @@ fn a_hover_over_the_canvas_replays_the_bars_and_the_panel_bodies() { for step in 1..=3 { h.event(Event::PointerMoved(at + vec2(step as f32, 0.0))); h.run_steps(1); - for slot in ["TitleSlot<", "OptionsSlot<", "status_bar::StatusProps<"] { - assert_eq!((views_ran(&h, slot), views(&h, slot, MemoRun::Replayed)), (0, 1), "hover step {step}: the {slot} view replays"); + for slot in [ShellSlot::Title, ShellSlot::Options, ShellSlot::Status] { + assert_eq!(slot_views(&h, slot), (0, 1), "hover step {step}: the {slot:?} slot's view replays"); } - let bodies = (views_ran(&h, "region_versions::PanelBody<"), views(&h, "region_versions::PanelBody<", MemoRun::Replayed)); - assert!(bodies.0 == 0 && bodies.1 >= 2, "hover step {step}: every panel body replays: {bodies:?}"); + let columns = (views_ran(&h, "area::ColumnView<"), views(&h, "area::ColumnView<", MemoRun::Replayed)); + assert!( + views_ran(&h, "region_versions::PanelBody<") == 0 && columns == (0, columns.1) && columns.1 >= 2, + "hover step {step}: every panel body replays with its column: {columns:?}" + ); } } -/// A hover over the canvas replays the toolbar's footer (the colour chips, Quick Mask and Screen Mode): the rail replays -/// its tool buttons but calls its footer every pass, so before it was a view of its own it ran on every frame (#15493). +/// A hover over the canvas replays the toolbar's footer (the colour chips, Quick Mask and Screen Mode) with the toolbar's +/// column: the rail replays its tool buttons but calls its footer every pass, so before it was a view of its own it ran +/// on every frame (#15493). #[test] fn a_hover_over_the_canvas_replays_the_toolbar_footer() { let mut h = harness(); @@ -107,11 +144,25 @@ fn a_hover_over_the_canvas_replays_the_toolbar_footer() { for step in 1..=3 { h.event(Event::PointerMoved(at + vec2(step as f32, 0.0))); h.run_steps(1); - let footer = (views_ran(&h, "toolbar::FooterProps<"), views(&h, "toolbar::FooterProps<", MemoRun::Replayed)); - assert_eq!(footer, (0, 1), "hover step {step}: the toolbar footer replays"); + let columns = (views_ran(&h, "area::ColumnView<"), views(&h, "area::ColumnView<", MemoRun::Replayed)); + assert!(views_ran(&h, "toolbar::FooterProps<") == 0 && columns.0 == 0 && columns.1 >= 1, "hover step {step}: the toolbar footer replays: {columns:?}"); } } +/// The pointer-move gate (#17148): a move within one toolbar button changes nothing under the pointer, so it runs no +/// frame; a move over the canvas runs one, since the canvas follows the pointer (its cursor, the rulers' marks and the +/// readouts). +#[test] +fn a_move_within_a_button_runs_no_frame_and_one_over_the_canvas_does() { + let h = harness(); + let viewport = egui::ViewportId::ROOT; + let button = h.query_all_by_label("Move Tool").last().map(|node| node.rect()).expect("the toolbar shows the Move tool"); + let inside = button.center(); + assert!(!h.ctx.pointer_move_needs_pass(viewport, Some(inside), inside + vec2(1.0, 1.0)), "a move within the button"); + let canvas = h.state().last_canvas_rect.center(); + assert!(h.ctx.pointer_move_needs_pass(viewport, Some(canvas), canvas + vec2(1.0, 1.0)), "a move over the canvas"); +} + /// Zoom In from the menu runs no panel body that does not show the view: before, every command counted as a command /// run, so a zoom ran every panel body in the next frame (#15493). #[test] @@ -120,8 +171,9 @@ fn a_zoom_runs_only_the_panels_that_show_the_view() { let ctx = h.ctx.clone(); crate::menus::invoke(h.state_mut(), &ctx, "view.zoomIn", json!({})).unwrap(); h.run_steps(1); - let bodies = (views_ran(&h, "region_versions::PanelBody<"), views(&h, "region_versions::PanelBody<", MemoRun::Replayed)); - assert!(bodies.0 <= 1 && bodies.1 >= 2, "only the Navigator's body may run, the others replay: {bodies:?}"); + let columns = views(&h, "area::ColumnView<", MemoRun::Replayed); + let bodies = views_ran(&h, "region_versions::PanelBody<"); + assert!(bodies <= 1 && columns >= 1, "only the Navigator's body may run, the other columns replay: {bodies} ran, {columns} columns replayed"); } /// The footer runs again when a colour it shows changes without a command (the Color panel's sliders, a Color Picker @@ -166,7 +218,7 @@ fn the_chrome_runs_when_what_it_shows_changes() { h.run_steps(1); // The new tab titles change label widths, so the frame takes a second pass that replays what the first ran: // the frame's views tell. - let (tabs, title) = (views_ran(&h, "docking::group::TabRow<"), views_ran(&h, "TitleSlot<")); + let (tabs, title) = (views_ran(&h, "docking::group::TabRow<"), slot_views(&h, ShellSlot::Title).0); assert!(tabs > 0 && title > 0, "a new language runs the tab rows and the title bar: {tabs} tab rows, {title} title bars"); h.run_steps(2); } @@ -181,7 +233,7 @@ fn the_chrome_runs_when_what_it_shows_changes() { h.state_mut().run("layer.new.layer", json!({})).unwrap(); h.run_steps(1); // The edit's frame takes two passes, and its second replays what the first ran: the frame's views tell. - assert!(views_ran(&h, "TitleSlot<") > 0, "an unsaved edit runs the title bar"); + assert!(slot_views(&h, ShellSlot::Title).0 > 0, "an unsaved edit runs the title bar"); } /// A dialog closed with Escape runs no command, and the menu bar takes the menu keys again: Alt+F opens the File menu. @@ -201,3 +253,90 @@ fn the_menu_keys_open_a_menu_after_a_dialog_closes_with_escape() { h.run_steps(4); assert!(items(&h) > titles, "Alt+F opens the File menu: {} menu items, {titles} titles", items(&h)); } + +/// What `ran` counts in each of the next `steps` frames, summed. +fn ran_over(h: &mut H, steps: usize, ran: impl Fn(&H) -> usize) -> usize { + (0..steps) + .map(|_| { + h.run_steps(1); + ran(h) + }) + .sum() +} + +/// The options bar's slot view, if it ran in the last frame. +fn options_ran(h: &H) -> usize { + slot_views(h, ShellSlot::Options).0 +} + +/// The status bar's body view, if it ran in the last frame. +fn status_ran(h: &H) -> usize { + views_ran(h, "status_bar::StatusProps<") +} + +/// A pan with a tool whose bar shows no view field runs neither the options bar nor the status bar (it shows the zoom +/// only); a zoom runs the status bar, and the options bar only while the Zoom tool's bar shows the zoom. +#[test] +fn a_pan_runs_neither_bar_and_a_zoom_runs_the_status_bar() { + let mut h = harness(); + h.state_mut().ui.tool = crate::state::Tool::Move; + h.run_steps(4); + h.state_mut().ui.views[0].center[0] += 40.0; + assert_eq!(ran_over(&mut h, 3, options_ran), 0, "a pan runs no options bar"); + h.state_mut().ui.views[0].center[0] += 40.0; + assert_eq!(ran_over(&mut h, 3, status_ran), 0, "a pan runs no status bar"); + + h.state_mut().ui.views[0].zoom *= 2.0; + let status = ran_over(&mut h, 3, status_ran); + assert!(status > 0, "a zoom runs the status bar: {status}"); +} + +/// The Zoom tool's bar shows the zoom, so a zoom runs it. +#[test] +fn a_zoom_runs_the_zoom_tools_options_bar() { + let mut h = harness(); + h.state_mut().ui.tool = crate::state::Tool::Zoom; + h.run_steps(4); + h.state_mut().ui.views[0].zoom *= 2.0; + assert!(ran_over(&mut h, 3, options_ran) > 0, "a zoom runs the Zoom tool's bar"); +} + +/// A tool option changed outside the bar runs the bar, and the frames after it replay it. +#[test] +fn a_tool_option_runs_the_options_bar_once() { + let mut h = harness(); + h.state_mut().ui.tool = crate::state::Tool::Move; + h.run_steps(4); + assert_eq!(ran_over(&mut h, 2, options_ran), 0, "settled"); + let on = h.state().ui.tool_options.move_auto_select; + h.state_mut().ui.tool_options.move_auto_select = !on; + assert!(ran_over(&mut h, 1, options_ran) > 0, "a changed option runs the bar"); + // What the bar's frame remembers of the option (the saved preferences) moves no version. + assert_eq!(ran_over(&mut h, 3, options_ran), 0, "the frames after the changed one run no bar"); +} + +/// A bar that runs and writes every control's value back leaves the tool options' revision alone, so idle frames never +/// move what the bar's version holds, whichever tool's bar is showing. +#[test] +fn an_idle_options_bar_leaves_the_tool_options_revision() { + let mut h = harness(); + let mut moved = Vec::new(); + for tool in crate::state::Tool::ALL { + h.state_mut().ui.tool = tool; + h.run_steps(4); + let settled = h.state().ui.tool_options.revision(); + h.run_steps(6); + if h.state().ui.tool_options.revision() != settled { + moved.push(tool); + } + } + assert!(moved.is_empty(), "idle frames moved the tool options under {moved:?}"); + // A changed option runs the bar, whose own writes then change nothing more. + h.state_mut().ui.tool = crate::state::Tool::Move; + h.run_steps(4); + let on = h.state().ui.tool_options.move_auto_select; + h.state_mut().ui.tool_options.move_auto_select = !on; + let changed = h.state().ui.tool_options.revision(); + h.run_steps(10); + assert_eq!(h.state().ui.tool_options.revision(), changed, "the bar's run after a change"); +} diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 1868302df4..0060603ca2 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -123,6 +123,8 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest outcome } +#[cfg(test)] +mod pointer_color_picker_sample_tests; #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/control/dispatch.rs b/crates/ui-egui/src/control/dispatch.rs index 933fdb9322..1d6384aab2 100644 --- a/crates/ui-egui/src/control/dispatch.rs +++ b/crates/ui-egui/src/control/dispatch.rs @@ -1215,6 +1215,9 @@ struct ParsedPointer { /// pickers, Color Range, the preview locator, context menus, Move transform controls). The host takes the /// whole queue on its next pass; a held Space is queued with the events (`hold`, then `let_go`), so it is down for /// exactly the events between them. +/// +/// The exception: with a Color Picker as the top dialog its press and drag steps sample at the request, here, so the +/// events never reach the window's input, where the dialog's own controls would take them (#16747). fn pointer(app: &mut PhotocraftApp, ctx: &egui::Context, p: &Value) -> Reply { // Every field and event is validated before the first event is queued, so a rejected call // changes nothing (#2449). @@ -1251,6 +1254,35 @@ fn pointer(app: &mut PhotocraftApp, ctx: &egui::Context, p: &Value) -> Reply { }) { return err(format!("events[{i}] is too far off the canvas: the point must be finite")); } + // #16747: with a Color Picker as the top dialog, whose canvas eyedropper it arms as top, a primary + // `down` and the `move`s of its drag sample the composite at their document points into the picker's + // new colour - the same pick a press on the canvas runs through the dialog tool - and the tool + // underneath is not driven. Nothing is queued for the window either: the dialog's modal layer sits + // over the canvas, so the picker's own controls would take the synthetic events as clicks. A gesture + // the canvas is already running keeps its tool to its release (the picker's pick begins at the next press). + if button == PointerButton::Primary + && !ToolHost::in_gesture(ctx, canvas) + && crate::dialogs::canvas_input::armed(app) == Some(crate::dialogs::canvas_input::DialogPick::Color) + { + let mut held = false; + for step in &parsed.events { + match step.kind { + PointerKind::Down => { + held = true; + crate::dialogs::canvas_input::pick_color(app, [step.x, step.y]); + } + PointerKind::Move if held => { + crate::dialogs::canvas_input::pick_color(app, [step.x, step.y]); + } + // A release ends the gesture without sampling (as the dialog tool's release does), and a + // move before any press is a hover: the picker's pipette samples neither. + PointerKind::Up => held = false, + PointerKind::Move => {} + } + } + ctx.request_repaint(); + return ok(json!({"status": app.ui.status})); + } let mods = tool_mods(modifiers_from(&parsed.modifiers)); // Space held: the Crop tool moves the frame being drawn, a marquee, lasso or shape being drawn moves // instead of growing. Like a modifier flag, it may be top-level or grouped under "modifiers"; it is a held key diff --git a/crates/ui-egui/src/control/pointer_color_picker_sample_tests.rs b/crates/ui-egui/src/control/pointer_color_picker_sample_tests.rs new file mode 100644 index 0000000000..734b4d21d6 --- /dev/null +++ b/crates/ui-egui/src/control/pointer_color_picker_sample_tests.rs @@ -0,0 +1,222 @@ +//! #16747 (EPIC-COLOR-PICKER #16738): with a Color Picker as the top dialog, `ui.pointer` +//! `down` and `move` sample the composite at their document points into the picker's new +//! colour, as a click on the canvas does, and the tool underneath is not driven +//! (`docs/control-protocol.md`). + +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::control::{ControlRequest, Reply, handle}; +use crate::dialogs::canvas_input::{self, DialogPick}; +use crate::state::Tool; + +/// The document points the pixel checks watch: the gesture's points, the line between them, +/// the cyan patch's outside and the canvas corners. +const WATCHED: &[(f64, f64)] = &[(40.0, 40.0), (32.0, 32.0), (28.0, 28.0), (24.0, 24.0), (16.0, 16.0), (55.0, 9.0), (9.0, 55.0), (3.0, 3.0)]; + +fn call(app: &mut PhotocraftApp, ctx: &egui::Context, method: &str, params: Value) -> Value { + let (req, _rx) = ControlRequest::new(method, params); + match handle(app, ctx, &req) { + Reply::Done(v) => v, + _ => panic!("{method}: expected an immediate reply"), + } +} + +fn nothing_queued(ctx: &egui::Context) -> bool { + craft::ui::runtime::windows::WindowHost::of(ctx).injected_idle() +} + +/// `ui.pointer` as the canvas takes it: the request is handled on the app's own context, then +/// canvas passes run until the window host reports its queue idle. +fn pointer(app: &mut PhotocraftApp, params: Value) -> Value { + let ctx = app.ctx().clone(); + crate::canvas::testing::frame(app); + let reply = call(app, &ctx, "ui.pointer", params); + for _ in 0..8 { + if nothing_queued(&ctx) { + break; + } + crate::canvas::testing::frame(app); + } + assert!(nothing_queued(&ctx), "the canvas took all the queued input: {reply}"); + reply +} + +/// The `ui.inspect` `dialogs` list: the hosted dialogs in stack order, the top last. +fn dialogs(app: &mut PhotocraftApp, ctx: &egui::Context) -> Vec { + call(app, ctx, "ui.inspect", json!({}))["result"]["dialogs"].as_array().cloned().unwrap_or_default() +} + +/// The colour the top dialog lists for the picker (`ui.inspect`'s `fields.color`). +fn shown_color(app: &mut PhotocraftApp, ctx: &egui::Context) -> Value { + dialogs(app, ctx).last().cloned().unwrap_or(Value::Null)["fields"]["color"].clone() +} + +/// The composite colour at every watched point: the pixel content around the gesture. +fn composites(app: &mut PhotocraftApp) -> Vec> { + WATCHED.iter().map(|(x, y)| crate::canvas::composite_color(app, *x, *y)).collect() +} + +fn history_len(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.past_len() +} + +/// A 64x64 document, every pixel orange `#ff8000` except the square x/y 12..20 cyan `#00ffff`, +/// and the Pencil selected: a gesture that drives a tool shows as a stroke. +fn pencil_app() -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.session.execute("tools.setColors", json!({"foreground": "#ff8000"})).unwrap(); + app.session.execute("select.rect", json!({"x": 0, "y": 0, "width": 64, "height": 64})).unwrap(); + app.session.execute("edit.fillForeground", json!({})).unwrap(); + app.session.execute("tools.setColors", json!({"foreground": "#00ffff"})).unwrap(); + app.session.execute("select.rect", json!({"x": 12, "y": 12, "width": 8, "height": 8})).unwrap(); + app.session.execute("edit.fillForeground", json!({})).unwrap(); + app.session.execute("select.deselect", json!({})).unwrap(); + // A foreground that is neither sample colour: what the picker shows when it opens can + // never be mistaken for a sampled colour. + app.session.execute("tools.setColors", json!({"foreground": "#123456"})).unwrap(); + app.ui.tool = Tool::Pencil; + app.sync_views(); + app +} + +/// The app with the foreground Color Picker open as the top dialog, its canvas eyedropper armed. +fn with_picker_open() -> (Box, egui::Context) { + let mut app = pencil_app(); + let ctx = app.ctx().clone(); + let opened = call(&mut app, &ctx, "ui.dialog.open", json!({"kind": "colorPicker", "target": "foreground"})); + assert_eq!(opened["ok"], true, "{opened}"); + crate::canvas::testing::frame(&mut app); + crate::canvas::testing::frame(&mut app); + let top = dialogs(&mut app, &ctx).last().cloned().unwrap_or(Value::Null); + assert_eq!(top["key"], "foreground", "the Color Picker is the top dialog: {top}"); + assert_eq!(shown_color(&mut app, &ctx), "#123456", "the picker opens on the foreground colour"); + assert_eq!(canvas_input::armed(&app), Some(DialogPick::Color), "the top picker arms its canvas eyedropper"); + (app, ctx) +} + +/// The Done-when rule: `down` and `move` over the image land the colour of their own document +/// point in the picker (the last one shown), no stroke appears, the tool stays put and no +/// history state is added. +#[test] +fn pointer_down_and_move_sample_their_points_into_the_open_color_picker() { + let (mut app, ctx) = with_picker_open(); + let pixels_before = composites(&mut app); + let tool_before = app.ui.tool; + let history_before = history_len(&app); + let reply = pointer( + &mut app, + json!({"events": [ + {"kind": "down", "x": 40, "y": 40}, + {"kind": "move", "x": 16, "y": 16}, + {"kind": "up", "x": 16, "y": 16}, + ]}), + ); + assert_eq!(reply["ok"], true, "{reply}"); + crate::canvas::testing::frame(&mut app); + assert_eq!(shown_color(&mut app, &ctx), "#00ffff", "the picker shows the colour of the move's point"); + assert_eq!(composites(&mut app), pixels_before, "the tool underneath is not driven: the watched pixels are identical"); + assert_eq!(app.ui.tool, tool_before, "the active tool is unchanged"); + assert_eq!(history_len(&app), history_before, "no history state is added"); +} + +/// A press alone samples its own point; the release at another point samples nothing (the +/// gesture ends where the picker shows the pressed point). +#[test] +fn pointer_down_samples_the_pressed_point_and_the_release_samples_nothing() { + let (mut app, ctx) = with_picker_open(); + let reply = pointer( + &mut app, + json!({"events": [ + {"kind": "down", "x": 40, "y": 40}, + {"kind": "up", "x": 16, "y": 16}, + ]}), + ); + assert_eq!(reply["ok"], true, "{reply}"); + crate::canvas::testing::frame(&mut app); + assert_eq!(shown_color(&mut app, &ctx), "#ff8000", "the picker shows the colour of the pressed point"); +} + +/// Off the image nothing changes: not the picker's colour, not the canvas, not the history. +#[test] +fn pointer_events_off_the_image_change_nothing_while_the_picker_is_open() { + let (mut app, ctx) = with_picker_open(); + let pixels_before = composites(&mut app); + let history_before = history_len(&app); + let reply = pointer( + &mut app, + json!({"events": [ + {"kind": "down", "x": -4, "y": -4}, + {"kind": "move", "x": -4, "y": -4}, + {"kind": "up", "x": -4, "y": -4}, + ]}), + ); + assert_eq!(reply["ok"], true, "{reply}"); + crate::canvas::testing::frame(&mut app); + assert_eq!(shown_color(&mut app, &ctx), "#123456", "off the image the picker keeps its colour"); + assert_eq!(composites(&mut app), pixels_before, "and the canvas changes nothing"); + assert_eq!(history_len(&app), history_before, "no history state is added"); +} + +/// Not measured, kept as today: the picker's pass-under-the-modal-layer registration is the +/// primary press, so a right-button event follows the unchanged queueing route and samples nothing. +#[test] +fn a_secondary_press_while_the_picker_is_open_still_samples_nothing() { + let (mut app, ctx) = with_picker_open(); + let pixels_before = composites(&mut app); + let reply = pointer( + &mut app, + json!({"button": "secondary", "events": [ + {"kind": "down", "x": 40, "y": 40}, + {"kind": "move", "x": 16, "y": 16}, + {"kind": "up", "x": 16, "y": 16}, + ]}), + ); + assert_eq!(reply["ok"], true, "{reply}"); + crate::canvas::testing::frame(&mut app); + assert_eq!(shown_color(&mut app, &ctx), "#123456", "the right button is not the picker's press"); + assert_eq!(composites(&mut app), pixels_before, "and the canvas changes nothing"); +} + +/// Not measured, kept as today: a `move` before any `down` is a hover; the picker's pipette +/// samples on a press and on the drag of a held press, not on hovering. +#[test] +fn a_leading_move_while_the_picker_is_open_still_samples_nothing() { + let (mut app, ctx) = with_picker_open(); + let pixels_before = composites(&mut app); + let reply = pointer( + &mut app, + json!({"events": [ + {"kind": "move", "x": 40, "y": 40}, + {"kind": "move", "x": 16, "y": 16}, + ]}), + ); + assert_eq!(reply["ok"], true, "{reply}"); + crate::canvas::testing::frame(&mut app); + assert_eq!(shown_color(&mut app, &ctx), "#123456", "a hover changes nothing in the picker"); + assert_eq!(composites(&mut app), pixels_before, "and nothing on the canvas"); +} + +/// The guard: with no picker open the same sequence keeps today's behaviour exactly - the +/// Pencil paints the line and the stroke is one history state. +#[test] +fn pointer_without_the_picker_open_still_drives_the_pencil_over_the_same_points() { + let mut app = pencil_app(); + app.session.execute("tools.setColors", json!({"foreground": "#ff0000"})).unwrap(); + let pixels_before = composites(&mut app); + let history_before = history_len(&app); + let reply = pointer( + &mut app, + json!({"events": [ + {"kind": "down", "x": 40, "y": 40}, + {"kind": "move", "x": 16, "y": 16}, + {"kind": "up", "x": 16, "y": 16}, + ]}), + ); + assert_eq!(reply["ok"], true, "{reply}"); + crate::canvas::testing::frame(&mut app); + assert_eq!(crate::canvas::composite_color(&mut app, 28.0, 28.0), Some([1.0, 0.0, 0.0]), "the Pencil drew the same gesture"); + assert_eq!(crate::canvas::composite_color(&mut app, 3.0, 3.0), pixels_before[WATCHED.len() - 1], "pixels off the stroke keep their colour"); + assert_eq!(history_len(&app), history_before + 1, "the stroke is one history state"); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 77aad0b079..5bfa384ffb 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -13,6 +13,17 @@ use serde_json::Value; use crate::PhotocraftApp; +/// The File Info dialog's title: the active document's name without its extension (#13824). +pub(crate) fn file_info_title(app: &PhotocraftApp) -> String { + app.session.active().map_or_else( + || tl!("File Info").to_string(), + |st| match st.doc.name.rsplit_once('.') { + Some((stem, _)) if !stem.is_empty() => stem.to_owned(), + _ => st.doc.name.clone(), + }, + ) +} + /// What a family of the hosted dialogs does with each result, and who owns which dialog key. pub(crate) mod params { use std::path::{Path, PathBuf}; @@ -64,6 +75,23 @@ pub(crate) mod params { } } + /// The File Info dialog's document, captured when it opened (#13824). + fn file_info_document(captured: &Value) -> Option { + captured.get("document").and_then(Value::as_u64).map(DocId) + } + + /// File Info's OK: run it on the document it opened on, even when another tab is active (#13824). + fn run_file_info(app: &mut PhotocraftApp, ctx: &egui::Context, result: ParamResult) { + let doc = file_info_document(&captured(app, "file.fileInfo")); + let outcome = match doc { + Some(doc) => app.with_document(doc, |app| filter_dialog::run_command(app, ctx, "file.fileInfo", result)), + None => filter_dialog::run_command(app, ctx, "file.fileInfo", result), + }; + if let Err(error) = outcome { + crate::notices::error(app, error); + } + } + /// Every family of parameter dialogs, first match wins; the generic filter family owns what is left. pub(crate) const PARAM_FAMILIES: &[ParamFamily] = &[ ParamFamily { check: Some(fill_ui::check), ..ParamFamily::new(fill_ui::owns, fill_ui::run) }, @@ -115,6 +143,7 @@ pub(crate) mod params { cancel: Some(filter_dialog::cancel), ..ParamFamily::new(|key| key == "file.automate.batch", filter_dialog::run) }, + ParamFamily { document: Some(file_info_document), ..ParamFamily::new(|key| key == "file.fileInfo", run_file_info) }, ParamFamily { cancel: Some(filter_dialog::cancel), ..ParamFamily::new(crate::view_cmds::dialogs::is_form, filter_dialog::run) }, crate::prefs_ui::PRESETS_FAMILY, crate::swatches_ui::SWATCH_NAME_FAMILY, @@ -453,6 +482,7 @@ pub(crate) fn prompts_take(app: &mut PhotocraftApp, ctx: &egui::Context) { /// The families that take their own results (one `take(app, ctx)` each), in order. pub(crate) const TAKERS: &[fn(&mut PhotocraftApp, &egui::Context)] = &[ alerts::take, + crate::file_open::take_open_alerts, discard_ui::take, open_prompt::take, credits::take, @@ -751,6 +781,9 @@ mod arbitrary_ruler_prefill_tests; pub mod assign_profile_layers_alert; #[cfg(test)] mod assign_profile_layers_alert_tests; +#[cfg(test)] +mod auto_align_dialog_tests; +pub(crate) mod auto_align_ui; pub(crate) mod bitmap_dialog; pub mod blend_options; pub mod blur_pins; @@ -772,6 +805,8 @@ mod color_lookup_smart_edit_tests; pub(crate) mod color_picker_preview; pub mod color_picker_ui; pub mod color_range_ui; +#[cfg(test)] +mod color_settings_policy_greying_tests; pub mod color_table_ui; pub(crate) mod conditional_mode_change_dialog; pub(crate) mod contact_sheet_ui; @@ -782,6 +817,8 @@ pub mod delete_layer_prompt; pub mod discard_ui; pub mod disk_change_prompt; pub mod distort_ui; +#[cfg(test)] +mod duplicate_layer_other_document_name_tests; pub mod duplicate_layer_ui; pub mod equalize_ui; pub mod export_dialog; diff --git a/crates/ui-egui/src/dialogs/adjust_editors.rs b/crates/ui-egui/src/dialogs/adjust_editors.rs index 4ff8b48570..7558da5ea0 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors.rs @@ -174,6 +174,8 @@ pub struct AdjustOut { pub ask: Option, /// The pass's edit events of the value, in order, with their gesture ids and phases. pub edit: EditEvents, + /// The tone Color Balance shows after the pass, for a host that keeps it; `None` for the other kinds. + pub tone: Option, } /// What the editor function reads, built once when the adjustment opens. @@ -189,7 +191,8 @@ pub struct EditorSetup { pub gradients: Vec, /// The current foreground and background colours ([`swatches`]), for the host's colour requests. pub swatches: [[f32; 3]; 2], - /// The tone Color Balance shows first; `None` keeps the editor's default (Midtones). + /// The tone Color Balance shows, for a host that keeps it (it stores [`AdjustOut::tone`]); `None` leaves the + /// tone to the editor (Midtones at first). pub tone: Option, /// The Smart Filter the dialog edits is not reachable from the active document: the editor shows no controls. pub stale: bool, @@ -215,7 +218,7 @@ impl Default for EditorSetup { /// The edit events of one editor lifted onto the value. fn lifted(events: EditEvents, wrap: impl Fn(T) -> AdjustValue) -> AdjustOut { - AdjustOut { ask: None, edit: events.map(wrap) } + AdjustOut { ask: None, edit: events.map(wrap), tone: None } } fn reset_legacy_toggle(value: BrightnessContrast, previous_legacy: bool, reset: bool) -> BrightnessContrast { @@ -288,7 +291,7 @@ fn show(kind: &str, setup: &EditorSetup, ui: &mut Ui, value: &mut AdjustValue, c *curves = converted.clone(); edit.push(EditEvent::set(Mixed::Same(from), AdjustValue::Curves { curves: converted }, Arc::from("Curves Mode"), None)); } - AdjustOut { ask: None, edit } + AdjustOut { ask: None, edit, tone: None } } ("exposure", AdjustValue::Exposure { values }) => { let fields = AdjustField::exposure(&Env::of(ui).words::()); @@ -315,16 +318,16 @@ fn show(kind: &str, setup: &EditorSetup, ui: &mut Ui, value: &mut AdjustValue, c editor = editor.tone(tone); } let out = editor.show(ui); - lifted(out.edit.events, |value| AdjustValue::ColorBalance { value }) + AdjustOut { tone: Some(out.tone), ..lifted(out.edit.events, |value| AdjustValue::ColorBalance { value }) } } ("blackWhite", AdjustValue::BlackWhite { value }) => { let out = BlackWhiteEditor::new("Black & White", Bind::bound(value)).context(context).show(ui); let ask = if out.auto { Some(AdjustAsk::Auto) } else { out.pick_color.map(AdjustAsk::PickColor) }; - AdjustOut { ask, edit: out.edit.events.map(|value| AdjustValue::BlackWhite { value }) } + AdjustOut { ask, edit: out.edit.events.map(|value| AdjustValue::BlackWhite { value }), tone: None } } ("photoFilter", AdjustValue::PhotoFilter { value }) => { let out = PhotoFilterEditor::new("Photo Filter", Bind::bound(value)).context(context).show(ui); - AdjustOut { ask: out.pick_color.map(AdjustAsk::PickColor), edit: out.edit.events.map(|value| AdjustValue::PhotoFilter { value }) } + AdjustOut { ask: out.pick_color.map(AdjustAsk::PickColor), edit: out.edit.events.map(|value| AdjustValue::PhotoFilter { value }), tone: None } } ("channelMixer", AdjustValue::ChannelMixer { value }) => { let out = ChannelMixerEditor::new("Channel Mixer", Bind::bound(value)).context(context).show(ui); @@ -358,7 +361,7 @@ fn show(kind: &str, setup: &EditorSetup, ui: &mut Ui, value: &mut AdjustValue, c AdjustAsk::PickColor(request) }) }; - AdjustOut { ask, edit } + AdjustOut { ask, edit, tone: None } } ("selectiveColor", AdjustValue::SelectiveColor { value }) => { let out = SelectiveColorEditor::new("Selective Color", Bind::bound(value)).context(context).show(ui); diff --git a/crates/ui-egui/src/dialogs/adjust_editors/session.rs b/crates/ui-egui/src/dialogs/adjust_editors/session.rs index 2c0b85ca45..f3493ab60d 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/session.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/session.rs @@ -32,7 +32,7 @@ pub(crate) struct PropertiesAdjust { pub channel: usize, /// The Levels clipping display. pub clipping: Option, - /// A tone for Color Balance to show, given once: the Reset to defaults shows Midtones again. + /// The tone Color Balance shows, as the editor last reported it; the Reset to defaults sets Midtones. pub tone: Option, /// The Color Picker a colour well opened, while it is open. pub pick: Option, @@ -187,7 +187,6 @@ pub fn layer_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj // count of passes the panel showed something else or nothing (`PhotocraftApp::properties_hidden`), which stays // put while it shows this layer, replays included. record.session.track(session_target(doc, id), app.properties_hidden, &committed); - app.properties_tracked = true; } follow_color_pick(app, id, &mut record, &committed, &vcx); let mut value = match &app.live_adjust { @@ -207,7 +206,7 @@ pub fn layer_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj }, gradients: if kind == "gradientMap" { gradient_presets(app) } else { Vec::new() }, swatches: swatches(app), - tone: record.tone.take(), + tone: record.tone, ..Default::default() }; let armed = crate::layer_picker::armed(app).filter(|(layer, _)| *layer == id).map(|(_, picker)| picker); @@ -220,6 +219,9 @@ pub fn layer_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj if picker != armed { crate::layer_picker::arm(app, id, picker); } + if out.tone.is_some() { + record.tone = out.tone; + } for event in out.edit { match &event { diff --git a/crates/ui-egui/src/dialogs/apply_image_mask_group_tests.rs b/crates/ui-egui/src/dialogs/apply_image_mask_group_tests.rs new file mode 100644 index 0000000000..9f29624e96 --- /dev/null +++ b/crates/ui-egui/src/dialogs/apply_image_mask_group_tests.rs @@ -0,0 +1,339 @@ +//! #14489: Image › Apply Image's Mask... checkbox and its group (Source, Layer, Channel, Invert). +//! +//! The five documents of the issue, opened in its order: "other" (RGB 8 bit, 300 x 200), "gray" (Grayscale 8 bit, +//! 400 x 300, left half black, right half white), "rgb16" (RGB 16 bit, 400 x 300), "source" (RGB 8 bit, 400 x 300, +//! Background 128 plus a layer "S1" white on the right half) and "target" (RGB 8 bit, 400 x 300; Background left half +//! 200/100/50, right half 50/150/250; layers "Top" and "Masked"; alpha channel "Alpha 1" white over (0,0)-(200,150)). +//! "target" is active, its Background targeted. + +use super::params_for; + +/// The dialog's row keys (shell keys: `__` keys never reach the command). +const MASK_ON: &str = "__mask"; +const MASK_SOURCE: &str = "__maskSource"; +const MASK_INVERT: &str = "__maskInvert"; + +fn mask_layer_key(index: usize) -> String { + format!("__maskLayer/{index}") +} + +fn mask_channel_key(index: usize) -> String { + format!("__maskChannel/{index}") +} +use crate::PhotocraftApp; +use craft::ui::dialog::DialogId; +use craft::ui::patterns::form_dialogs::ParamKind; +use serde_json::{Value, json}; + +const APPLY: &str = "image.applyImage"; + +fn run(app: &mut PhotocraftApp, id: &str, params: Value) { + app.run(id, params).unwrap_or_else(|e| panic!("{id}: {e}")); +} + +/// Fills the rectangle `x, y, w, h` of the active layer with `color`. +fn fill(app: &mut PhotocraftApp, rect: [u32; 4], color: &str) { + run(app, "select.rect", json!({"x": rect[0], "y": rect[1], "width": rect[2], "height": rect[3]})); + run(app, "edit.fill", json!({"color": color})); + run(app, "select.deselect", json!({})); +} + +fn five_documents() -> (Box, egui::Context) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + run(&mut app, "file.new", json!({"width": 300, "height": 200, "name": "other"})); + run(&mut app, "file.new", json!({"width": 400, "height": 300, "mode": "gray", "background": "#000000", "name": "gray"})); + fill(&mut app, [200, 0, 200, 300], "#ffffff"); + run(&mut app, "file.new", json!({"width": 400, "height": 300, "depth": 16, "background": "#404040", "name": "rgb16"})); + run(&mut app, "file.new", json!({"width": 400, "height": 300, "background": "#808080", "name": "source"})); + run(&mut app, "layer.new.layer", json!({"name": "S1"})); + fill(&mut app, [200, 0, 200, 300], "#ffffff"); + run(&mut app, "file.new", json!({"width": 400, "height": 300, "background": "#c86432", "name": "target"})); + fill(&mut app, [200, 0, 200, 300], "#3296fa"); + run(&mut app, "select.rect", json!({"x": 0, "y": 0, "width": 200, "height": 150})); + run(&mut app, "select.saveSelection", json!({"name": "Alpha 1"})); + run(&mut app, "select.deselect", json!({})); + run(&mut app, "layer.new.layer", json!({"name": "Top"})); + run(&mut app, "layer.new.layer", json!({"name": "Masked"})); + run(&mut app, "layer.select", json!({"name": "Background"})); + app.sync_views(); + let ctx = app.ctx().clone(); + (app, ctx) +} + +fn frame(app: &mut PhotocraftApp, ctx: &egui::Context) { + let mut output = ctx.run_ui(Default::default(), |ui| { + let mut frame = eframe::Frame::_new_kittest(); + app.logic_frame(ui.ctx(), &mut frame); + app.ui_frame(ui, &mut frame); + }); + output.textures_delta.clear(); +} + +fn open(app: &mut PhotocraftApp, ctx: &egui::Context) -> DialogId { + let reply = crate::menus::invoke(app, ctx, APPLY, json!({})).unwrap(); + let want = reply["dialog"].as_str().expect("the reply names a dialog").to_owned(); + let id = app.framework.dialogs.open_dialogs().into_iter().map(|d| d.id).find(|id| id.value().to_string() == want).expect("the dialog is open"); + frame(app, ctx); + id +} + +fn fields(app: &PhotocraftApp, id: DialogId) -> Value { + app.framework.dialogs.open_dialogs().into_iter().find(|open| open.id == id).and_then(|open| open.fields).expect("an open dialog") +} + +fn set(app: &mut PhotocraftApp, ctx: &egui::Context, id: DialogId, key: &str, value: Value) { + app.framework.dialogs.set_json_field(ctx, id, key, value).unwrap_or_else(|e| panic!("{key}: {e}")); + // The form brings its derived keys up to date at its next pass. + frame(app, ctx); +} + +/// The `(id, label)` options of choice row `key`. +fn options(app: &mut PhotocraftApp, key: &str) -> Vec<(String, String)> { + let (params, _) = params_for(app, APPLY).expect("Apply Image has a form"); + match ¶ms.iter().find(|p| p.key == key).unwrap_or_else(|| panic!("no row {key}")).kind { + ParamKind::Choice { options, .. } => options.iter().map(|(id, label)| (id.clone(), label.as_str().to_owned())).collect(), + other => panic!("{key} is not a choice: {other:?}"), + } +} + +fn ids(app: &mut PhotocraftApp, key: &str) -> Vec { + options(app, key).into_iter().map(|(id, _)| id).collect() +} + +fn index_of(app: &PhotocraftApp, name: &str) -> usize { + app.session.documents().iter().position(|st| st.doc.name == name).unwrap_or_else(|| panic!("no document {name}")) +} + +/// The active layer's 8-bit RGB at `(x, y)`. +fn rgb(app: &PhotocraftApp, x: i32, y: i32) -> [u8; 3] { + let st = app.session.active().unwrap(); + let p = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().pixel(x, y); + [0, 1, 2].map(|c| (p[c] * 255.0).round() as u8) +} + +#[test] +fn mask_is_off_by_default_and_sends_no_mask() { + let (mut app, ctx) = five_documents(); + let d = open(&mut app, &ctx); + let shown = fields(&app, d); + assert_eq!(shown[MASK_ON], false); + for key in ["maskDocument", "maskLayer", "maskChannel", "maskInvert"] { + assert!(shown.get(key).is_none(), "{key} is sent with Mask off: {shown}"); + } + // Ticked, then unticked again: no mask either. + set(&mut app, &ctx, d, MASK_ON, json!(true)); + assert!(fields(&app, d).get("maskChannel").is_some()); + set(&mut app, &ctx, d, MASK_ON, json!(false)); + assert!(fields(&app, d).get("maskChannel").is_none()); + set(&mut app, &ctx, d, "blending", json!("normal")); + set(&mut app, &ctx, d, "sourceInvert", json!(true)); + crate::dialogs::confirm(&mut app, &ctx, d).unwrap(); + // The whole layer is the inverted target. + assert_eq!(rgb(&app, 50, 50), [55, 155, 205]); + assert_eq!(rgb(&app, 300, 50), [205, 105, 5]); +} + +#[test] +fn mask_source_lists_same_size_and_depth_documents_in_open_order() { + let (mut app, ctx) = five_documents(); + let names: Vec = options(&mut app, MASK_SOURCE).into_iter().map(|(_, name)| name).collect(); + assert_eq!(names, ["gray", "source", "target"]); + let d = open(&mut app, &ctx); + assert_eq!(fields(&app, d)[MASK_SOURCE], index_of(&app, "gray").to_string(), "the first document of the list"); +} + +#[test] +fn mask_layer_follows_the_mask_source() { + let (mut app, _) = five_documents(); + let (gray, source, target) = (index_of(&app, "gray"), index_of(&app, "source"), index_of(&app, "target")); + assert_eq!(ids(&mut app, &mask_layer_key(gray)), ["Background"]); + assert_eq!(ids(&mut app, &mask_layer_key(source)), ["merged", "S1", "Background"]); + assert_eq!(ids(&mut app, &mask_layer_key(target)), ["merged", "Masked", "Top", "Background"]); + let (params, _) = params_for(&mut app, APPLY).unwrap(); + let default = |key: &str| match ¶ms.iter().find(|p| p.key == key).unwrap().kind { + ParamKind::Choice { default, .. } => default.clone(), + _ => None, + }; + assert_eq!(default(&mask_layer_key(gray)).as_deref(), Some("Background")); + assert_eq!(default(&mask_layer_key(target)).as_deref(), Some("merged")); + // Documents of another size or bit depth have no rows. + let rgb16 = index_of(&app, "rgb16"); + assert!(params.iter().all(|p| p.key != mask_layer_key(rgb16))); +} + +#[test] +fn mask_channel_lists_gray_the_colours_and_the_alpha_channels() { + let (mut app, _) = five_documents(); + let (gray, target) = (index_of(&app, "gray"), index_of(&app, "target")); + let labels = |list: Vec<(String, String)>| list.into_iter().map(|(_, label)| label).collect::>(); + assert_eq!(labels(options(&mut app, &mask_channel_key(gray))), ["Gray"]); + assert_eq!(labels(options(&mut app, &mask_channel_key(target))), ["Gray", "Red", "Green", "Blue", "Alpha 1"]); + // The composite keeps the engine's id; the engine reads a mask composite as luminosity. + assert_eq!(ids(&mut app, &mask_channel_key(target))[0], "RGB"); +} + +#[test] +fn ok_applies_through_the_chosen_mask_and_its_invert() { + let (mut app, ctx) = five_documents(); + let target = index_of(&app, "target"); + for (invert, at_50, at_300) in [(false, [55, 155, 205], [50, 150, 250]), (true, [200, 100, 50], [205, 105, 5])] { + let d = open(&mut app, &ctx); + set(&mut app, &ctx, d, "blending", json!("normal")); + set(&mut app, &ctx, d, "sourceInvert", json!(true)); + set(&mut app, &ctx, d, MASK_ON, json!(true)); + set(&mut app, &ctx, d, MASK_SOURCE, json!(target.to_string())); + set(&mut app, &ctx, d, &mask_channel_key(target), json!("Alpha 1")); + set(&mut app, &ctx, d, MASK_INVERT, json!(invert)); + let sent = fields(&app, d); + assert_eq!(sent["maskDocument"], target); + assert_eq!(sent["maskLayer"], "merged"); + assert_eq!(sent["maskChannel"], "Alpha 1"); + // Invert is recorded only when it is on. + assert_eq!(sent.get("maskInvert").cloned(), invert.then_some(json!(true))); + crate::dialogs::confirm(&mut app, &ctx, d).unwrap(); + assert_eq!(rgb(&app, 50, 50), at_50, "invert {invert}"); + assert_eq!(rgb(&app, 300, 50), at_300, "invert {invert}"); + run(&mut app, "edit.undo", json!({})); + } +} + +#[test] +fn a_mask_from_another_document() { + let (mut app, ctx) = five_documents(); + let gray = index_of(&app, "gray"); + let d = open(&mut app, &ctx); + set(&mut app, &ctx, d, "blending", json!("normal")); + set(&mut app, &ctx, d, "sourceInvert", json!(true)); + set(&mut app, &ctx, d, MASK_ON, json!(true)); + assert_eq!(fields(&app, d)["maskDocument"], gray); + crate::dialogs::confirm(&mut app, &ctx, d).unwrap(); + // "gray" is black on the left, white on the right. + assert_eq!(rgb(&app, 50, 50), [200, 100, 50]); + assert_eq!(rgb(&app, 300, 50), [205, 105, 5]); + run(&mut app, "edit.undo", json!({})); + // OK right after an edit, with no pass in between, sends the edited mask. + let d = open(&mut app, &ctx); + app.framework.dialogs.set_json_field(&ctx, d, MASK_INVERT, json!(true)).unwrap(); + crate::dialogs::confirm(&mut app, &ctx, d).unwrap(); + assert_eq!(rgb(&app, 50, 50), [55, 155, 205]); + assert_eq!(rgb(&app, 300, 50), [50, 150, 250]); +} + +/// "clash" (RGB 8 bit, 400 x 300, Background 200/100/50): an alpha channel named "Red" white on the left half, and a +/// pixel layer named "merged" white on the right half above the Background, which is targeted. +fn names_like_the_built_in_choices() -> (Box, egui::Context, usize) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + run(&mut app, "file.new", json!({"width": 400, "height": 300, "background": "#c86432", "name": "clash"})); + run(&mut app, "select.rect", json!({"x": 0, "y": 0, "width": 200, "height": 300})); + run(&mut app, "select.saveSelection", json!({"name": "Red"})); + run(&mut app, "select.deselect", json!({})); + run(&mut app, "layer.new.layer", json!({"name": "merged"})); + fill(&mut app, [200, 0, 200, 300], "#ffffff"); + run(&mut app, "layer.select", json!({"name": "Background"})); + app.sync_views(); + let ctx = app.ctx().clone(); + let clash = index_of(&app, "clash"); + (app, ctx, clash) +} + +/// The option id of row `key` at `position` of its list, after checking the list's labels and that no two options +/// share an id. +fn option_at(app: &mut PhotocraftApp, key: &str, labels: &[&str], position: usize) -> String { + let list = options(app, key); + assert_eq!(list.iter().map(|(_, label)| label.as_str()).collect::>(), labels, "{key}"); + let mut unique: Vec<&String> = list.iter().map(|(id, _)| id).collect(); + unique.sort(); + unique.dedup(); + assert_eq!(unique.len(), list.len(), "{key} options share an id: {list:?}"); + list[position].0.clone() +} + +#[test] +fn a_mask_alpha_named_like_a_colour_channel_reads_the_alpha() { + let (mut app, ctx, clash) = names_like_the_built_in_choices(); + let alpha = option_at(&mut app, &mask_channel_key(clash), &["Gray", "Red", "Green", "Blue", "Red"], 4); + let d = open(&mut app, &ctx); + set(&mut app, &ctx, d, "blending", json!("normal")); + set(&mut app, &ctx, d, "sourceInvert", json!(true)); + set(&mut app, &ctx, d, MASK_ON, json!(true)); + set(&mut app, &ctx, d, MASK_SOURCE, json!(clash.to_string())); + set(&mut app, &ctx, d, &mask_channel_key(clash), json!(alpha)); + assert_eq!(fields(&app, d)["maskChannel"], json!({"alpha": 0}), "an explicit alpha selector"); + crate::dialogs::confirm(&mut app, &ctx, d).unwrap(); + // The alpha masks the left half in and the right half out; the red plane (200 everywhere) would mix both. + assert_eq!(rgb(&app, 50, 50), [55, 155, 205]); + assert_eq!(rgb(&app, 300, 50), [200, 100, 50]); +} + +#[test] +fn a_mask_layer_named_merged_is_that_layer_not_the_composite() { + let (mut app, ctx, clash) = names_like_the_built_in_choices(); + let layer = option_at(&mut app, &mask_layer_key(clash), &["Merged", "merged", "Background"], 1); + let d = open(&mut app, &ctx); + set(&mut app, &ctx, d, "blending", json!("normal")); + set(&mut app, &ctx, d, "sourceInvert", json!(true)); + set(&mut app, &ctx, d, MASK_ON, json!(true)); + set(&mut app, &ctx, d, MASK_SOURCE, json!(clash.to_string())); + set(&mut app, &ctx, d, &mask_layer_key(clash), json!(layer)); + assert_eq!(fields(&app, d)["maskLayer"], json!({"name": "merged"}), "an explicit layer name selector"); + crate::dialogs::confirm(&mut app, &ctx, d).unwrap(); + let through_dialog = [rgb(&app, 50, 50), rgb(&app, 300, 50)]; + run(&mut app, "edit.undo", json!({})); + // The same as the command with the layer named explicitly, and not the result of the composite as mask. + let mask = |layer: Value| json!({"sourceInvert": true, "blending": "normal", "mask": {"document": clash, "layer": layer, "channel": "RGB"}}); + run(&mut app, APPLY, mask(json!({"name": "merged"}))); + assert_eq!([rgb(&app, 50, 50), rgb(&app, 300, 50)], through_dialog); + run(&mut app, "edit.undo", json!({})); + run(&mut app, APPLY, mask(json!("merged"))); + assert_ne!([rgb(&app, 50, 50), rgb(&app, 300, 50)], through_dialog, "the composite masks differently"); +} + +/// "sentinels" (RGB 8 bit, 400 x 300, Background 200/100/50, targeted): an alpha channel named "none" white on the left +/// half, and an alpha channel with no name white on the right half. The engine reads a mask channel "none" as no mask +/// and drops an empty one. +fn alphas_named_like_no_mask() -> (Box, egui::Context, usize) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + run(&mut app, "file.new", json!({"width": 400, "height": 300, "background": "#c86432", "name": "sentinels"})); + run(&mut app, "select.rect", json!({"x": 0, "y": 0, "width": 200, "height": 300})); + run(&mut app, "select.saveSelection", json!({"name": "none"})); + run(&mut app, "select.rect", json!({"x": 200, "y": 0, "width": 200, "height": 300})); + run(&mut app, "select.saveSelection", json!({"name": "unnamed"})); + run(&mut app, "select.deselect", json!({})); + // The commands refuse an empty name; a file can still bring one. + std::sync::Arc::make_mut(app.session.active_mut().unwrap().doc_mut()).channels[1].name = String::new(); + app.sync_views(); + let ctx = app.ctx().clone(); + let doc = index_of(&app, "sentinels"); + (app, ctx, doc) +} + +/// Applies the inverted target with Normal through the mask alpha at `position` of the Channel list of "sentinels", +/// checking the selector the dialog sends. +fn apply_through_mask_alpha(position: usize, selector: Value) -> PhotocraftApp { + let (mut app, ctx, doc) = alphas_named_like_no_mask(); + let alpha = option_at(&mut app, &mask_channel_key(doc), &["Gray", "Red", "Green", "Blue", "none", ""], position); + let d = open(&mut app, &ctx); + set(&mut app, &ctx, d, "blending", json!("normal")); + set(&mut app, &ctx, d, "sourceInvert", json!(true)); + set(&mut app, &ctx, d, MASK_ON, json!(true)); + set(&mut app, &ctx, d, MASK_SOURCE, json!(doc.to_string())); + set(&mut app, &ctx, d, &mask_channel_key(doc), json!(alpha)); + assert_eq!(fields(&app, d)["maskChannel"], selector, "an explicit alpha selector"); + crate::dialogs::confirm(&mut app, &ctx, d).unwrap(); + *app +} + +#[test] +fn a_mask_alpha_named_none_masks() { + let app = apply_through_mask_alpha(4, json!({"alpha": 0})); + // Only the left half, where the alpha is white, takes the inverted target; without a mask both halves would. + assert_eq!(rgb(&app, 50, 50), [55, 155, 205]); + assert_eq!(rgb(&app, 300, 50), [200, 100, 50]); +} + +#[test] +fn a_mask_alpha_with_no_name_masks() { + let app = apply_through_mask_alpha(5, json!({"alpha": 1})); + assert_eq!(rgb(&app, 50, 50), [200, 100, 50]); + assert_eq!(rgb(&app, 300, 50), [55, 155, 205]); +} diff --git a/crates/ui-egui/src/dialogs/apply_image_source_document_tests.rs b/crates/ui-egui/src/dialogs/apply_image_source_document_tests.rs new file mode 100644 index 0000000000..f220e9f323 --- /dev/null +++ b/crates/ui-egui/src/dialogs/apply_image_source_document_tests.rs @@ -0,0 +1,421 @@ +//! #14480: Image › Apply Image's Source document dropdown, the Layer and Channel rows that follow it, the Target +//! line, and the refusal of a source of another bit depth. +//! +//! The five documents of the issue, opened in its order: "other" (RGB 8 bit, 300 x 200), "gray" (Grayscale 8 bit, +//! 400 x 300, left half black, right half white), "rgb16" (RGB 16 bit, 400 x 300), "source" (RGB 8 bit, 400 x 300, +//! Background 128 plus a layer "S1" white on the right half) and "target" (RGB 8 bit, 400 x 300; Background left half +//! 200/100/50, right half 50/150/250; layers "Top" and "Masked"; alpha channel "Alpha 1" white over (0,0)-(200,150)). +//! "target" is active, its Background targeted. + +use super::params_for; + +/// The dialog's row keys (shell keys: `__` keys never reach the command). +const SOURCE: &str = "__sourceDocument"; + +/// The Layer row of a source document that is not the target. +fn layer_key(index: usize) -> String { + format!("__sourceLayer/{index}") +} + +/// The Channel row of a source document that is not the target. +fn channel_key(index: usize) -> String { + format!("__sourceChannel/{index}") +} +use crate::PhotocraftApp; +use craft::ui::dialog::DialogId; +use craft::ui::patterns::form_dialogs::ParamKind; +use serde_json::{Value, json}; + +const APPLY: &str = "image.applyImage"; + +fn run(app: &mut PhotocraftApp, id: &str, params: Value) { + app.run(id, params).unwrap_or_else(|e| panic!("{id}: {e}")); +} + +/// Fills the rectangle `x, y, w, h` of the active layer with `color`. +fn fill(app: &mut PhotocraftApp, rect: [u32; 4], color: &str) { + run(app, "select.rect", json!({"x": rect[0], "y": rect[1], "width": rect[2], "height": rect[3]})); + run(app, "edit.fill", json!({"color": color})); + run(app, "select.deselect", json!({})); +} + +fn five_documents() -> (Box, egui::Context) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + run(&mut app, "file.new", json!({"width": 300, "height": 200, "name": "other"})); + run(&mut app, "file.new", json!({"width": 400, "height": 300, "mode": "gray", "background": "#000000", "name": "gray"})); + fill(&mut app, [200, 0, 200, 300], "#ffffff"); + run(&mut app, "file.new", json!({"width": 400, "height": 300, "depth": 16, "background": "#404040", "name": "rgb16"})); + run(&mut app, "file.new", json!({"width": 400, "height": 300, "background": "#808080", "name": "source"})); + run(&mut app, "layer.new.layer", json!({"name": "S1"})); + fill(&mut app, [200, 0, 200, 300], "#ffffff"); + run(&mut app, "file.new", json!({"width": 400, "height": 300, "background": "#c86432", "name": "target"})); + fill(&mut app, [200, 0, 200, 300], "#3296fa"); + run(&mut app, "select.rect", json!({"x": 0, "y": 0, "width": 200, "height": 150})); + run(&mut app, "select.saveSelection", json!({"name": "Alpha 1"})); + run(&mut app, "select.deselect", json!({})); + run(&mut app, "layer.new.layer", json!({"name": "Top"})); + run(&mut app, "layer.new.layer", json!({"name": "Masked"})); + run(&mut app, "layer.select", json!({"name": "Background"})); + app.sync_views(); + let ctx = app.ctx().clone(); + (app, ctx) +} + +fn frame(app: &mut PhotocraftApp, ctx: &egui::Context) { + let mut output = ctx.run_ui(Default::default(), |ui| { + let mut frame = eframe::Frame::_new_kittest(); + app.logic_frame(ui.ctx(), &mut frame); + app.ui_frame(ui, &mut frame); + }); + output.textures_delta.clear(); +} + +fn open(app: &mut PhotocraftApp, ctx: &egui::Context) -> DialogId { + let reply = crate::menus::invoke(app, ctx, APPLY, json!({})).unwrap(); + let want = reply["dialog"].as_str().expect("the reply names a dialog").to_owned(); + let id = app.framework.dialogs.open_dialogs().into_iter().map(|d| d.id).find(|id| id.value().to_string() == want).expect("the dialog is open"); + frame(app, ctx); + id +} + +fn fields(app: &PhotocraftApp, id: DialogId) -> Value { + app.framework.dialogs.open_dialogs().into_iter().find(|open| open.id == id).and_then(|open| open.fields).expect("an open dialog") +} + +fn set(app: &mut PhotocraftApp, ctx: &egui::Context, id: DialogId, key: &str, value: Value) { + app.framework.dialogs.set_json_field(ctx, id, key, value).unwrap_or_else(|e| panic!("{key}: {e}")); + // The form brings its derived keys up to date at its next pass. + frame(app, ctx); +} + +/// The `(id, label)` options of choice row `key`. +fn options(app: &mut PhotocraftApp, key: &str) -> Vec<(String, String)> { + let (params, _) = params_for(app, APPLY).expect("Apply Image has a form"); + match ¶ms.iter().find(|p| p.key == key).unwrap_or_else(|| panic!("no row {key}")).kind { + ParamKind::Choice { options, .. } => options.iter().map(|(id, label)| (id.clone(), label.as_str().to_owned())).collect(), + other => panic!("{key} is not a choice: {other:?}"), + } +} + +fn ids(app: &mut PhotocraftApp, key: &str) -> Vec { + options(app, key).into_iter().map(|(id, _)| id).collect() +} + +fn index_of(app: &PhotocraftApp, name: &str) -> usize { + app.session.documents().iter().position(|st| st.doc.name == name).unwrap_or_else(|| panic!("no document {name}")) +} + +/// The active layer's 8-bit RGB at `(x, y)`. +fn rgb(app: &PhotocraftApp, x: i32, y: i32) -> [u8; 3] { + let st = app.session.active().unwrap(); + let p = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().pixel(x, y); + [0, 1, 2].map(|c| (p[c] * 255.0).round() as u8) +} + +#[test] +fn source_lists_same_size_and_depth_documents_and_defaults_to_the_target() { + let (mut app, ctx) = five_documents(); + let names: Vec = options(&mut app, SOURCE).into_iter().map(|(_, name)| name).collect(); + assert_eq!(names, ["gray", "source", "target"], "not other (size), not rgb16 (bit depth)"); + let d = open(&mut app, &ctx); + assert_eq!(fields(&app, d)[SOURCE], index_of(&app, "target").to_string()); +} + +#[test] +fn another_target_lists_its_own_size_and_depth() { + let (mut app, _) = five_documents(); + // rgb16 as the target: only itself. + let rgb16 = index_of(&app, "rgb16"); + run(&mut app, "document.activate", json!({"document": rgb16})); + let names: Vec = options(&mut app, SOURCE).into_iter().map(|(_, name)| name).collect(); + assert_eq!(names, ["rgb16"]); + // gray as the target: the RGB documents of its size and depth too. + let gray = index_of(&app, "gray"); + run(&mut app, "document.activate", json!({"document": gray})); + let names: Vec = options(&mut app, SOURCE).into_iter().map(|(_, name)| name).collect(); + assert_eq!(names, ["gray", "source", "target"]); +} + +#[test] +fn layer_and_channel_follow_the_chosen_document() { + let (mut app, ctx) = five_documents(); + let (gray, source) = (index_of(&app, "gray"), index_of(&app, "source")); + // The target's own rows: Merged, then its layers top to bottom. + assert_eq!(ids(&mut app, "sourceLayer"), ["merged", "Masked", "Top", "Background"]); + assert_eq!(ids(&mut app, &layer_key(source)), ["merged", "S1", "Background"]); + assert_eq!(ids(&mut app, &channel_key(source)), ["RGB", "Red", "Green", "Blue"]); + // A single-layer document lists only Background, with no Merged entry. + assert_eq!(ids(&mut app, &layer_key(gray)), ["Background"]); + assert_eq!(ids(&mut app, &channel_key(gray)), ["Gray"]); + // Choosing a document shows its rows and hides the target's. + let d = open(&mut app, &ctx); + set(&mut app, &ctx, d, SOURCE, json!(source.to_string())); + let shown = fields(&app, d); + assert_eq!(shown["__sourceIsTarget"], false); + assert_eq!(shown[format!("__sourceShown/{source}")], true); + assert_eq!(shown[format!("__sourceShown/{gray}")], false); + assert_eq!(shown["source"], json!({"document": source, "layer": "merged", "channel": "RGB", "invert": false})); + let target = index_of(&app, "target"); + set(&mut app, &ctx, d, SOURCE, json!(target.to_string())); + let shown = fields(&app, d); + assert_eq!(shown["__sourceIsTarget"], true); + assert!(shown.get("source").is_none(), "the target sends the flat keys: {shown}"); +} + +#[test] +fn the_source_rows_read_layer_and_channel_for_every_document() { + let (mut app, _) = five_documents(); + let source = index_of(&app, "source"); + let (params, _) = params_for(&mut app, APPLY).unwrap(); + let label = |key: &str| params.iter().find(|p| p.key == key).map(|p| p.label.as_str().to_owned()); + assert_eq!(label("sourceChannel").as_deref(), Some("Channel")); + assert_eq!(label(&channel_key(source)).as_deref(), Some("Channel")); + assert_eq!(label("sourceLayer").as_deref(), Some("Layer")); +} + +#[test] +fn the_target_line_names_the_target() { + let (mut app, _) = five_documents(); + let (params, _) = params_for(&mut app, APPLY).unwrap(); + let row = params.iter().find(|p| p.key == "__target").expect("a Target row"); + assert_eq!(row.label.as_str(), "Target"); + match &row.kind { + ParamKind::ReadOnlyText { text, .. } => assert_eq!(text.as_str(), "target"), + other => panic!("the Target row is static text: {other:?}"), + } +} + +#[test] +fn ok_applies_the_chosen_source_document() { + let (mut app, ctx) = five_documents(); + let source = index_of(&app, "source"); + let d = open(&mut app, &ctx); + set(&mut app, &ctx, d, "blending", json!("normal")); + set(&mut app, &ctx, d, SOURCE, json!(source.to_string())); + crate::dialogs::confirm(&mut app, &ctx, d).unwrap(); + // "source" Merged: 128 on the left, white on the right. + assert_eq!(rgb(&app, 50, 50), [128, 128, 128]); + assert_eq!(rgb(&app, 300, 50), [255, 255, 255]); + run(&mut app, "edit.undo", json!({})); + // Its Background alone (128 everywhere), inverted. The dialog opens on the target again: choose "source". + let d = open(&mut app, &ctx); + set(&mut app, &ctx, d, SOURCE, json!(source.to_string())); + set(&mut app, &ctx, d, &layer_key(source), json!("Background")); + set(&mut app, &ctx, d, "sourceInvert", json!(true)); + crate::dialogs::confirm(&mut app, &ctx, d).unwrap(); + assert_eq!(rgb(&app, 50, 50), [127, 127, 127]); + assert_eq!(rgb(&app, 300, 50), [127, 127, 127]); +} + +#[test] +fn ok_with_the_mask_of_the_issue() { + let (mut app, ctx) = five_documents(); + let (source, target) = (index_of(&app, "source"), index_of(&app, "target")); + for (invert, at_50, at_300) in [(false, [128, 128, 128], [50, 150, 250]), (true, [200, 100, 50], [255, 255, 255])] { + let d = open(&mut app, &ctx); + set(&mut app, &ctx, d, "blending", json!("normal")); + set(&mut app, &ctx, d, SOURCE, json!(source.to_string())); + set(&mut app, &ctx, d, "__mask", json!(true)); + set(&mut app, &ctx, d, "__maskSource", json!(target.to_string())); + set(&mut app, &ctx, d, &format!("__maskChannel/{target}"), json!("Alpha 1")); + set(&mut app, &ctx, d, "__maskInvert", json!(invert)); + crate::dialogs::confirm(&mut app, &ctx, d).unwrap(); + assert_eq!(rgb(&app, 50, 50), at_50, "invert {invert}"); + assert_eq!(rgb(&app, 300, 50), at_300, "invert {invert}"); + run(&mut app, "edit.undo", json!({})); + } +} + +#[test] +fn a_source_of_another_bit_depth_is_refused_and_changes_nothing() { + let (mut app, _) = five_documents(); + let rgb16 = index_of(&app, "rgb16"); + let revision = app.session.active().unwrap().revision; + for params in [ + json!({"source": {"document": rgb16}, "blending": "normal"}), + json!({"sourceDocument": rgb16, "blending": "normal"}), + json!({"mask": {"document": rgb16, "channel": "RGB"}, "blending": "normal"}), + ] { + let error = app.session.execute(APPLY, params.clone()).expect_err("another bit depth is refused").to_string(); + assert!(error.contains("bit depth"), "{params}: {error}"); + assert_eq!(app.session.active().unwrap().revision, revision, "{params} changed the target"); + } + assert_eq!(rgb(&app, 50, 50), [200, 100, 50]); + // The same bit depth in another mode still applies. + let gray = index_of(&app, "gray"); + app.session.execute(APPLY, json!({"source": {"document": gray}, "blending": "normal"})).unwrap(); + assert_eq!(rgb(&app, 300, 50), [255, 255, 255]); +} + +/// "clash" (RGB 8 bit, 400 x 300, Background 128; an alpha channel named "Red" white on the left half; a pixel layer +/// named "merged" white on the right half; its Background targeted), then "target" (RGB 8 bit, 400 x 300, Background +/// 200/100/50), which is active. +fn names_like_the_built_in_choices() -> (Box, egui::Context, usize) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + run(&mut app, "file.new", json!({"width": 400, "height": 300, "background": "#808080", "name": "clash"})); + run(&mut app, "select.rect", json!({"x": 0, "y": 0, "width": 200, "height": 300})); + run(&mut app, "select.saveSelection", json!({"name": "Red"})); + run(&mut app, "select.deselect", json!({})); + run(&mut app, "layer.new.layer", json!({"name": "merged"})); + fill(&mut app, [200, 0, 200, 300], "#ffffff"); + run(&mut app, "layer.select", json!({"name": "Background"})); + run(&mut app, "file.new", json!({"width": 400, "height": 300, "background": "#c86432", "name": "target"})); + app.sync_views(); + let ctx = app.ctx().clone(); + let clash = index_of(&app, "clash"); + (app, ctx, clash) +} + +/// The option id of row `key` at `position` of its list, after checking that no two options share an id (and the +/// labels, when given). +fn option_at(app: &mut PhotocraftApp, key: &str, labels: Option<&[&str]>, position: usize) -> String { + let list = options(app, key); + if let Some(labels) = labels { + assert_eq!(list.iter().map(|(_, label)| label.as_str()).collect::>(), labels, "{key}"); + } + let mut unique: Vec<&String> = list.iter().map(|(id, _)| id).collect(); + unique.sort(); + unique.dedup(); + assert_eq!(unique.len(), list.len(), "{key} options share an id: {list:?}"); + list[position].0.clone() +} + +/// Both pixels of the result of `params` run on the active layer, undone after. +fn applied(app: &mut PhotocraftApp, params: Value) -> [[u8; 3]; 2] { + run(app, APPLY, params); + let out = [rgb(app, 50, 50), rgb(app, 300, 50)]; + run(app, "edit.undo", json!({})); + out +} + +#[test] +fn a_source_alpha_named_like_a_colour_channel_reads_the_alpha() { + let (mut app, ctx, clash) = names_like_the_built_in_choices(); + let alpha = option_at(&mut app, &channel_key(clash), Some(&["RGB", "Red", "Green", "Blue", "Red"]), 4); + let d = open(&mut app, &ctx); + set(&mut app, &ctx, d, "blending", json!("normal")); + set(&mut app, &ctx, d, SOURCE, json!(clash.to_string())); + set(&mut app, &ctx, d, &channel_key(clash), json!(alpha)); + assert_eq!(fields(&app, d)["source"]["channel"], json!({"alpha": 0}), "an explicit alpha selector"); + crate::dialogs::confirm(&mut app, &ctx, d).unwrap(); + // The alpha: white on the left, black on the right. The red plane would be 128 and 255. + assert_eq!(rgb(&app, 50, 50), [255, 255, 255]); + assert_eq!(rgb(&app, 300, 50), [0, 0, 0]); +} + +#[test] +fn a_source_layer_named_merged_is_that_layer_not_the_composite() { + let (mut app, ctx, clash) = names_like_the_built_in_choices(); + let layer = option_at(&mut app, &layer_key(clash), Some(&["Merged", "merged", "Background"]), 1); + let d = open(&mut app, &ctx); + set(&mut app, &ctx, d, "blending", json!("normal")); + set(&mut app, &ctx, d, SOURCE, json!(clash.to_string())); + set(&mut app, &ctx, d, &layer_key(clash), json!(layer)); + assert_eq!(fields(&app, d)["source"]["layer"], json!({"name": "merged"}), "an explicit layer name selector"); + crate::dialogs::confirm(&mut app, &ctx, d).unwrap(); + let through_dialog = [rgb(&app, 50, 50), rgb(&app, 300, 50)]; + run(&mut app, "edit.undo", json!({})); + let source = |layer: Value| json!({"blending": "normal", "source": {"document": clash, "layer": layer, "channel": "RGB"}}); + assert_eq!(applied(&mut app, source(json!({"name": "merged"}))), through_dialog); + assert_ne!(applied(&mut app, source(json!("merged"))), through_dialog, "the composite applies differently"); +} + +#[test] +fn the_targets_own_rows_keep_an_alpha_named_red_and_a_layer_named_merged() { + let (mut app, ctx, clash) = names_like_the_built_in_choices(); + run(&mut app, "document.activate", json!({"document": clash})); + app.sync_views(); + // Channel: the alpha "Red" after the colour channels, as an explicit selector. + let alpha = option_at(&mut app, "sourceChannel", None, 4); + let d = open(&mut app, &ctx); + set(&mut app, &ctx, d, "blending", json!("normal")); + set(&mut app, &ctx, d, "sourceChannel", json!(alpha)); + crate::dialogs::confirm(&mut app, &ctx, d).unwrap(); + assert_eq!([rgb(&app, 50, 50), rgb(&app, 300, 50)], [[255, 255, 255], [0, 0, 0]], "the alpha, not the red plane"); + run(&mut app, "edit.undo", json!({})); + // Layer: the layer "merged" beside Merged. + let layer = option_at(&mut app, "sourceLayer", Some(&["Merged", "merged", "Background"]), 1); + let d = open(&mut app, &ctx); + set(&mut app, &ctx, d, "blending", json!("normal")); + set(&mut app, &ctx, d, "sourceLayer", json!(layer)); + // The dialog opens with the last Channel (the alpha): back to the composite. + set(&mut app, &ctx, d, "sourceChannel", json!("RGB")); + crate::dialogs::confirm(&mut app, &ctx, d).unwrap(); + let through_dialog = [rgb(&app, 50, 50), rgb(&app, 300, 50)]; + run(&mut app, "edit.undo", json!({})); + let source = |layer: Value| json!({"blending": "normal", "source": {"layer": layer, "channel": "RGB"}}); + assert_eq!(applied(&mut app, source(json!({"name": "merged"}))), through_dialog); + assert_ne!(applied(&mut app, source(json!("merged"))), through_dialog, "the composite applies differently"); +} + +#[test] +fn source_defaults_to_the_target_again_after_a_run_with_another() { + let (mut app, ctx) = five_documents(); + let (source, target) = (index_of(&app, "source"), index_of(&app, "target")); + let d = open(&mut app, &ctx); + set(&mut app, &ctx, d, "blending", json!("normal")); + set(&mut app, &ctx, d, SOURCE, json!(source.to_string())); + crate::dialogs::confirm(&mut app, &ctx, d).unwrap(); + let d = open(&mut app, &ctx); + assert_eq!(fields(&app, d)[SOURCE], target.to_string(), "the same target again"); + crate::dialogs::cancel(&mut app, &ctx, d).unwrap(); + // Another target opens on itself. + let gray = index_of(&app, "gray"); + run(&mut app, "document.activate", json!({"document": gray})); + app.sync_views(); + let d = open(&mut app, &ctx); + assert_eq!(fields(&app, d)[SOURCE], gray.to_string(), "another target"); +} + +#[test] +fn the_targets_own_alpha_with_no_name_reads_the_alpha() { + let (mut app, ctx, clash) = names_like_the_built_in_choices(); + run(&mut app, "document.activate", json!({"document": clash})); + // The commands refuse an empty name; a file can still bring one. + std::sync::Arc::make_mut(app.session.active_mut().unwrap().doc_mut()).channels[0].name = String::new(); + app.sync_views(); + let alpha = option_at(&mut app, "sourceChannel", None, 4); + let d = open(&mut app, &ctx); + set(&mut app, &ctx, d, "blending", json!("normal")); + set(&mut app, &ctx, d, "sourceChannel", json!(alpha)); + assert_eq!(fields(&app, d)["source"]["channel"], json!({"alpha": 0}), "an explicit alpha selector"); + crate::dialogs::confirm(&mut app, &ctx, d).unwrap(); + assert_eq!([rgb(&app, 50, 50), rgb(&app, 300, 50)], [[255, 255, 255], [0, 0, 0]], "the alpha, not the composite"); +} + +#[test] +fn a_lower_layer_sharing_a_name_is_its_own_source_and_mask_option() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + run(&mut app, "file.new", json!({"width": 400, "height": 300, "background": "#808080", "name": "dupes"})); + run(&mut app, "layer.new.layer", json!({"name": "Copy"})); + fill(&mut app, [0, 0, 400, 300], "#ffffff"); + run(&mut app, "layer.new.layer", json!({"name": "Copy"})); + fill(&mut app, [0, 0, 400, 300], "#000000"); + run(&mut app, "layer.select", json!({"name": "Background"})); + app.sync_views(); + let ctx = app.ctx().clone(); + let doc = index_of(&app, "dupes"); + // The walk runs bottom to top: Background, the lower Copy, the upper Copy. + let ids: Vec = app.session.active().unwrap().doc.walk().iter().map(|(_, _, l)| l.id.0).collect(); + let (lower, upper) = (ids[1], ids[2]); + let layer = option_at(&mut app, "sourceLayer", Some(&["Merged", "Copy", "Copy", "Background"]), 2); + let d = open(&mut app, &ctx); + set(&mut app, &ctx, d, "blending", json!("normal")); + set(&mut app, &ctx, d, "sourceLayer", json!(layer)); + set(&mut app, &ctx, d, "sourceChannel", json!("RGB")); + assert_eq!(fields(&app, d)["source"]["layer"], json!(lower), "the lower layer by its id"); + // The Mask group lists both too and sends the lower one's id. + let mask = option_at(&mut app, &format!("__maskLayer/{doc}"), Some(&["Merged", "Copy", "Copy", "Background"]), 2); + set(&mut app, &ctx, d, "__mask", json!(true)); + set(&mut app, &ctx, d, "__maskSource", json!(doc.to_string())); + set(&mut app, &ctx, d, &format!("__maskLayer/{doc}"), json!(mask)); + assert_eq!(fields(&app, d)["maskLayer"], json!(lower)); + set(&mut app, &ctx, d, "__mask", json!(false)); + crate::dialogs::confirm(&mut app, &ctx, d).unwrap(); + let through_dialog = [rgb(&app, 50, 50), rgb(&app, 300, 50)]; + run(&mut app, "edit.undo", json!({})); + assert_eq!(through_dialog, [[255, 255, 255]; 2], "the lower Copy (white), not the upper (black)"); + let source = |layer: Value| json!({"blending": "normal", "source": {"layer": layer, "channel": "RGB"}}); + assert_eq!(applied(&mut app, source(json!(lower))), through_dialog); + assert_eq!(applied(&mut app, source(json!(upper))), [[0, 0, 0]; 2], "the upper Copy"); +} diff --git a/crates/ui-egui/src/dialogs/auto_align_dialog_tests.rs b/crates/ui-egui/src/dialogs/auto_align_dialog_tests.rs new file mode 100644 index 0000000000..a39c7a1a21 --- /dev/null +++ b/crates/ui-egui/src/dialogs/auto_align_dialog_tests.rs @@ -0,0 +1,276 @@ +//! #14196: Edit › Auto-Align Layers opens the reference application's dialog: a Projection group of six radios over +//! three columns (Auto, Perspective, Collage / Cylindrical, Spherical, Reposition) with Auto selected on a fresh +//! start, a Lens Correction group (Vignette Removal, Geometric Distortion, both off; Collage and Reposition grey and +//! clear them), the selected projection's description line and the warnings under them, OK and Cancel. No +//! Interpolation or Registration rows, Alt keeps Cancel a Cancel, and the last run's projection (also a scripted +//! one) is what the dialog reopens with. + +use craft::ui::dialog::DialogId; +use egui::accesskit::{Role, Toggled}; +use egui::{Event, Modifiers, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_doc::LayerId; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::new_layer_ui::testing::{fields, set, top}; + +const COMMAND: &str = "edit.autoAlignLayers"; +/// The radios in reading order: the first row, then the second. +const RADIOS: [&str; 6] = ["Auto", "Perspective", "Collage", "Cylindrical", "Spherical", "Reposition"]; + +type H = Harness<'static, Box>; + +/// The deterministic texture of the engine's Auto-Align tests, written into layer `id` at offset (dx, dy). +fn paint_texture(app: &mut PhotocraftApp, id: LayerId, dx: i32, dy: i32) { + app.session + .edit("tex", |doc, _| { + let surf = doc.layer_mut(id).unwrap().surface_mut().unwrap(); + let mut seed = 99u64; + let mut rnd = || { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 33) as f64 / (1u64 << 31) as f64 + }; + surf.fill_rect(photocraft_geom::Rect::new(dx, dy, dx + 240, dy + 180), &[0.4, 0.4, 0.4, 1.0]); + for _ in 0..120 { + let (x, y) = ((rnd() * 220.0) as i32, (rnd() * 160.0) as i32); + let (sw, sh) = (4 + (rnd() * 14.0) as i32, 4 + (rnd() * 10.0) as i32); + let v = rnd() as f32; + surf.fill_rect(photocraft_geom::Rect::new(dx + x, dy + y, dx + x + sw, dy + y + sh), &[v, 1.0 - v, v * 0.5, 1.0]); + } + Ok(()) + }) + .unwrap(); +} + +/// A 300x240 document with two textured layers, the second offset, both selected: Auto-Align can run on it. +fn two_layers(app: &mut PhotocraftApp) { + app.run("file.new", json!({"width": 300, "height": 240, "background": "transparent"})).unwrap(); + let mut ids = Vec::new(); + for (name, dx, dy) in [("A", 20, 20), ("B", 31, 13)] { + app.run("layer.new.layer", json!({"name": name})).unwrap(); + let id = app.session.active().unwrap().active_layer.unwrap(); + paint_texture(app, id, dx, dy); + ids.push(id); + } + app.run("layer.select", json!({"layer": ids[0].0})).unwrap(); + app.run("layer.select", json!({"layer": ids[1].0, "mode": "add"})).unwrap(); +} + +/// The whole app with the two-layer document, before the dialog opens. +fn harness() -> H { + let mut h = Harness::builder().with_size(vec2(1600.0, 900.0)).with_step_dt(1.0 / 60.0).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = false; + two_layers(&mut app); + app + }); + h.run_steps(3); + h +} + +/// Opens the dialog through the menu and draws a few frames. +fn open(h: &mut H) -> DialogId { + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, COMMAND, json!({})).unwrap(); + let id = top(h.state()); + h.run_steps(4); + id +} + +fn dialog() -> (H, DialogId) { + let mut h = harness(); + let id = open(&mut h); + (h, id) +} + +fn radio(h: &H, label: &str) -> egui::Rect { + h.get_by_role_and_label(Role::RadioButton, label).rect() +} + +fn checked(h: &H, role: Role, label: &str) -> bool { + h.get_by_role_and_label(role, label).accesskit_node().toggled() == Some(Toggled::True) +} + +fn disabled(h: &H, role: Role, label: &str) -> bool { + h.get_by_role_and_label(role, label).accesskit_node().is_disabled() +} + +fn sent(h: &H, id: DialogId) -> Value { + crate::filter_dialog::command_params(COMMAND, fields(h.state(), id)) +} + +fn shows(h: &H, text: &str) -> bool { + h.query_all_by_label(text).next().is_some() +} + +#[test] +fn six_projection_radios_stand_three_by_two_with_auto_selected() { + let (h, _) = dialog(); + let rects: Vec = RADIOS.iter().map(|label| radio(&h, label)).collect(); + for row in [&rects[0..3], &rects[3..6]] { + for r in &row[1..] { + assert!((r.center().y - row[0].center().y).abs() < 4.0, "one row: {row:?}"); + } + assert!(row[0].right() < row[1].left() && row[1].right() < row[2].left(), "left to right: {row:?}"); + } + assert!(rects[3].top() > rects[0].bottom(), "Cylindrical, Spherical and Reposition stand under the first row"); + for col in 0..3 { + assert!((rects[col].left() - rects[col + 3].left()).abs() < 4.0, "column {col} lines up"); + } + assert!(checked(&h, Role::RadioButton, "Auto"), "a fresh dialog selects Auto"); + for label in &RADIOS[1..] { + assert!(!checked(&h, Role::RadioButton, label), "{label} starts clear"); + } +} + +#[test] +fn the_description_line_follows_the_selected_radio() { + let (mut h, id) = dialog(); + assert!(shows(&h, "Determine the best projection automatically.")); + for (label, line) in [ + ("Perspective", "Only allow perspective image transform."), + ("Collage", "Allow image rotation, scale and translation."), + ("Cylindrical", "Only allow cylindrical image transform."), + ("Spherical", "Only allow spherical image transform."), + ("Reposition", "Only allow image translation."), + ] { + h.get_by_role_and_label(Role::RadioButton, label).click(); + h.run_steps(3); + assert!(shows(&h, line), "{label}: {line}"); + assert!(!shows(&h, "Determine the best projection automatically."), "{label}: one description line"); + assert_eq!(sent(&h, id)["projection"], json!(label.to_lowercase())); + } +} + +#[test] +fn lens_correction_has_two_clear_boxes_that_collage_and_reposition_grey_and_clear() { + let (mut h, id) = dialog(); + assert!(shows(&h, "Projection") && shows(&h, "Lens Correction"), "the two groups are named"); + for label in ["Vignette Removal", "Geometric Distortion"] { + assert!(!checked(&h, Role::CheckBox, label), "{label} starts off"); + } + h.get_by_role_and_label(Role::CheckBox, "Geometric Distortion").click(); + h.run_steps(3); + assert!(checked(&h, Role::CheckBox, "Geometric Distortion")); + assert_eq!(sent(&h, id)["geometricCorrection"], json!(true), "Geometric Distortion drives geometricCorrection"); + for picked in ["Collage", "Reposition"] { + h.get_by_role_and_label(Role::RadioButton, picked).click(); + h.run_steps(3); + assert!(disabled(&h, Role::CheckBox, "Geometric Distortion") && disabled(&h, Role::CheckBox, "Vignette Removal"), "{picked} greys both"); + assert!(!checked(&h, Role::CheckBox, "Geometric Distortion"), "{picked} clears it"); + assert_eq!(sent(&h, id)["geometricCorrection"], json!(false)); + } + h.get_by_role_and_label(Role::RadioButton, "Auto").click(); + h.run_steps(3); + assert!(!disabled(&h, Role::CheckBox, "Geometric Distortion"), "Auto enables it again"); + assert!(!checked(&h, Role::CheckBox, "Geometric Distortion"), "still cleared"); +} + +#[test] +fn no_interpolation_or_registration_rows_and_the_command_keeps_them() { + let (h, id) = dialog(); + assert!(h.query_by_label("Interpolation").is_none(), "no Interpolation row"); + assert!(h.query_by_label("Registration").is_none(), "no Registration row"); + let params = sent(&h, id); + assert!(params.get("interpolation").is_none() && params.get("registration").is_none(), "the command's defaults apply: {params}"); + let spec = photocraft_engine::commands::find(COMMAND).unwrap(); + let keys: Vec = craft::ui::patterns::form_dialogs::Param::parse_list(spec.params).into_iter().map(|p| p.key).collect(); + assert!(keys.iter().any(|k| k == "interpolation") && keys.iter().any(|k| k == "registration"), "{keys:?}"); +} + +#[test] +fn the_metadata_warning_shows_for_layers_without_camera_metadata() { + let (h, _) = dialog(); + assert!( + shows( + &h, + "Warning: Could not detect camera metadata. Use the \"File > Scripts > Load Images into Stack...\" script to preserve metadata for Vignette Removal and/or Geometric Distortion." + ), + "the document has no EXIF" + ); + assert!( + !shows( + &h, + "Warning: For better Vignette Removal results, shoot with the same camera, lens, aperture, resolution, orientation, focal length and focus settings." + ), + "Vignette Removal is off" + ); +} + +/// The text block's lines: the description, the metadata warning, then the vignette warning while it is ticked. +#[test] +fn the_text_block_lists_the_warnings_in_order() { + use super::auto_align_ui::{METADATA_WARNING, VIGNETTE_WARNING, lines}; + assert_eq!(lines("reposition", false, true), vec!["Only allow image translation."]); + assert_eq!(lines("auto", false, false), vec!["Determine the best projection automatically.", METADATA_WARNING]); + assert_eq!(lines("auto", true, false), vec!["Determine the best projection automatically.", METADATA_WARNING, VIGNETTE_WARNING]); + assert_eq!(lines("spherical", true, true), vec!["Only allow spherical image transform.", VIGNETTE_WARNING]); +} + +#[test] +fn alt_keeps_cancel_and_escape_cancels() { + let (mut h, _) = dialog(); + h.event(Event::ModifiersChanged(Modifiers::ALT)); + h.run_steps(2); + assert!(h.query_by_label("Reset").is_none(), "Alt does not turn Cancel into Reset"); + h.get_by_role_and_label(Role::Button, "Cancel"); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); + let before = h.state().session.active().unwrap().history.past_len(); + h.key_press(egui::Key::Escape); + h.run_steps(3); + assert!(h.query_by_label("Only allow image translation.").is_none() && !shows(&h, "Lens Correction"), "Escape closes the dialog"); + assert_eq!(h.state().session.active().unwrap().history.past_len(), before, "Escape leaves the history alone"); +} + +#[test] +fn ok_runs_and_the_dialog_reopens_with_the_projection_and_ticks_it_ran_with() { + let (mut h, id) = dialog(); + h.get_by_role_and_label(Role::RadioButton, "Perspective").click(); + h.run_steps(2); + h.get_by_role_and_label(Role::CheckBox, "Geometric Distortion").click(); + h.run_steps(2); + let before = h.state().session.active().unwrap().history.past_len(); + crate::dialogs::testing::confirm(h.state_mut(), id).unwrap(); + h.run_steps(3); + assert_eq!(h.state().session.active().unwrap().history.past_len(), before + 1, "OK runs Auto-Align"); + let id = open(&mut h); + assert!(checked(&h, Role::RadioButton, "Perspective"), "reopens with Perspective"); + assert!(checked(&h, Role::CheckBox, "Geometric Distortion"), "and the tick confirmed with OK"); + assert_eq!(sent(&h, id)["projection"], json!("perspective")); +} + +#[test] +fn a_scripted_run_decides_the_projection_the_dialog_reopens_with() { + let mut h = harness(); + // An OK with Geometric Distortion ticked first, so the script's run has something to replace. + let id = open(&mut h); + h.get_by_role_and_label(Role::CheckBox, "Geometric Distortion").click(); + h.run_steps(2); + crate::dialogs::testing::confirm(h.state_mut(), id).unwrap(); + h.run_steps(3); + h.state_mut().run(COMMAND, json!({"projection": "reposition"})).unwrap(); + h.run_steps(2); + let id = open(&mut h); + assert!(checked(&h, Role::RadioButton, "Reposition"), "the scripted projection"); + assert!(!checked(&h, Role::CheckBox, "Geometric Distortion"), "a run without the lens keys leaves the box clear"); + assert!(shows(&h, "Only allow image translation.")); + assert_eq!(sent(&h, id)["projection"], json!("reposition")); +} + +#[test] +fn an_agent_sets_the_projection_by_its_id_and_a_bad_one_is_refused() { + let (mut h, id) = dialog(); + set(h.state_mut(), id, "projection", json!("cylindrical")).unwrap(); + h.run_steps(3); + assert!(checked(&h, Role::RadioButton, "Cylindrical")); + assert_eq!(sent(&h, id)["projection"], json!("cylindrical")); + // An unknown id never reaches the command: the row keeps a projection it knows. + let _ = set(h.state_mut(), id, "projection", json!("sideways")); + h.run_steps(3); + let projection = sent(&h, id)["projection"].as_str().unwrap().to_owned(); + assert!(RADIOS.iter().any(|r| r.to_lowercase() == projection), "{projection}"); +} diff --git a/crates/ui-egui/src/dialogs/auto_align_ui.rs b/crates/ui-egui/src/dialogs/auto_align_ui.rs new file mode 100644 index 0000000000..0e16b6e75e --- /dev/null +++ b/crates/ui-egui/src/dialogs/auto_align_ui.rs @@ -0,0 +1,285 @@ +//! Edit › Auto-Align Layers: the reference application's dialog (#14196). A Projection group of six radios with a +//! small picture under each (3 x 2), a Lens Correction group with Vignette Removal and Geometric Distortion, and a +//! text block at the foot: the selected projection's description and the warnings. OK and Cancel; Alt does not turn +//! Cancel into Reset. +//! +//! It stays the command's schema dialog (`filter_dialog::open`), so Enter / Escape, `ui.dialog.*`, action step +//! dialogs and the no-match alert work as for every other command dialog; only its rows and buttons differ. The +//! command keeps its `interpolation` and `registration` params for scripts: the dialog has no rows for them, so the +//! command's own defaults apply. +//! +//! Memory: the projection lives in a hidden radio row ([`LAST`]) the framework remembers on OK beside the two boxes. +//! A run that did not come from this dialog (a script, the control channel, an action step) lands in the session's +//! journal; opening the dialog copies the last journaled run into those remembered values, so it reopens with the +//! projection (and the lens keys) that run used. + +use craft::behavior::ColumnWidth; +use craft::ui::choice::{Radio, RadioGroup}; +use craft::ui::contract::{Bind, Gap, Props as _, Show as _, ShowContainer as _}; +use craft::ui::display::{Shade, Text}; +use craft::ui::layout_components::{Grid, Stack}; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamKind}; +use craft::ui::runtime::env::Label; +use craft::ui::runtime::memory::{SaveKey, saved_value, set_saved_value}; +use egui::{Color32, Pos2, Rect, Shape, Stroke, pos2, vec2}; +use serde_json::{Map, Value}; + +use crate::PhotocraftApp; +use crate::theme::Tokens; + +pub const COMMAND: &str = "edit.autoAlignLayers"; +/// The projection the command runs with. The custom row writes it; an agent's `ui.dialog.set` may too. +pub const PROJECTION: &str = "projection"; +/// The hidden radio row that keeps the projection the framework remembers (a custom row's value is not remembered). +pub const LAST: &str = "__projection"; +/// The Geometric Distortion box: the command's `geometricCorrection`. +pub const GEOMETRIC: &str = "geometricCorrection"; +/// The Vignette Removal box: the command's `vignetteRemoval`, once the engine takes it (#14197). +pub const VIGNETTE: &str = "vignetteRemoval"; + +/// The projections in the reference application's order, row by row over three columns: id, label and the +/// description line it shows while selected. +pub const PROJECTIONS: [(&str, &str, &str); 6] = [ + ("auto", "Auto", "Determine the best projection automatically."), + ("perspective", "Perspective", "Only allow perspective image transform."), + ("collage", "Collage", "Allow image rotation, scale and translation."), + ("cylindrical", "Cylindrical", "Only allow cylindrical image transform."), + ("spherical", "Spherical", "Only allow spherical image transform."), + ("reposition", "Reposition", "Only allow image translation."), +]; +/// The projections that grey and clear both Lens Correction boxes. +const NO_LENS: [&str; 2] = ["collage", "reposition"]; +const COLUMNS: &[ColumnWidth] = &[ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content]; +/// The picture under each radio, in points. +const PICTURE: egui::Vec2 = vec2(64.0, 40.0); + +/// The text under the boxes when the layers carry no camera metadata. +pub const METADATA_WARNING: &str = "Warning: Could not detect camera metadata. Use the \"File > Scripts > Load Images into Stack...\" script to preserve metadata for Vignette Removal and/or Geometric Distortion."; +/// The text under the boxes while Vignette Removal is ticked. +pub const VIGNETTE_WARNING: &str = + "Warning: For better Vignette Removal results, shoot with the same camera, lens, aperture, resolution, orientation, focal length and focus settings."; + +/// `id` when it names one of the six projections. +fn known(id: &str) -> Option<&'static str> { + PROJECTIONS.iter().map(|(p, _, _)| *p).find(|p| *p == id) +} + +/// Whether the projection `id` lets the Lens Correction boxes take input. +pub fn lens_allowed(id: &str) -> bool { + !NO_LENS.contains(&id) +} + +/// Whether the engine's command takes `vignetteRemoval` yet (#14197); until then the box is shown disabled. +pub fn vignette_supported() -> bool { + photocraft_engine::commands::find(COMMAND).is_some_and(|c| Param::parse_list(c.params).iter().any(|p| p.key == VIGNETTE)) +} + +/// The projection the dialog's values hold: the row's own value (text, or the JSON string `ui.dialog.set` writes), +/// else the remembered one, else Auto. +pub fn projection(fields: &DialogFields) -> &'static str { + let own = match fields.get(PROJECTION) { + Some(FieldValue::Text(id)) => known(id), + Some(FieldValue::Json(Value::String(id))) => known(id), + _ => None, + }; + own.or_else(|| fields.text(LAST).and_then(known)).unwrap_or("auto") +} + +/// The save key the schema dialog remembers this command's values under. +fn remembered_key() -> SaveKey { + SaveKey::named(super::params::memory_scope(COMMAND)) +} + +/// Whether the active document carries camera metadata (a camera make or model in its EXIF). +fn has_camera_metadata(app: &PhotocraftApp) -> bool { + app.session.active().and_then(|st| st.doc.metadata.exif.as_ref()).is_some_and(|exif| { + let info = photocraft_algo::exif::read(exif); + info.make.is_some_and(|m| !m.trim().is_empty()) || info.model.is_some_and(|m| !m.trim().is_empty()) + }) +} + +/// Copies the session's last journaled run of the command into the values the dialog remembers, so a run from a +/// script, the control channel or an action step decides what the dialog reopens with, as one confirmed with OK +/// does. Keys the run left out are their defaults: a scripted run without the lens keys leaves both boxes clear. +pub(crate) fn adopt_last_run(app: &PhotocraftApp) { + let Some((_, params)) = app.session.journal.iter().rev().find(|(id, _)| id == COMMAND) else { return }; + let ctx = app.ctx(); + let key = remembered_key(); + let mut saved = saved_value::>(ctx, &key).unwrap_or_default(); + let id = params.get(PROJECTION).and_then(Value::as_str).and_then(known).unwrap_or("auto"); + let lens = lens_allowed(id); + let flag = |k: &str| lens && params.get(k).and_then(Value::as_bool).unwrap_or(false); + saved.set(LAST, FieldValue::Text(id.to_owned())); + saved.set(GEOMETRIC, FieldValue::Bool(flag(GEOMETRIC))); + saved.set(VIGNETTE, FieldValue::Bool(flag(VIGNETTE))); + set_saved_value(ctx, &key, Some(saved)); +} + +/// The dialog's rows, in place of the schema's: the Projection group, the Lens Correction group and the text block. +/// Opening also adopts the last journaled run ([`adopt_last_run`]). +pub(crate) fn params(app: &PhotocraftApp) -> Vec { + adopt_last_run(app); + let metadata = has_camera_metadata(app); + let lens: Vec = PROJECTIONS.iter().map(|(id, _, _)| *id).filter(|id| lens_allowed(id)).map(str::to_owned).collect(); + let vignette_on: Vec = if vignette_supported() { lens.clone() } else { Vec::new() }; + let options = PROJECTIONS.iter().map(|(id, label, _)| ((*id).to_owned(), Label::from(crate::i18n::t(label).to_string()))).collect(); + vec![ + Param::section(tl!("Projection")), + // The remembered projection: never shown, never sent (keys under `__` are not command params). + Param::new(LAST, tl!("Projection"), ParamKind::radio(options, Some("auto".into()))).visible_when("__hidden", true), + Param::custom(PROJECTION, tl!("Projection"), |ui, fields, _| projection_row(ui, fields)).full_width(), + Param::section(tl!("Lens Correction")), + Param::new(VIGNETTE, tl!("Vignette Removal"), ParamKind::bool(false)).enabled_when_in(LAST, vignette_on), + Param::new(GEOMETRIC, tl!("Geometric Distortion"), ParamKind::bool(false)).enabled_when_in(LAST, lens), + Param::custom("__notes", Label::Empty, move |ui, fields, _| notes(ui, fields, metadata)).full_width(), + ] +} + +/// The command params of the dialog's values: the projection the row shows (the remembered one when the row never +/// drew), no lens correction under Collage or Reposition, and no `vignetteRemoval` until the engine takes it. +pub(crate) fn command_params(map: &mut Map, fields: &DialogFields) { + let id = projection(fields); + map.insert(PROJECTION.into(), Value::String(id.to_owned())); + if !lens_allowed(id) { + map.insert(GEOMETRIC.into(), Value::Bool(false)); + map.insert(VIGNETTE.into(), Value::Bool(false)); + } + if !vignette_supported() { + map.remove(VIGNETTE); + } +} + +/// Keeps the values in step with the projection: both keys hold it as text, and Collage or Reposition clears the +/// Lens Correction boxes (switching back leaves them clear). +fn settle(fields: &mut DialogFields, id: &str) { + if fields.get(PROJECTION) != Some(&FieldValue::Text(id.to_owned())) { + fields.set(PROJECTION, FieldValue::Text(id.to_owned())); + } + if fields.text(LAST) != Some(id) { + fields.set(LAST, FieldValue::Text(id.to_owned())); + } + if !lens_allowed(id) { + for key in [GEOMETRIC, VIGNETTE] { + if fields.bool(key) != Some(false) { + fields.set(key, FieldValue::Bool(false)); + } + } + } +} + +/// The six radios over three columns, each with its picture under it. A press on a picture selects nothing. +fn projection_row(ui: &mut egui::Ui, fields: &mut DialogFields) -> egui::Response { + let current = projection(fields); + settle(fields, current); + let group = RadioGroup::new(tl!("Projection").to_owned(), Bind::given(current.to_owned())).show(ui, |ui, _| { + Grid::new(COLUMNS).gap(Gap::Section).show(ui, |ui, _| { + for (id, label, _) in PROJECTIONS { + Stack::new().show(ui, |ui, _| { + Radio::new(id.to_owned()).label(crate::i18n::t(label).to_string()).show(ui); + picture(ui, id); + }); + } + }); + }); + if let Some(picked) = group.output.value().and_then(|id| known(id)) { + settle(fields, picked); + } + group.output.response.clone() +} + +/// The lines of the text block at the foot, in English: the projection `id`'s description, the metadata warning when +/// the layers carry no camera `metadata`, then the vignette warning while `vignette` is ticked. +pub fn lines(id: &str, vignette: bool, metadata: bool) -> Vec<&'static str> { + let mut out: Vec<&'static str> = PROJECTIONS.iter().filter(|(p, _, _)| *p == id).map(|(_, _, d)| *d).collect(); + if !metadata { + out.push(METADATA_WARNING); + } + if vignette { + out.push(VIGNETTE_WARNING); + } + out +} + +/// The text block at the foot ([`lines`]): the description, then the warnings, dimmer. +fn notes(ui: &mut egui::Ui, fields: &mut DialogFields, metadata: bool) -> egui::Response { + let shown = lines(projection(fields), fields.bool(VIGNETTE) == Some(true), metadata); + Stack::new() + .show(ui, |ui, _| { + for (k, line) in shown.iter().enumerate() { + let text = Text::new(crate::i18n::t(line).to_string()); + if k == 0 { + text.show(ui) + } else { + text.shade(Shade::Muted).show(ui) + }; + } + }) + .output +} + +/// The small line drawing under a projection's radio (look only; it takes no press). +fn picture(ui: &mut egui::Ui, id: &str) { + let (rect, _) = ui.allocate_exact_size(PICTURE, egui::Sense::hover()); + let t = Tokens::get(ui.ctx()); + let painter = ui.painter_at(rect); + painter.rect_filled(rect, t.radius_sm, t.field); + let ink = Stroke::new(1.0, t.icon); + let fill = t.accent_soft; + let c = rect.center(); + let image = Rect::from_center_size(c, vec2(22.0, 15.0)); + let poly = |points: Vec| Shape::convex_polygon(points, fill, ink); + match id { + "auto" => { + painter.rect(image, 0.0, fill, ink, egui::StrokeKind::Inside); + for (corner, out) in [ + (image.left_top(), vec2(-6.0, -5.0)), + (image.right_top(), vec2(6.0, -5.0)), + (image.left_bottom(), vec2(-6.0, 5.0)), + (image.right_bottom(), vec2(6.0, 5.0)), + ] { + painter.arrow(corner, out, ink); + } + } + "perspective" => { + painter.add(poly(vec![pos2(c.x - 26.0, c.y - 6.0), pos2(c.x - 12.0, c.y - 10.0), pos2(c.x - 12.0, c.y + 10.0), pos2(c.x - 26.0, c.y + 6.0)])); + painter.rect(Rect::from_center_size(c, vec2(22.0, 20.0)), 0.0, fill, ink, egui::StrokeKind::Inside); + painter.add(poly(vec![pos2(c.x + 12.0, c.y - 10.0), pos2(c.x + 26.0, c.y - 6.0), pos2(c.x + 26.0, c.y + 6.0), pos2(c.x + 12.0, c.y + 10.0)])); + } + "collage" => { + let turn = egui::emath::Rot2::from_angle(-0.3); + let corners = [vec2(-11.0, -7.5), vec2(11.0, -7.5), vec2(11.0, 7.5), vec2(-11.0, 7.5)]; + painter.add(poly(corners.iter().map(|v| c + turn * *v).collect())); + let (a, b) = (pos2(c.x + 10.0, c.y + 14.0), pos2(c.x + 24.0, c.y + 4.0)); + painter.arrow(a, b - a, ink); + painter.arrow(b, a - b, ink); + } + "cylindrical" => { + let mut top: Vec = + (0..=8).map(|k| k as f32 / 8.0).map(|s| pos2(c.x - 18.0 + 36.0 * s, c.y - 10.0 + 4.0 * (s - 0.5).powi(2) * 4.0 - 4.0)).collect(); + let bottom: Vec = + (0..=8).rev().map(|k| k as f32 / 8.0).map(|s| pos2(c.x - 18.0 + 36.0 * s, c.y + 10.0 - 4.0 * (s - 0.5).powi(2) * 4.0 + 4.0)).collect(); + top.extend(bottom); + painter.add(Shape::closed_line(top.clone(), ink)); + painter.add(Shape::line(vec![pos2(c.x, c.y - 14.0), pos2(c.x, c.y + 14.0)], Stroke::new(1.0, t.text_faint))); + } + "spherical" => { + // An image whose corners are pulled in: each side bows inward. + let (l, r, tp, b) = (c.x - 16.0, c.x + 16.0, c.y - 12.0, c.y + 12.0); + let side = |from: Pos2, to: Pos2, bow: egui::Vec2| -> Vec { + (0..8).map(|k| k as f32 / 8.0).map(|s| from + (to - from) * s - bow * (1.0 - (2.0 * s - 1.0).powi(2))).collect() + }; + let mut outline = side(pos2(l, tp), pos2(r, tp), vec2(0.0, -4.0)); + outline.extend(side(pos2(r, tp), pos2(r, b), vec2(4.0, 0.0))); + outline.extend(side(pos2(r, b), pos2(l, b), vec2(0.0, 4.0))); + outline.extend(side(pos2(l, b), pos2(l, tp), vec2(-4.0, 0.0))); + painter.add(Shape::closed_line(outline, ink)); + } + _ => { + // Reposition: the image with blocks around it. + painter.rect(image, 0.0, fill, ink, egui::StrokeKind::Inside); + for offset in [vec2(-20.0, -9.0), vec2(20.0, -9.0), vec2(-20.0, 9.0), vec2(20.0, 9.0)] { + painter.rect(Rect::from_center_size(c + offset, vec2(10.0, 8.0)), 0.0, Color32::TRANSPARENT, ink, egui::StrokeKind::Inside); + } + } + } +} diff --git a/crates/ui-egui/src/dialogs/color_range_ui.rs b/crates/ui-egui/src/dialogs/color_range_ui.rs index a308d0a051..1611261f36 100644 --- a/crates/ui-egui/src/dialogs/color_range_ui.rs +++ b/crates/ui-egui/src/dialogs/color_range_ui.rs @@ -170,6 +170,13 @@ pub fn params(value: &ColorRangeValue) -> Value { Value::Object(p) } +/// What the canvas shows of the open Color Range dialog's Selection Preview, for the document area's version +/// (`region_versions::canvas`): the preview mode and the fields, which change with no command. +pub(crate) fn canvas_key(app: &PhotocraftApp) -> Option<(PreviewMode, String)> { + let dialog = app.framework.dialogs.get::()?; + Some((dialog.preview_mode(), params(dialog.value()).to_string())) +} + /// Cached preview: the document proxy (per revision) and the pictures drawn from it. pub struct Preview { doc: DocId, diff --git a/crates/ui-egui/src/dialogs/color_settings_policy_greying_tests.rs b/crates/ui-egui/src/dialogs/color_settings_policy_greying_tests.rs new file mode 100644 index 0000000000..321a6bd9e7 --- /dev/null +++ b/crates/ui-egui/src/dialogs/color_settings_policy_greying_tests.rs @@ -0,0 +1,64 @@ +//! #14245: in Color Settings, with the RGB, CMYK and Gray policies all Off, "Ask When Pasting" and "Missing +//! Profiles: Ask When Opening" are greyed with their values kept, and "Profile Mismatches: Ask When Opening" stays +//! enabled; any policy other than Off enables both again. + +use craft::ui::dialog::DialogId; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; + +fn open() -> (Box, DialogId) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let id = crate::filter_dialog::open(&mut app, "edit.colorSettings").unwrap(); + crate::dialogs::testing::show(&mut app); + (app, id) +} + +fn set(app: &mut PhotocraftApp, id: DialogId, key: &str, value: Value) -> Result<(), String> { + let ctx = app.ctx().clone(); + let r = app.framework.dialogs.set_json_field(&ctx, id, key, value); + crate::dialogs::testing::show(app); + r +} + +fn field(app: &PhotocraftApp, id: DialogId, key: &str) -> Value { + app.framework.dialogs.open_dialogs().into_iter().find(|d| d.id == id).and_then(|d| d.fields).unwrap()[key].clone() +} + +/// Whether the row `key` takes input: a disabled row refuses a value. +fn takes_input(app: &mut PhotocraftApp, id: DialogId, key: &str) -> bool { + let before = field(app, id, key); + let flipped = json!(!before.as_bool().unwrap()); + let ok = set(app, id, key, flipped).is_ok(); + if ok { + set(app, id, key, before).unwrap(); + } + ok +} + +fn all_off(app: &mut PhotocraftApp, id: DialogId) { + for key in ["policyRgb", "policyCmyk", "policyGray"] { + set(app, id, key, json!("off")).unwrap(); + } +} + +#[test] +fn all_policies_off_grey_the_paste_and_missing_boxes() { + let (mut app, id) = open(); + let (paste, missing) = (field(&app, id, "askOnPaste"), field(&app, id, "askOnMissing")); + all_off(&mut app, id); + assert!(!takes_input(&mut app, id, "askOnPaste"), "Ask When Pasting is greyed"); + assert!(!takes_input(&mut app, id, "askOnMissing"), "Missing Profiles is greyed"); + assert!(takes_input(&mut app, id, "askOnMismatch"), "Ask When Opening stays enabled"); + assert_eq!((field(&app, id, "askOnPaste"), field(&app, id, "askOnMissing")), (paste, missing), "their values are kept"); +} + +#[test] +fn any_policy_back_on_enables_them_again() { + for (key, value) in [("policyRgb", "preserve"), ("policyCmyk", "convert"), ("policyGray", "preserve")] { + let (mut app, id) = open(); + all_off(&mut app, id); + set(&mut app, id, key, json!(value)).unwrap(); + assert!(takes_input(&mut app, id, "askOnPaste") && takes_input(&mut app, id, "askOnMissing"), "{key} {value}"); + } +} diff --git a/crates/ui-egui/src/dialogs/duplicate_layer_indexed_tests.rs b/crates/ui-egui/src/dialogs/duplicate_layer_indexed_tests.rs index 96958d5d6a..e1df6960ad 100644 --- a/crates/ui-egui/src/dialogs/duplicate_layer_indexed_tests.rs +++ b/crates/ui-egui/src/dialogs/duplicate_layer_indexed_tests.rs @@ -87,7 +87,7 @@ fn ok_on_the_document_after_an_indexed_one_copies_into_that_document() { crate::dialogs::testing::show(&mut app); } let names: Vec<_> = app.session.documents()[2].doc.walk().into_iter().map(|(_, _, l)| l.name.clone()).collect(); - assert!(names.contains(&"Ink copy".to_string()), "Card receives the copy: {names:?}"); + assert!(names.contains(&"Ink".to_string()), "Card receives the copy: {names:?}"); assert_eq!(app.session.documents()[1].doc.layer_count(), palette_layers, "the Indexed document is untouched"); assert_eq!(app.session.documents()[0].doc.layer_count(), 2, "the source is untouched"); } diff --git a/crates/ui-egui/src/dialogs/duplicate_layer_other_document_name_tests.rs b/crates/ui-egui/src/dialogs/duplicate_layer_other_document_name_tests.rs new file mode 100644 index 0000000000..72e14c7437 --- /dev/null +++ b/crates/ui-egui/src/dialogs/duplicate_layer_other_document_name_tests.rs @@ -0,0 +1,188 @@ +//! #14604: Duplicate Layer proposes the layer's own name for another document or New, and " copy" for the +//! source document; the copy keeps that name also beside a layer of the same name. A Background goes to another +//! document as a normal layer named "Background" and to New as a Background. A typed name is used as typed; an empty +//! As takes the destination's default. Dragging between documents keeps its names. + +use craft::ui::dialog::DialogId; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::new_layer_ui::testing::{set, top}; + +/// "source" (active: Background, then "Top") and "target" (Background, then a layer also named "Top"). +fn app() -> Box { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 20, "height": 20, "name": "source"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Top"})).unwrap(); + s.execute("file.new", json!({"width": 20, "height": 20, "name": "target"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Top"})).unwrap(); + s.set_active(0); + PhotocraftApp::new(s, crate::Services::default()) +} + +fn open(app: &mut PhotocraftApp) -> DialogId { + let ctx = app.ctx().clone(); + crate::menus::invoke(app, &ctx, "layer.duplicate", json!({})).unwrap(); + crate::dialogs::testing::show(app); + top(app) +} + +/// Chooses the Document entry `value` and shows the dialog once. +fn choose(app: &mut PhotocraftApp, dialog: DialogId, value: Value) { + set(app, dialog, "document", value).unwrap(); + crate::dialogs::testing::show(app); +} + +fn proposed(app: &PhotocraftApp, dialog: DialogId) -> Value { + app.framework.dialogs.open_dialogs().into_iter().find(|d| d.id == dialog).and_then(|d| d.fields).unwrap()["name"].clone() +} + +fn doc_key(app: &PhotocraftApp, i: usize) -> Value { + json!(app.session.documents()[i].doc.id.0.to_string()) +} + +fn ok(app: &mut PhotocraftApp, dialog: DialogId) { + let ctx = app.ctx().clone(); + crate::dialogs::confirm(app, &ctx, dialog).unwrap(); + for _ in 0..2 { + crate::dialogs::testing::show(app); + } +} + +fn names(app: &PhotocraftApp, i: usize) -> Vec { + app.session.documents()[i].doc.walk().into_iter().map(|(_, _, l)| l.name.clone()).collect() +} + +fn count(app: &PhotocraftApp, i: usize, name: &str) -> usize { + names(app, i).iter().filter(|n| *n == name).count() +} + +#[test] +fn the_document_choice_rewrites_the_proposed_name() { + let mut app = app(); + let dialog = open(&mut app); + assert_eq!(proposed(&app, dialog), json!("Top copy")); + let target = doc_key(&app, 1); + choose(&mut app, dialog, target); + assert_eq!(proposed(&app, dialog), json!("Top"), "another document: the plain name"); + choose(&mut app, dialog, json!("new")); + assert_eq!(proposed(&app, dialog), json!("Top"), "New: the plain name"); + let source = doc_key(&app, 0); + choose(&mut app, dialog, source); + assert_eq!(proposed(&app, dialog), json!("Top copy"), "the source again: the copy name"); +} + +#[test] +fn the_plain_name_lands_beside_a_layer_of_the_same_name_and_in_a_new_document() { + let mut app = app(); + let dialog = open(&mut app); + let target = doc_key(&app, 1); + choose(&mut app, dialog, target); + ok(&mut app, dialog); + assert_eq!(count(&app, 1, "Top"), 2, "{:?}", names(&app, 1)); + assert_eq!(count(&app, 1, "Top copy"), 0); + app.session.set_active(0); + let dialog = open(&mut app); + choose(&mut app, dialog, json!("new")); + ok(&mut app, dialog); + let new = app.session.documents().len() - 1; + assert_eq!(names(&app, new), vec!["Top".to_string()]); +} + +#[test] +fn a_background_arrives_as_background_in_another_document_and_in_new() { + let mut app = app(); + let bg = app.session.active().unwrap().doc.background().unwrap().id; + app.session.select_layer(bg).unwrap(); + let dialog = open(&mut app); + let target = doc_key(&app, 1); + choose(&mut app, dialog, target); + ok(&mut app, dialog); + let target = &app.session.documents()[1].doc; + let copy = target.walk().into_iter().map(|(_, _, l)| l).filter(|l| l.name == "Background").find(|l| !target.is_background(l.id)); + assert!(copy.is_some(), "a normal layer named Background: {:?}", names(&app, 1)); + app.session.set_active(0); + app.session.select_layer(bg).unwrap(); + let dialog = open(&mut app); + choose(&mut app, dialog, json!("new")); + ok(&mut app, dialog); + let new = &app.session.documents().last().unwrap().doc; + assert!(new.background().is_some_and(|l| l.name == "Background"), "{:?}", names(&app, app.session.documents().len() - 1)); +} + +#[test] +fn a_typed_name_is_used_and_an_empty_one_takes_the_default() { + let mut app = app(); + let dialog = open(&mut app); + let target = doc_key(&app, 1); + choose(&mut app, dialog, target.clone()); + set(&mut app, dialog, "name", json!("Typed copy")).unwrap(); + ok(&mut app, dialog); + assert_eq!(count(&app, 1, "Typed copy"), 1); + app.session.set_active(0); + let dialog = open(&mut app); + choose(&mut app, dialog, target); + set(&mut app, dialog, "name", json!("")).unwrap(); + ok(&mut app, dialog); + assert_eq!(count(&app, 1, "Top"), 2, "empty As into another document: the plain name"); + app.session.set_active(0); + let dialog = open(&mut app); + set(&mut app, dialog, "name", json!("")).unwrap(); + ok(&mut app, dialog); + assert_eq!(count(&app, 0, "Top copy"), 1, "empty As in the source: the copy name"); +} + +#[test] +fn dragging_between_documents_keeps_its_names() { + let mut app = app(); + let bg = app.session.active().unwrap().doc.background().unwrap().id; + let before = names(&app, 1).len(); + app.run("layer.copyToDocument", json!({"source": 0, "document": 1, "layers": [bg.0]})).unwrap(); + let after = names(&app, 1); + assert_eq!(after.len(), before + 1); + assert!(!after.iter().any(|n| n == "Background copy")); + assert_eq!(after.iter().filter(|n| *n == "Background").count(), 1, "a dragged Background is renamed as today: {after:?}"); +} + +#[test] +fn an_empty_name_for_a_background_into_another_document_is_background() { + let mut app = app(); + let bg = app.session.active().unwrap().doc.background().unwrap().id; + app.session.select_layer(bg).unwrap(); + let dialog = open(&mut app); + let target = doc_key(&app, 1); + choose(&mut app, dialog, target); + set(&mut app, dialog, "name", json!("")).unwrap(); + ok(&mut app, dialog); + assert_eq!(count(&app, 1, "Background"), 2, "the target's own Background and the copy: {:?}", names(&app, 1)); +} + +/// A name the user typed survives a change of destination; only an untouched proposal is rewritten (CodeRabbit on #16090). +#[test] +fn a_typed_name_survives_a_change_of_destination() { + let mut app = app(); + let dialog = open(&mut app); + set(&mut app, dialog, "name", json!("Shadow")).unwrap(); + let target = doc_key(&app, 1); + choose(&mut app, dialog, target); + assert_eq!(proposed(&app, dialog), json!("Shadow"), "another document"); + choose(&mut app, dialog, json!("new")); + assert_eq!(proposed(&app, dialog), json!("Shadow"), "New"); + let source = doc_key(&app, 0); + choose(&mut app, dialog, source); + assert_eq!(proposed(&app, dialog), json!("Shadow"), "the source again"); +} + +/// A group is outside the new proposal policy: its " copy" stays whatever the destination (CodeRabbit on #16090). +#[test] +fn a_groups_proposal_does_not_change_with_the_destination() { + let mut app = app(); + app.run("layer.new.group", json!({"name": "Folder"})).unwrap(); + let dialog = open(&mut app); + assert_eq!(proposed(&app, dialog), json!("Folder copy")); + let target = doc_key(&app, 1); + choose(&mut app, dialog, target); + assert_eq!(proposed(&app, dialog), json!("Folder copy"), "another document"); + choose(&mut app, dialog, json!("new")); + assert_eq!(proposed(&app, dialog), json!("Folder copy"), "New"); +} diff --git a/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs b/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs index dd47475180..0b038712c9 100644 --- a/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs +++ b/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs @@ -3,7 +3,7 @@ //! the New Layer button still duplicate at once. use craft::ui::contract::Bind; use craft::ui::dialog::DialogId; -use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamDialog, ParamKind, ParamResult}; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind, ParamResult}; use craft::ui::runtime::env::Label; use serde_json::{Value, json}; @@ -63,7 +63,27 @@ pub fn open(app: &mut PhotocraftApp) -> Result { }; 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")))); + // Another document or New proposes the layer's own name; the source document, " copy" again (#14604). + // A group's naming is not measured and stays as it was (CodeRabbit on #16090). + let names = name.clone().filter(|_| !layer.is_group()).map(|copy| (copy, layer.name.clone())); + let shown_for = std::sync::Mutex::new(source.to_string()); + // The proposal the As: field currently holds: only an untouched one is replaced when the destination changes. + let proposal = std::sync::Mutex::new(name.clone().unwrap_or_default()); Ok(params::open_param(app, KEY, DialogFields::new(), captured, move |fields: &mut DialogFields| { + if let Some((copy, plain)) = &names { + let chosen = fields.text("document").map(str::to_owned); + let mut shown = shown_for.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(chosen) = chosen.filter(|chosen| *chosen != *shown) { + let proposed = if chosen == source.to_string() { copy } else { plain }; + let mut last = proposal.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + // A name the user typed is theirs: keep it across destination changes (CodeRabbit on #16090). + if fields.text("name").is_none_or(|now| now.is_empty() || now == *last) { + fields.set("name", FieldValue::Text(proposed.clone())); + *last = proposed.clone(); + } + *shown = chosen; + } + } let mut rows = Vec::new(); if let Some(name) = &name { rows.push(Param::new("name", tl!("As:"), ParamKind::text(name.clone()))); @@ -110,10 +130,21 @@ pub(crate) fn run(app: &mut PhotocraftApp, _ctx: &egui::Context, result: ParamRe fn duplicate(app: &mut PhotocraftApp, fields: &DialogFields) -> Result { let index = app.session.active_index().ok_or("The document is closed")?; let mut params = serde_json::Map::new(); - if let Some(name) = fields.text("name") { - params.insert("name".into(), json!(name)); + let destination = destination(app, fields)?; + match fields.text("name") { + Some(name) if !name.is_empty() => { + params.insert("name".into(), json!(name)); + } + // An empty As: another document or New takes the layer's own name, as the dialog proposes for them (#14604). + // A group keeps its previous behaviour (CodeRabbit on #16090). + Some(_) if !matches!(destination, Destination::Document(d) if d == index) => { + if let Some(layer) = app.session.active().and_then(|st| st.active_layer.and_then(|id| st.doc.layer(id))).filter(|l| !l.is_group()) { + params.insert("name".into(), json!(layer.name)); + } + } + _ => {} } - match destination(app, fields)? { + match destination { Destination::New => { if let Some(doc_name) = fields.text("documentName").filter(|n| !n.is_empty()) { params.insert("documentName".into(), json!(doc_name)); @@ -193,7 +224,7 @@ mod tests { set(&mut app, dialog, "document", pick).unwrap(); confirm(&mut app, &ctx, dialog).unwrap(); assert_eq!(app.session.documents()[0].doc.layer_count(), 2); - assert!(names(&app, 1).contains(&"Ink copy".to_string())); + assert!(names(&app, 1).contains(&"Ink".to_string())); } #[test] @@ -208,7 +239,7 @@ mod tests { assert_eq!(app.session.active_index(), Some(1)); assert_eq!(app.session.documents()[1].doc.name, "Card"); assert_eq!(app.session.documents()[0].doc.layer_count(), 2, "the source is untouched"); - assert!(names(&app, 1).contains(&"Ink copy".to_string())); + assert!(names(&app, 1).contains(&"Ink".to_string())); } #[test] @@ -218,7 +249,7 @@ mod tests { let dialog = invoke(&mut app); set(&mut app, dialog, "document", json!("new")).unwrap(); confirm(&mut app, &ctx, dialog).unwrap(); - assert_eq!(app.session.documents()[1].doc.name, "Poster copy"); + assert_eq!(app.session.documents()[1].doc.name, "Untitled-1"); let dialog = invoke(&mut app); // Either the select refuses the id or the held OK does. if set(&mut app, dialog, "document", json!(u64::MAX.to_string())).is_ok() { @@ -259,7 +290,7 @@ mod tests { let docs = app.session.documents(); let spare = docs.iter().position(|d| d.doc.name == "Spare").unwrap(); let spare_names: Vec<_> = docs[spare].doc.walk().into_iter().map(|(_, _, l)| l.name.clone()).collect(); - assert!(spare_names.contains(&"Ink copy".to_string()), "{change}: Spare receives the copy: {spare_names:?}"); + assert!(spare_names.contains(&"Ink".to_string()), "{change}: Spare receives the copy: {spare_names:?}"); if let Some(card) = docs.iter().position(|d| d.doc.name == "Card") { assert_eq!(docs[card].doc.layer_count(), 1, "{change}: Card is untouched"); } diff --git a/crates/ui-egui/src/dialogs/export_dialog.rs b/crates/ui-egui/src/dialogs/export_dialog.rs index 98b95896cb..9aac59ac13 100644 --- a/crates/ui-egui/src/dialogs/export_dialog.rs +++ b/crates/ui-egui/src/dialogs/export_dialog.rs @@ -541,6 +541,15 @@ fn export_document(doc: &Document, f: &Map, max_side: Option session.active().map(|d| (*d.doc).clone()).ok_or_else(|| "export failed".into()) } +/// Materialize the source interpretation only on the copy handed to an encoder. +fn export_for_encoding(doc: &Document, f: &Map, max_side: Option, source_profile: &Profile) -> Result { + let mut out = export_document(doc, f, max_side, source_profile)?; + if settings(f).embed_icc && out.icc_profile.is_none() && matches!(out.mode, ColorMode::Rgb | ColorMode::Grayscale) { + out.icc_profile = Some(source_profile.to_bytes()); + } + Ok(out) +} + /// The exported pixel size: each side scaled and rounded on its own, never below 1 px. The /// dialog's size label and `export_document` share it so the label names the file's real size. fn scaled_size(w: f64, h: f64, scale: f64) -> (f64, f64) { @@ -630,7 +639,7 @@ fn settings(f: &Map) -> ExportSettings { /// The preview and size estimate share a single reduced document. Resizing every layer twice is /// especially expensive for layered PSDs, even when the canvas itself is small. fn preview_proxy(doc: &Document, f: &Map, source_profile: &Profile) -> Result { - export_document(doc, f, Some(if s_fmt(f) == "ico" { 256 } else { 512 }), source_profile) + export_for_encoding(doc, f, Some(if s_fmt(f) == "ico" { 256 } else { 512 }), source_profile) } fn scaled_estimate(bytes: usize, doc: &Document, proxy: &Document, f: &Map) -> u64 { @@ -750,7 +759,7 @@ fn exact_estimate(doc: &Document, f: &Map, source_profile: &Profi if !px.is_finite() || px > EXACT_ESTIMATE_PX { return None; } - let full = export_document(doc, f, None, source_profile).ok()?; + let full = export_for_encoding(doc, f, None, source_profile).ok()?; let bytes = photocraft_io::export(&full, &format!("estimate.{}", s_fmt(f)), &settings(f).io_options()).ok()?.bytes; u64::try_from(bytes.len()).ok() } @@ -1139,7 +1148,7 @@ fn export_sizes(app: &mut PhotocraftApp, f: &Map, rows: &[ScaleRo /// Exports `doc` to `path` with the dialog settings `f` (Export As, and its replayed action step). fn write_export(app: &mut PhotocraftApp, doc: &Document, f: &Map, path: &str, source_profile: &Profile) -> Result { - let out = export_document(doc, f, None, source_profile)?; + let out = export_for_encoding(doc, f, None, source_profile)?; crate::app::ensure_memory_to_save(&out, path)?; let export = app.services.export.as_ref().ok_or("no exporter configured")?; let (bytes, warnings) = export(&out, path, &settings(f))?; @@ -1214,7 +1223,7 @@ fn write_layer_file( source_profile: &Profile, path: &str, ) -> Result { - let out = export_document(doc, f, None, source_profile)?; + let out = export_for_encoding(doc, f, None, source_profile)?; crate::app::ensure_memory_to_save(&out, path)?; let export = app.services.export.as_ref().ok_or("no exporter configured")?; let (bytes, warnings) = export(&out, path, settings)?; @@ -1317,6 +1326,8 @@ mod preserve_details_tests; mod srgb_default_tests; #[cfg(test)] mod tests; +#[cfg(test)] +mod working_profile_tests; #[cfg(test)] mod jpg_progressive_tests; diff --git a/crates/ui-egui/src/dialogs/export_dialog/working_profile_tests.rs b/crates/ui-egui/src/dialogs/export_dialog/working_profile_tests.rs new file mode 100644 index 0000000000..dab4a34cd7 --- /dev/null +++ b/crates/ui-egui/src/dialogs/export_dialog/working_profile_tests.rs @@ -0,0 +1,109 @@ +//! Export As (#17199): Document Profile describes untagged pixels in the session working space. + +use super::replay; +use crate::{PhotocraftApp, Services}; +use craft::cms::{Builtin, Intent}; +use photocraft_doc::{Color, ColorMode, Document, SampleType, Size}; +use serde_json::json; +use std::{cell::RefCell, rc::Rc, sync::Arc}; + +type Writes = Rc>>>; + +fn app(mode: ColorMode, tagged: Option) -> (Box, Writes) { + let writes = Writes::default(); + let captured = writes.clone(); + let services = Services { + export: Some(Box::new(|doc, path, settings| { + photocraft_io::export(doc, path, &settings.io_options()).map(|result| (result.bytes, result.warnings)).map_err(|error| error.to_string()) + })), + write: Some(Box::new(move |_, bytes| { + captured.borrow_mut().push(bytes.to_vec()); + Ok(()) + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + app.session + .execute( + "edit.colorSettings", + json!({"workingRgb": Builtin::ProPhotoCompat.id(), "workingGray": Builtin::GrayGamma22.id(), "policyRgb": "off", "policyGray": "off"}), + ) + .unwrap(); + let (left, right) = match mode { + ColorMode::Grayscale => ([0.25, 0.25, 0.25, 1.0], [0.65, 0.65, 0.65, 1.0]), + _ => ([200.0 / 255.0, 30.0 / 255.0, 30.0 / 255.0, 1.0], [30.0 / 255.0, 60.0 / 255.0, 200.0 / 255.0, 1.0]), + }; + let mut doc = Document::with_background("working-profile", Size::new(8, 4), mode, SampleType::U8, Color::rgba(left[0], left[1], left[2], left[3])); + let surface = doc.layers[0].surface_mut().unwrap(); + surface.fill_rect(photocraft_geom::Rect::from_xywh(4, 0, 4, 4), &photocraft_raster::from_rgba(&surface.format(), right)); + doc.icc_profile = tagged.map(|profile| profile.profile().to_bytes()); + // Add the exact fixture without an import-policy conversion or mismatch prompt. + app.session.add_document(doc, None); + (app, writes) +} + +fn pixels(doc: &Document) -> Vec<[f32; 4]> { + let surface = doc.layers[0].surface().unwrap(); + (0..doc.size.height).flat_map(|y| (0..doc.size.width).map(move |x| surface.rgba(x as i32, y as i32))).collect() +} + +fn replay_png(app: &mut PhotocraftApp, writes: &Writes, profile: &str, embed: bool) -> Document { + replay(app, &json!({"path": "out.png", "format": "png", "profile": profile, "embedProfile": embed, "transparency": true, "metadata": "none"})).unwrap(); + let bytes = writes.borrow_mut().pop().expect("replay writes the encoded PNG"); + photocraft_io::import("out.png", &bytes).unwrap().document +} + +#[test] +fn document_profile_png_embeds_working_or_tagged_rgb_and_gray_without_changing_pixels() { + for (mode, working, own) in [(ColorMode::Rgb, Builtin::ProPhotoCompat, Builtin::DisplayP3), (ColorMode::Grayscale, Builtin::GrayGamma22, Builtin::SGray)] { + for tagged in [None, Some(own)] { + let (mut app, writes) = app(mode, tagged); + let source = app.session.active().unwrap().doc.clone(); + let before = (*source).clone(); + assert_eq!(source.icc_profile, tagged.map(|profile| profile.profile().to_bytes()), "the fixture keeps its original tag state"); + let samples = pixels(&source); + let expected_icc = tagged.unwrap_or(working).profile().to_bytes(); + for embed in [true, false] { + let output = replay_png(&mut app, &writes, "document", embed); + assert_eq!(output.size, source.size); + assert_eq!(output.mode, mode); + assert_eq!( + output.icc_profile.as_ref().map(|icc| icc.as_slice()), + embed.then_some(expected_icc.as_slice()), + "{mode:?} {tagged:?} embed={embed}" + ); + assert_eq!(pixels(&output), samples, "Document Profile must tag without converting the samples"); + assert!(Arc::ptr_eq(&source, &app.session.active().unwrap().doc), "export must retain the source document"); + assert_eq!(pixels(&source), samples, "the source samples stay unchanged"); + assert_eq!(*source, before, "export must not change the source ICC or pixels"); + } + } + } +} + +#[test] +fn explicit_srgb_png_converts_from_working_rgb_and_gray_and_keeps_embedding_optional() { + for (mode, working) in [(ColorMode::Rgb, Builtin::ProPhotoCompat), (ColorMode::Grayscale, Builtin::GrayGamma22)] { + let (mut app, writes) = app(mode, None); + let source = app.session.active().unwrap().doc.clone(); + let before = (*source).clone(); + assert!(source.icc_profile.is_none(), "the conversion source is actually untagged"); + let original_pixels = pixels(&source); + let mut expected = before.clone(); + expected.icc_profile = Some(working.profile().to_bytes()); + photocraft_engine::color_cmds::convert_document(&mut expected, Builtin::Srgb.profile(), Intent::Perceptual, true).unwrap(); + let samples = pixels(&expected); + assert_ne!(samples, original_pixels, "the fixture must distinguish conversion from working-profile tagging"); + let srgb = Builtin::Srgb.profile().to_bytes(); + for embed in [true, false] { + let output = replay_png(&mut app, &writes, "srgb", embed); + assert_eq!(output.size, source.size); + assert_eq!(output.mode, ColorMode::Rgb); + assert_eq!(output.icc_profile.as_ref().map(|icc| icc.as_slice()), embed.then_some(srgb.as_slice()), "{mode:?} embed={embed}"); + assert_eq!(pixels(&output), samples, "explicit sRGB must keep its pixel conversion, not just change the tag"); + assert!(Arc::ptr_eq(&source, &app.session.active().unwrap().doc)); + assert_eq!(pixels(&source), original_pixels, "the source samples stay unchanged"); + assert_eq!(*source, before, "export must not change the source ICC or pixels"); + } + } +} diff --git a/crates/ui-egui/src/dialogs/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index 39ed8fe67a..34f944bb4c 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -318,6 +318,12 @@ pub(crate) fn params(app: &mut PhotocraftApp, command: &str, spec: &str) -> Vec< let kind = if command == "layer.layerStyle.globalLight" { ParamKind::angle_in(min, max, default, 0) } else { ParamKind::angle(default) }; p = Param::new(p.key, p.label, kind); } + // Artboard from Layers' Width and Height take 4 to 32000 px; a value typed outside is + // clamped when the field is left (#14577). + if command == "layer.new.artboardFromLayers" && matches!(p.key.as_str(), "width" | "height") { + use photocraft_engine::artboard_cmds::{FROM_LAYERS_MAX, FROM_LAYERS_MIN}; + p = Param::new(p.key, p.label, ParamKind::int(Some(FROM_LAYERS_MIN), Some(FROM_LAYERS_MAX), 0)); + } if command == SCALE_EFFECTS && p.key == "scale" { return scale_effects_row(p); } @@ -374,6 +380,10 @@ pub(crate) fn params(app: &mut PhotocraftApp, command: &str, spec: &str) -> Vec< if command == super::rotate_canvas_ui::COMMAND { list = super::rotate_canvas_ui::params(); } + // Auto-Align Layers: the Projection and Lens Correction groups and the text block (#14196). + if command == super::auto_align_ui::COMMAND { + list = super::auto_align_ui::params(app); + } rows::custom_rows(app, command, &mut list); if command == color_settings_presets::COMMAND { // The Settings menu: Custom, a greyed group label and the named setups in groups (#14229). @@ -458,12 +468,13 @@ fn command_defaults(app: &PhotocraftApp, command: &str, params: &[Param]) -> Map map.insert("name".into(), json!(photocraft_engine::pattern_cmds::default_name(&app.session))); } // The reference application's Artboard from Layers opens at the next Artboard N and the - // selected layers' size every time, never a remembered size; past the field's 30000 px + // selected layers' size every time, never a remembered size; past the field's 32000 px // range, 0 keeps the bounds. if command == "layer.new.artboardFromLayers" && let Some((name, [w, h])) = photocraft_engine::artboard_cmds::from_layers_defaults(&app.session) { - let fits = w <= 30_000 && h <= 30_000; + let max = photocraft_engine::artboard_cmds::FROM_LAYERS_MAX; + let fits = w <= max && h <= max; map.insert("name".into(), json!(name)); map.insert("width".into(), json!(if fits { w } else { 0 })); map.insert("height".into(), json!(if fits { h } else { 0 })); @@ -571,13 +582,14 @@ fn builder( let key = command.to_owned(); let canvas = app.session.active_index().map(|idx| crate::canvas::document_display::CanvasHost::primary(app, idx).canvas_id()); move |fields: &mut DialogFields| { - let mut dialog = ParamDialog::command(key.clone(), title.clone(), params.clone()) + let params = if key == "edit.colorSettings" { color_settings_greying(¶ms, fields) } else { params.clone() }; + let mut dialog = ParamDialog::command(key.clone(), title.clone(), params) .values(Bind::bound(fields)) .reset_to(reset.clone()) .layout(ParamLayout::Stacked) .previews(preview) - // Alt keeps Rotate Canvas's Cancel a Cancel, as in the reference application (#14462). - .alt_resets(key != super::rotate_canvas_ui::COMMAND) + // Alt keeps Rotate Canvas's and Auto-Align's Cancel a Cancel, as in the reference application (#14462, #14196). + .alt_resets(key != super::rotate_canvas_ui::COMMAND && key != super::auto_align_ui::COMMAND) .alert_title(tl!("PhotoCraft")); if let Some(canvas) = canvas { dialog = dialog.canvas(canvas); @@ -592,6 +604,13 @@ fn builder( } } +/// Color Settings with the RGB, CMYK and Gray policies all Off: "Ask When Pasting" and "Missing Profiles" are greyed, +/// their values kept; "Ask When Opening" stays (#14245). A row that may hold no value takes no input. +fn color_settings_greying(params: &[Param], fields: &DialogFields) -> Vec { + let all_off = ["policyRgb", "policyCmyk", "policyGray"].iter().all(|key| fields.text(key) == Some("off")); + params.iter().map(|p| if all_off && matches!(p.key.as_str(), "askOnPaste" | "askOnMissing") { p.clone().disabled() } else { p.clone() }).collect() +} + /// Opens `command`'s schema dialog using the current settings and editing target. The dialog's key /// is the command; Match Color captures its destination document and layer. pub fn open(app: &mut PhotocraftApp, command: &str) -> Result { @@ -737,6 +756,9 @@ pub(crate) fn command_params(command: &str, fields: &DialogFields) -> Value { if command == super::rotate_canvas_ui::COMMAND { super::rotate_canvas_ui::command_params(&mut map); } + if command == super::auto_align_ui::COMMAND { + super::auto_align_ui::command_params(&mut map, fields); + } // After dialog keys have been reshaped into command keys (Image Processor's jpeg/width // becomes jpeg.width, and so on). Doing this earlier dropped those rows. // Drop display-only and other keys a closed schema does not take (Bitmap's Input row is @@ -1422,6 +1444,8 @@ pub struct FilterPreviewKey { pub scratch: u64, } +#[cfg(test)] +mod artboard_from_layers_size_range_tests; #[cfg(test)] mod global_light_angle_range_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/filter_dialog/artboard_from_layers_size_range_tests.rs b/crates/ui-egui/src/dialogs/filter_dialog/artboard_from_layers_size_range_tests.rs new file mode 100644 index 0000000000..8987d8f92d --- /dev/null +++ b/crates/ui-egui/src/dialogs/filter_dialog/artboard_from_layers_size_range_tests.rs @@ -0,0 +1,93 @@ +//! #14577: Artboard from Layers' Width and Height take 4 to 32000 px. A value typed outside is +//! clamped when the field is left (Tab): 99999 becomes 32000, 1 becomes 4. + +use craft::ui::patterns::form_dialogs::HostedParamDialog; +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use crate::{PhotocraftApp, Services}; + +const CMD: &str = "layer.new.artboardFromLayers"; + +/// A 100 x 80 document whose new layer holds 20 x 30 px of red, with the dialog open over it. +fn dialog() -> (Harness<'static, Box>, craft::ui::dialog::DialogId) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({"width": 100, "height": 80})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 10, "y": 5, "width": 20, "height": 30})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + let id = super::open(&mut app, CMD).unwrap(); + let mut h = Harness::builder() + .with_context(app.ctx().clone()) + .with_size(egui::vec2(1200.0, 900.0)) + .build_ui_state(|ui, app: &mut Box| crate::dialogs::run(app, ui), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::AppTheme::pro()); + h.run_steps(4); + (h, id) +} + +fn int(h: &Harness<'static, Box>, id: craft::ui::dialog::DialogId, key: &str) -> Option { + h.state().framework.dialogs.get_by_id::(id).and_then(|d| d.fields().int(key)) +} + +/// The open alerts' messages. +fn alerts(h: &Harness<'static, Box>) -> Vec { + h.state().framework.dialogs.open_dialogs().iter().filter_map(|d| d.fields.as_ref()?.get("message")?.as_str().map(str::to_string)).collect() +} + +/// Types `text` into the number field labelled `name` and leaves it with Tab. +fn type_and_tab(h: &mut Harness<'static, Box>, name: &str, text: &str) { + h.query_all_by_role(Role::SpinButton) + .find(|n| n.accesskit_node().label().as_deref().is_some_and(|l| l.trim_end_matches(':') == name)) + .unwrap_or_else(|| panic!("the {name} field")) + .click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +#[test] +fn width_and_height_clamp_to_4_to_32000_when_the_field_is_left() { + // (field, key, typed, kept) + for (name, key, typed, kept) in [("Width", "width", "99999", 32_000), ("Height", "height", "1", 4), ("Width", "width", "640", 640)] { + let (mut h, id) = dialog(); + assert_eq!((int(&h, id, "width"), int(&h, id, "height")), (Some(20), Some(30)), "opens at the layers' size"); + type_and_tab(&mut h, name, typed); + assert_eq!(int(&h, id, key), Some(kept), "{name} {typed}"); + // The framework's range alert says the closest value was kept; OK on it keeps the value. + if typed.parse::().ok() != Some(kept) { + let shown = alerts(&h); + assert!(shown.iter().any(|m| m.starts_with("An integer between 4 and ") && m.contains("Closest value inserted")), "{name} {typed}: {shown:?}"); + } + } +} + +/// A union of 30000 to 32000 px fits the field now, so the dialog opens at it. +#[test] +fn a_union_up_to_32000_px_opens_at_its_size() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({"width": 31_000, "height": 8})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + let id = super::open(&mut app, CMD).unwrap(); + let f = app.framework.dialogs.get_by_id::(id).unwrap().fields().clone(); + assert_eq!((f.int("width"), f.int("height")), (Some(31_000), Some(8))); +} + +#[test] +fn a_union_wider_than_32000_px_still_opens_at_0_to_keep_the_bounds() { + // Not measured in the reference: today's 0 x 0 ("keep the layers' bounds") stays, now past 32000 px. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({"width": 33_000, "height": 8})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + let id = super::open(&mut app, CMD).unwrap(); + let f = app.framework.dialogs.get_by_id::(id).unwrap().fields().clone(); + assert_eq!((f.int("width"), f.int("height")), (Some(0), Some(0))); +} diff --git a/crates/ui-egui/src/dialogs/layer_style.rs b/crates/ui-egui/src/dialogs/layer_style.rs index 5a0da87adb..4de9473444 100644 --- a/crates/ui-egui/src/dialogs/layer_style.rs +++ b/crates/ui-egui/src/dialogs/layer_style.rs @@ -29,6 +29,7 @@ use craft::ui::primitives::ContentPainterCx; use craft::ui::primitives::FacePaint; use craft::ui::primitives::textures::TextureCache; use craft::ui::runtime::env::Env; +use craft::ui::runtime::memory::{SaveKey, run_value, set_run_value}; use egui::{ColorImage, Pos2, Rect, pos2}; use photocraft_doc::effects::{FxPaint, GlowSource, GlowTechnique, StrokePosition}; use photocraft_doc::{Document, Effect, Layer, LayerId}; @@ -50,6 +51,8 @@ mod gradient_field; #[cfg(test)] mod gradient_method_tests; #[cfg(test)] +mod outer_glow_last_values_tests; +#[cfg(test)] mod pattern_overlay_picker_tests; /// The Styles preset gallery page id. @@ -204,6 +207,11 @@ fn values_of(e: &Effect, light: f32) -> Value { if let Some(source) = interpolation { set(&mut v, "method", json!(source.method)); set(&mut v, "smoothness", json!(source.smoothness)); + } else { + // No recorded method (a baked PSD curve): the factory Smooth (#14900) must not + // rebuild it on an unchanged OK, so the page shows its stops as they are. + set(&mut v, "method", json!("custom")); + drop_keys(&mut v, &["smoothness"]); } let (stops, opacity) = gradient_field::stops_to_json(&gradient_field::stops_of_doc(stops, &g.opacity_stops)); set(&mut v, gradient_field::KEY, stops); @@ -494,6 +502,11 @@ pub fn open(app: &mut PhotocraftApp, select: Option<&str>) -> Option { let keys = blend_keys(); let mut specs = specs(&keys, &user, light); start_from_last_committed(app, &mut specs, light); + if let Some(spec) = specs.iter_mut().find(|spec| spec.kind == EffectKind::OuterGlow) + && let Some(values) = run_value::>(app.ctx(), &OUTER_GLOW_SESSION) + { + spec.defaults = style_params(spec.kind, &values, None).over(&spec.defaults); + } let mut draft = LayerStyleDraft::new(draft_of(&layer, light, mode)); match select { None => { @@ -584,7 +597,29 @@ fn keep_last_committed(app: &PhotocraftApp, style: &LayerStyle) { } } +/// The starting values of a new Outer Glow live only in this app session (#14945). +const OUTER_GLOW_SESSION: SaveKey = SaveKey::new("photocraft.layerStyle.outerGlow.session"); + +/// Remember the last enabled glow added or edited by this confirmation, in the units shown by +/// the page. The original snapshot distinguishes an edit from an unchanged layer effect. +fn keep_outer_glow(app: &PhotocraftApp, layer: LayerId, style: &LayerStyle) { + let Some(layer) = app.session.active().and_then(|state| state.doc.layer(layer)) else { return }; + let light = style.global_light; + let last = style.effects.iter().zip(&layer.effects.items).rev().find_map(|(draft, applied)| { + if draft.kind != EffectKind::OuterGlow || !applied.enabled() { + return None; + } + let values = values_of(applied, light); + let original = fx_of(&draft.params).and_then(|fx| serde_json::from_value::(fx).ok()); + original.is_none_or(|original| !original.enabled() || values_of(&original, light) != values).then_some(values) + }); + if let Some(values) = last { + set_run_value(app.ctx(), &OUTER_GLOW_SESSION, Some(values)); + } +} + /// The effect pages with the user's defaults (Make Default) over the factory ones. +/// Outer Glow starts at factory values after a restart; Reset still uses the saved default. fn specs(keys: &HashMap, user: &Map, light: f32) -> Vec { KINDS .iter() @@ -601,7 +636,8 @@ fn specs(keys: &HashMap, user: &Map, light: f32) spec.fields.insert(after + 1, field); } } - spec.defaults = style_params(kind, &fresh_params(key, light, user.get(*key)), None).over(&spec.defaults); + let saved = if kind == EffectKind::OuterGlow { None } else { user.get(*key) }; + spec.defaults = style_params(kind, &fresh_params(key, light, saved), None).over(&spec.defaults); Some(spec) }) .collect() @@ -978,8 +1014,12 @@ pub(crate) fn take(app: &mut PhotocraftApp, ctx: &egui::Context) { LayerStyleAsk::NewStyle => save_new_style(app, id, layer), LayerStyleAsk::MakeDefault(kind, params) => { // The stored defaults reach new instances from the next open and, through `set_defaults`, the open dialog. - match app.run("layer.layerStyle.makeDefault", json!({"kind": kind.key(), "params": style_params_json(¶ms)})) { + let values = style_params_json(¶ms); + match app.run("layer.layerStyle.makeDefault", json!({"kind": kind.key(), "params": values})) { Ok(_) => { + if kind == EffectKind::OuterGlow { + set_run_value(app.ctx(), &OUTER_GLOW_SESSION, Some(values)); + } if let Some(dialog) = app.framework.dialogs.get_mut_by_id::(id) { dialog.set_defaults(kind, params); } @@ -1006,6 +1046,7 @@ fn finish(app: &mut PhotocraftApp, doc: photocraft_doc::DocId, layer: LayerId, s return fail(app, error); } keep_last_committed(app, style); + keep_outer_glow(app, layer, style); } /// Applies a style preset to the draft without touching the document: Cancel leaves the document @@ -1056,6 +1097,10 @@ fn reset_to_default(app: &mut PhotocraftApp, dialog: DialogId, instance: EffectI }; let Ok(v) = app.run("layer.layerStyle.defaultFor", json!({"kind": kind.key()})) else { return }; let mut values = v["params"].clone(); + if kind == EffectKind::OuterGlow { + // A partial saved default should clear every field seeded from the last OK. + values = with_defaults(kind.key(), &values); + } drop_from_to(&mut values); if values.get("useGlobalLight").and_then(Value::as_bool) == Some(true) && let Some(o) = values.as_object_mut() diff --git a/crates/ui-egui/src/dialogs/layer_style/outer_glow_last_values_tests.rs b/crates/ui-egui/src/dialogs/layer_style/outer_glow_last_values_tests.rs new file mode 100644 index 0000000000..c57d6c5e8d --- /dev/null +++ b/crates/ui-egui/src/dialogs/layer_style/outer_glow_last_values_tests.rs @@ -0,0 +1,170 @@ +//! #14945: a new Outer Glow uses the last settings confirmed in Layer Style for this app session. + +use craft::imaging::layer_style::{EffectKind, StyleValue}; +use craft::theme::Srgba; +use egui_kittest::kittest::Queryable as _; +use photocraft_engine::prefs::SavedPrefsExt; +use serde_json::{Value, json}; + +use super::tests::{app_with_layer, cancel, draft, edit, first_of, harness}; +use super::{DialogId, style_params_json}; +use crate::PhotocraftApp; + +const COMMAND: &str = "layer.layerStyle.outerGlow"; + +fn open_glow(app: &mut PhotocraftApp) -> DialogId { + let ctx = app.ctx().clone(); + crate::menus::invoke(app, &ctx, COMMAND, json!({})).unwrap(); + app.layer_style_target.unwrap().0 +} + +fn values(app: &PhotocraftApp, id: DialogId) -> Value { + let glow = first_of(app, id, EffectKind::OuterGlow); + style_params_json(&draft(app, id).style.effect(glow).unwrap().params) +} + +fn set_glow(app: &mut PhotocraftApp, id: DialogId, opacity: f64) { + let glow = first_of(app, id, EffectKind::OuterGlow); + edit(app, id, |draft| { + draft.set_param(glow, "blend", StyleValue::Text("Normal".into())); + draft.set_param(glow, "color", StyleValue::Color(Srgba::from_rgb_array([0.0; 3]))); + draft.set_param(glow, "opacity", StyleValue::Number(opacity)); + draft.set_param(glow, "size", StyleValue::Number(10.0)); + }); +} + +fn confirm(app: &mut PhotocraftApp, id: DialogId) { + crate::dialogs::testing::confirm(app, id).unwrap(); + assert!(!app.ui.status_error, "{}", app.ui.status); +} + +fn other_document(app: &mut PhotocraftApp) { + app.run("file.new", json!({"width": 40, "height": 32})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); +} + +fn remember_glow(app: &mut PhotocraftApp) -> Value { + let id = open_glow(app); + set_glow(app, id, 100.0); + let remembered = values(app, id); + confirm(app, id); + other_document(app); + remembered +} + +#[test] +fn a_new_outer_glow_reuses_the_confirmed_values_on_another_document() { + let mut app = app_with_layer(32); + let remembered = remember_glow(&mut app); + let id = open_glow(&mut app); + assert_eq!(values(&app, id), remembered); + confirm(&mut app, id); + let id = open_glow(&mut app); + assert_eq!(values(&app, id), remembered, "the seeded glow applies to the layer"); +} + +#[test] +fn cancelled_edits_and_an_unchanged_scripted_glow_leave_the_last_ok_alone() { + let mut app = app_with_layer(32); + let remembered = remember_glow(&mut app); + let pending = open_glow(&mut app); + set_glow(&mut app, pending, 40.0); + cancel(&mut app, pending); + + app.run(COMMAND, json!({"blend": "Screen", "color": "#0000ff", "size": 21, "opacity": 60})).unwrap(); + let scripted = open_glow(&mut app); + assert_eq!(values(&app, scripted)["color"], "#0000ff", "the existing layer effect supplies its own values"); + confirm(&mut app, scripted); + + other_document(&mut app); + let next = open_glow(&mut app); + assert_eq!(values(&app, next), remembered); +} + +#[test] +fn editing_an_existing_outer_glow_updates_the_next_new_glow() { + let mut app = app_with_layer(32); + remember_glow(&mut app); + app.run(COMMAND, json!({"size": 21})).unwrap(); + let id = open_glow(&mut app); + set_glow(&mut app, id, 50.0); + let edited = values(&app, id); + confirm(&mut app, id); + other_document(&mut app); + let next = open_glow(&mut app); + assert_eq!(values(&app, next), edited); +} + +#[test] +fn reset_uses_factory_or_user_defaults_and_a_fresh_app_starts_at_factory() { + let mut app = app_with_layer(32); + let initial = open_glow(&mut app); + let factory = values(&app, initial); + cancel(&mut app, initial); + remember_glow(&mut app); + let id = open_glow(&mut app); + let mut h = harness(app); + h.get_by_label("Reset to Default").click(); + h.run_steps(3); + assert_eq!(values(h.state(), id), factory); + + let saved_default = json!({"kind": "outerGlow", "params": {"opacity": 18.0}}); + h.state_mut().run("layer.layerStyle.makeDefault", saved_default).unwrap(); + // Reset must replace every remembered field, even when the saved default is partial. + cancel(h.state_mut(), id); + let id = open_glow(h.state_mut()); + h.run_steps(3); + h.get_by_label("Reset to Default").click(); + h.run_steps(3); + let mut user = factory.clone(); + user["opacity"] = json!(18.0); + assert_eq!(values(h.state(), id), user); + + // A fresh app opens at factory values even with an existing Make Default entry. + let saved = h.state().session.prefs_to_json(); + let mut restarted = app_with_layer(32); + restarted.session.load_prefs_json(&saved).unwrap(); + let id = open_glow(&mut restarted); + assert_eq!(values(&restarted, id), factory); + let mut h = harness(restarted); + h.get_by_label("Reset to Default").click(); + h.run_steps(3); + assert_eq!(values(h.state(), id), user); +} + +#[test] +fn make_default_in_the_current_session_seeds_new_glows() { + let mut app = app_with_layer(32); + remember_glow(&mut app); + let id = open_glow(&mut app); + set_glow(&mut app, id, 60.0); + let user = values(&app, id); + let mut h = harness(app); + h.get_by_label("Make Default").click(); + h.run_steps(3); + cancel(h.state_mut(), id); + let next = open_glow(h.state_mut()); + assert_eq!(values(h.state(), next), user); +} + +#[test] +fn disabled_or_refused_glows_do_not_replace_the_last_ok() { + let mut app = app_with_layer(32); + let remembered = remember_glow(&mut app); + let disabled = open_glow(&mut app); + set_glow(&mut app, disabled, 70.0); + let glow = first_of(&app, disabled, EffectKind::OuterGlow); + edit(&mut app, disabled, |draft| draft.toggle(glow)); + confirm(&mut app, disabled); + + other_document(&mut app); + let refused = open_glow(&mut app); + set_glow(&mut app, refused, 80.0); + let glow = first_of(&app, refused, EffectKind::OuterGlow); + edit(&mut app, refused, |draft| draft.set_param(glow, "fx", StyleValue::Other("{}".into()))); + crate::dialogs::testing::confirm(&mut app, refused).unwrap(); + assert!(app.ui.status_error); + + let next = open_glow(&mut app); + assert_eq!(values(&app, next), remembered); +} diff --git a/crates/ui-egui/src/dialogs/open_prompt.rs b/crates/ui-egui/src/dialogs/open_prompt.rs index 1bb022d47d..d5173f383b 100644 --- a/crates/ui-egui/src/dialogs/open_prompt.rs +++ b/crates/ui-egui/src/dialogs/open_prompt.rs @@ -70,6 +70,8 @@ pub struct MemoryPrompt { pub id: u64, pub name: String, pub path: Option, + /// Original read source when an untitled open has no save/recent path. + pub error_source: Option, pub slot: Option, pub order: Option, pub estimated: u64, @@ -406,6 +408,7 @@ pub fn arrive_memory( id: u64, name: String, path: Option, + error_source: Option, slot: Option, order: Option, estimated: u64, @@ -413,7 +416,18 @@ pub fn arrive_memory( capacity_unknown: bool, uncertain_capacity_warning: bool, ) { - app.held_memory_prompts.push_back(MemoryPrompt { id, name, path, slot, order, estimated, available, capacity_unknown, uncertain_capacity_warning }); + app.held_memory_prompts.push_back(MemoryPrompt { + id, + name, + path, + error_source, + slot, + order, + estimated, + available, + capacity_unknown, + uncertain_capacity_warning, + }); app.prompt_order.push_back(PromptKind::Memory); advance_memory(app); } @@ -480,6 +494,7 @@ pub(crate) fn answer_memory(app: &mut PhotocraftApp, accept: bool) -> Result Result { if accept { if let Some(job) = r.get("job").and_then(Value::as_u64) { - app.jobs.opens.push(crate::jobs_ui::OpenTab { job: photocraft_engine::jobs::JobId(job), name: name.clone(), path, slot, order }); + app.jobs.opens.push(crate::jobs_ui::OpenTab { + job: photocraft_engine::jobs::JobId(job), + name: name.clone(), + path, + error_source: error_source.clone(), + slot, + order, + }); app.jobs.focus = Some(photocraft_engine::jobs::JobId(job)); app.ui.chrome.home = None; app.ui.status = crate::i18n::fmt(tl!("Opening {name}…"), &[("name", &name)]); app.ui.status_error = false; } else if let Some(result) = r.get("result") { - let tab = crate::jobs_ui::OpenTab { job: photocraft_engine::jobs::JobId(0), name: name.clone(), path: path.clone(), slot, order }; + let tab = crate::jobs_ui::OpenTab { + job: photocraft_engine::jobs::JobId(0), + name: name.clone(), + path: path.clone(), + error_source: error_source.clone(), + slot, + order, + }; if let Err(e) = crate::jobs_ui::finish_open_tab(app, &tab, result) { app.ui.status = e; app.ui.status_error = true; @@ -511,8 +540,13 @@ pub(crate) fn answer_memory(app: &mut PhotocraftApp, accept: bool) -> Result { - app.ui.status = err.clone(); - app.ui.status_error = true; + let source = path.as_deref().or(error_source.as_deref()).unwrap_or(&name); + // A template may have reserved an Untitled name; presentation names its read source, + // while the returned error keeps the approval command's original wrapper. + let prefix = format!("{name}: "); + let error = err.strip_prefix(&prefix).unwrap_or(&err); + let reason = if name != crate::file_open::display_name(source) { error.strip_prefix(&prefix).unwrap_or(error) } else { error }; + app.open_failed(source, reason); crate::jobs_ui::end_batch(app); advance(app); crate::jobs_ui::end_batch(app); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 11bdb80991..6030e04d50 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -23,7 +23,7 @@ pub fn persist(app: &mut PhotocraftApp) { } let now = snapshot(app); if app.session.prefs().panel_layout != now { - app.session.prefs.edit(|prefs| prefs.panel_layout = now); + app.session.prefs.remember(|prefs| prefs.panel_layout = now); } } diff --git a/crates/ui-egui/src/file_dialog.rs b/crates/ui-egui/src/file_dialog.rs index 4fe5c16ae2..40f69e60c4 100644 --- a/crates/ui-egui/src/file_dialog.rs +++ b/crates/ui-egui/src/file_dialog.rs @@ -379,7 +379,7 @@ impl PhotocraftApp { for (seq, path) in paths.iter().enumerate() { let order = crate::jobs_ui::OpenOrder { batch, seq }; if let Err(e) = crate::jobs_ui::start_open_as_smart_object(app, path, Some(order)) { - app.open_failed(&crate::file_open::display_name(path), &e); + app.open_failed(path, &e); } } crate::jobs_ui::end_batch(app); diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs index 84b63dbf2f..c40cb777e5 100644 --- a/crates/ui-egui/src/file_open.rs +++ b/crates/ui-egui/src/file_open.rs @@ -3,9 +3,10 @@ //! and the OS's "open these documents" requests (macOS Finder double-click, Open With, drops on the //! Dock icon) all go through [`PhotocraftApp::open_file`], so each one names the document after the //! file, remembers its path (File › Save writes back to it) and adds it to Open Recent. Failures -//! are shown as errors (status bar + notice); import warnings as a notice. +//! are shown as modal alerts and in the status bar; import warnings as a notice. use crate::{PhotocraftApp, notices}; +use craft::ui::dialog::{Alert, DialogId, DialogResult, DialogStack, HostedAlert, StackDialog}; use craft::ui::runtime::drag::OsFile; use craft::ui::runtime::windows::{WindowAction, WindowHost}; use photocraft_doc::DocId; @@ -206,6 +207,64 @@ pub fn display_name(path: &str) -> String { std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).filter(|n| !n.is_empty()).unwrap_or_else(|| path.to_string()) } +// Named PSD/PSB/templates deliberately keep the PSD parser's errors for direct callers. Only +// its missing file-header signature means unrecognized content; damaged internal signatures +// (8BIM, etc.) and a recognized 8BPS file's other parse errors must retain their reasons. +fn unrecognized_open_reason(reason: &str) -> bool { + if reason == "codec: unrecognized image format" { + return true; + } + let Some(signature) = reason.strip_prefix("PSD: invalid signature [").and_then(|s| s.strip_suffix("], expected 8BPS")) else { + return false; + }; + let mut values = signature.split(", "); + let mut found = [0u8; 4]; + for byte in &mut found { + let Some(text) = values.next() else { return false }; + let Ok(value) = text.parse::() else { return false }; + if text != value.to_string() { + return false; + } + *byte = value; + } + values.next().is_none() && &found != b"8BPS" +} + +/// One failed file, rendered by the shared alert. Distinct instances keep a multi-file open's +/// errors separate; a plain HostedAlert has one fixed identity and would replace the earlier file. +struct OpenFailureAlert { + id: DialogId, + alert: HostedAlert, +} + +impl StackDialog for OpenFailureAlert { + type Result = (); + + fn id(&self) -> DialogId { + self.id + } + fn instance(&self) -> Option { + Some(self.id) + } + fn key(&self) -> Option<&str> { + self.alert.key() + } + fn json_fields(&self) -> Option { + self.alert.json_fields() + } + fn confirm(&mut self, ctx: &egui::Context) -> Option<()> { + self.alert.confirm(ctx) + } + fn show(&mut self, ui: &mut egui::Ui, stack: &DialogStack) -> Option> { + ui.push_id(self.id, |ui| self.alert.show(ui, stack)).inner + } +} + +/// Acknowledgements contain no command; drain every completed occurrence without reopening it. +pub(crate) fn take_open_alerts(app: &mut PhotocraftApp, _ctx: &egui::Context) { + while app.framework.dialogs.take_keyed::().is_some() {} +} + impl PhotocraftApp { /// Open `bytes` read from the file at `path`: the document is named after the file, keeps /// `path` for File › Save unless it is a derivative preview, and `path` goes to the top of Open Recent. Returns the import @@ -337,7 +396,7 @@ impl PhotocraftApp { // prompt that is answered later all place the file at its place in the set. match self.open_path_placed(abs, None, Some(order)) { Ok(_) => opened += 1, - Err(e) => self.open_failed(&display_name(abs), &e), + Err(e) => self.open_failed(abs, &e), } } crate::jobs_ui::end_batch(self); @@ -371,12 +430,31 @@ impl PhotocraftApp { true } - /// Show "Couldn't open : " as an error (status bar + notice). - pub fn open_failed(&mut self, name: &str, err: &str) { - self.failed({ + /// Report one failed open in an OK alert, naming its source file once. Pass the source path + /// when available so its exact prefix can be removed from filesystem read errors too. + pub fn open_failed(&mut self, source: &str, err: &str) { + let name = display_name(source); + let source_prefix = format!("{source}: "); + let name_prefix = format!("{name}: "); + // The native background importer wraps its path-prefixed read error in the file name. + let wrapped_source_prefix = format!("{name}: {source}: "); + let reason = (source != name) + .then(|| err.strip_prefix(&wrapped_source_prefix)) + .flatten() + .or_else(|| err.strip_prefix(&source_prefix)) + .or_else(|| err.strip_prefix(&name_prefix)) + .unwrap_or(err); + let msg = if unrecognized_open_reason(reason) { + crate::i18n::fmt(tl!("Could not open \"{name}\" because PhotoCraft does not recognize this type of file."), &[("name", &name)]) + } else { let template = "Couldn't open {name}: {error}"; - crate::i18n::fmt(tl!(template), &[("name", name), ("error", err)]) - }); + crate::i18n::fmt(tl!(template), &[("name", &name), ("error", reason)]) + }; + log::warn!("{msg}"); + self.ui.status = msg.clone(); + self.ui.status_error = true; + let id = crate::jobs_ui::open_failure_id(self); + self.framework.dialogs.open(OpenFailureAlert { id, alert: HostedAlert::new(Alert::new("PhotoCraft", msg)) }); } /// Show "Couldn't place : " as an error (status bar + notice). @@ -417,11 +495,13 @@ impl PhotocraftApp { } for f in files { let name = dropped_name(&f); + let source = f.path.as_deref().filter(|path| path.is_absolute()).map(|path| path.to_string_lossy().into_owned()).unwrap_or_else(|| name.clone()); let route = to.route(&name); + if let Some(why) = f.path.as_deref().and_then(folder_error) { match route { DropRoute::Place => self.failed(crate::i18n::fmt(tl!("Couldn't place {name}: {error}"), &[("name", &name), ("error", &why)])), - DropRoute::Open => self.open_failed(&name, &why), + DropRoute::Open => self.open_failed(&source, &why), } continue; } @@ -434,7 +514,7 @@ impl PhotocraftApp { match self.open_dropped_file(&f, &name, slot) { Ok(true) => slot = slot.map(|s| s + 1), Ok(false) => {} - Err(e) => self.open_failed(&name, &e), + Err(e) => self.open_failed(&source, &e), } } } @@ -804,3 +884,6 @@ mod dialog_order_tests; mod place_multiple_files_tests; #[cfg(test)] mod tests; + +#[cfg(test)] +mod unreadable_alert_tests; diff --git a/crates/ui-egui/src/file_open/tests.rs b/crates/ui-egui/src/file_open/tests.rs index 974dfff68e..aa14793201 100644 --- a/crates/ui-egui/src/file_open/tests.rs +++ b/crates/ui-egui/src/file_open/tests.rs @@ -186,7 +186,7 @@ fn the_web_opens_every_selected_file() { // Each good file is its own tab; the broken one is reported without stopping the rest. let names: Vec<_> = app.session.documents().iter().map(|st| st.doc.name.as_str()).collect(); assert_eq!(names, ["one.png", "two.jpg"]); - assert!(app.ui.notices.iter().any(|n| n.tone == craft::theme::variant::Tone::Bad && n.title.contains("broken.png")), "{:?}", app.ui.notices); + assert!(open_error_messages(&app).iter().any(|message| message.contains("broken.png")), "{:?}", app.ui.notices); } /// #5749: the web shell reads dropped files itself, so it asks where they landed: image files @@ -417,7 +417,7 @@ fn open_failures_are_errors_and_leave_no_document() { assert!(app.ui.recent_files.is_empty()); assert!(app.ui.status_error); assert!(app.ui.status.starts_with("Couldn't open broken.psd"), "{}", app.ui.status); - assert!(app.ui.notices.last().is_some_and(|n| n.tone == craft::theme::variant::Tone::Bad)); + assert_eq!(open_error_messages(&app).len(), 1); let _ = std::fs::remove_dir_all(&dir); } @@ -430,8 +430,9 @@ fn a_picked_file_that_cannot_be_read_is_reported_like_any_open_failure() { answer(&mut app); assert!(app.session.documents().is_empty()); assert!(app.ui.status_error); - let notice = app.ui.notices.last().unwrap(); - assert!(notice.tone == craft::theme::variant::Tone::Bad && notice.title.starts_with("Couldn't open big.psb: "), "{}", notice.title); + let messages = open_error_messages(&app); + assert_eq!(messages.len(), 1); + assert!(messages[0].starts_with("Couldn't open big.psb: "), "{}", messages[0]); // Commands that read a picked file (scripts, notes, Place) fail with the file's name. app.ui.status_error = false; app.pick_file_bytes(|_, _, _| Err("read".into())).unwrap(); @@ -452,7 +453,8 @@ fn open_paths_reports_each_failure_without_panicking() { assert_eq!(n, 0); assert!(app.session.documents().is_empty()); assert!(app.ui.status_error); - assert_eq!(app.ui.notices.len(), 4, "one notice per failure"); + assert_eq!(open_error_messages(&app).len(), 4, "one modal alert per failure"); + assert!(app.ui.notices.is_empty()); // Bad control params error instead of panicking. let ctx = egui::Context::default(); assert!(menus::invoke(&mut app, &ctx, "file.open", json!({ "path": "" })).is_err()); @@ -557,7 +559,9 @@ fn dropped_files_open_with_path_and_recent() { assert_eq!(app.session.documents()[1].path, None); assert_eq!(*app.ui.recent_files, vec![abs_s]); assert!(app.ui.status_error); - assert_eq!(app.ui.notices.iter().filter(|n| n.tone == craft::theme::variant::Tone::Bad).count(), 2); + assert_eq!(open_error_messages(&app), ["Couldn't open gone.psd: couldn't read the file", "Couldn't open dropped: not an image"]); + assert!(app.ui.notices.is_empty(), "open failures use modal alerts, not corner notices"); + assert_eq!(app.ui.status, "Couldn't open dropped: not an image"); let _ = std::fs::remove_dir_all(&dir); } @@ -1397,7 +1401,14 @@ fn a_set_of_background_opens_keeps_its_order_however_they_finish() { let (mut app, _) = app_with(Vec::new()); app.open_bytes("existing.psd", b"x").unwrap(); let batch = jobs_ui::begin_batch(&mut app); - let tab = |seq: usize| OpenTab { job: JobId(100 + seq as u64), name: format!("f{seq}.psd"), path: None, slot: None, order: Some(OpenOrder { batch, seq }) }; + let tab = |seq: usize| OpenTab { + job: JobId(100 + seq as u64), + name: format!("f{seq}.psd"), + path: None, + error_source: None, + slot: None, + order: Some(OpenOrder { batch, seq }), + }; app.jobs.opens.extend((0..4).map(tab)); // f1 opened at once (a preset file, say, or background jobs off for it). app.jobs.opens.remove(1); @@ -1419,11 +1430,11 @@ fn a_set_of_background_opens_keeps_its_order_however_they_finish() { assert_eq!(app.ui.views.len(), 5, "views follow their documents"); assert!(app.jobs.batches.is_empty(), "forgotten once every member opened"); // A tab with a slot (dropped on the tabs) keeps it; one from a forgotten set goes to the end. - let dropped = OpenTab { job: JobId(200), name: "dropped.psd".into(), path: None, slot: Some(0), order: None }; + let dropped = OpenTab { job: JobId(200), name: "dropped.psd".into(), path: None, error_source: None, slot: Some(0), order: None }; let index = app.session.add_document(Document::new("dropped.psd", Size::new(4, 4), ColorMode::Rgb, SampleType::U8), None); let id = app.session.documents()[index].doc.id; jobs_ui::finish_open_tab(&mut app, &dropped, &json!({"document": index, "docId": id.0})).unwrap(); - let late = OpenTab { job: JobId(201), name: "late.psd".into(), path: None, slot: None, order: Some(OpenOrder { batch: 999, seq: 0 }) }; + let late = OpenTab { job: JobId(201), name: "late.psd".into(), path: None, error_source: None, slot: None, order: Some(OpenOrder { batch: 999, seq: 0 }) }; let index = app.session.add_document(Document::new("late.psd", Size::new(4, 4), ColorMode::Rgb, SampleType::U8), None); let id = app.session.documents()[index].doc.id; jobs_ui::finish_open_tab(&mut app, &late, &json!({"document": index, "docId": id.0})).unwrap(); @@ -1691,7 +1702,17 @@ fn scratch(tag: &str) -> std::path::PathBuf { } fn error_titles(app: &PhotocraftApp) -> Vec { - app.ui.notices.iter().filter(|n| n.tone == craft::theme::variant::Tone::Bad).map(|n| n.title.clone()).collect() + app.ui.notices.iter().filter(|n| n.tone == craft::theme::variant::Tone::Bad).map(|n| n.title.clone()).chain(open_error_messages(app)).collect() +} + +fn open_error_messages(app: &PhotocraftApp) -> Vec { + app.framework + .dialogs + .open_dialogs() + .into_iter() + .filter(|d| d.key.as_deref() == Some("alert")) + .filter_map(|d| d.fields.and_then(|f| f.get("message").and_then(serde_json::Value::as_str).map(str::to_owned))) + .collect() } /// The Home screen (no document open) is where a first drop lands: every file opens as its own @@ -1717,6 +1738,7 @@ fn files_dropped_with_no_document_open_all_open() { assert_eq!(doc_names(&app), names); assert!(app.drop_places.is_empty()); assert!(error_titles(&app).is_empty(), "{:?}", app.ui.notices); + assert!(open_error_messages(&app).is_empty(), "{:?}", app.framework.dialogs.open_dialogs()); let _ = std::fs::remove_dir_all(&dir); } @@ -1799,7 +1821,7 @@ fn several_files_dropped_on_the_canvas_are_queued_in_order() { }) .collect(); assert_eq!(queued, ["one.png", "two.jpg"]); - assert!(error_titles(&app).iter().any(|t| t.starts_with("Couldn't open set.abr: ")), "{:?}", app.ui.notices); + assert!(open_error_messages(&app).iter().any(|t| t.starts_with("Couldn't open set.abr: ")), "{:?}", app.framework.dialogs.open_dialogs()); } #[test] @@ -1836,9 +1858,11 @@ fn open_as_smart_object_dialog_opens_one_document_per_selected_file() { assert_eq!(app.session.documents().iter().map(|d| d.doc.name.as_str()).collect::>(), ["one-1", "two-1"]); assert!(app.session.documents().iter().all(|d| d.path.is_none() && d.doc.layers.len() == 1)); - assert!( - app.ui.notices.iter().any(|n| n.tone == craft::theme::variant::Tone::Bad && n.title.starts_with("Couldn't open bad.png")), - "the unreadable file is reported" + assert_eq!( + open_error_messages(&app), + ["Could not open \"bad.png\" because PhotoCraft does not recognize this type of file."], + "the unreadable file has one exact modal alert; status: {}", + app.ui.status ); let _ = std::fs::remove_dir_all(&dir); } @@ -1861,9 +1885,11 @@ fn open_as_smart_object_opens_in_the_background_in_name_order() { tick_until(&mut app, &ctx, |app| app.jobs.opens.is_empty()); assert_eq!(app.session.documents().iter().map(|d| d.doc.name.as_str()).collect::>(), ["one-1", "two-1"]); assert!(app.session.documents().iter().all(|d| d.path.is_none() && d.doc.layers.len() == 1)); - assert!( - app.ui.notices.iter().any(|n| n.tone == craft::theme::variant::Tone::Bad && n.title.starts_with("Couldn't open bad.png")), - "the unreadable file is reported" + assert_eq!( + open_error_messages(&app), + ["Could not open \"bad.png\" because PhotoCraft does not recognize this type of file."], + "the unreadable file has one exact modal alert; status: {}", + app.ui.status ); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs new file mode 100644 index 0000000000..41580d6888 --- /dev/null +++ b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs @@ -0,0 +1,581 @@ +//! #14059: unreadable File > Open inputs use one modal alert per file, while callers that +//! request an error result still receive it. + +use super::*; +use crate::control::{ControlRequest, Reply, handle}; +use crate::{Services, menus}; +use craft::host::{Picked, ScriptedFiles}; +use craft::ui::dialog::{DialogId, OpenDialog}; +use craft::ui::runtime::drag::OsFile; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use std::sync::Arc; + +fn app_with(answer: Option) -> Box { + let services = Services { + files: Some(Arc::new(ScriptedFiles::answering(vec![answer.unwrap_or(Picked::Cancelled)]))), + import: Some(Box::new(|name, bytes, opts| { + photocraft_io::import_with_options(name, bytes, opts).map(|r| (r.document, r.warnings)).map_err(|e| format!("{name}: {e}")) + })), + ..Default::default() + }; + PhotocraftApp::new(photocraft_engine::Session::new(), services) +} + +fn pick(app: &mut PhotocraftApp) { + let ctx = app.ctx().clone(); + menus::invoke(app, &ctx, "file.open", json!({})).unwrap(); + app.poll_file_dialog(); +} + +fn error_dialogs(app: &PhotocraftApp) -> Vec { + app.framework.dialogs.open_dialogs().into_iter().filter(|d| d.key.as_deref() == Some("alert")).collect() +} + +fn messages(app: &PhotocraftApp) -> Vec { + error_dialogs(app).into_iter().map(|d| d.fields.unwrap()["message"].as_str().unwrap().to_owned()).collect() +} + +fn no_dialogs(app: &PhotocraftApp) -> bool { + app.framework.dialogs.open_dialogs().is_empty() +} + +fn memory_id(app: &PhotocraftApp) -> DialogId { + crate::dialogs::alerts::prompt_tagged::(app).unwrap() +} + +fn expected(name: &str) -> String { + format!("Could not open \"{name}\" because PhotoCraft does not recognize this type of file.") +} + +fn png() -> Vec { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 2, "height": 2, "background": "white"})).unwrap(); + photocraft_io::export(&s.active().unwrap().doc, "valid.png", &Default::default()).unwrap().bytes +} + +#[test] +fn unrecognized_and_mislabeled_files_show_the_exact_alert_without_opening_documents() { + for (name, bytes) in [ + ("notes.txt", b"ordinary text".to_vec()), + ("broken.png", b"ordinary text".to_vec()), + ("zz-bad.png", (1..=17).collect()), + ("unknown.psd", b"ordinary text".to_vec()), + ("unknown.psb", b"ordinary text".to_vec()), + ("unknown.psdt", b"ordinary text".to_vec()), + ] { + let mut app = app_with(Some(Picked::Contents(vec![(name.into(), bytes)]))); + pick(&mut app); + let wanted = expected(name); + assert_eq!(messages(&app), [wanted.as_str()]); + assert!(app.session.documents().is_empty()); + assert!(app.ui.recent_files.is_empty()); + assert!(app.ui.notices.is_empty(), "the modal replaces the corner notice"); + assert!(app.ui.status_error); + assert_eq!(app.ui.status, wanted); + assert_eq!(app.ui.status.matches(name).count(), 1); + } + // Interactive foreground errors now retain the source name instead of a generated Untitled-N. + let mut interactive = app_with(None); + assert_eq!( + interactive.open_bytes("unknown.psdt", b"ordinary text").unwrap_err(), + "unknown.psdt: PSD: invalid signature [111, 114, 100, 105], expected 8BPS" + ); + assert!(no_dialogs(&interactive), "the caller owns presentation of a returned error"); + + #[cfg(not(target_arch = "wasm32"))] + { + let mut app = app_with(Some(Picked::Contents(vec![("unknown.psdt".into(), b"ordinary text".to_vec())]))); + app.background_jobs = true; + pick(&mut app); + assert_eq!(app.jobs.opens.len(), 1); + let tab = &app.jobs.opens[0]; + assert_eq!(tab.name, "Untitled-1"); + assert!(tab.path.is_none()); + assert_eq!(tab.error_source.as_deref(), Some("unknown.psdt")); + let worker_error = format!("{}: codec: unrecognized image format", tab.name); + finish_read_failure(&mut app, "unknown.psdt", "codec: unrecognized image format", &worker_error); + assert!(app.ui.recent_files.is_empty()); + } +} + +#[test] +fn an_open_failure_alert_has_one_ok_button_and_closes_when_clicked() { + let mut app = app_with(None); + app.open_failed("notes.txt", "notes.txt: codec: unrecognized image format"); + let mut h = egui_kittest::Harness::builder() + .with_size(egui::vec2(900.0, 600.0)) + .with_context(app.ctx().clone()) + .build_ui_state(|ui, app| crate::dialogs::run(app, ui), app); + h.run_steps(3); + assert!(h.query_by_label(&expected("notes.txt")).is_some()); + assert!(h.query_by_label("Cancel").is_none()); + h.get_by_label("OK").click(); + h.run_steps(3); + assert!(no_dialogs(h.state())); + assert!(h.state().session.documents().is_empty()); +} + +#[test] +fn other_read_errors_keep_their_reason_and_only_exact_leading_source_prefixes_are_removed() { + let source = std::path::Path::new("pictures").join("missing.png").to_string_lossy().into_owned(); + for (err, reason) in [ + (format!("{source}: file not found"), "file not found"), + ("missing.png: permission denied".into(), "permission denied"), + (format!("missing.png: {source}: file not found"), "file not found"), + ("missing.png: elsewhere/missing.png: keep this reason".into(), "elsewhere/missing.png: keep this reason"), + ("the directory is missing.png: keep this reason".into(), "the directory is missing.png: keep this reason"), + ] { + let mut app = app_with(None); + app.open_failed(&source, &err); + assert_eq!(messages(&app), [format!("Couldn't open missing.png: {reason}")]); + assert!(app.ui.notices.is_empty()); + } +} + +#[test] +fn several_failed_files_each_get_one_alert_and_valid_files_still_open() { + let files = vec![("a.txt".into(), b"text".to_vec()), ("b.png".into(), png()), ("c.png".into(), b"text".to_vec()), ("d.png".into(), png())]; + let mut app = app_with(Some(Picked::Contents(files))); + pick(&mut app); + assert_eq!(messages(&app), [expected("a.txt"), expected("c.png")]); + assert_eq!(app.session.documents().iter().map(|d| d.doc.name.as_str()).collect::>(), ["b.png", "d.png"]); + assert!(app.ui.notices.iter().all(|n| n.tone != craft::theme::variant::Tone::Bad)); + let app_ctx = app.ctx().clone(); + let first = error_dialogs(&app)[0].id; + crate::dialogs::confirm(&mut app, &app_ctx, first).unwrap(); + assert_eq!(messages(&app), [expected("c.png")]); + let second = error_dialogs(&app)[0].id; + assert_ne!(first, second, "each failed file has its own instance"); + let (request, _rx) = ControlRequest::new("ui.dialog.confirm", json!({"dialog": second.value()})); + let Reply::Done(reply) = handle(&mut app, &app_ctx, &request) else { panic!("alert confirmation is immediate") }; + assert_eq!(reply["ok"], true); + app_ctx.run_ui(Default::default(), |ui| crate::dialogs::run(&mut app, ui)).textures_delta.clear(); + assert!(messages(&app).is_empty()); + assert_eq!(app.session.documents().len(), 2); + assert!(app.framework.dialogs.take_keyed::().is_none(), "the consumer drains both instance-bound acknowledgements"); + + // The per-file consumer owns only its wrapper, even though a plain alert also answers (). + let plain = app.framework.dialogs.open(HostedAlert::new(Alert::new("PhotoCraft", "unrelated alert"))); + assert!(app.framework.dialogs.confirm_by_id(&app_ctx, plain)); + take_open_alerts(&mut app, &app_ctx); + assert!(matches!(app.framework.dialogs.take::(), Some(DialogResult::Ok(())))); + assert!(app.framework.dialogs.take_keyed::().is_none()); +} + +#[test] +fn background_open_failures_are_reported_once_when_the_jobs_finish() { + let mut app = app_with(None); + app.background_jobs = true; + app.open_bytes("first.txt", b"text").unwrap(); + app.open_bytes("second.png", b"text").unwrap(); + app.open_bytes("valid.png", &png()).unwrap(); + let ctx = app.ctx().clone(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + while !app.jobs.opens.is_empty() { + assert!(std::time::Instant::now() < deadline, "open jobs did not finish"); + crate::jobs_ui::tick(&mut app, &ctx); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + let mut actual = messages(&app); + actual.sort(); + let mut wanted = vec![expected("first.txt"), expected("second.png")]; + wanted.sort(); + assert_eq!(actual, wanted); + assert_eq!(app.session.documents().iter().map(|d| d.doc.name.as_str()).collect::>(), ["valid.png"]); + crate::jobs_ui::tick(&mut app, &ctx); + assert_eq!(messages(&app).len(), 2, "a consumed failure event cannot show twice"); + assert!(app.ui.notices.iter().all(|n| n.tone != craft::theme::variant::Tone::Bad)); +} + +#[test] +fn cancelling_file_open_does_not_show_an_error() { + let mut app = app_with(None); + pick(&mut app); + assert!(!app.file_dialog_open()); + assert!(app.session.documents().is_empty()); + assert!(no_dialogs(&app)); + assert!(app.ui.notices.is_empty()); + assert!(!app.ui.status_error); +} + +#[test] +fn automation_and_control_open_still_return_the_original_error() { + // app.open reserves the template's untitled name before its separate automation decode. + for (name, expected_error, expected_control_error) in [ + ("notes.txt", "notes.txt: codec: unrecognized image format", "notes.txt: codec: unrecognized image format"), + ("unknown.psdt", "unknown.psdt: PSD: invalid signature [116, 101, 120, 116], expected 8BPS", "Untitled-1: codec: unrecognized image format"), + ] { + let mut app = app_with(None); + let err = app.open_automation_bytes(name, b"text").unwrap_err(); + assert_eq!(err, expected_error); + assert!(no_dialogs(&app)); + let read_name = name.to_string(); + app.services.automation_read = + Some(Box::new(move |_| Ok(crate::AutomationReadResult { name: read_name.clone(), bytes: b"text".to_vec(), save_path: None }))); + let (request, _rx) = ControlRequest::new("app.open", json!({"path": name})); + let Reply::Done(reply) = handle(&mut app, &egui::Context::default(), &request) else { panic!("open should return immediately") }; + assert_eq!(reply["ok"], false); + assert_eq!(reply["error"], expected_control_error); + assert!(app.session.documents().is_empty()); + assert!(no_dialogs(&app)); + assert!(app.ui.notices.is_empty()); + } +} + +/// This path must remain absent: both the foreground and worker open really fail to read it. +#[cfg(not(target_arch = "wasm32"))] +fn missing_source(tag: &str, name: &str) -> (std::path::PathBuf, String, String) { + let path = std::env::temp_dir().join(format!("photocraft-unreadable-{tag}-{}", std::process::id())).join(name); + assert!(!path.exists()); + let reason = photocraft_format::read_file(&path).unwrap_err().to_string(); + let source = path.to_string_lossy().into_owned(); + (path, source, reason) +} + +/// A native path plus tempting valid bytes: choosing bytes instead of reading the path would +/// open a document and fail the original missing-file and raw-error assertions below. +#[cfg(not(target_arch = "wasm32"))] +fn unreadable_native_drop(path: std::path::PathBuf) -> OsFile { + let mut file = OsFile::default(); + file.name = display_name(&path.to_string_lossy()); + file.path = Some(path); + file.bytes = Some(png().into()); + file +} + +/// Apply actual worker events and check the unmodified error sent to a waiting control client. +#[cfg(not(target_arch = "wasm32"))] +fn finish_read_failure(app: &mut PhotocraftApp, source: &str, reason: &str, worker_error: &str) { + let job = app.jobs.opens.first().map(|tab| tab.job); + let reply = job.map(|job| { + let (request, reply) = ControlRequest::new("engine.execute", json!({})); + let channel = app.control.get_or_insert_with(|| craft::automation::ControlChannel::new(std::sync::mpsc::channel().1)); + channel.settle(request, Reply::AfterJob(job.0), None, 0.0); + reply + }); + let ctx = app.ctx().clone(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + while !app.jobs.opens.is_empty() { + assert!(std::time::Instant::now() < deadline, "open job did not finish"); + crate::jobs_ui::tick(app, &ctx); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + if let Some(reply) = reply { + assert_eq!(reply.try_recv().unwrap(), json!({"ok": false, "error": worker_error})); + } + let name = display_name(source); + let wanted = if reason == "codec: unrecognized image format" { expected(&name) } else { format!("Couldn't open {name}: {reason}") }; + assert_eq!(messages(app), [wanted]); + assert_eq!(app.ui.status, messages(app)[0]); + assert_eq!(app.ui.status.matches(name.as_str()).count(), 1); + assert!(app.session.documents().is_empty()); + assert!(app.ui.notices.is_empty()); + crate::jobs_ui::tick(app, &ctx); + assert_eq!(messages(app).len(), 1, "the finished event is consumed once"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_drop_read_failures_name_the_source_once_in_foreground_and_background() { + for name in ["missing.psd", "missing.psdt"] { + let (path, source, reason) = missing_source("drop", name); + for background in [false, true] { + let mut app = app_with(None); + app.background_jobs = background; + app.open_dropped(&egui::Context::default(), vec![unreadable_native_drop(path.clone())], crate::file_open::DropTo::Window); + assert_eq!(app.jobs.opens.len(), usize::from(background), "exercise the actual selected execution route"); + let worker_name = app.jobs.opens.first().map(|tab| tab.name.as_str()).unwrap_or(name); + if background { + assert_eq!(worker_name, if name == "missing.psdt" { "Untitled-1" } else { name }); + } + let worker_error = format!("{worker_name}: {source}: {reason}"); + finish_read_failure(&mut app, &source, &reason, &worker_error); + assert!(app.ui.recent_files.is_empty()); + } + } + + // The public path-plus-bytes API retains the source while the actual template worker is untitled. + let (_, source, _) = missing_source("template-codec", "unknown.psdt"); + let mut app = app_with(None); + app.background_jobs = true; + app.open_file(&source, b"ordinary text").unwrap(); + assert_eq!(app.jobs.opens.len(), 1); + let tab = &app.jobs.opens[0]; + assert_eq!(tab.name, "Untitled-1"); + assert_eq!(tab.path.as_deref(), Some(source.as_str())); + let worker_error = format!("{}: codec: unrecognized image format", tab.name); + finish_read_failure(&mut app, &source, "codec: unrecognized image format", &worker_error); + assert!(app.ui.recent_files.is_empty()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn recent_grid_and_list_read_failures_keep_the_reason_without_repeating_the_path() { + let (path, source, reason) = missing_source("recent", "missing.psd"); + for grid in [false, true] { + let mut app = app_with(None); + app.background_jobs = false; + app.ui.chrome.home_recent_view = if grid { craft::ui::shell::RecentView::Grid } else { craft::ui::shell::RecentView::List }; + app.push_recent(&source); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 760.0)).with_context(app.ctx().clone()).build_ui_state( + |ui, app: &mut Box| { + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + h.run_steps(3); + let label = if grid { "missing.psd".to_owned() } else { format!("missing.psd, {}", path.parent().unwrap().display()) }; + h.get_by_role_and_label(egui::accesskit::Role::ListItem, &label).click(); + h.run_steps(3); + finish_read_failure(h.state_mut(), &source, &reason, "no worker in this foreground control"); + assert_eq!(h.state().ui.recent_files.as_slice(), std::slice::from_ref(&source)); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn os_open_read_failures_keep_the_existing_full_source_route() { + let (_, source, reason) = missing_source("os", "missing.psd"); + for background in [false, true] { + let mut app = app_with(None); + app.background_jobs = background; + let mut events = vec![OsEvent::Open(vec![source.clone()])]; + app.services.os_events = Some(Box::new(move || std::mem::take(&mut events))); + app.drain_os_events(&egui::Context::default()); + assert_eq!(app.jobs.opens.len(), usize::from(background), "exercise the actual selected execution route"); + let worker_error = format!("{}: {source}: {reason}", display_name(&source)); + finish_read_failure(&mut app, &source, &reason, &worker_error); + assert!(app.ui.recent_files.is_empty()); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn smart_object_open_read_failures_retain_the_read_source_without_a_save_or_recent_path() { + let (_, source, reason) = missing_source("smart-object", "missing.psd"); + for background in [false, true] { + let mut app = app_with(Some(Picked::Paths(vec![source.clone().into()]))); + app.background_jobs = background; + app.open_dialog_as_smart_object().unwrap(); + app.poll_file_dialog(); + assert_eq!(app.jobs.opens.len(), usize::from(background), "exercise the actual selected execution route"); + assert!(app.jobs.opens.iter().all(|tab| tab.path.is_none()), "a Smart Object remains untitled"); + assert!(app.jobs.opens.iter().all(|tab| tab.error_source.as_deref() == Some(source.as_str()))); + finish_read_failure(&mut app, &source, &reason, &format!("{source}: {reason}")); + assert!(app.ui.recent_files.is_empty()); + } +} + +#[test] +fn recognized_psd_header_failures_keep_their_diagnostic_and_raw_error() { + // The file signature is recognized: a bad version is a PSD error, not a codec miss. + let bytes = b"8BPS\0\0".to_vec(); + let mut app = app_with(Some(Picked::Contents(vec![("corrupt.psdt".into(), bytes.clone())]))); + pick(&mut app); + assert_eq!(messages(&app), ["Couldn't open corrupt.psdt: PSD: unsupported file version 0"]); + assert!(app.session.documents().is_empty()); + assert!(app.ui.recent_files.is_empty()); + assert!(app.ui.notices.is_empty()); + let mut direct = app_with(None); + // The typed PSD path returns its raw IO error without adding a source-name prefix. + assert_eq!(direct.open_bytes("corrupt.psdt", &bytes).unwrap_err(), "PSD: unsupported file version 0"); + assert!(no_dialogs(&direct)); + + // A damaged internal block or an unrelated/malformed diagnostic retains its reason. + for reason in [ + "PSD: invalid signature [0, 0, 0, 0], expected 8BIM (layer blend mode)", + "PSD: invalid signature [56, 66, 80, 83], expected 8BPS", + "PSD: invalid signature [0, 0, 0], expected 8BPS", + "PSD: invalid signature [256, 0, 0, 0], expected 8BPS", + "PSD: invalid signature [+1, 0, 0, 0], expected 8BPS", + "PSD: invalid signature [00, 0, 0, 0], expected 8BPS", + "PSD: invalid signature [0, 0, 0, 0], expected 8BPS; keep this detail", + "embedded PSD: invalid signature [0, 0, 0, 0], expected 8BPS", + ] { + let mut app = app_with(None); + app.open_failed("corrupt.psdt", reason); + assert_eq!(messages(&app), [format!("Couldn't open corrupt.psdt: {reason}")]); + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn template_psd_for_memory_prompt() -> Vec { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 4, "height": 3, "background": "white"})).unwrap(); + photocraft_io::export(&s.active().unwrap().doc, "small.psd", &Default::default()).unwrap().bytes +} + +#[cfg(not(target_arch = "wasm32"))] +fn memory_dialog_reply(app: &mut PhotocraftApp, dialog: DialogId, accept: bool) -> serde_json::Value { + let method = if accept { "ui.dialog.confirm" } else { "ui.dialog.cancel" }; + let (request, _rx) = ControlRequest::new(method, json!({"dialog": dialog.value()})); + let ctx = app.ctx().clone(); + let Reply::Done(reply) = handle(app, &ctx, &request) else { panic!("memory prompt reply is immediate") }; + ctx.run_ui(Default::default(), |ui| crate::dialogs::run(app, ui)).textures_delta.clear(); + reply +} + +#[cfg(not(target_arch = "wasm32"))] +fn finish_successful_template_jobs(app: &mut PhotocraftApp) { + let jobs: Vec<_> = app.jobs.opens.iter().map(|tab| tab.job).collect(); + for job in jobs { + app.session.wait_job(job).unwrap(); + } + crate::jobs_ui::tick(app, &egui::Context::default()); +} + +/// A real picked byte template reaches preflight through both immediate and worker completion. +/// Its original source is metadata only: approval still opens Untitled-1 without a save path. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn byte_template_memory_prompt_keeps_the_source_through_real_open_approve_and_cancel() { + if cfg!(target_pointer_width = "32") { + return; // The scoped 3 GiB estimate charge exceeds the 32-bit product cap. + } + let gb = 1u64 << 30; + let psd = template_psd_for_memory_prompt(); + let memory = photocraft_io::memory::MemorySnapshot { available_ram: Some(5 * gb), swap_free: None, commit_headroom: None }; + for background in [false, true] { + for accept in [false, true] { + let mut app = app_with(Some(Picked::Contents(vec![("card.psdt".into(), psd.clone())]))); + app.background_jobs = background; + photocraft_io::psd_budget::with_test_estimate_charge(3 * gb, || { + photocraft_io::memory::with_mock_memory(memory, || { + pick(&mut app); + assert_eq!(app.jobs.opens.len(), usize::from(background)); + if background { + finish_successful_template_jobs(&mut app); + } + assert!(app.session.documents().is_empty()); + assert_eq!(app.held_memory_prompts.len(), 1, "use the real high-memory preflight"); + let prompt = &app.held_memory_prompts[0]; + assert_eq!(prompt.name, "Untitled-1"); + assert!(prompt.path.is_none()); + assert_eq!(prompt.error_source.as_deref(), Some("card.psdt")); + assert!(prompt.estimated > 3 * gb); + let preflight = prompt.id; + let dialog = memory_id(&app); + assert!(crate::dialogs::alerts::prompt_tag::(&app).is_some()); + let reply = memory_dialog_reply(&mut app, dialog, accept); + assert_eq!(reply["ok"], true, "{reply}"); + if background && accept { + let tab = app.jobs.opens.first().unwrap(); + assert_eq!(tab.name, "Untitled-1"); + assert!(tab.path.is_none()); + assert_eq!(tab.error_source.as_deref(), Some("card.psdt")); + finish_successful_template_jobs(&mut app); + } + assert_eq!(app.session.documents().len(), usize::from(accept)); + if accept { + let opened = &app.session.documents()[0]; + assert_eq!(opened.doc.name, "Untitled-1"); + assert!(opened.path.is_none(), "error source is never a save destination"); + } + assert!(app.ui.recent_files.is_empty(), "byte input does not acquire a Recent path"); + assert!(no_dialogs(&app)); + assert!(app.held_memory_prompts.is_empty()); + assert!(app.prompt_order.is_empty()); + assert!(app.jobs.opens.is_empty()); + assert!(app.jobs.batches.is_empty()); + assert!(app.session.take_pending_preflight(preflight).is_none()); + assert_eq!(app.session.pending_preflight_bytes().unwrap(), 0); + assert!(!app.ui.status_error); + }); + }); + } + } +} + +/// A stored byte preflight with a valid identity but invalid PSD version drives the real +/// approval decoder, so both the immediate error and the later worker failure keep raw replies. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn byte_template_memory_approval_decode_failures_name_the_source_and_keep_raw_replies() { + let header = vec![ + b'8', b'B', b'P', b'S', 0, 0, // unsupported version + 0, 0, 0, 0, 0, 0, // reserved + 0, 3, // channels + 0, 0, 0, 1, // height + 0, 0, 0, 1, // width + 0, 8, // depth + 0, 3, // RGB + ]; + // The typed UI confirmation is an acknowledgement. The underlying approval result keeps + // its original raw wrapper, checked independently through the same real stored preflight. + { + let mut direct = app_with(None); + direct.background_jobs = false; + let source = photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(header.clone())); + let fingerprint = photocraft_engine::jobs::SourceFingerprint::of(&source).unwrap(); + let id = direct + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: "Untitled-1".into(), + source, + fingerprint, + required: 1000, + soft_limit: 500, + hard_limit: 2000, + available_ram: Some(4000), + confirm_damage: true, + }) + .unwrap(); + crate::open_prompt::arrive_memory(&mut direct, id, "Untitled-1".into(), None, Some("card.psdt".into()), None, None, 1000, Some(4000), false, false); + let error = crate::open_prompt::answer_memory(&mut direct, true).unwrap_err(); + assert_eq!(error, "Untitled-1: Untitled-1: PSD: unsupported file version 0", "preserve the approval's original wrapper"); + } + for background in [false, true] { + let mut app = app_with(None); + app.background_jobs = background; + let source = photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(header.clone())); + let fingerprint = photocraft_engine::jobs::SourceFingerprint::of(&source).unwrap(); + let preflight = app + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: "Untitled-1".into(), + source, + fingerprint, + required: 1000, + soft_limit: 500, + hard_limit: 2000, + available_ram: Some(4000), + confirm_damage: true, + }) + .unwrap(); + crate::open_prompt::arrive_memory(&mut app, preflight, "Untitled-1".into(), None, Some("card.psdt".into()), None, None, 1000, Some(4000), false, false); + let dialog = memory_id(&app); + let reply = memory_dialog_reply(&mut app, dialog, true); + let reason = "PSD: unsupported file version 0"; + if background { + assert_eq!(reply["ok"], true, "the actual approval starts a worker: {reply}"); + let tab = app.jobs.opens.first().unwrap(); + assert_eq!(tab.name, "Untitled-1"); + assert!(tab.path.is_none()); + assert_eq!(tab.error_source.as_deref(), Some("card.psdt")); + finish_read_failure(&mut app, "card.psdt", reason, &format!("Untitled-1: {reason}")); + } else { + assert_eq!(reply["ok"], true, "typed confirmation acknowledges its receipt; the approval error is presented by the real prompt consumer: {reply}"); + assert_eq!(messages(&app), [format!("Couldn't open card.psdt: {reason}")]); + } + assert_eq!(app.ui.status, format!("Couldn't open card.psdt: {reason}")); + assert_eq!(app.ui.status.matches("card.psdt").count(), 1); + assert!(!app.ui.status.contains("Untitled-1")); + assert!(app.ui.status_error); + assert!(app.ui.notices.is_empty()); + assert!(app.session.documents().is_empty()); + assert!(app.ui.recent_files.is_empty()); + assert!(app.jobs.opens.is_empty()); + assert!(app.held_memory_prompts.is_empty()); + assert!(app.prompt_order.is_empty()); + assert!(app.jobs.batches.is_empty()); + assert_eq!(app.session.pending_preflight_bytes().unwrap(), 0); + assert!(app.session.take_pending_preflight(preflight).is_none()); + let alert = error_dialogs(&app)[0].id; + let ctx = app.ctx().clone(); + crate::dialogs::confirm(&mut app, &ctx, alert).unwrap(); + assert!(no_dialogs(&app), "the one error alert closes normally"); + } +} diff --git a/crates/ui-egui/src/filter_preview_locator_tests.rs b/crates/ui-egui/src/filter_preview_locator_tests.rs index 983f9545ea..39da50f6b8 100644 --- a/crates/ui-egui/src/filter_preview_locator_tests.rs +++ b/crates/ui-egui/src/filter_preview_locator_tests.rs @@ -31,7 +31,7 @@ fn harness(command: Option<&str>, rotation: f32) -> Harness<'static, Box Harness<'static, (Box, bool)> { let mut h = Harness::builder().with_size(egui::vec2(900.0, 760.0)).with_context(app.ctx().clone()).build_ui_state( |ui, (app, ready): &mut (Box, bool)| { if *ready { - egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| crate::canvas::document_area(app, ui)); + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| crate::canvas::testing::document_area(app, ui)); } }, (app, false), diff --git a/crates/ui-egui/src/home_recent_ui.rs b/crates/ui-egui/src/home_recent_ui.rs index 02470d1340..73bf196644 100644 --- a/crates/ui-egui/src/home_recent_ui.rs +++ b/crates/ui-egui/src/home_recent_ui.rs @@ -210,7 +210,7 @@ pub(crate) fn act(app: &mut PhotocraftApp, action: &StartAction) -> bool { StartAction::OpenRecent(path) => { let path = path.to_string_lossy(); if let Err(e) = open_recent_gate(app, &path).and_then(|()| app.open_path(&path)) { - app.open_failed(&crate::file_open::display_name(&path), &e); + app.open_failed(&path, &e); } true } diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs index f01e730403..7c9ff4da05 100644 --- a/crates/ui-egui/src/jobs_ui.rs +++ b/crates/ui-egui/src/jobs_ui.rs @@ -48,6 +48,8 @@ pub struct OpenTab { pub name: String, /// Where it was read from (File › Save writes back there; added to Open Recent). pub path: Option, + /// Actual read source when it differs from the save/recent path (an untitled Smart Object or byte-backed template). + pub error_source: Option, /// The tab position it goes to when it opens (a file dropped on the tabs); `None`: the end. pub slot: Option, /// Its place in a set of files opened together, when it is one of several (see [`OpenOrder`]). @@ -172,6 +174,8 @@ pub struct JobsUi { pub(crate) batches: Vec, /// The id of the next set. next_batch: u64, + /// Identity of the next per-file failure alert (never a document/save identity). + next_open_failure: u64, /// Background saves. pub saves: Vec, /// The window was asked to close while a save was writing: close it once none is left. @@ -187,6 +191,13 @@ pub struct JobsUi { pub(crate) caf_settings: Vec<(JobId, Value)>, } +/// A fresh identity for one failed file. Kept with the window's open bookkeeping, not persisted. +pub(crate) fn open_failure_id(app: &mut PhotocraftApp) -> craft::ui::dialog::DialogId { + let serial = app.jobs.next_open_failure; + app.jobs.next_open_failure = serial.wrapping_add(1); + craft::ui::dialog::dialog_id(("file-open-failure", serial)) +} + /// Run command `id`: in the background when background jobs are on and the command is a job /// (the result is then `{"job": id, "pending": true}` and the edit lands when [`tick`] applies /// it), else synchronously like [`photocraft_engine::Session::execute`]. @@ -285,13 +296,15 @@ pub fn start_open( slot: Option, order: Option, ) -> Result<(), String> { - let name = &app.open_name(name); + let source_name = name; + let name = &app.open_name(source_name); + let error_source = (path.is_none() && name.as_str() != source_name).then(|| source_name.to_string()); match app.session.start_open_for_user_with_background(name, source, app.background_jobs).map_err(|e| e.to_string())? { // Inline (wasm, or background jobs off): finish now, like a background open that ended at // once. A preflight keeps the slot and set order in its memory prompt. - Started::Done(v) => finish_open(app, name, path.as_deref(), &v, slot, order), + Started::Done(v) => finish_open(app, name, path.as_deref(), error_source.as_deref(), &v, slot, order), Started::Job(job) => { - track_open(app, OpenTab { job, name: name.to_string(), path, slot, order }); + track_open(app, OpenTab { job, name: name.to_string(), path, error_source, slot, order }); Ok(()) } } @@ -320,9 +333,9 @@ pub(crate) fn start_open_as_smart_object(app: &mut PhotocraftApp, path: &str, or Started::Done(app.session.execute("file.openAsSmartObject", params).map_err(|e| e.to_string())?) }; match started { - Started::Done(v) => finish_open(app, &name, None, &v, None, order), + Started::Done(v) => finish_open(app, &name, None, Some(path), &v, None, order), Started::Job(job) => { - track_open(app, OpenTab { job, name, path: None, slot: None, order }); + track_open(app, OpenTab { job, name, path: None, error_source: Some(path.to_string()), slot: None, order }); Ok(()) } } @@ -376,7 +389,7 @@ pub(crate) fn tab_slot(app: &mut PhotocraftApp, slot: Option, order: Opti /// [`JobsUi::opens`]: the document goes to the tab's slot, or to its place in its set. A memory /// preflight keeps both in its prompt. pub(crate) fn finish_open_tab(app: &mut PhotocraftApp, tab: &OpenTab, v: &Value) -> Result<(), String> { - let r = finish_open(app, &tab.name, tab.path.as_deref(), v, tab.slot, tab.order); + let r = finish_open(app, &tab.name, tab.path.as_deref(), tab.error_source.as_deref(), v, tab.slot, tab.order); end_batch(app); r } @@ -639,13 +652,19 @@ fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) { if e.command == OPEN_JOB || app.jobs.opens.iter().any(|o| o.job == e.id) { let Some(i) = app.jobs.opens.iter().position(|o| o.job == e.id) else { return }; let tab = app.jobs.opens.remove(i); + let source = tab.path.as_deref().or(tab.error_source.as_deref()).unwrap_or(&tab.name); match e.outcome { JobOutcome::Done(v) => { if let Err(err) = finish_open_tab(app, &tab, &v) { - app.open_failed(&tab.name, &err); + app.open_failed(source, &err); } } - JobOutcome::Failed(err) => app.open_failed(&tab.name, &err), + JobOutcome::Failed(err) => { + // A template's worker name is Untitled-N, while its alert names the read source. + let reason = + if tab.name != crate::file_open::display_name(source) { err.strip_prefix(&format!("{}: ", tab.name)).unwrap_or(&err) } else { &err }; + app.open_failed(source, reason); + } JobOutcome::Cancelled => { app.ui.status = crate::i18n::fmt(tl!("Canceled opening {name}"), &[("name", &tab.name)]); app.ui.status_error = false; @@ -707,7 +726,15 @@ fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) { /// (`{document, docId, warnings, color}` or `{held, …}`). `slot` and `order` are the tab position /// and set place the file keeps: through a memory prompt, a profile/damage prompt and the final /// document, so an inline completion lands where a background tab would. -fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, v: &Value, slot: Option, order: Option) -> Result<(), String> { +fn finish_open( + app: &mut PhotocraftApp, + name: &str, + path: Option<&str>, + error_source: Option<&str>, + v: &Value, + slot: Option, + order: Option, +) -> Result<(), String> { if let Some(preflight_id) = v.get("pendingPreflight").and_then(Value::as_u64) { let estimated = v.get("estimated").and_then(Value::as_u64).unwrap_or(0); let available = v.get("availableRam").and_then(Value::as_u64); @@ -718,6 +745,7 @@ fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, v: &Valu preflight_id, name.to_string(), path.map(str::to_string), + error_source.map(str::to_string), slot, order, estimated, @@ -855,16 +883,25 @@ pub(crate) fn status_job(app: &PhotocraftApp) -> Option<(JobId, crate::panels::s Some((j.id, crate::panels::status_bar::Progress { label, fraction: shown_fraction(&j), cancel: Some(tl!("Cancel (Esc)").to_owned()), refused })) } -/// Show the folder Batch worker's immutable current document in the canvas area. The worker -/// publishes snapshots rather than adding them to `Session`, so no edit or Save can target one. -pub(crate) fn batch_preview(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> bool { - let current = app - .session +/// The running Batch job whose worker has published its current input, with that snapshot. +fn shown_batch_preview(app: &PhotocraftApp) -> Option<(JobId, photocraft_engine::jobs::BatchPreview)> { + app.session .jobs() .into_iter() .filter(|job| job.command == "file.automate.batch") - .find_map(|job| app.session.batch_preview(job.id).map(|preview| (job.id, preview))); - let Some((id, preview)) = current else { return false }; + .find_map(|job| app.session.batch_preview(job.id).map(|preview| (job.id, preview))) +} + +/// What [`batch_preview`] shows, for the document area's version: the job and the snapshot's generation. The worker +/// publishes a new input with no command or input reaching the area. +pub(crate) fn batch_preview_key(app: &PhotocraftApp) -> Option<(JobId, u64)> { + shown_batch_preview(app).map(|(id, preview)| (id, preview.generation)) +} + +/// Show the folder Batch worker's immutable current document in the canvas area. The worker +/// publishes snapshots rather than adding them to `Session`, so no edit or Save can target one. +pub(crate) fn batch_preview(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> bool { + let Some((id, preview)) = shown_batch_preview(app) else { return false }; let name = std::path::Path::new(&preview.path).file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_else(|| preview.path.clone()); Row::new().show(ui, |ui, _| { Text::new(name.clone()).role(TypeRole::BodyStrong).show(ui); diff --git a/crates/ui-egui/src/jobs_ui/tests.rs b/crates/ui-egui/src/jobs_ui/tests.rs index 0a235c97c5..f931c57c8c 100644 --- a/crates/ui-egui/src/jobs_ui/tests.rs +++ b/crates/ui-egui/src/jobs_ui/tests.rs @@ -1040,7 +1040,7 @@ fn background_open_warns_about_missing_fonts() { // What the open job leaves behind: the decoded document in the session, then its result. let (index, _) = app.session.open_document(doc, None); let id = app.session.documents()[index].doc.id; - super::finish_open(&mut app, "poster.psd", None, &json!({"document": index, "docId": id.0, "warnings": []}), None, None).unwrap(); + super::finish_open(&mut app, "poster.psd", None, None, &json!({"document": index, "docId": id.0, "warnings": []}), None, None).unwrap(); let want = vec!["font 'NoSuchFamily4559' is not installed; text may render using a fallback face".to_string()]; assert!(app.ui.notices.last().is_some_and(|n| n.title.contains("poster.psd") && n.lines == want), "{:?}", app.ui.notices); } @@ -1122,7 +1122,7 @@ fn open_identity_survives_tab_reordering() { let old_index = result["document"].as_u64().unwrap() as usize; app.session.move_document(old_index, 0).unwrap(); assert_eq!(app.session.documents()[old_index].doc.id, control.doc.id); - super::finish_open(&mut app, "imported.png", Some("imported.png"), &result, None, None).unwrap(); + super::finish_open(&mut app, "imported.png", Some("imported.png"), None, &result, None, None).unwrap(); control.assert_untouched(&app); assert_eq!(app.session.active().unwrap().doc.id, imported); assert_eq!(app.session.active().unwrap().path.as_deref(), Some("imported.png")); @@ -1137,7 +1137,7 @@ fn open_identity_survives_an_earlier_tab_closing() { let (result, imported) = identified_result(&app, result); app.session.close(1).unwrap(); app.session.set_active(0); - super::finish_open(&mut app, "imported.png", Some("imported.png"), &result, Some(0), None).unwrap(); + super::finish_open(&mut app, "imported.png", Some("imported.png"), None, &result, Some(0), None).unwrap(); control.assert_untouched(&app); assert_eq!(app.session.active().unwrap().doc.id, imported); assert_eq!(app.session.documents()[0].doc.id, imported, "the requested destination slot applies to the correct document"); @@ -1159,13 +1159,16 @@ fn open_identity_rejects_closed_missing_and_invalid_identities() { } Some(value) => result["docId"] = value, } - assert!(super::finish_open(&mut app, "closed.png", Some("closed.png"), &result, Some(0), None).is_err(), "invalid identity was accepted: {result}"); + assert!( + super::finish_open(&mut app, "closed.png", Some("closed.png"), None, &result, Some(0), None).is_err(), + "invalid identity was accepted: {result}" + ); control.assert_untouched(&app); assert_eq!(app.session.active().unwrap().doc.id, control.doc.id); assert_eq!(app.session.documents().len(), 1); result["docId"] = json!(imported.0); assert!( - super::finish_open(&mut app, "closed.png", Some("closed.png"), &result, None, None).is_err(), + super::finish_open(&mut app, "closed.png", Some("closed.png"), None, &result, None, None).is_err(), "a closed identity must not fall back to the old tab index" ); control.assert_untouched(&app); @@ -1186,9 +1189,9 @@ fn open_identity_keeps_same_poll_results_in_the_profile_queue() { let (second, second_id) = identified_result(&app, second); // All engine applies have finished. Handling the first ordinary result removes its tab, // shifting the second result before its UI callback runs. - super::finish_open(&mut app, "profile.png", Some("profile.png"), &prompt, None, None).unwrap(); - super::finish_open(&mut app, "first.png", Some("first.png"), &first, None, None).unwrap(); - super::finish_open(&mut app, "second.png", Some("second.png"), &second, None, None).unwrap(); + super::finish_open(&mut app, "profile.png", Some("profile.png"), None, &prompt, None, None).unwrap(); + super::finish_open(&mut app, "first.png", Some("first.png"), None, &first, None, None).unwrap(); + super::finish_open(&mut app, "second.png", Some("second.png"), None, &second, None, None).unwrap(); assert_eq!(app.held_opens.iter().map(|held| held.name.as_str()).collect::>(), ["profile.png", "first.png", "second.png"]); assert_eq!(app.held_opens.iter().skip(1).map(|held| held.doc.id).collect::>(), [first_id, second_id]); assert_eq!(app.session.documents().len(), 1, "both completed imports wait behind the profile prompt"); diff --git a/crates/ui-egui/src/levels_clipping.rs b/crates/ui-egui/src/levels_clipping.rs index 82ec781dae..749acb4582 100644 --- a/crates/ui-egui/src/levels_clipping.rs +++ b/crates/ui-egui/src/levels_clipping.rs @@ -221,6 +221,13 @@ fn dialog(app: &PhotocraftApp) -> Option<&crate::adjust_dialog::OpenAdjust> { crate::adjust_dialog::open_value(app).filter(|open| open.kind == "levels" && open.smart_filter.is_none()) } +/// What the canvas shows of an open Levels dialog's clipping display, for the document area's version +/// (`region_versions::canvas`): the dialog and its fields, which change with no command. +pub(crate) fn canvas_key(app: &PhotocraftApp) -> Option<(craft::ui::dialog::DialogId, String)> { + let open = dialog(app)?; + Some((open.id, crate::adjust_dialog::open_params(app).map(|params| params.to_string()).unwrap_or_default())) +} + /// The display the open Levels dialog asks for on document `idx`. None when no Levels dialog /// shows clipping, `idx` isn't the active document, or the document can't show it: CMYK and Lab, /// a channel, mask or Quick Mask target, or a target that isn't a pixel layer. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index ce9a6dffae..7e6cc44d0c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -461,12 +461,10 @@ pub struct PhotocraftApp { /// The Properties panel's adjustment edit in progress, with the tone editor's shown channel /// (`adjust_editors::PropertiesAdjust`). pub(crate) adjust_session: Option, - /// Twice the passes the Properties panel was not in front or ran without showing the Reset session's layer: the + /// Twice the passes the Properties panel was not in front or ran showing no adjustment layer's controls: the /// session (`adjust_editors`) takes a layer's settings anew after the panel stopped showing it. A pass count would /// also move while the panel replays its memoized body, which is still showing it. pub(crate) properties_hidden: u64, - /// Whether the Properties panel's run showed the Reset session's layer (`properties_hidden`). - pub(crate) properties_tracked: bool, /// The Color Picker dialog asking for a screen sample: the dialog and the field that took it. pub(crate) dialog_dropper: Option<(craft::ui::dialog::DialogId, String)>, /// The child dialog (colour picker or contour editor) the open Layer Style dialog has, with that dialog's id. @@ -499,6 +497,9 @@ pub struct PhotocraftApp { filter_preview_worker: crate::dialogs::filter_preview_worker::Worker, /// Full CPU canvas redraws running in the background, by document (#4024). pub(crate) redraws: std::collections::HashMap, + /// How many redraw blocks have landed (`background_redraw::poll`): they reach the GPU canvas between the document + /// area's runs, so the area's version holds the count (`region_versions::canvas`). + pub(crate) redraw_landed: u64, /// The last finished background redraws, for going back to a state drawn a moment ago (#6528). pub(crate) kept: background_redraw::KeptComposites, /// Select › Color Range dialog preview (proxy document + mask / image textures). @@ -747,6 +748,8 @@ mod eyedropper_context_menu_tests; #[cfg(test)] mod menu_automate_groups_tests; #[cfg(test)] +mod paint_bucket_options_fields_tests; +#[cfg(test)] mod patch_rasterize_prompt_tests; #[cfg(test)] mod patch_shift_constrain_tests; @@ -1014,6 +1017,9 @@ mod warp_text_dialog_tests; #[cfg(test)] mod options_bar_mode_wheel_tests; +#[cfg(test)] +mod options_bar_percent_arrow_repeat_tests; + #[cfg(test)] mod field_wheel_app_tests; diff --git a/crates/ui-egui/src/marquee_tests.rs b/crates/ui-egui/src/marquee_tests.rs index d9009ae3f7..2d79b25b11 100644 --- a/crates/ui-egui/src/marquee_tests.rs +++ b/crates/ui-egui/src/marquee_tests.rs @@ -28,7 +28,7 @@ fn harness_with_step_dt(tool: Tool, step_dt: f32) -> Harness<'static, Box>; @@ -80,8 +81,14 @@ fn a_status_message_runs_only_the_status_bar() { h.run_steps(2); h.state_mut().ui.status = "Saved".into(); h.run_steps(1); - let ran: Vec<&'static str> = last_frame_memo_runs(&h.ctx).into_iter().filter(|(_, _, run)| *run == MemoRun::Ran).map(|(name, _, _)| name).collect(); - assert!(!ran.is_empty() && ran.iter().all(|name| name.contains("status_bar::StatusProps")), "only the status bar's view runs: {ran:?}"); + let runs = last_frame_memo_runs(&h.ctx); + let ran: Vec<&'static str> = runs.iter().filter(|(_, _, run)| *run == MemoRun::Ran).map(|(name, _, _)| *name).collect(); + let slots = [ShellSlot::Title, ShellSlot::Options, ShellSlot::Status].map(|slot| slot_runs(&runs, slot).0); + assert!(slots[0] == 0 && slots[1] == 0 && slots[2] > 0, "of the shell's slots only the status bar runs: {slots:?}"); + assert!( + ran.iter().all(|name| name.contains("status_bar::StatusProps") || name.contains("app_shell::SlotView<")), + "only the status slot and the status bar's body view run: {ran:?}" + ); } #[test] diff --git a/crates/ui-egui/src/menus/parity.rs b/crates/ui-egui/src/menus/parity.rs index f320b4a4a4..ac2ff1cedf 100644 --- a/crates/ui-egui/src/menus/parity.rs +++ b/crates/ui-egui/src/menus/parity.rs @@ -6,6 +6,93 @@ use crate::menu_catalog::CATALOG; use crate::menus::is_live; +/// RFC-0052 hand marks for catalog ids that aren't engine commands: `(id, headless, reach, why)`. +/// +/// `headless` is `no` or `partial`; `reach` is `window` (needs a desktop window, dialog or pointer), +/// `os` (needs an OS service the engine doesn't wrap) or `engine-gap` (could be an engine command, +/// isn't one yet). `yes` is never written here: an item is `yes` only when +/// `photocraft_engine::commands::find` has its id, the registry `photocraft-cli` and the MCP server +/// load. [`is_live`] also counts a dozen desktop-only sources; those make an item live in the menu, +/// not headless. Without a mark, an id the desktop serves as a panel, workspace or pointer tool is +/// `no` with `reach: window` ([`desktop_window`]); any other is `unknown`. +pub const HEADLESS: &[(&str, &str, &str, &str)] = &[]; + +/// Why a non-engine id needs a desktop window, when the desktop serves it as a panel, a workspace +/// or a pointer tool. +fn desktop_window(id: &str) -> Option<&'static str> { + if super::invoke::panel_alias(id).is_some() || crate::panel_docking::toggle_panel(id).is_some() { + Some("shows or hides a desktop panel") + } else if super::invoke::workspace_id(id).is_some() || crate::workspace_ui::handles(id) { + Some("a desktop workspace") + } else if crate::tool_shortcuts::tool(id).is_some() { + Some("picks a pointer tool") + } else { + None + } +} + +/// An item's RFC-0052 `(headless, reach, why)`: `yes` for an engine command, else its mark in +/// `marks`, else `no`/`window` for a desktop panel, workspace or tool, else `unknown`. +pub fn headless_of<'a>(id: &str, in_engine: bool, marks: &[(&'a str, &'a str, &'a str, &'a str)]) -> (&'a str, Option<&'a str>, &'a str) { + if in_engine { + return ("yes", None, ""); + } + if let Some(m) = marks.iter().find(|m| m.0 == id) { + return (m.1, Some(m.2), m.3); + } + match desktop_window(id) { + Some(why) => ("no", Some("window"), why), + None => ("unknown", None, ""), + } +} + +/// Problems with `marks` against `ids` (`(id, is an engine command)`): bad values, repeats, ids +/// not in the catalog, and marks on engine commands (they would hide a `yes`). +pub fn headless_errors(marks: &[(&str, &str, &str, &str)], ids: &[(&str, bool)]) -> Vec { + let mut errs = Vec::new(); + for (i, (id, value, reach, _)) in marks.iter().enumerate() { + if !matches!(*value, "no" | "partial") { + errs.push(format!("headless mark `{id}`: `{value}` is not `no` or `partial` (`yes` comes from the registry)")); + } + if !matches!(*reach, "window" | "os" | "engine-gap") { + errs.push(format!("headless mark `{id}`: reach `{reach}` is not window, os or engine-gap")); + } + if marks[..i].iter().any(|m| m.0 == *id) { + errs.push(format!("headless mark `{id}` is written twice")); + } + match ids.iter().find(|x| x.0 == *id) { + None => errs.push(format!("headless mark `{id}` is not a catalog id")), + Some((_, true)) => errs.push(format!("headless mark `{id}` is stale: it is an engine command, so it is `yes`")), + Some(_) => {} + } + } + errs +} + +/// RFC-0052 counts over the catalog. +#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize)] +pub struct HeadlessCounts { + pub yes: usize, + pub no_window: usize, + pub no_os: usize, + pub no_engine_gap: usize, + pub partial: usize, + pub unknown: usize, +} + +impl HeadlessCounts { + fn add(&mut self, value: &str, reach: Option<&str>) { + match (value, reach) { + ("yes", _) => self.yes += 1, + ("no", Some("window")) => self.no_window += 1, + ("no", Some("os")) => self.no_os += 1, + ("no", _) => self.no_engine_gap += 1, + ("partial", _) => self.partial += 1, + _ => self.unknown += 1, + } + } +} + /// Minimum number of live catalog items. Raise it when parity grows; never lower it. pub const FLOOR: usize = 663; @@ -17,6 +104,8 @@ pub struct MenuParity { pub total: usize, /// Labels (with submenu path) of items not implemented yet. pub missing: Vec, + /// Items that aren't `headless: yes`, with their value (RFC-0052). + pub not_headless: Vec, } #[derive(Clone, Debug, serde::Serialize)] @@ -24,6 +113,7 @@ pub struct Parity { pub live: usize, pub total: usize, pub menus: Vec, + pub headless: HeadlessCounts, } impl Parity { @@ -42,6 +132,18 @@ impl Parity { let pct = if m.total == 0 { 0.0 } else { 100.0 * m.live as f64 / m.total as f64 }; s.push_str(&format!("| {} | {} | {} | {:.0}% |\n", m.menu, m.live, m.total, pct)); } + let h = &self.headless; + s.push_str(&format!( + "\n**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): {} yes, {} no (window {}, os {}, engine-gap {}), {} partial, {} unknown.**\n\n", + h.yes, + h.no_window + h.no_os + h.no_engine_gap, + h.no_window, + h.no_os, + h.no_engine_gap, + h.partial, + h.unknown + )); + s.push_str("Live counts the desktop app's own panels, workspaces, tools and view handlers. Headless counts only the engine registry that `photocraft-cli` and the MCP server load: an item is `yes` when its id is an engine command. The rest are listed under [Not headless](#not-headless), with the hand mark from `HEADLESS` in `crates/ui-egui/src/menus/parity.rs`, `no` (`window`) for a desktop panel, workspace or tool, or `unknown`.\n"); s.push_str("\n## Not yet implemented\n"); for m in self.menus.iter().filter(|m| !m.missing.is_empty()) { s.push_str(&format!("\n### {} ({})\n\n", m.menu, m.missing.len())); @@ -49,6 +151,13 @@ impl Parity { s.push_str(&format!("- {item}\n")); } } + s.push_str("\n## Not headless\n"); + for m in self.menus.iter().filter(|m| !m.not_headless.is_empty()) { + s.push_str(&format!("\n### {} ({})\n\n", m.menu, m.not_headless.len())); + for item in &m.not_headless { + s.push_str(&format!("* {item}\n")); + } + } s } } @@ -57,6 +166,7 @@ impl Parity { pub fn compute() -> Parity { let mut menus: Vec = Vec::new(); let mut seen = std::collections::HashSet::new(); + let mut headless = HeadlessCounts::default(); for &(path, label, _, id) in CATALOG { if id == "---" || !seen.insert(id) { continue; @@ -65,21 +175,28 @@ pub fn compute() -> Parity { let i = match menus.iter().position(|m| m.menu == top) { Some(i) => i, None => { - menus.push(MenuParity { menu: top.to_string(), live: 0, total: 0, missing: Vec::new() }); + menus.push(MenuParity { menu: top.to_string(), live: 0, total: 0, missing: Vec::new(), not_headless: Vec::new() }); menus.len() - 1 } }; let Some(m) = menus.get_mut(i) else { continue }; m.total += 1; + let mut full: Vec<&str> = path[1..].to_vec(); + full.push(label); + let name = format!("{} (`{id}`)", full.join(" › ")); + let (value, reach, why) = headless_of(id, photocraft_engine::commands::find(id).is_some(), HEADLESS); + headless.add(value, reach); + if value != "yes" { + let reach = reach.map(|r| format!(", reach: {r} ({why})")).unwrap_or_default(); + m.not_headless.push(format!("{name}: headless: {value}{reach}")); + } if is_live(id) { m.live += 1; } else { - let mut full: Vec<&str> = path[1..].to_vec(); - full.push(label); - m.missing.push(format!("{} (`{id}`)", full.join(" › "))); + m.missing.push(name); } } - Parity { live: menus.iter().map(|m| m.live).sum(), total: menus.iter().map(|m| m.total).sum(), menus } + Parity { live: menus.iter().map(|m| m.live).sum(), total: menus.iter().map(|m| m.total).sum(), menus, headless } } #[cfg(test)] @@ -93,10 +210,51 @@ mod tests { assert!(p.live >= FLOOR, "menu parity regressed: {} live < floor {FLOOR}", p.live); } + #[test] + fn headless_marks_are_current() { + let ids: Vec<(&str, bool)> = CATALOG.iter().filter(|c| c.3 != "---").map(|c| (c.3, photocraft_engine::commands::find(c.3).is_some())).collect(); + let errs = headless_errors(HEADLESS, &ids); + assert!(errs.is_empty(), "{errs:?}"); + } + + #[test] + fn headless_yes_is_the_engine_registry_only() { + let p = compute(); + let h = &p.headless; + assert_eq!(h.yes + h.no_window + h.no_os + h.no_engine_gap + h.partial + h.unknown, p.total); + assert!(h.yes < p.live, "desktop-only sources are live, not headless"); + let listed: usize = p.menus.iter().map(|m| m.not_headless.len()).sum(); + assert_eq!(listed, p.total - h.yes); + // A panel toggle is live in the desktop app and never headless. + let window = p.menus.iter().find(|m| m.menu == "Window").map(|m| m.not_headless.len()).unwrap_or(0); + assert!(window > 0, "Window panels read as not headless"); + assert!(p.to_markdown().contains(&format!("{} yes,", h.yes))); + } + + #[test] + fn headless_values_and_bad_marks() { + let marks = [("c.d", "no", "engine-gap", "could be a command")]; + assert_eq!(headless_of("c.d", true, &marks).0, "yes", "an engine id is yes whatever the mark says"); + assert_eq!(headless_of("c.d", false, &marks), ("no", Some("engine-gap"), "could be a command")); + assert_eq!(headless_of("q.never", false, &marks).0, "unknown"); + let ids = [("a.b", true), ("c.d", false)]; + let bad = [("c.d", "yes", "os", ""), ("c.d", "no", "desk", ""), ("a.b", "no", "os", ""), ("z.z", "no", "os", "")]; + let errs = headless_errors(&bad, &ids); + for want in ["is not `no` or `partial`", "reach `desk`", "written twice", "`a.b` is stale", "`z.z` is not a catalog id"] { + assert!(errs.iter().any(|e| e.contains(want)), "{want}: {errs:?}"); + } + let mut c = HeadlessCounts::default(); + for (v, r) in [("yes", None), ("no", Some("window")), ("no", Some("os")), ("no", Some("engine-gap")), ("partial", Some("os")), ("unknown", None)] { + c.add(v, r); + } + assert_eq!(c, HeadlessCounts { yes: 1, no_window: 1, no_os: 1, no_engine_gap: 1, partial: 1, unknown: 1 }); + } + #[test] fn markdown_lists_every_missing_item() { let p = compute(); let md = p.to_markdown(); + // `- ` lines are the missing items; the Not headless list uses `* `. let listed = md.lines().filter(|l| l.starts_with("- ")).count(); assert_eq!(listed, p.total - p.live); } diff --git a/crates/ui-egui/src/menus/view_cmds.rs b/crates/ui-egui/src/menus/view_cmds.rs index c16a6c731e..7aed10a946 100644 --- a/crates/ui-egui/src/menus/view_cmds.rs +++ b/crates/ui-egui/src/menus/view_cmds.rs @@ -214,3 +214,7 @@ mod fit_image_sticky_tests; #[cfg(test)] #[path = "view_cmds/save_a_copy_name_tests.rs"] mod save_a_copy_name_tests; + +#[cfg(test)] +#[path = "view_cmds/file_info_title_labels_tests.rs"] +mod file_info_title_labels_tests; diff --git a/crates/ui-egui/src/menus/view_cmds/arrange.rs b/crates/ui-egui/src/menus/view_cmds/arrange.rs index 6b34351e46..82242b89c9 100644 --- a/crates/ui-egui/src/menus/view_cmds/arrange.rs +++ b/crates/ui-egui/src/menus/view_cmds/arrange.rs @@ -42,18 +42,42 @@ pub(super) fn layout_checked(app: &PhotocraftApp, k: &str) -> Option { N_UP.contains(&k).then(|| app.ui.document_windows.arrangement == Some(arrangement)) } -/// A finite `[x, y]` screen position within a sane range (window systems reject wild values). -fn screen_position(v: &Value) -> Option<[f32; 2]> { +/// Where the app window stands on the desktop, in desktop points. The app's own rects (the document area's) are in +/// the app window's points, while a document window that opens as an OS window opens at a desktop rect +/// (`DocumentWindow::first_placed` takes the outer rect in desktop points, and `follow_os_window` reads one back once +/// the user moved the window): this is the offset between the two. +/// Zero where the app shows its document windows on the fallback layer inside its own window, and where the host has +/// not reported the app window's rect yet (before its first pass): both keep today's placement. +/// One fallback this gate does not read: the framework also shows the layer inside the app window while OS windows are +/// available, when the app window itself is full screen or (on Wayland) maximized — `opens_over` in craft-libs +/// `ui-contract/src/runtime/windows.rs`. `WindowHost::opens_windows()` answers for the viewport of the running pass, +/// not for the app window, so a command run from the menu cannot decide that here; the offset is still added, and the +/// epic's #16846 is where full-screen modes with floating document windows are worked. +fn desktop_origin(app: &PhotocraftApp) -> egui::Pos2 { + let host = craft::ui::runtime::windows::WindowHost::of(app.ctx()); + if !host.viewports_available() { + return egui::Pos2::ZERO; + } + host.facts(egui::ViewportId::ROOT).map_or(egui::Pos2::ZERO, |facts| facts.inner.min) +} + +/// A finite `[x, y]` screen position within a sane range (window systems reject wild values). The point is one of the +/// app window's own points, where a torn-off tab was released, so it takes the same offset as the document area. +fn screen_position(v: &Value, app: &PhotocraftApp) -> Option<[f32; 2]> { const LIMIT: f64 = 1.0e6; let a = v.as_array().filter(|a| a.len() == 2)?; let n = |i: usize| a.get(i).and_then(Value::as_f64).filter(|x| x.is_finite() && x.abs() <= LIMIT).map(|x| x as f32); - Some([n(0)?, n(1)?]) + let (x, y) = (n(0)?, n(1)?); + let origin = desktop_origin(app); + Some([x + origin.x, y + origin.y]) } /// The area and sizes the framework's arrangements work in: the document area, not the app's whole content. New /// windows take half of it; a window that follows its document's size is resized by `DocumentWindow` afterwards. pub(super) fn space(app: &PhotocraftApp) -> ArrangeSpace { - let area = app.last_canvas_rect; + // The framework places a new window on the desktop and cascades within this area, while the document area is a + // rect of the app window's own points: move it across by where the app window stands. + let area = app.last_canvas_rect.translate(desktop_origin(app).to_vec2()); let step = craft::ui::style::StyleCx::with_root(app.ctx(), |cx| cx.tokens.size.window.cascade); ArrangeSpace::new(area, area.size() * 0.5, step, app.session.active().map(|st| st.doc.id)) } @@ -102,7 +126,7 @@ fn float_in_window(app: &mut PhotocraftApp, p: &Value) -> Result }; let position = match p.get("position") { None | Some(Value::Null) => None, - Some(v) => Some(screen_position(v).ok_or("position must be [x, y] in points")?), + Some(v) => Some(screen_position(v, app).ok_or("position must be [x, y] in points")?), }; let space = space(app); // A document alone in a floating window keeps the window where it is. diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index 6c48c63f29..9a81a77de5 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -56,6 +56,11 @@ fn opened(id: DialogId) -> Value { /// Opens the hosted parameter form of command `id`. `fixed` holds values the command needs that no row edits. fn open_form(app: &mut PhotocraftApp, id: &str, title: &str, params: Vec, fields: DialogFields, fixed: Value) -> DialogId { let title = crate::dialogs::filter_dialog::title_of(title); + open_form_label(app, id, title, params, fields, fixed) +} + +/// [`open_form`] with its title already built (File Info's document name, #13824). +fn open_form_label(app: &mut PhotocraftApp, id: &str, title: Label, params: Vec, fields: DialogFields, fixed: Value) -> DialogId { let key = id.to_owned(); let image_processor = id == image_processor_ui::COMMAND; let calculations = id == crate::dialogs::calculations_ui::COMMAND; @@ -85,6 +90,10 @@ fn derive(id: &str, fields: &mut DialogFields) { if id == artboard_name_options::COMMAND { artboard_name_options::derive(fields); } + if id == "image.applyImage" { + apply_image_source_derive(fields); + apply_image_mask_derive(fields); + } } /// Choice options from `(id, label)` pairs whose labels are `tl!` literals at the call site. @@ -367,7 +376,8 @@ pub(super) fn params_for(app: &mut PhotocraftApp, id: &str) -> Option<(Vec Option<(Vec Option<(Vec, DialogFields)> { +pub(super) fn file_info_form(app: &mut PhotocraftApp) -> Option<(Vec, DialogFields)> { let info = app.session.execute("file.fileInfo", json!({})).ok()?; let text = |key: &str| info[key].as_str().unwrap_or_default().to_owned(); let keywords = info["keywords"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect::>().join("; ")).unwrap_or_default(); @@ -638,28 +648,27 @@ fn channel_form(app: &PhotocraftApp, id: &str) -> Option<(Vec, DialogFiel ] } "image.applyImage" => { - let mut masks = vec!["none".to_string()]; - masks.extend(load.iter().cloned()); - // Source layer: Merged, then the pixel layers top to bottom (the engine takes - // the topmost layer of a name), shown by their own names. - let mut layers = vec!["merged".to_string()]; - for (_, _, l) in d.walk().into_iter().rev() { - if l.surface().is_some() && !layers.contains(&l.name) { - layers.push(l.name.clone()); - } - } + // The target's own Layer and Channel rows; another source document has its own pair (#14480). + let (layers, layer) = apply_image_layers(d); + let on_target = |row: Param| row.visible_when(SOURCE_IS_TARGET, true); + let mut rows = apply_image_source_rows(app); // Scale and Offset only affect Add and Subtract. - vec![ - choice("sourceLayer", tl!("Layer"), channels(&layers), "merged"), - choice("sourceChannel", tl!("Source Channel"), channels(&load), &chans[0]), + rows.extend([ + on_target(choice("sourceLayer", tl!("Layer"), layers, &layer)), + on_target(choice("sourceChannel", tl!("Channel"), apply_image_target_channels(d, &load, chans.len()), &chans[0])), + ]); + rows.extend(apply_image_other_source_rows(app)); + rows.extend([ Param::new("sourceInvert", tl!("Invert"), ParamKind::bool(false)), + Param::read_only_text("__target", tl!("Target"), d.name.clone()), choice("blending", tl!("Blending"), blend_modes(), "multiply"), Param::new("opacity", tl!("Opacity"), ParamKind::number(Some(0.0), Some(100.0), 100.0, 1.0, 0)), Param::new("scale", tl!("Scale"), ParamKind::number(Some(0.001), Some(2.0), 1.0, 0.1, 3)), Param::new("offset", tl!("Offset"), ParamKind::int(Some(-255), Some(255), 0)), Param::new("preserveTransparency", tl!("Preserve Transparency"), ParamKind::bool(false)), - choice("maskChannel", tl!("Mask Channel"), channels(&masks), "none"), - ] + ]); + rows.extend(apply_image_mask_rows(app)); + rows } "image.calculations" => { // Image ▸ Calculations lists the channels of the source it reads (#14521), not the shared @@ -693,6 +702,298 @@ fn channel_form(app: &PhotocraftApp, id: &str) -> Option<(Vec, DialogFiel Some((rows, DialogFields::new())) } +/// Apply Image's Source (#14480): the index of one of [`apply_image_documents`], the target by default. +const SOURCE_DOCUMENT: &str = "__sourceDocument"; +/// Shows the target's own Layer and Channel rows (`sourceLayer`, `sourceChannel`): the target is the chosen Source. +const SOURCE_IS_TARGET: &str = "__sourceIsTarget"; + +/// The Layer row of source document `index` when it is not the target. +fn source_layer_key(index: usize) -> String { + format!("__sourceLayer/{index}") +} + +/// The Channel row of source document `index` when it is not the target. +fn source_channel_key(index: usize) -> String { + format!("__sourceChannel/{index}") +} + +/// Shows the Layer and Channel rows of source document `index`. +fn source_shown_key(index: usize) -> String { + format!("__sourceShown/{index}") +} + +/// Apply Image's Source row (#14480): the documents of [`apply_image_documents`], the target first chosen at every +/// opening (the row is not remembered). +fn apply_image_source_rows(app: &PhotocraftApp) -> Vec { + let names: Vec<(String, Label)> = apply_image_documents(app).iter().map(|(i, d)| (i.to_string(), Label::from(d.name.clone()))).collect(); + let target = app.session.active_index().map(|i| i.to_string()).unwrap_or_default(); + vec![choice(SOURCE_DOCUMENT, tl!("Source"), names, &target).not_remembered()] +} + +/// The target's own Channel options: `load` (the Load Selection list: its first `chans` entries the composite, the +/// colours and the alphas, then transparency, mask and selection) with the alpha channels as +/// [`apply_image_alpha_options`], so an alpha named as a built-in channel keeps its own option. +fn apply_image_target_channels(doc: &photocraft_doc::Document, load: &[String], chans: usize) -> Vec<(String, Label)> { + let builtins = chans.saturating_sub(doc.channels.len()); + let mut list = channels(load.get(..builtins).unwrap_or_default()); + list.extend(apply_image_alpha_options(doc)); + list.extend(channels(load.get(chans..).unwrap_or_default())); + list +} + +/// The Layer and Channel rows of each source document other than the target (#14480): its Layer list (as the +/// target's) and its channels (the composite, the colour channels of a colour document, the alpha channels). +fn apply_image_other_source_rows(app: &PhotocraftApp) -> Vec { + let target = app.session.active_index(); + let mut rows = Vec::new(); + for (i, doc) in apply_image_documents(app).into_iter().filter(|(i, _)| Some(*i) != target) { + let (layers, layer) = apply_image_layers(doc); + let mode = doc.pixel_format().mode; + let mut names = vec![photocraft_engine::channel_cmds::composite_name(mode).to_string()]; + if mode.color_channels() > 1 { + names.extend(photocraft_engine::channel_cmds::color_names(mode).iter().map(|n| n.to_string())); + } + let composite = names.first().cloned().unwrap_or_default(); + let mut list = channels(&names); + list.extend(apply_image_alpha_options(doc)); + rows.push(choice(&source_layer_key(i), tl!("Layer"), layers, &layer).visible_when(source_shown_key(i), true)); + rows.push(choice(&source_channel_key(i), tl!("Channel"), list, &composite).visible_when(source_shown_key(i), true)); + } + rows +} + +/// Brings the Source group's shell keys and the source parameter up to date: the target as Source shows its own +/// Layer and Channel rows, which send the flat `sourceLayer` / `sourceChannel` / `sourceInvert` as before; another +/// document shows its own pair and sends `source: {document, layer, channel, invert}`, which the command reads before +/// the flat keys. +fn apply_image_source_derive(fields: &mut DialogFields) { + let chosen = fields.text(SOURCE_DOCUMENT).and_then(|s| s.parse::().ok()); + let others: Vec = fields.iter().filter_map(|(k, _)| k.strip_prefix("__sourceLayer/").and_then(|i| i.parse().ok())).collect(); + for &i in &others { + fields.set(source_shown_key(i), chosen == Some(i)); + } + fields.remove("source"); + let other = chosen.filter(|i| others.contains(i)); + fields.set(SOURCE_IS_TARGET, other.is_none()); + let invert = fields.bool("sourceInvert") == Some(true); + let Some(i) = other else { + // The target's flat keys carry plain names; an alpha or layer the engine would read as something else by its + // name goes as an explicit selector in `source`, which the command reads before them. + let layer = apply_image_layer_selector(fields.text("sourceLayer").unwrap_or("merged")); + let channel = fields.text("sourceChannel").map(apply_image_channel_selector); + if !layer.is_string() || channel.as_ref().is_some_and(Value::is_object) { + let mut source = json!({"layer": layer, "invert": invert}); + if let (Some(channel), Some(map)) = (channel, source.as_object_mut()) { + map.insert("channel".into(), channel); + } + fields.set("source", FieldValue::Json(source)); + } + return; + }; + let (Some(layer), Some(channel)) = + (fields.text(&source_layer_key(i)).map(apply_image_layer_selector), fields.text(&source_channel_key(i)).map(apply_image_channel_selector)) + else { + return; + }; + fields.set("source", FieldValue::Json(json!({"document": i, "layer": layer, "channel": channel, "invert": invert}))); +} + +#[cfg(test)] +#[path = "../../dialogs/apply_image_source_document_tests.rs"] +mod apply_image_source_document_tests; + +/// Apply Image's Mask... checkbox (#14489): off by default; ticked, it shows the mask group below it. +const MASK_ON: &str = "__mask"; +/// The mask group's Source: the index of one of [`apply_image_documents`]. +const MASK_SOURCE: &str = "__maskSource"; +/// The mask group's Invert. +const MASK_INVERT: &str = "__maskInvert"; + +/// The mask Layer row of the source document `index`: each candidate document has its own Layer and Channel rows, +/// as their lists are that document's, and only the chosen document's pair is shown. +fn mask_layer_key(index: usize) -> String { + format!("__maskLayer/{index}") +} + +/// The mask Channel row of the source document `index`. +fn mask_channel_key(index: usize) -> String { + format!("__maskChannel/{index}") +} + +/// The shell key that shows the Layer and Channel rows of document `index`: the mask ticked and that document chosen +/// (a row takes one `visible_when` condition). +fn mask_shown_key(index: usize) -> String { + format!("__maskShown/{index}") +} + +/// The open documents Apply Image can read from (#14480, #14489): those with the target's pixel size and bit depth, +/// whatever their colour mode, in the order they were opened, as `(index, document)`. The target is among them. +pub(crate) fn apply_image_documents(app: &PhotocraftApp) -> Vec<(usize, &photocraft_doc::Document)> { + let Some(target) = app.session.active() else { return Vec::new() }; + let (size, depth) = (target.doc.size, target.doc.depth); + let mut documents: Vec<(usize, &photocraft_doc::Document)> = + app.session.documents().iter().enumerate().filter(|(_, st)| st.doc.size == size && st.doc.depth == depth).map(|(i, st)| (i, &*st.doc)).collect(); + // Document ids are handed out as documents open, so they keep the opening order when tabs are dragged. + documents.sort_by_key(|(_, d)| d.id.0); + documents +} + +/// The option id prefix of a layer the engine would not read by its plain name: one named "merged" (the composite) or +/// with no name, and so that no plain name is mistaken for one, any name with this prefix. The rest of the id is the +/// name, sent as `{"name": …}` ([`apply_image_layer_selector`]). +const LAYER_NAMED: &str = "layer#"; +/// The option id prefix of a layer below another of the same name, which the engine would read as that upper layer by +/// name. The rest of the id is the layer's id, sent as the number itself ([`apply_image_layer_selector`]). +const LAYER_ID: &str = "layer@"; +/// The option id prefix of an alpha channel the engine would not read by its plain name: one named as a built-in +/// channel ("Red", "RGB", "selection"…), a later one of a repeated name, one named as a channel value the source and +/// mask paths read as no channel ([`NO_CHANNEL`]), or one with this prefix. The rest of the id is its index, sent as +/// `{"alpha": index}` ([`apply_image_channel_selector`]). +const ALPHA_AT: &str = "alpha#"; +/// Channel values the engine reads as no channel: a mask channel "none" is no mask, and an empty channel is dropped +/// from a flat source or mask (the source then reads the composite, the mask is off). +const NO_CHANNEL: [&str; 2] = ["", "none"]; + +/// The option id of the layer `name`: the name itself, unless the engine would read it as something else or the +/// dialog as one of its prefixed ids. +fn apply_image_layer_option(name: &str) -> String { + if name.is_empty() || name == "merged" || name.starts_with(LAYER_NAMED) || name.starts_with(LAYER_ID) { + format!("{LAYER_NAMED}{name}") + } else { + name.to_owned() + } +} + +/// The layer selector an Apply Image Layer option sends: `{"name": …}` for a [`LAYER_NAMED`] id, the layer id as a +/// number for a [`LAYER_ID`] id, else the id. +fn apply_image_layer_selector(id: &str) -> Value { + if let Some(layer) = id.strip_prefix(LAYER_ID).and_then(|n| n.parse::().ok()) { + return json!(layer); + } + id.strip_prefix(LAYER_NAMED).map_or_else(|| json!(id), |name| json!({"name": name})) +} + +/// The channel selector an Apply Image Channel option sends: `{"alpha": index}` for an [`ALPHA_AT`] id, else the id. +fn apply_image_channel_selector(id: &str) -> Value { + id.strip_prefix(ALPHA_AT).and_then(|i| i.parse::().ok()).map_or_else(|| json!(id), |i| json!({"alpha": i})) +} + +/// A selector as a dialog field: a plain id as text, an explicit selector as JSON. +fn selector_field(selector: Value) -> FieldValue { + match selector { + Value::String(id) => FieldValue::Text(id), + other => FieldValue::Json(other), + } +} + +/// The alpha channel options of a source document, labelled by name: an alpha whose name the engine reads as itself +/// keeps it as its id, any other is [`ALPHA_AT`] and its index, so no option shares an id with a built-in channel or +/// another alpha. +fn apply_image_alpha_options(doc: &photocraft_doc::Document) -> Vec<(String, Label)> { + use photocraft_engine::channel_cmds::{ChanRef, parse_ref}; + doc.channels + .iter() + .enumerate() + .map(|(i, c)| { + let plain = !c.name.starts_with(ALPHA_AT) && !NO_CHANNEL.contains(&c.name.as_str()) && parse_ref(&json!(c.name), doc) == Some(ChanRef::Alpha(i)); + (if plain { c.name.clone() } else { format!("{ALPHA_AT}{i}") }, Label::from(c.name.clone())) + }) + .collect() +} + +/// The Layer list of a source document and its default: Merged, then its pixel layers top to bottom, Merged first; a +/// single-layer document lists only that layer. A layer keeps its own option beside Merged whatever its name +/// ([`apply_image_layer_option`]); the engine reads a name as the topmost layer of that name, so a layer below another +/// of its name is offered by its id ([`LAYER_ID`]). +fn apply_image_layers(doc: &photocraft_doc::Document) -> (Vec<(String, Label)>, String) { + let all = doc.walk(); + if let [(_, _, only)] = all.as_slice() { + let id = apply_image_layer_option(&only.name); + return (vec![(id.clone(), Label::from(only.name.clone()))], id); + } + let mut names: Vec<&str> = Vec::new(); + let mut layers = vec![("merged".to_string(), Label::from(tl!("Merged")))]; + for (_, _, l) in all.iter().rev() { + if l.surface().is_none() { + continue; + } + let id = if names.contains(&l.name.as_str()) { format!("{LAYER_ID}{}", l.id.0) } else { apply_image_layer_option(&l.name) }; + names.push(&l.name); + layers.push((id, Label::from(l.name.clone()))); + } + (layers, "merged".to_string()) +} + +/// The mask Channel list of a source document and its default (#14489): its composite, read as luminosity and so named +/// Gray, the colour channels of a colour document, then its alpha channels (and Selection while it has one). A colour +/// document starts at its first colour channel, a one-channel document at Gray. The reference draws a rule before the +/// alpha channels; the hosted choice row takes no separators. +fn apply_image_mask_channels(doc: &photocraft_doc::Document) -> (Vec<(String, Label)>, String) { + let mode = doc.pixel_format().mode; + let composite = photocraft_engine::channel_cmds::composite_name(mode).to_string(); + let mut list = vec![(composite.clone(), Label::from(tl!("Gray")))]; + let mut default = composite; + if mode.color_channels() > 1 { + let colors = photocraft_engine::channel_cmds::color_names(mode); + if let Some(first) = colors.first() { + default = (*first).to_string(); + } + list.extend(colors.iter().map(|n| (n.to_string(), Label::from(n.to_string())))); + } + list.extend(apply_image_alpha_options(doc)); + if doc.selection.is_some() { + list.extend(channels(&["selection".to_string()])); + } + (list, default) +} + +/// Apply Image's Mask... checkbox and the group it opens (#14489): Source (the documents of [`apply_image_documents`], +/// the first by default), then that document's Layer and Channel, and Invert. +fn apply_image_mask_rows(app: &PhotocraftApp) -> Vec { + let documents = apply_image_documents(app); + let shown = |row: Param| row.visible_when(MASK_ON, true); + let names: Vec<(String, Label)> = documents.iter().map(|(i, d)| (i.to_string(), Label::from(d.name.clone()))).collect(); + let first = names.first().map(|(id, _)| id.clone()).unwrap_or_default(); + let mut rows = vec![Param::new(MASK_ON, tl!("Mask…"), ParamKind::bool(false)), shown(choice(MASK_SOURCE, tl!("Source"), names, &first))]; + for (i, doc) in documents { + let (layers, layer) = apply_image_layers(doc); + let (list, channel) = apply_image_mask_channels(doc); + rows.push(choice(&mask_layer_key(i), tl!("Layer"), layers, &layer).visible_when(mask_shown_key(i), true)); + rows.push(choice(&mask_channel_key(i), tl!("Channel"), list, &channel).visible_when(mask_shown_key(i), true)); + } + rows.push(shown(Param::new(MASK_INVERT, tl!("Invert"), ParamKind::bool(false)))); + rows +} + +/// Brings the mask group's shell keys and the `mask*` parameters of `image.applyImage` up to date: the chosen +/// document's Layer and Channel rows are shown, and OK sends `maskDocument`, `maskLayer`, `maskChannel` and, only when +/// Invert is ticked, `maskInvert`. With Mask unticked it sends no mask at all. A layer or alpha the engine would read as +/// something else by its name goes as an explicit selector. +fn apply_image_mask_derive(fields: &mut DialogFields) { + let on = fields.bool(MASK_ON) == Some(true); + let source = fields.text(MASK_SOURCE).and_then(|s| s.parse::().ok()); + let documents: Vec = fields.iter().filter_map(|(k, _)| k.strip_prefix("__maskLayer/").and_then(|i| i.parse().ok())).collect(); + for i in documents { + fields.set(mask_shown_key(i), on && source == Some(i)); + } + for key in ["maskDocument", "maskLayer", "maskChannel", "maskInvert"] { + fields.remove(key); + } + let Some(i) = source.filter(|_| on) else { return }; + let Some(channel) = fields.text(&mask_channel_key(i)).map(apply_image_channel_selector) else { return }; + let layer = apply_image_layer_selector(fields.text(&mask_layer_key(i)).unwrap_or("merged")); + fields.set("maskDocument", FieldValue::Int(i64::try_from(i).unwrap_or(i64::MAX))); + fields.set("maskLayer", selector_field(layer)); + fields.set("maskChannel", selector_field(channel)); + if fields.bool(MASK_INVERT) == Some(true) { + fields.set("maskInvert", true); + } +} + +#[cfg(test)] +#[path = "../../dialogs/apply_image_mask_group_tests.rs"] +mod apply_image_mask_group_tests; + /// The Channel options of one Image ▸ Calculations source (#14521), in the reference application's /// order: the composite read as "Gray", the mode's colour channels, then the source layer's Layer /// Mask and Transparency — Layer Mask only when that layer has one — and then the document's alpha @@ -940,7 +1241,13 @@ pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, para "file.automate.batch" if crate::actions::selected_action(app).is_none() => Some(Err("record an action in the Actions panel first".into())), _ if is_form(id) => { let (rows, fields) = params_for(app, id)?; - Some(Ok(opened(open_form(app, id, label, rows, fields, Value::Null)))) + if id == "file.fileInfo" { + let doc = app.session.active()?.doc.id; + let title = Label::from(crate::dialogs::file_info_title(app)); + Some(Ok(opened(open_form_label(app, id, title, rows, fields, json!({"document": doc.0}))))) + } else { + Some(Ok(opened(open_form(app, id, label, rows, fields, Value::Null)))) + } } _ => None, } diff --git a/crates/ui-egui/src/menus/view_cmds/file_info_title_labels_tests.rs b/crates/ui-egui/src/menus/view_cmds/file_info_title_labels_tests.rs new file mode 100644 index 0000000000..b4ac113f81 --- /dev/null +++ b/crates/ui-egui/src/menus/view_cmds/file_info_title_labels_tests.rs @@ -0,0 +1,74 @@ +//! File Info (#13824): the dialog is titled with the document it opened on (the name without +//! its extension), edits that document even if another tab becomes active, and the Basic page's +//! two remaining labels are title case. Other generated form dialogs keep their labels. + +use craft::ui::dialog::DialogId; + +use super::*; + +fn app_with_document(name: &str) -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"name": name, "width": 64, "height": 64})).unwrap(); + app.sync_views(); + app +} + +fn open_file_info(app: &mut PhotocraftApp) -> DialogId { + let ctx = app.ctx().clone(); + crate::menus::invoke(app, &ctx, "file.fileInfo", json!({})).unwrap(); + app.framework.dialogs.stack().top().expect("File Info opens") +} + +#[test] +fn the_title_is_the_document_name_without_its_extension() { + for (document, title) in [("oracle.psd", "oracle"), ("oracle", "oracle"), ("my.photo.png", "my.photo"), (".hidden", ".hidden")] { + let app = app_with_document(document); + assert_eq!(crate::dialogs::file_info_title(&app), title, "{document}"); + } +} + +#[test] +fn the_author_title_and_copyright_status_labels_are_title_case() { + let mut app = app_with_document("oracle.psd"); + let (rows, _) = super::dialogs::file_info_form(&mut app).expect("File Info form"); + let label = |key: &str| rows.iter().find(|p| p.key == key).map(|p| p.label.as_str()).unwrap_or_default(); + assert_eq!(label("authorTitle"), "Author Title"); + assert_eq!(label("copyrightStatus"), "Copyright Status"); + // The labels that were already fixed stay as they are. + assert_eq!(label("title"), "Document Title"); + assert_eq!(label("copyright"), "Copyright Notice"); + assert_eq!(label("copyrightUrl"), "Copyright Info URL"); +} + +#[test] +fn other_form_dialogs_keep_their_generated_labels() { + assert_eq!(super::dialogs::label_of("authorTitle"), "Author title"); + assert_eq!(super::dialogs::label_of("copyrightStatus"), "Copyright status"); +} + +/// The dialog belongs to the document it opened on. Activating another tab keeps its title, and +/// OK writes the metadata there, never into the newly active document. +#[test] +fn switching_documents_keeps_the_edit_on_the_document_it_opened_on() { + let mut app = app_with_document("oracle.psd"); + let id = open_file_info(&mut app); + assert_eq!(crate::dialogs::file_info_title(&app), "oracle"); + + app.run("file.new", json!({"name": "other.psd", "width": 32, "height": 32})).unwrap(); + assert_eq!(app.session.active().map(|st| st.doc.name.as_str()), Some("other.psd")); + + let ctx = app.ctx().clone(); + app.framework.dialogs.set_json_field(&ctx, id, "title", json!("Oracle title")).unwrap(); + crate::dialogs::testing::confirm(&mut app, id).unwrap(); + + let has_title = |name: &str| { + app.session + .documents() + .iter() + .find(|st| st.doc.name == name) + .is_some_and(|st| st.doc.metadata.xmp.as_deref().is_some_and(|xmp| xmp.contains("Oracle title"))) + }; + assert!(has_title("oracle.psd"), "the edited document gets the metadata"); + assert!(!has_title("other.psd"), "the newly active document is untouched"); + assert_eq!(app.session.active().map(|st| st.doc.name.as_str()), Some("other.psd"), "the active tab is restored"); +} diff --git a/crates/ui-egui/src/menus/workspace_ui.rs b/crates/ui-egui/src/menus/workspace_ui.rs index 1be3ffaf14..fce826ac76 100644 --- a/crates/ui-egui/src/menus/workspace_ui.rs +++ b/crates/ui-egui/src/menus/workspace_ui.rs @@ -7,7 +7,7 @@ use craft::behavior::dock::{NamedWorkspace, WorkspaceChrome, WorkspaceError, WorkspaceKeeps, WorkspaceSet}; use craft::keymap::{CommandRef, Mods}; -use craft::ui::contract::{Bind, CommandSet as _}; +use craft::ui::contract::{Bind, CommandSet as _, Entry}; use craft::ui::dialog::DialogResult; use craft::ui::docking::{WorkspaceAsk, WorkspaceCommands, run_workspace, workspace_states}; use craft::ui::patterns::dock::{HostedDeleteWorkspace, HostedNewWorkspace, NewWorkspace}; @@ -317,6 +317,52 @@ pub fn take(app: &mut PhotocraftApp, _ctx: &egui::Context) { } } +/// A row of the options bar's workspace switcher. Each runs the Window › Workspace command of the same row. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub(crate) enum SwitcherPick { + /// Make workspace `id` current (`window.workspace.`). + Workspace(String), + /// Reset the current workspace (`workspace.reset`). + Reset, + /// New Workspace… (`workspace.new`). + New, + /// Delete Workspace… (`workspace.delete`). + Delete, +} + +impl SwitcherPick { + /// The id of the Window › Workspace command the row runs. + pub(crate) fn command(&self) -> String { + match self { + SwitcherPick::Workspace(id) => format!("window.workspace.{id}"), + SwitcherPick::Reset => "workspace.reset".into(), + SwitcherPick::New => "workspace.new".into(), + SwitcherPick::Delete => "workspace.delete".into(), + } + } +} + +/// The rows of the options bar's workspace switcher, as in the reference application: the built-in workspaces sorted +/// by name with the current one checked, the saved ones after them as Window › Workspace lists them, then Reset with +/// the current workspace's name, New Workspace… and Delete Workspace…. Lock Workspace and Keyboard Shortcuts stay in +/// the Window menu. +pub(crate) fn switcher_entries(set: &WorkspaceSet) -> Vec> { + let row = |w: &NamedWorkspace| Entry::new(SwitcherPick::Workspace(w.id.clone()), w.name.clone()).checked(set.current == w.id); + let mut builtin: Vec<&NamedWorkspace> = set.builtin.iter().collect(); + builtin.sort_by_cached_key(|w| w.name.to_lowercase()); + let mut rows: Vec> = builtin.into_iter().map(row).collect(); + if !set.saved.is_empty() { + rows.push(Entry::separator()); + rows.extend(set.saved.iter().map(row)); + } + rows.push(Entry::separator()); + let current = set.find(&set.current).map_or("", |w| w.name.as_str()); + rows.push(Entry::new(SwitcherPick::Reset, tl!("Reset {}").replacen("{}", current, 1))); + rows.push(Entry::new(SwitcherPick::New, tl!("New Workspace…").to_owned())); + rows.push(Entry::new(SwitcherPick::Delete, tl!("Delete Workspace…").to_owned())); + rows +} + /// The state of each workspace command, for the command source. pub fn states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandState)> { workspace_states(&app.workspaces.set).into_iter().map(|(command, state)| (CommandRef::from(command), state)).collect() diff --git a/crates/ui-egui/src/modifier_keys.rs b/crates/ui-egui/src/modifier_keys.rs index ccc892373f..64d5e599c5 100644 --- a/crates/ui-egui/src/modifier_keys.rs +++ b/crates/ui-egui/src/modifier_keys.rs @@ -1,5 +1,5 @@ //! The Modifier Keys panel: latching Shift, ⌘ and ⌥ for touch and pen users. Code that needs the held modifiers reads -//! `craft::ui::runtime::pointer::frame(ctx).mods`, which includes the latched keys. +//! `craft::ui::runtime::pointer::mods(ctx)`, which includes the latched keys. use craft::ui::contract::Bind; use craft::ui::patterns::panels::ModifierKeysPanel; diff --git a/crates/ui-egui/src/options_bar_percent_arrow_repeat_tests.rs b/crates/ui-egui/src/options_bar_percent_arrow_repeat_tests.rs new file mode 100644 index 0000000000..5695caa309 --- /dev/null +++ b/crates/ui-egui/src/options_bar_percent_arrow_repeat_tests.rs @@ -0,0 +1,123 @@ +//! #16806: Up and Down in the painting tools' % fields (Opacity, Flow, Smoothing; the Mixer Brush's +//! Wet, Load, Mix and Flow) step on every press. The brush keeps these as `f32` fractions, so 0.51 +//! reads back as 50.999999..., which the field took for a value off its grid and stepped to 51 again. + +use egui::accesskit::Role; +use egui::{Key, Modifiers, 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 a new document with `tool`. +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; + crate::paint_mouse::sync_tool_brush(&mut app); + 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(2400.0, 300.0)).with_step_dt(1.0 / 60.0).build_ui_state( + move |ui, app: &mut Box| { + crate::panels::options_bar(app, ui); + }, + app, + ); + h.run_steps(4); + h +} + +/// The field named `label`, with or without its caption's colon. +fn field<'a>(h: &'a Harness<'static, Box>, label: &str) -> egui_kittest::Node<'a> { + h.query_all_by_role(Role::SpinButton) + .find(|n| n.accesskit_node().label().is_some_and(|l| l.trim_end_matches(':') == label)) + .unwrap_or_else(|| panic!("the {label} field")) +} + +/// The value the field named `label` holds, to a billionth (the field's own grid tolerance), so +/// 50.999999 (an `f32` read as it is) stays apart from 51. +fn shown(h: &Harness<'static, Box>, label: &str) -> f64 { + let value = field(h, label).accesskit_node().numeric_value().unwrap_or_else(|| panic!("the {label} field's value")); + (value * 1e9).round() / 1e9 +} + +/// Clicks into the field named `label`, types `text` over it and presses Enter; the focus stays in it. +fn type_into(h: &mut Harness<'static, Box>, label: &str, text: &str) { + let at = field(h, label).rect().center(); + h.hover_at(at); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.key_press_modifiers(Modifiers::COMMAND, Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(Key::Enter); + h.run_steps(3); +} + +/// Presses `key` with `mods` `times` times, letting the bar redraw from the stored value in between. +fn press(h: &mut Harness<'static, Box>, key: Key, mods: Modifiers, times: usize) { + for _ in 0..times { + h.key_press_modifiers(mods, key); + h.run_steps(3); + } +} + +/// From 50, Up x3 shows 53 and Down x3 (from 50 again) shows 47 in the field named `label`. +fn steps_every_press(tool: Tool, label: &str) { + let mut h = bar(tool); + type_into(&mut h, label, "50"); + assert_eq!(shown(&h, label), 50.0, "{tool:?} {label} typed 50"); + press(&mut h, Key::ArrowUp, Modifiers::NONE, 3); + assert_eq!(shown(&h, label), 53.0, "{tool:?} {label}: 50, Up x3"); + type_into(&mut h, label, "50"); + press(&mut h, Key::ArrowDown, Modifiers::NONE, 3); + assert_eq!(shown(&h, label), 47.0, "{tool:?} {label}: 50, Down x3"); +} + +#[test] +fn brush_opacity_flow_and_smoothing_step_on_every_press() { + for label in ["Opacity", "Flow", "Smoothing"] { + steps_every_press(Tool::Brush, label); + } +} + +#[test] +fn pencil_and_eraser_percent_fields_step_on_every_press() { + steps_every_press(Tool::Pencil, "Opacity"); + steps_every_press(Tool::Pencil, "Smoothing"); + steps_every_press(Tool::Eraser, "Opacity"); + steps_every_press(Tool::Eraser, "Flow"); +} + +#[test] +fn mixer_brush_percent_fields_step_on_every_press() { + for label in ["Wet", "Load", "Mix", "Flow"] { + steps_every_press(Tool::MixerBrush, label); + } +} + +#[test] +fn shift_up_steps_ten_on_every_press() { + let mut h = bar(Tool::Brush); + type_into(&mut h, "Opacity", "50"); + press(&mut h, Key::ArrowUp, Modifiers::SHIFT, 2); + assert_eq!(shown(&h, "Opacity"), 70.0, "50, Shift+Up x2"); + assert_eq!((h.state().session.tools.brush.opacity * 100.0).round(), 70.0, "the brush holds 70 %"); +} + +#[test] +fn an_f32_opacity_of_0_51_steps_up_twice_to_53() { + let mut h = bar(Tool::Brush); + type_into(&mut h, "Opacity", "40"); + h.state_mut().session.tools.brush.opacity = 0.51_f32; + h.run_steps(3); + assert_eq!(shown(&h, "Opacity"), 51.0); + press(&mut h, Key::ArrowUp, Modifiers::NONE, 2); + assert_eq!(shown(&h, "Opacity"), 53.0, "0.51 (f32), Up x2"); + assert_eq!((h.state().session.tools.brush.opacity * 100.0).round(), 53.0, "the brush holds 53 %"); +} diff --git a/crates/ui-egui/src/options_bar_search_button_tests.rs b/crates/ui-egui/src/options_bar_search_button_tests.rs new file mode 100644 index 0000000000..baa3d32966 --- /dev/null +++ b/crates/ui-egui/src/options_bar_search_button_tests.rs @@ -0,0 +1,92 @@ +//! #16800: the Search button at the right end of the options bar. It runs `edit.search`, as Edit › Search… does, +//! stays for every tool and hides with the bar. + +use egui::accesskit::Role; +use egui::{Rect, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; + +/// The button's name and tooltip, as in the reference application. +const SEARCH: &str = "Search for tools, help, and more"; + +/// The window width the trials use, in points. +const WIDTH: f32 = 1440.0; + +/// The app with a new document and `tool` chosen. +fn harness(tool: Tool) -> Harness<'static, Box> { + let mut h = Harness::builder().with_size(vec2(WIDTH, 900.0)).with_max_steps(64).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app.ui.tool = tool; + app + }); + h.run_steps(8); + h +} + +/// The Search button's rect, if the button is shown. +fn search_button(h: &Harness<'_, Box>) -> Option { + h.query_by_role_and_label(Role::Button, SEARCH).map(|n| n.rect()) +} + +/// The options bar's Home button: the bar's first member, on the bar's line. +fn home(h: &Harness<'_, Box>) -> Rect { + h.get_by_label("Home").rect() +} + +#[test] +fn the_search_button_sits_at_the_right_end_of_the_options_bar() { + let h = harness(Tool::Move); + let search = search_button(&h).expect("the options bar has a Search button"); + let home = home(&h); + assert!(search.center().y > home.top() && search.center().y < home.bottom(), "on the bar's line: {search:?} vs Home {home:?}"); + assert!(search.right() > WIDTH - 48.0, "at the bar's right end: {search:?}"); + // Every other control on the bar's line sits left of it, but the workspace switcher (#16799), which ends the bar. + let switcher = h.query_by_role_and_label(Role::Button, "Choose a Workspace").map(|n| n.rect()); + let line = |r: Rect| r.center().y > home.top() && r.center().y < home.bottom() && Some(r) != switcher; + let rightmost_other = h + .query_all_by_role(Role::Button) + .chain(h.query_all_by_role(Role::CheckBox)) + .chain(h.query_all_by_role(Role::ComboBox)) + .map(|n| n.rect()) + .filter(|r| line(*r) && *r != search) + .map(|r| r.right()) + .fold(f32::MIN, f32::max); + assert!(rightmost_other <= search.left(), "nothing on the bar but the switcher is right of Search: {rightmost_other} > {}", search.left()); +} + +#[test] +fn a_click_opens_the_search_and_a_second_click_closes_it() { + let mut h = harness(Tool::Move); + assert!(!h.state().ui.palette.open); + h.get_by_role_and_label(Role::Button, SEARCH).click(); + h.run_steps(4); + assert!(h.state().ui.palette.open, "a click runs edit.search"); + h.get_by_role_and_label(Role::Button, SEARCH).click(); + h.run_steps(4); + assert!(!h.state().ui.palette.open, "a second click closes the search"); +} + +#[test] +fn the_search_button_stays_in_place_for_every_tool() { + let at = search_button(&harness(Tool::Move)).expect("Search with the Move tool"); + for tool in [Tool::Brush, Tool::Crop, Tool::Type, Tool::Gradient, Tool::Zoom] { + let rect = search_button(&harness(tool)).unwrap_or_else(|| panic!("Search with {tool:?}")); + assert!((rect.right() - at.right()).abs() < 0.5, "{tool:?}: {rect:?} vs {at:?}"); + } +} + +#[test] +fn the_search_button_hides_with_the_options_bar() { + let mut h = harness(Tool::Move); + assert!(search_button(&h).is_some()); + h.state_mut().ui.panels.options_bar = false; + h.run_steps(4); + assert!(search_button(&h).is_none(), "no Search button without the options bar"); + assert!(h.query_by_label("Home").is_none(), "the bar itself is hidden"); +} diff --git a/crates/ui-egui/src/options_bar_workspace_switcher_tests.rs b/crates/ui-egui/src/options_bar_workspace_switcher_tests.rs new file mode 100644 index 0000000000..d71b1fbbf6 --- /dev/null +++ b/crates/ui-egui/src/options_bar_workspace_switcher_tests.rs @@ -0,0 +1,190 @@ +//! #16799: the workspace switcher at the right end of the options bar. Its menu has the built-in workspaces sorted by +//! name with the current one checked, the saved ones, then Reset, New and Delete, and runs the Window › Workspace +//! commands. It stays for every tool and hides with the bar. + +use egui::accesskit::{Role, Toggled}; +use egui::{Rect, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; + +/// The switcher's name and tooltip, as in the reference application. +const SWITCHER: &str = "Choose a Workspace"; + +/// The Search button's name (#16800), which sits left of the switcher. +const SEARCH: &str = "Search for tools, help, and more"; + +/// The window width the trials use, in points. +const WIDTH: f32 = 1440.0; + +/// The roles a menu row can have. +const ROWS: [Role; 3] = [Role::MenuItem, Role::MenuItemCheckBox, Role::MenuItemRadio]; + +/// The app with a new document and `tool` chosen. +fn harness(tool: Tool) -> Harness<'static, Box> { + let mut h = Harness::builder().with_size(vec2(WIDTH, 900.0)).with_max_steps(64).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app.ui.tool = tool; + app + }); + h.run_steps(8); + h +} + +/// The switcher button's rect, if it is shown. +fn switcher(h: &Harness<'_, Box>) -> Option { + h.query_by_role_and_label(Role::Button, SWITCHER).map(|n| n.rect()) +} + +/// Opens the switcher's menu with a click on its button. +fn open_menu(h: &mut Harness<'_, Box>) { + h.get_by_role_and_label(Role::Button, SWITCHER).click(); + h.run_steps(6); +} + +/// The open menu's rows below the options bar, top to bottom: (name, checked, rect). +fn menu_rows(h: &Harness<'_, Box>) -> Vec<(String, bool, Rect)> { + let bar_bottom = switcher(h).map_or(0.0, |r| r.bottom()); + let mut rows: Vec<(String, bool, Rect)> = ROWS + .iter() + .flat_map(|role| h.query_all_by_role(*role)) + .map(|n| (n.accesskit_node().label().unwrap_or_default(), n.accesskit_node().toggled() == Some(Toggled::True), n.rect())) + .filter(|(_, _, rect)| rect.top() >= bar_bottom) + .collect(); + rows.sort_by(|a, b| a.2.top().total_cmp(&b.2.top())); + rows +} + +/// Clicks the open menu's row named `name`. +fn pick(h: &mut Harness<'_, Box>, name: &str) { + let row = ROWS.iter().find_map(|role| h.query_by_role_and_label(*role, name)).unwrap_or_else(|| panic!("no row {name}: {:?}", menu_rows(h))); + row.click(); + h.run_steps(6); +} + +/// The names of the menu's rows. +fn names(rows: &[(String, bool, Rect)]) -> Vec<&str> { + rows.iter().map(|(n, ..)| n.as_str()).collect() +} + +#[test] +fn the_switcher_sits_at_the_right_end_right_of_search() { + let h = harness(Tool::Move); + let switcher = switcher(&h).expect("the options bar has a workspace switcher"); + let search = h.get_by_role_and_label(Role::Button, SEARCH).rect(); + assert!(search.right() <= switcher.left(), "Search is left of the switcher: {search:?} {switcher:?}"); + assert!((search.center().y - switcher.center().y).abs() < 1.0, "both on the bar's line"); + assert!(switcher.right() > WIDTH - 48.0, "at the bar's right end: {switcher:?}"); +} + +#[test] +fn the_switcher_keeps_its_place_for_every_tool() { + let at = switcher(&harness(Tool::Move)).expect("the switcher with the Move tool"); + for tool in [Tool::Brush, Tool::Crop, Tool::Type, Tool::Gradient, Tool::Zoom] { + let rect = switcher(&harness(tool)).unwrap_or_else(|| panic!("the switcher with {tool:?}")); + assert!((rect.right() - at.right()).abs() < 0.5, "{tool:?}: {rect:?} vs {at:?}"); + } +} + +#[test] +fn the_menu_lists_the_built_in_workspaces_sorted_then_reset_new_and_delete() { + let mut h = harness(Tool::Move); + open_menu(&mut h); + let rows = menu_rows(&h); + assert_eq!( + names(&rows), + ["Essentials", "Graphic and Web", "Motion", "Painting", "Photography", "Pixel Art", "Reset Essentials", "New Workspace…", "Delete Workspace…"], + "{rows:?}" + ); + let checked: Vec<&str> = rows.iter().filter(|(_, on, _)| *on).map(|(n, ..)| n.as_str()).collect(); + assert_eq!(checked, ["Essentials"], "only the current workspace is checked"); + // The menu hangs under the button, not over the bar. + let button = switcher(&h).unwrap(); + assert!(rows.iter().all(|(_, _, r)| r.top() >= button.bottom()), "below the button"); + // At the window's right edge the menu ends near the button's right edge: it slides left to fit (#16799). + let right = rows.iter().map(|(_, _, r)| r.right()).fold(f32::MIN, f32::max); + assert!((right - button.right()).abs() <= 8.0 && right <= WIDTH, "under the button's right end: rows end at {right}, {button:?}"); +} + +#[test] +fn picking_a_workspace_makes_it_current_as_window_workspace_does() { + let mut h = harness(Tool::Move); + open_menu(&mut h); + pick(&mut h, "Painting"); + assert_eq!(h.state().workspaces.set.current, "painting"); + assert!(menu_rows(&h).is_empty(), "the menu closes"); + open_menu(&mut h); + let rows = menu_rows(&h); + let checked: Vec<&str> = rows.iter().filter(|(_, on, _)| *on).map(|(n, ..)| n.as_str()).collect(); + assert_eq!(checked, ["Painting"]); + assert!(names(&rows).contains(&"Reset Painting"), "Reset names the current workspace: {rows:?}"); +} + +#[test] +fn saved_workspaces_follow_the_built_in_ones() { + let mut h = harness(Tool::Move); + crate::workspace_ui::save(h.state_mut(), "My Layout").unwrap(); + h.run_steps(4); + open_menu(&mut h); + let rows = menu_rows(&h); + let names = names(&rows); + let at = names.iter().position(|n| *n == "My Layout").unwrap_or_else(|| panic!("the saved workspace is listed: {names:?}")); + assert_eq!(names.get(at - 1), Some(&"Pixel Art"), "after the built-in ones: {names:?}"); + assert_eq!(names.get(at + 1), Some(&"Reset My Layout"), "then Reset: {names:?}"); + assert!(rows.iter().any(|(n, on, _)| n == "My Layout" && *on), "a new workspace is current"); +} + +#[test] +fn the_menu_has_no_lock_or_keyboard_shortcuts_rows() { + let mut h = harness(Tool::Move); + open_menu(&mut h); + let rows = menu_rows(&h); + assert!(!rows.iter().any(|(n, ..)| n.contains("Lock") || n.contains("Keyboard")), "{rows:?}"); +} + +#[test] +fn new_workspace_opens_the_window_menus_dialog() { + let mut h = harness(Tool::Move); + assert!(h.state().framework.dialogs.is_empty()); + open_menu(&mut h); + pick(&mut h, "New Workspace…"); + assert!(!h.state().framework.dialogs.is_empty(), "New Workspace… opens its dialog"); +} + +#[test] +fn delete_workspace_opens_the_window_menus_dialog() { + let mut h = harness(Tool::Move); + crate::workspace_ui::save(h.state_mut(), "Spare").unwrap(); + h.run_steps(4); + assert!(h.state().framework.dialogs.is_empty()); + open_menu(&mut h); + pick(&mut h, "Delete Workspace…"); + assert!(!h.state().framework.dialogs.is_empty(), "Delete Workspace… opens its dialog"); +} + +#[test] +fn reset_runs_window_workspace_reset_and_keeps_the_workspace() { + let mut h = harness(Tool::Move); + let id = crate::workspace_ui::save(h.state_mut(), "Spare").unwrap(); + h.run_steps(4); + let runs = h.state().commands_run; + open_menu(&mut h); + pick(&mut h, "Reset Spare"); + assert_eq!(h.state().workspaces.set.current, id, "Reset keeps the workspace"); + assert!(h.state().commands_run > runs, "Reset runs a command"); + assert!(!h.state().ui.status_error, "Reset runs without an error: {}", h.state().ui.status); +} + +#[test] +fn the_switcher_hides_with_the_options_bar() { + let mut h = harness(Tool::Move); + assert!(switcher(&h).is_some()); + h.state_mut().ui.panels.options_bar = false; + h.run_steps(4); + assert!(switcher(&h).is_none(), "no switcher without the options bar"); +} diff --git a/crates/ui-egui/src/paint_bucket_options_fields_tests.rs b/crates/ui-egui/src/paint_bucket_options_fields_tests.rs new file mode 100644 index 0000000000..4d0d34e3e9 --- /dev/null +++ b/crates/ui-egui/src/paint_bucket_options_fields_tests.rs @@ -0,0 +1,183 @@ +//! #12533: the Paint Bucket's Tolerance takes whole numbers 0..255 and Opacity whole percents +//! 1..100; a value typed past either range becomes the closest one with the reference's "Closest +//! value inserted" alert. A typed fraction rounds to the closest whole number: in Tolerance with +//! the same alert, in Opacity without one. The seven controls carry the +//! reference's tooltips, and the Source dropdown has no "Fill" label. The Magic Wand and the Magic +//! Eraser share Tolerance and keep their own behaviour. + +use std::cell::Cell; + +use craft::ui::runtime::env::Env; +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; + +type H = Harness<'static, Box>; + +const TOLERANCE_ALERT: &str = "An integer between 0 and 255 is required. Closest value inserted."; +const OPACITY_ALERT: &str = "An integer between 1% and 100% is required. Closest value inserted."; + +thread_local! { + /// The decimal mark the bar's fields read, from the env they are drawn in: the system region's + /// unless the host sets one, so a typed fraction must use it to be read as one. + static MARK: Cell = const { Cell::new('.') }; +} + +/// The options bar with `tool` active, and the dialog host its alerts open on. +fn bar(tool: Tool) -> H { + 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; + app.ui.tool_options.tolerance = 32.0; + app.ui.tool_options.fill_opacity = 37.0; + 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, 300.0)).with_step_dt(1.0 / 60.0).build_ui_state( + move |ui, app: &mut Box| { + MARK.set(Env::of(ui).format().separators().0); + crate::panels::options_bar(app, ui); + crate::dialogs::run(app, ui); + }, + app, + ); + h.run_steps(4); + h +} + +/// `text` with `.` replaced by the fields' decimal mark. +fn localized(text: &str) -> String { + text.replace('.', &MARK.get().to_string()) +} + +/// The number field named `label`, with or without its caption's colon. +fn field<'a>(h: &'a H, label: &str) -> Option> { + h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().is_some_and(|l| l.trim_end_matches(':') == label)) +} + +/// Types `text` (with `.` as the decimal mark) into the field named `label` and commits it with Enter. +fn type_into(h: &mut H, label: &str, text: &str) { + let text = localized(text); + field(h, label).unwrap_or_else(|| panic!("the {label} field")).click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text)); + h.run_steps(1); + h.key_press(egui::Key::Enter); + h.run_steps(3); +} + +/// The messages of the open framework alerts. +fn alerts(h: &H) -> Vec { + h.state().framework.dialogs.open_dialogs().iter().filter_map(|d| d.fields.as_ref()?.get("message")?.as_str().map(str::to_string)).collect() +} + +/// The description (tooltip) of the control labelled `label`: not its caption's text node. +fn tip(h: &H, label: &str) -> Option { + let named = move |n: &egui_kittest::kittest::AccessKitNode<'_>| n.role() != Role::Label && n.label().is_some_and(|l| l.trim_end_matches(':') == label); + let node = h.query_all(egui_kittest::kittest::by().predicate(named)).next()?; + node.accesskit_node().description().map(|d| d.to_string()) +} + +#[test] +fn tolerance_past_0_255_takes_the_closest_value_and_alerts() { + for (typed, want) in [("300", 255.0), ("256", 255.0), ("-5", 0.0)] { + let mut h = bar(Tool::PaintBucket); + type_into(&mut h, "Tolerance", typed); + assert_eq!(h.state().ui.tool_options.tolerance, want, "{typed}"); + assert_eq!(alerts(&h), vec![TOLERANCE_ALERT.to_string()], "{typed}: one alert"); + } +} + +#[test] +fn tolerance_is_a_whole_number() { + for (typed, want) in [("12.7", 13.0), ("12.4", 12.0), ("255", 255.0), ("0", 0.0), ("abc", 32.0)] { + let mut h = bar(Tool::PaintBucket); + type_into(&mut h, "Tolerance", typed); + assert_eq!(h.state().ui.tool_options.tolerance, want, "{typed}"); + if !typed.contains('.') { + assert!(alerts(&h).is_empty(), "{typed}: no alert, got {:?}", alerts(&h)); + } + } +} + +#[test] +fn a_fractional_tolerance_takes_the_closest_value_and_alerts() { + for (typed, want) in [("12.7", 13.0), ("12.4", 12.0), ("0.4", 0.0), ("254.6", 255.0)] { + let mut h = bar(Tool::PaintBucket); + type_into(&mut h, "Tolerance", typed); + assert_eq!(h.state().ui.tool_options.tolerance, want, "{typed}"); + assert_eq!(alerts(&h), vec![TOLERANCE_ALERT.to_string()], "{typed}: one alert"); + } +} + +#[test] +fn a_fractional_opacity_rounds_without_an_alert() { + for (typed, want) in [("50.5", 51.0), ("50.4", 50.0), ("1.4", 1.0), ("99.6", 100.0)] { + let mut h = bar(Tool::PaintBucket); + type_into(&mut h, "Opacity", typed); + assert_eq!(h.state().ui.tool_options.fill_opacity, want, "{typed}"); + assert!(alerts(&h).is_empty(), "{typed}: no alert, got {:?}", alerts(&h)); + } +} + +#[test] +fn opacity_past_1_100_takes_the_closest_value_and_alerts() { + for (typed, want) in [("150", 100.0), ("0", 1.0), ("-3", 1.0)] { + let mut h = bar(Tool::PaintBucket); + type_into(&mut h, "Opacity", typed); + assert_eq!(h.state().ui.tool_options.fill_opacity, want, "{typed}"); + assert_eq!(alerts(&h), vec![OPACITY_ALERT.to_string()], "{typed}: one alert"); + } +} + +#[test] +fn opacity_in_range_rounds_to_a_whole_percent_without_an_alert() { + for (typed, want) in [("50.5", 51.0), ("50.4", 50.0), ("100", 100.0), ("1", 1.0), ("abc", 37.0)] { + let mut h = bar(Tool::PaintBucket); + type_into(&mut h, "Opacity", typed); + assert_eq!(h.state().ui.tool_options.fill_opacity, want, "{typed}"); + assert!(alerts(&h).is_empty(), "{typed}: no alert, got {:?}", alerts(&h)); + } +} + +#[test] +fn the_seven_controls_have_the_reference_tooltips() { + let h = bar(Tool::PaintBucket); + for (control, want) in [ + ("Source", "Set source for fill area"), + ("Mode", "Fill Mode"), + ("Opacity", "Set opacity for fill"), + ("Tolerance", "Range of colors to fill"), + ("Anti-alias", "Smoothes edge transition"), + ("Contiguous", "Fill only contiguous pixels"), + ("All Layers", "Fill composite image"), + ] { + assert_eq!(tip(&h, control).as_deref(), Some(want), "{control}"); + } +} + +#[test] +fn the_source_dropdown_has_no_fill_label() { + let h = bar(Tool::PaintBucket); + assert!(h.query_by_label("Fill").is_none() && h.query_by_label("Fill:").is_none(), "a Fill label is shown"); + assert!(h.query_all_by_role(Role::ComboBox).any(|n| n.accesskit_node().label().as_deref() == Some("Source")), "the Source dropdown is shown"); +} + +/// The Magic Wand and the Magic Eraser share Tolerance and keep today's behaviour: a value past +/// 0..255 is clamped without an alert. +#[test] +fn magic_wand_and_magic_eraser_tolerance_are_unchanged() { + for tool in [Tool::MagicWand, Tool::MagicEraser] { + for (typed, want) in [("300", 255.0), ("-5", 0.0), ("128", 128.0)] { + let mut h = bar(tool); + type_into(&mut h, "Tolerance", typed); + assert_eq!(h.state().ui.tool_options.tolerance, want, "{tool:?} {typed}"); + assert!(alerts(&h).is_empty(), "{tool:?} {typed}: no alert, got {:?}", alerts(&h)); + } + } +} diff --git a/crates/ui-egui/src/paint_bucket_refusal_alerts_tests.rs b/crates/ui-egui/src/paint_bucket_refusal_alerts_tests.rs new file mode 100644 index 0000000000..84eb482cb0 --- /dev/null +++ b/crates/ui-egui/src/paint_bucket_refusal_alerts_tests.rs @@ -0,0 +1,234 @@ +//! #12537: when the Paint Bucket can't fill (a hidden target layer, Lock All or Lock Image Pixels, +//! a group active), a click opens the reference application's alert with OK and fills nothing: no +//! History step, the target layer stays selected. Lock transparent pixels and Lock position still +//! fill; a pixel layer inside a group fills normally; a group's targeted layer mask is not refused +//! and takes today's step-without-fill. The Brush's alerts (Lock all only) and the other tools +//! stay as they are. + +use egui::Modifiers; +use serde_json::json; + +use super::brush_refusal_alert_tests::{active, alerts, app, steps, stroke}; +use super::*; +use crate::canvas::{ToolEvent, tool_event}; +use crate::control::{ControlRequest, Reply, handle}; + +/// A Paint Bucket click on the painted layer. +fn click(app: &mut PhotocraftApp) { + tool_event(app, ToolEvent::Down { x: 30.0, y: 30.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Up { x: 30.0, y: 30.0 }, Modifiers::NONE); +} + +/// The active layer's pixel at the click point; a group has no surface, hence `None`. +fn pixel(app: &PhotocraftApp) -> Option<[f32; 4]> { + let st = app.session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap())?.surface().map(|s| s.rgba(30, 30)) +} + +/// A named layer's pixel at the click point - the byte check when the active layer is a group. +fn child_rgba(app: &PhotocraftApp, id: photocraft_doc::LayerId) -> [f32; 4] { + let st = app.session.active().unwrap(); + st.doc.layer(id).and_then(|l| l.surface()).map(|s| s.rgba(30, 30)).unwrap_or([0.0; 4]) +} + +/// The click opens one alert with `want` and changes nothing: the same pixels, no History step, the +/// same active layer. OK closes the alert. +fn refused(app: &mut PhotocraftApp, want: &str) { + let before = (steps(app), pixel(app), active(app)); + click(app); + assert_eq!(alerts(app), [want], "the alert, once"); + assert_eq!((steps(app), pixel(app), active(app)), before, "nothing filled, no History step, the target stays selected"); + let id = app.framework.dialogs.open_dialogs().first().map(|d| d.id).unwrap(); + let ctx = app.ctx().clone(); + crate::dialogs::confirm(app, &ctx, id).unwrap(); + assert!(alerts(app).is_empty(), "OK closes the alert"); +} + +#[test] +fn a_hidden_target_layer() { + let mut app = app(Tool::PaintBucket); + let id = active(&app); + app.run("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + refused(&mut app, "Could not use the paint bucket because the target layer is hidden."); + assert!(app.ui.status.is_empty() || !app.ui.status_error, "no status-bar error as well: {:?}", app.ui.status); + assert_eq!( + photocraft_engine::hidden_target::HIDDEN, + "Could not complete your request because the target layer is hidden.", + "the engine's shared text stays as it is" + ); +} + +#[test] +fn lock_all_and_lock_image_pixels() { + // Both are the one "the layer is locked." alert in the reference application. + for lock in ["all", "pixels"] { + let mut bucket = app(Tool::PaintBucket); + bucket.run("layer.lockLayers", json!({ lock: true })).unwrap(); + refused(&mut bucket, "Could not use the paint bucket because the layer is locked."); + } +} + +#[test] +fn a_group_is_active() { + // The group holds the painted child layer, so its pixels are the byte check: a group has no + // surface of its own and the group's own check would be vacuous. + let mut app = app(Tool::PaintBucket); + let child = app.session.active().unwrap().active_layer.unwrap(); + let red = child_rgba(&app, child); + assert!(red[0] > 0.8 && red[3] > 0.99, "the child starts painted red: {red:?}"); + app.run("layer.groupLayers", json!({})).unwrap(); + // Once, with the measured wording: `press_refused` answers before `refuse_group` can add its + // own alert. + refused(&mut app, "Could not use the paint bucket because the pixels in a group cannot be edited without merging the group."); + assert_eq!(child_rgba(&app, child), red, "the child layer's pixels inside the group stay as they were"); +} + +#[test] +fn a_group_inside_a_group_is_refused_once() { + // Neighbour (pattern 3): the active inner group sits inside the outer group, which holds a + // painted child; neither group has pixels of its own at the click, so the byte check is the + // child's. + let mut app = app(Tool::PaintBucket); + app.run("layer.new.group", json!({})).unwrap(); + app.run("layer.new.group", json!({})).unwrap(); + let inner = app.session.active().unwrap().active_layer.unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + let child = app.session.active().unwrap().active_layer.unwrap(); + app.run("edit.fill", json!({"color": "#dc1e1e"})).unwrap(); + app.run("layer.select", json!({"layer": inner.0})).unwrap(); + let st = app.session.active().unwrap(); + let path = st.doc.path_of(st.active_layer.unwrap()).unwrap(); + assert_eq!(path.len(), 2, "the active group sits inside the outer group: {path:?}"); + let red = child_rgba(&app, child); + assert!(red[0] > 0.8 && red[3] > 0.99, "the child inside the groups starts painted red: {red:?}"); + refused(&mut app, "Could not use the paint bucket because the pixels in a group cannot be edited without merging the group."); + assert_eq!(child_rgba(&app, child), red, "the child layer's pixels inside the groups stay as they were"); +} + +#[test] +fn the_alert_is_listed_and_confirmed_over_the_control_channel() { + let ctx = egui::Context::default(); + let mut app = app(Tool::PaintBucket); + app.run("layer.lockLayers", json!({"pixels": true})).unwrap(); + click(&mut app); + let mut call = |method: &str, params: serde_json::Value| { + let (req, _rx) = ControlRequest::new(method, params); + match handle(&mut app, &ctx, &req) { + Reply::Done(v) => v, + _ => panic!("{method}: expected an immediate reply"), + } + }; + let inspect = call("ui.inspect", json!({})); + let dialog = &inspect["result"]["dialogs"][0]; + assert_eq!(dialog["fields"]["message"], "Could not use the paint bucket because the layer is locked.", "{inspect}"); + assert_eq!(call("ui.dialog.confirm", json!({"dialog": dialog["id"]}))["ok"], true); + assert!(alerts(&app).is_empty()); +} + +#[test] +fn a_click_on_a_visible_unlocked_layer_still_fills() { + // The guard for the whole change: the painting path is untouched. + let mut app = app(Tool::PaintBucket); + let before = steps(&app); + click(&mut app); + assert!(alerts(&app).is_empty(), "{:?}", alerts(&app)); + assert_eq!(steps(&app), before + 1, "the fill was applied"); + let st = app.session.active().unwrap(); + let surface = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + for (x, y) in [(30, 30), (2, 2), (61, 61)] { + let [r, g, b, a] = surface.rgba(x, y); + assert!(a > 0.99 && r < 0.01 && g < 0.01 && b < 0.01, "the black foreground at ({x}, {y}): {:?}", [r, g, b, a]); + } +} + +#[test] +fn lock_transparent_pixels_still_fills_the_opaque_pixels() { + let mut app = app(Tool::PaintBucket); + app.run("layer.lockLayers", json!({"transparency": true})).unwrap(); + let before = steps(&app); + click(&mut app); + assert!(alerts(&app).is_empty(), "{:?}", alerts(&app)); + assert_eq!(steps(&app), before + 1); + let [r, g, b, a] = pixel(&app).unwrap(); + assert!(a > 0.99 && r < 0.01 && g < 0.01 && b < 0.01, "the opaque region filled black: {:?}", [r, g, b, a]); +} + +#[test] +fn lock_position_still_fills() { + let mut app = app(Tool::PaintBucket); + app.run("layer.lockLayers", json!({"position": true})).unwrap(); + let before = steps(&app); + click(&mut app); + assert!(alerts(&app).is_empty(), "{:?}", alerts(&app)); + assert_eq!(steps(&app), before + 1); + let [r, g, b, a] = pixel(&app).unwrap(); + assert!(a > 0.99 && r < 0.01 && g < 0.01 && b < 0.01, "filled black: {:?}", [r, g, b, a]); +} + +#[test] +fn a_pixel_layer_inside_a_group_fills_normally() { + let mut app = app(Tool::PaintBucket); + app.run("layer.new.group", json!({})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + let st = app.session.active().unwrap(); + let id = st.active_layer.unwrap(); + let path = st.doc.path_of(id).unwrap(); + assert_eq!(path.len(), 2, "the new layer is a child of the group: {path:?}"); + assert!(st.doc.layer_at(&path[..1]).is_some_and(|l| l.is_group()), "its parent is a group"); + let before = steps(&app); + click(&mut app); + assert!(alerts(&app).is_empty(), "{:?}", alerts(&app)); + assert_eq!(steps(&app), before + 1, "the click filled the layer inside the group"); + let [r, g, b, a] = pixel(&app).unwrap(); + assert!(a > 0.99 && r < 0.01 && g < 0.01 && b < 0.01, "filled black: {:?}", [r, g, b, a]); +} + +#[test] +fn a_group_s_targeted_mask_takes_a_step_that_fills_nothing() { + // Not measured: keeps today's behaviour as a whole. Measured on `main` before and after this + // change: the click opens no alert (the alert path only speaks for pixel targets), the engine + // adds one "Paint Bucket" state, and its command answers `filled: true` while leaving the + // all-white mask's samples as they are - all pinned here, so the name says exactly what today + // is: a step, and no fill. + let mut app = app(Tool::PaintBucket); + app.run("layer.new.group", json!({})).unwrap(); + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + app.ui.mask_target = true; + app.sync_mask_targets(); + assert_eq!(crate::canvas::paint_target(&app), json!("mask"), "the group's mask is targeted"); + let before = steps(&app); + click(&mut app); + assert!(alerts(&app).is_empty(), "no refusal alert on a mask target: {:?}", alerts(&app)); + assert_eq!(steps(&app), before + 1, "the engine's own step lands as today"); + let labels = app.run("document.inspect", json!({})).unwrap()["history"].as_array().cloned().unwrap_or_default(); + assert_eq!(labels.last(), Some(&json!("Paint Bucket")), "the step the click added carries the engine's own label"); + // The command's own answer, pinned once through the engine: it claims a fill and writes nothing. + let reply = app.run("paint.bucket", json!({"x": 30, "y": 30, "target": "mask"})).unwrap(); + assert_eq!(reply["filled"], json!(true), "the engine reports filled: true, as on main"); + assert_eq!(steps(&app), before + 2, "and that call adds its step too"); + let st = app.session.active().unwrap(); + let mask = st.doc.layer(st.active_layer.unwrap()).unwrap().mask.as_ref().unwrap(); + for (x, y) in [(30, 30), (2, 2), (61, 61)] { + assert_eq!(mask.surface.sample_channel(x, y, 0), 1.0, "the mask samples stay white at ({x}, {y}) as on main"); + } +} + +#[test] +fn the_brush_alerts_stay_as_they_are_and_the_other_tools_stay_quiet() { + // The Brush (#11898): Lock all only, never Lock Image Pixels. + let mut brush = app(Tool::Brush); + brush.run("layer.lockLayers", json!({"all": true})).unwrap(); + stroke(&mut brush); + assert_eq!(alerts(&brush), ["Could not use the brush tool because the layer is locked."], "the Brush's Lock all alert is unchanged"); + let mut brush = app(Tool::Brush); + brush.run("layer.lockLayers", json!({"pixels": true})).unwrap(); + stroke(&mut brush); + assert!(alerts(&brush).is_empty(), "the Brush keeps no alert for Lock Image Pixels: {:?}", alerts(&brush)); + // The Dodge tool has no layer alerts: a hidden target stays in the status bar. + let mut dodge = app(Tool::Dodge); + let id = active(&dodge); + dodge.run("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + stroke(&mut dodge); + assert!(alerts(&dodge).is_empty()); + assert_eq!(dodge.ui.status, photocraft_engine::hidden_target::HIDDEN); +} diff --git a/crates/ui-egui/src/panels/channels_panel.rs b/crates/ui-egui/src/panels/channels_panel.rs index 2d4dc86584..356abab352 100644 --- a/crates/ui-egui/src/panels/channels_panel.rs +++ b/crates/ui-egui/src/panels/channels_panel.rs @@ -484,7 +484,7 @@ pub(crate) fn run_fired(app: &mut PhotocraftApp, ctx: &egui::Context, command: & } return true; } - let mods = craft::ui::runtime::pointer::frame(ctx).mods; + let mods = craft::ui::runtime::pointer::mods(ctx); if let Some(event) = command.event(&rows(app), mods) { apply(app, ctx, event); } diff --git a/crates/ui-egui/src/panels/color_hud.rs b/crates/ui-egui/src/panels/color_hud.rs index 11a3b3b490..81f9013939 100644 --- a/crates/ui-egui/src/panels/color_hud.rs +++ b/crates/ui-egui/src/panels/color_hud.rs @@ -125,7 +125,7 @@ mod tests { if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { return; } - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); }, app, ); diff --git a/crates/ui-egui/src/panels/color_panel_ui.rs b/crates/ui-egui/src/panels/color_panel_ui.rs index dc1b08d934..e854766d01 100644 --- a/crates/ui-egui/src/panels/color_panel_ui.rs +++ b/crates/ui-egui/src/panels/color_panel_ui.rs @@ -15,7 +15,7 @@ pub fn persist(app: &mut PhotocraftApp) { } let Ok(now) = serde_json::to_value(app.ui.color_panel) else { return }; if stored != now { - app.session.prefs.edit(|p| p.color_panel = now.clone()); + app.session.prefs.remember(|p| p.color_panel = now.clone()); } app.ui.color_panel_synced = Some(now); } diff --git a/crates/ui-egui/src/panels/layer_reveal.rs b/crates/ui-egui/src/panels/layer_reveal.rs index fddbd6cc8a..284f495a3e 100644 --- a/crates/ui-egui/src/panels/layer_reveal.rs +++ b/crates/ui-egui/src/panels/layer_reveal.rs @@ -6,7 +6,7 @@ //! //! The command dispatch takes a [`mark`] before a command and calls [`file`] after it; when the //! active layer moved, the reveal waits in `PhotocraftApp::pending_reveal` until the panel next -//! draws and [`take`]s it, so a hidden panel reveals the layer when it is shown again. +//! draws and applies it, so a hidden panel reveals the layer when it is shown again. //! //! Only a change of the active layer reveals: closing the group that holds it, or scrolling //! away, is left alone until the next change. @@ -50,9 +50,9 @@ pub(crate) fn file(app: &mut PhotocraftApp, before: Mark) { app.pending_reveal = Some((id, groups)); } -/// The pending reveal, for the Layers panel's draw: the layer and what its closed parent groups -/// do. The first pass of a frame takes it, so a second pass in the same frame reveals nothing -/// again. +/// The pending reveal: the layer and what its closed parent groups do. The Layers panel takes it +/// once its real run applied it (`LayersOutput::requests_taken`), so a measuring run or a later +/// pass of the same frame reveals nothing again. pub(crate) fn take(app: &mut PhotocraftApp) -> Option<(LayerId, Groups)> { app.pending_reveal.take() } diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 9ec0163369..59a627b4c0 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -23,7 +23,7 @@ pub(super) fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) { use super::layers_tree::{self, PhotoThumbs}; // A Move-way pick of a layer opens its groups only when the Move option says so (#11381). - let reveal = crate::layer_reveal::take(app); + let reveal = app.pending_reveal; let ctx = ui.ctx().clone(); // Thumbnail Contents is the clip preference alone, so the panel reads it each pass. app.ui.layers_settings.options.thumbnail_contents = crate::layers_panel_ui::thumbnail_contents(app); @@ -62,8 +62,11 @@ pub(super) fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) { panel = panel.start_rename(id); } let out = panel.show(ui); - app.find_layers_focus = false; - app.layers_rename = None; + if out.requests_taken { + crate::layer_reveal::take(app); + app.find_layers_focus = false; + app.layers_rename = None; + } if filter != before { app.ui.layer_filter = filter; } diff --git a/crates/ui-egui/src/panels/layers_events.rs b/crates/ui-egui/src/panels/layers_events.rs index 36344f5f94..8d38e64b10 100644 --- a/crates/ui-egui/src/panels/layers_events.rs +++ b/crates/ui-egui/src/panels/layers_events.rs @@ -324,6 +324,14 @@ fn target_on_click(app: &mut PhotocraftApp, l: &Layer, was_active: bool, part: O return; } match part { + // A second click on the targeted vector mask un-targets it: the pixels take the target and + // Paths drops the mask's path (#16783). The layer mask stays targeted instead. + Some(LayerPart::VectorMask) if was_active && app.ui.vector_mask_target => { + if app.ui.selected_path.as_deref() == Some("layer") { + app.ui.selected_path = None; + } + actions.push(("ui.vectorMaskTarget".into(), json!(false))); + } Some(LayerPart::VectorMask) => { app.ui.selected_path = Some("layer".into()); actions.push(("ui.vectorMaskTarget".into(), json!(true))); @@ -371,7 +379,11 @@ fn activate( let command = match on { ActivateOn::Thumbnail(LayerPart::LayerMask | LayerPart::VectorMask) => { let kind = if on == ActivateOn::Thumbnail(LayerPart::VectorMask) { MaskKind::Vector } else { MaskKind::Pixel }; - actions.push((if kind == MaskKind::Vector { "ui.vectorMaskTarget" } else { "ui.maskTarget" }.into(), json!(true))); + // A plain double click's first click has already targeted the vector mask, or un-targeted the + // targeted one, which this leaves as it is (#16783). + if kind == MaskKind::Pixel || !ctx.input(|i| i.modifiers.is_none()) { + actions.push((if kind == MaskKind::Vector { "ui.vectorMaskTarget" } else { "ui.maskTarget" }.into(), json!(true))); + } match crate::mask_thumbs_ui::double_click_command(app, kind) { Some((cmd, val)) => actions.push((cmd.into(), val)), None => actions.push(("ui.properties".into(), json!(true))), @@ -566,6 +578,8 @@ fn menu_pick(app: &mut PhotocraftApp, ctx: &egui::Context, row: &Option Vec> { + let size = |s: ThumbSize| format!("{THUMB_SIZE}{}", crate::layers_panel_ui::size_key(s)); + vec![ + Some(BLEND.into()), + Some(EDIT_ADJ.into()), + None, + Some(SELECT_PIXELS.into()), + None, + Some(format!("{LOAD_PIXELS}add")), + Some(format!("{LOAD_PIXELS}subtract")), + Some(format!("{LOAD_PIXELS}intersect")), + None, + Some(size(ThumbSize::None)), + Some(size(ThumbSize::Small)), + Some(size(ThumbSize::Medium)), + Some(size(ThumbSize::Large)), + None, + Some(format!("{CLIP_THUMBS}true")), + Some(format!("{CLIP_THUMBS}false")), + ] +} + +/// The expected pins: every item enabled except `greyed`. +fn want(greyed: &[&str]) -> Vec { + plan() + .into_iter() + .map(|e| match e { + None => SEP.to_string(), + Some(v) => format!("{}{}", if greyed.contains(&v.as_str()) { "!" } else { "=" }, v), + }) + .collect() +} + +/// One pin per entry: `"―"` for a separator, else `=`/`!` (enabled or greyed) and the entry value. +fn pins(menu: &[Entry]) -> Vec { + menu.iter() + .map( + |e| { + if e.is_separator() { SEP.to_string() } else { format!("{}{}", if e.is_enabled() { "=" } else { "!" }, e.value().cloned().unwrap_or_default()) } + }, + ) + .collect() +} + +struct Kinds { + pixel: LayerId, + shape: LayerId, + smart: LayerId, + typed: LayerId, + adjust: LayerId, + group: LayerId, + frame: LayerId, + artboard: LayerId, + background: LayerId, +} + +/// A 60 x 40 document with one layer of every kind on top of a white Background. +fn kinds() -> (Box, Kinds) { + let mut app = PhotocraftApp::new(Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 60, "height": 40, "background": "white"})).unwrap(); + let background = app.session.active().unwrap().doc.layers.first().unwrap().id; + let created = |app: &mut PhotocraftApp| app.session.active().unwrap().active_layer.unwrap(); + app.run("layer.new.layer", json!({"name": "Pix"})).unwrap(); + let pixel = created(&mut app); + app.run("select.rect", json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.run("shape.create", json!({"kind": "rect", "rect": [30, 4, 12, 8], "fill": "#00ff00"})).unwrap(); + let shape = created(&mut app); + app.run("type.create", json!({"x": 6, "y": 28, "text": "Hi", "size": 10})).unwrap(); + let typed = created(&mut app); + app.run("layer.new.layer", json!({"name": "Smart"})).unwrap(); + app.run("select.rect", json!({"x": 44, "y": 20, "width": 10, "height": 8})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": "#0000ff"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.run("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let smart = created(&mut app); + app.run("layer.newAdjustmentLayer.levels", json!({})).unwrap(); + let adjust = created(&mut app); + // The new groups and the frame go in with the pixel layer active: with a group, artboard or + // frame active, `layer.new.group` and `layer.new.frame` land inside it instead of at top level. + activate(&mut app, pixel); + app.run("layer.new.group", json!({"name": "G"})).unwrap(); + let group = created(&mut app); + activate(&mut app, pixel); + app.run("layer.new.group", json!({"name": "AB"})).unwrap(); + let artboard = created(&mut app); + app.run("layer.new.artboardFromGroup", json!({"layer": artboard.0})).unwrap(); + activate(&mut app, pixel); + app.run("layer.new.frame", json!({"x": 4, "y": 4, "width": 40, "height": 30})).unwrap(); + let frame = created(&mut app); + (app, Kinds { pixel, shape, smart, typed, adjust, group, frame, artboard, background }) +} + +fn activate(app: &mut PhotocraftApp, id: LayerId) { + app.run("layer.select", json!({"layer": id.0, "mode": "replace"})).unwrap(); +} + +/// The menu a right-click on `id`'s thumbnail builds for the panel. +fn thumb_menu(app: &PhotocraftApp, id: LayerId) -> Vec> { + let st = app.session.active().unwrap(); + let tree = PhotoLayers::new(app, st, &Default::default(), false, None); + let mut target = MenuTarget::new(Some(LayerRowKey::Layer(id))); + target.part = Some(LayerPart::Pixels); + row_menu(app, &tree, &target) +} + +fn enabled_of(menu: &[Entry], value: &str) -> bool { + menu.iter().find(|e| e.value().is_some_and(|v| v == value)).is_some_and(|e| e.is_enabled()) +} + +/// A pixel layer's thumbnail menu, without a document selection: the full list, Edit Adjustment… +/// and the three Transparency Mask rows greyed, and the new rows carry their measured labels. +#[test] +fn a_pixel_thumbnail_lists_the_full_menu_and_greys_the_mask_rows_without_a_selection() { + let (mut app, k) = kinds(); + activate(&mut app, k.pixel); + let menu = thumb_menu(&app, k.pixel); + assert_eq!(pins(&menu), want(&[EDIT_ADJ, &format!("{LOAD_PIXELS}add"), &format!("{LOAD_PIXELS}subtract"), &format!("{LOAD_PIXELS}intersect")])); + let label = |value: &str| menu.iter().find(|e| e.value().is_some_and(|v| v == value)).map(|e| e.label().as_str().to_string()).expect("entry shown"); + assert_eq!(label(BLEND), "Blending Options…"); + assert_eq!(label(EDIT_ADJ), "Edit Adjustment…"); + for (op, text) in [("add", "Add Transparency Mask"), ("subtract", "Subtract Transparency Mask"), ("intersect", "Intersect Transparency Mask")] { + assert_eq!(label(&format!("{LOAD_PIXELS}{op}")), text, "{op}"); + } +} + +/// With a selection, only Edit Adjustment… stays greyed; the three Transparency Mask rows come live. +#[test] +fn a_selection_only_greys_edit_adjustment_on_a_pixel_thumbnail() { + let (mut app, k) = kinds(); + activate(&mut app, k.pixel); + app.run("select.rect", json!({"x": 20, "y": 20, "width": 10, "height": 10})).unwrap(); + let menu = thumb_menu(&app, k.pixel); + assert_eq!(pins(&menu), want(&[EDIT_ADJ])); +} + +/// Shape, smart object, type, adjustment, group and Background thumbnails open the same list, +/// in the same order, as the pixel layer's thumbnail. +#[test] +fn every_measured_kind_gets_the_same_thumbnail_menu_list() { + let (mut app, k) = kinds(); + let values: Vec = plan().into_iter().flatten().collect(); + for (case, id) in + [("shape", k.shape), ("smart object", k.smart), ("type", k.typed), ("adjustment", k.adjust), ("group", k.group), ("Background", k.background)] + { + activate(&mut app, id); + let got: Vec = thumb_menu(&app, id).into_iter().filter_map(|e| e.value().cloned()).collect(); + assert_eq!(got, values, "{case}"); + } +} + +/// The greyed states follow the measured table for every kind and both selection states. +#[test] +fn the_greyed_states_follow_the_measured_table() { + let (mut app, k) = kinds(); + let ops: Vec = ["add", "subtract", "intersect"].iter().map(|op| format!("{LOAD_PIXELS}{op}")).collect(); + let size = |s: ThumbSize| format!("{THUMB_SIZE}{}", crate::layers_panel_ui::size_key(s)); + + // Pixel, no selection: Edit Adjustment… and the three mask rows greyed, the rest live. + activate(&mut app, k.pixel); + let m = thumb_menu(&app, k.pixel); + assert!(enabled_of(&m, BLEND) && enabled_of(&m, SELECT_PIXELS)); + assert!(!enabled_of(&m, EDIT_ADJ)); + for op in &ops { + assert!(!enabled_of(&m, op), "pixel without a selection greys {op}"); + } + + // Adjustment layer, no selection: Edit Adjustment… is the only live new row among these. + activate(&mut app, k.adjust); + let m = thumb_menu(&app, k.adjust); + assert!(enabled_of(&m, BLEND) && enabled_of(&m, SELECT_PIXELS) && enabled_of(&m, EDIT_ADJ)); + for op in &ops { + assert!(!enabled_of(&m, op), "adjustment without a selection greys {op}"); + } + + // Group: Edit Adjustment…, Select Pixels and the three mask rows greyed; Blending Options… live. + activate(&mut app, k.group); + let m = thumb_menu(&app, k.group); + assert!(enabled_of(&m, BLEND)); + assert!(!enabled_of(&m, EDIT_ADJ) && !enabled_of(&m, SELECT_PIXELS)); + for op in &ops { + assert!(!enabled_of(&m, op), "a group greys {op}"); + } + + // Background, even with a selection: everything except the four sizes and the two clip rows. + activate(&mut app, k.background); + app.run("select.rect", json!({"x": 20, "y": 20, "width": 10, "height": 10})).unwrap(); + let m = thumb_menu(&app, k.background); + assert!(!enabled_of(&m, BLEND), "Background greys Blending Options…"); + assert!(!enabled_of(&m, EDIT_ADJ) && !enabled_of(&m, SELECT_PIXELS)); + for op in &ops { + assert!(!enabled_of(&m, op), "Background greys {op}"); + } + for s in [ThumbSize::None, ThumbSize::Small, ThumbSize::Medium, ThumbSize::Large] { + assert!(enabled_of(&m, &size(s)), "Background keeps the {s:?} size row live"); + } + assert!(enabled_of(&m, &format!("{CLIP_THUMBS}true")) && enabled_of(&m, &format!("{CLIP_THUMBS}false")), "Background keeps the clip rows live"); +} + +/// Picking a Transparency Mask row runs `select.loadSelection` on the clicked layer's transparency: +/// the intersect leaves the layer's pixels, subtracting them again empties the selection, and a far +/// rectangle survives an add/subtract pair of the same layer. +#[test] +fn picking_the_transparency_rows_loads_the_layers_pixels() { + let (mut app, k) = kinds(); + let ctx = app.ctx().clone(); + activate(&mut app, k.pixel); + let target = MenuTarget::new(Some(LayerRowKey::Layer(k.pixel))); + let pick = |app: &mut PhotocraftApp, op: &str| { + apply_layers_events(app, &ctx, vec![LayersEvent::menu(target.clone(), format!("{LOAD_PIXELS}{op}"))]); + }; + + app.run("select.all", json!({})).unwrap(); + let steps = app.session.active().unwrap().history.past_len(); + pick(&mut app, "intersect"); + assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1, "one history step"); + assert!(app.session.active().unwrap().doc.selection.is_some(), "the intersect leaves the layer's pixels"); + pick(&mut app, "subtract"); + assert_eq!(app.session.active().unwrap().history.past_len(), steps + 2, "one history step each"); + assert!(app.session.active().unwrap().doc.selection.is_none(), "subtracting the same pixels leaves nothing"); + + app.run("select.rect", json!({"x": 30, "y": 30, "width": 10, "height": 5})).unwrap(); + pick(&mut app, "add"); + pick(&mut app, "subtract"); + assert!(app.session.active().unwrap().doc.selection.is_some(), "the far rectangle survives an add/subtract pair"); +} + +/// Frames and artboards were not measured and keep today's full layer menu, as does the name area. +#[test] +fn frames_artboards_and_the_name_area_keep_the_full_layer_menu() { + let (mut app, k) = kinds(); + for (case, id, part) in [("frame", k.frame, Some(LayerPart::Pixels)), ("artboard", k.artboard, Some(LayerPart::Pixels)), ("name area", k.pixel, None)] { + activate(&mut app, id); + let menu = { + let st = app.session.active().unwrap(); + let tree = PhotoLayers::new(&app, st, &Default::default(), false, None); + let mut target = MenuTarget::new(Some(LayerRowKey::Layer(id))); + target.part = part; + row_menu(&app, &tree, &target) + }; + let values: Vec = menu.into_iter().filter_map(|e| e.value().cloned()).collect(); + assert!(values.iter().any(|v| v == "layer.duplicate"), "{case}: the full layer menu"); + assert!(!values.iter().any(|v| v.starts_with(LOAD_PIXELS)), "{case}: no thumbnail mask rows"); + } +} + +/// The menu is built from the clicked row: a thumbnail press on a layer the panel has not made +/// active yet still lists that layer's thumbnail menu (its kind decides the list, not the active +/// layer's; the engine enablement behind two greyed flags is read from the session as in today's +/// row menus). +#[test] +fn the_menu_of_a_row_that_is_not_active_still_lists_the_clicked_layer() { + let (mut app, k) = kinds(); + activate(&mut app, k.pixel); + let got: Vec = thumb_menu(&app, k.adjust).into_iter().filter_map(|e| e.value().cloned()).collect(); + assert_eq!(got, plan().into_iter().flatten().collect::>(), "the adjustment's own list, not the active pixel layer's"); +} + +/// The size and clip rows still follow the panel's current settings: only the current size is +/// checked, and the clip row matching the preference. +#[test] +fn the_size_and_clip_rows_follow_the_current_settings() { + let (app, k) = kinds(); + let menu = thumb_menu(&app, k.pixel); + let current = app.ui.layers_settings.options.thumbnail_size; + for s in [ThumbSize::None, ThumbSize::Small, ThumbSize::Medium, ThumbSize::Large] { + let v = format!("{THUMB_SIZE}{}", crate::layers_panel_ui::size_key(s)); + let entry = menu.iter().find(|e| e.value().is_some_and(|x| *x == v)).expect("the size row is shown"); + assert_eq!(entry.is_checked(), current == s, "only the current size is checked ({s:?})"); + } + let clip = app.session.prefs().interface.clip_thumbnails_to_layer_bounds; + for to_layer in [true, false] { + let v = format!("{CLIP_THUMBS}{to_layer}"); + let entry = menu.iter().find(|e| e.value().is_some_and(|x| *x == v)).expect("the clip row is shown"); + assert_eq!(entry.is_checked(), clip == to_layer, "the clip row matching the preference is checked"); + } +} + +/// The thumbnail menu ends with the row's Color submenu, like the row menu. +#[test] +fn the_thumbnail_menu_offers_the_rows_colour_submenu() { + let (app, k) = kinds(); + let st = app.session.active().unwrap(); + let tree = PhotoLayers::new(&app, st, &Default::default(), false, None); + let mut target = MenuTarget::new(Some(LayerRowKey::Layer(k.pixel))); + target.part = Some(LayerPart::Pixels); + assert!(tree.label_colors_in_menu(&target), "the thumbnail menu carries the colour submenu"); + let empty = MenuTarget::new(None); + assert!(!tree.label_colors_in_menu(&empty), "the empty-space menu does not"); +} + +/// The issue lists a hidden, locked or clipped row as not measured and keeps it on today's menu +/// (#16777): the pixel layer, which had the short menu in every state, keeps it, and a layer of any +/// other kind keeps the full layer menu its measured twin no longer gets. +#[test] +fn a_hidden_locked_or_clipped_row_keeps_todays_menu() { + let (mut app, k) = kinds(); + let set = |app: &mut PhotocraftApp, id: LayerId, key: &str, on: bool| app.run("layer.setProps", json!({"layer": id.0, key: on})).unwrap(); + // `state` is the value that puts the row into the unmeasured state, `plain` the value it had before. + for (key, state, plain, case) in [("visible", false, true, "hidden"), ("locked", true, false, "locked"), ("clipped", true, false, "clipped")] { + for (kind, id) in [("pixel", k.pixel), ("shape", k.shape)] { + set(&mut app, id, key, state); + let values: Vec = thumb_menu(&app, id).into_iter().filter_map(|e| e.value().cloned()).collect(); + let short = values.iter().any(|v| v.starts_with(LOAD_PIXELS)); + let full = values.iter().any(|v| v == "layer.duplicate"); + assert_eq!((short, full), (kind == "pixel", kind != "pixel"), "a {case} {kind} thumbnail keeps today's menu"); + set(&mut app, id, key, plain); + } + } +} + +/// The measured Background row carries the Background's own transparency and position locks, and +/// those are the only locks its exemption covers. A lock it does not carry by itself - all or +/// artboard - is the locked state the issue lists as not measured, so that row keeps the full layer +/// menu it had before. Locking the pixels is no such case: that clears the transparency lock, and +/// the layer stops being a Background. +#[test] +fn a_background_with_an_extra_lock_keeps_todays_layer_menu() { + let (mut app, k) = kinds(); + let shown = |app: &PhotocraftApp| -> (bool, bool) { + let values: Vec = thumb_menu(app, k.background).into_iter().filter_map(|e| e.value().cloned()).collect(); + (values.iter().any(|v| v.starts_with(LOAD_PIXELS)), values.iter().any(|v| v == "layer.duplicate")) + }; + let own_locks = photocraft_doc::Locks { transparency: true, position: true, ..Default::default() }; + assert_eq!(shown(&app), (true, false), "the Background with its own locks opens the short menu"); + for key in ["all", "artboard"] { + app.run("layer.setProps", json!({"layer": k.background.0, "locks": {key: true}})).unwrap(); + assert!(app.session.active().unwrap().doc.is_background(k.background), "the {key} lock leaves the row a Background"); + assert_eq!(shown(&app), (false, true), "a Background with the {key} lock keeps today's full layer menu"); + app.run("layer.setProps", json!({"layer": k.background.0, "locks": {key: false}})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.layers.first().unwrap().locks, own_locks, "only the Background's own locks are left after the {key} case"); + assert_eq!(shown(&app), (true, false), "the Background is back on the short menu with the {key} lock off"); + } +} diff --git a/crates/ui-egui/src/panels/layers_tree.rs b/crates/ui-egui/src/panels/layers_tree.rs index 7e2d6c7afa..1b30713394 100644 --- a/crates/ui-egui/src/panels/layers_tree.rs +++ b/crates/ui-egui/src/panels/layers_tree.rs @@ -555,7 +555,7 @@ impl LayerTree for PhotoLayers { } fn label_colors_in_menu(&self, target: &MenuTarget) -> bool { - matches!(menu_kind(self, target), MenuKind::Layer(_)) + matches!(menu_kind(self, target), MenuKind::Layer(_) | MenuKind::Thumbnail(_)) } fn hovered(&self) -> Option { @@ -567,8 +567,8 @@ impl LayerTree for PhotoLayers { enum MenuKind { /// The empty space: thumbnail size and clipping. Empty, - /// A pixel layer's thumbnail: Select Pixels, then thumbnail size and clipping. - Thumbnail, + /// A layer thumbnail's short menu: blending, the transparency loads, size and clipping. + Thumbnail(LayerId), /// A layer mask's thumbnail. Mask(LayerId), /// An effects row. @@ -585,12 +585,19 @@ fn menu_kind(tree: &PhotoLayers, target: &MenuTarget) -> MenuKind { Some(LayerRowKey::Effects(..)) => MenuKind::Effects, Some(LayerRowKey::Layer(id)) => { let Some(l) = tree.layer(id) else { return MenuKind::None }; + // #16777 measured visible, unlocked, unclipped rows and left every other state on today's + // menu: the short one only where a pixel layer already had it. A Background's own + // transparency and position locks are measured - its row stands in the table - so only a + // lock the Background does not carry by itself counts as locked there. + let background = tree.doc().is_background(*id); + let unlocked = if background { !(l.locks.all || l.locks.pixels || l.locks.artboard) } else { !l.locks.any() }; + let measured_state = l.visible && !l.clipped && unlocked; + let short_menu_today = matches!(l.content, LayerContent::Raster(_)) && !background; match target.part { Some(LayerPart::LayerMask) if l.mask.is_some() => MenuKind::Mask(*id), - // A pixel layer's thumbnail; not the Background's, which has no transparency to load. - Some(LayerPart::Pixels) if matches!(l.content, LayerContent::Raster(_)) && l.frame.is_none() && !tree.doc().is_background(*id) => { - MenuKind::Thumbnail - } + // A thumbnail opens the short menu for every kind (#16777). Frames, artboards and the + // hidden, locked or clipped rows the issue did not measure keep today's menu. + Some(LayerPart::Pixels) if l.frame.is_none() && l.artboard().is_none() && (measured_state || short_menu_today) => MenuKind::Thumbnail(*id), Some(LayerPart::LayerMask | LayerPart::VectorMask | LayerPart::FilterMask) => MenuKind::None, _ => MenuKind::Layer(*id), } @@ -614,12 +621,13 @@ pub(crate) const RENAME: &str = "layersPanel:rename"; pub(crate) const THUMB_SIZE: &str = "layersPanel:thumbs:"; pub(crate) const CLIP_THUMBS: &str = "layersPanel:clip:"; pub(crate) const SELECT_PIXELS: &str = "layersPanel:selectPixels"; +pub(crate) const LOAD_PIXELS: &str = "layersPanel:loadPixels:"; pub(crate) const LOAD_MASK: &str = "layersPanel:loadMask:"; pub(crate) const MASK_REFINE: &str = "layersPanel:selectAndMask"; pub(crate) const MASK_OPTIONS: &str = "layersPanel:maskOptions"; /// The row menu at `target` as entries: the layer menu (Photoshop's order, trimmed to the kind), -/// a mask thumbnail's menu, a pixel thumbnail's, an effects row's, or the empty space's. +/// a mask thumbnail's menu, a layer thumbnail's, an effects row's, or the empty space's. pub(crate) fn row_menu(app: &PhotocraftApp, tree: &PhotoLayers, target: &MenuTarget) -> Vec> { let has_selection = tree.doc().selection.is_some(); let commands = |entries: Vec, on_set: bool| -> Vec> { @@ -663,8 +671,29 @@ pub(crate) fn row_menu(app: &PhotocraftApp, tree: &PhotoLayers, target: &MenuTar thumbnail_items(&mut out); out } - MenuKind::Thumbnail => { - let mut out = vec![Entry::new(SELECT_PIXELS.to_string(), tl!("Select Pixels").to_string()), Entry::separator()]; + MenuKind::Thumbnail(id) => { + let Some(l) = tree.layer(&id) else { return Vec::new() }; + // Measured greyed states: no selection greys the three Transparency Mask rows; Edit Adjustment… is + // live only on an adjustment layer; a group also greys Select Pixels; the Background greys + // everything but the size and clip rows (#16777). + let background = tree.doc().is_background(id); + let group = l.is_group(); + let mask_rows_live = has_selection && !background && !group; + let mut out = vec![ + Entry::new("layer.layerStyle.blendingOptions".to_string(), tl!("Blending Options…").to_string()) + .enabled(!background && crate::menus::is_enabled(app, "layer.layerStyle.blendingOptions")), + Entry::new("layer.layerContentOptions".to_string(), tl!("Edit Adjustment…").to_string()) + .enabled(matches!(l.content, LayerContent::Adjustment(_)) && crate::menus::is_enabled(app, "layer.layerContentOptions")), + Entry::separator(), + Entry::new(SELECT_PIXELS.to_string(), tl!("Select Pixels").to_string()).enabled(!background && !group), + Entry::separator(), + ]; + for (label, op) in + [(tl!("Add Transparency Mask"), "add"), (tl!("Subtract Transparency Mask"), "subtract"), (tl!("Intersect Transparency Mask"), "intersect")] + { + out.push(Entry::new(format!("{LOAD_PIXELS}{op}"), label.to_string()).enabled(mask_rows_live)); + } + out.push(Entry::separator()); thumbnail_items(&mut out); out } @@ -813,3 +842,7 @@ pub(crate) fn select_pixels(layer: LayerId) -> Value { #[cfg(test)] #[path = "indexed_background_name_tests.rs"] mod indexed_background_name_tests; + +#[cfg(test)] +#[path = "layers_thumbnail_menu_tests.rs"] +mod layers_thumbnail_menu_tests; diff --git a/crates/ui-egui/src/panels/layers_vector_mask_click_tests.rs b/crates/ui-egui/src/panels/layers_vector_mask_click_tests.rs new file mode 100644 index 0000000000..2d09ac1c41 --- /dev/null +++ b/crates/ui-egui/src/panels/layers_vector_mask_click_tests.rs @@ -0,0 +1,87 @@ +//! #16783: a second click on the targeted vector mask thumbnail un-targets it, while the layer mask +//! stays targeted. Each click is a `LayersEvent::Select` sent through `apply_layers_events`, as the +//! panel reports it. + +use craft::behavior::SelectionChange; +use craft::layers::ui::panel::{ActivateOn, LayerSelect, LayersEvent}; +use craft::layers::ui::tree::{LayerPart, LayerRowKey}; +use photocraft_doc::LayerId; +use serde_json::json; + +use super::apply_layers_events; +use super::tests::session; +use crate::PhotocraftApp; + +fn app_of(s: photocraft_engine::Session) -> Box { + let mut app = PhotocraftApp::new(s, crate::Services::default()); + app.background_jobs = false; + app.sync_views(); + app +} + +fn click(app: &mut PhotocraftApp, layer: u64, part: LayerPart) { + let ctx = app.ctx().clone(); + let event = LayersEvent::Select(LayerSelect::new(SelectionChange::Set(vec![LayerId(layer)]), Some(part))); + apply_layers_events(app, &ctx, vec![event]); +} + +/// A double click as the panel reports it: the first click selects, the second only activates. +fn double_click(app: &mut PhotocraftApp, layer: u64, part: LayerPart) { + click(app, layer, part); + let ctx = app.ctx().clone(); + apply_layers_events(app, &ctx, vec![LayersEvent::activate(LayerRowKey::Layer(LayerId(layer)), ActivateOn::Thumbnail(part))]); +} + +fn vector_mask_targeted(app: &PhotocraftApp) -> bool { + app.ui.vector_mask_target && !app.ui.mask_target && app.ui.selected_path.as_deref() == Some("layer") +} + +#[test] +fn a_second_click_on_the_targeted_vector_mask_untargets_it() { + let (s, masked, _) = session(); + let mut app = app_of(s); + click(&mut app, masked, LayerPart::VectorMask); + assert!(vector_mask_targeted(&app)); + click(&mut app, masked, LayerPart::VectorMask); + assert!(!app.ui.vector_mask_target && !app.ui.mask_target, "the layer's pixels are the target"); + assert_eq!(app.ui.selected_path, None, "Paths no longer selects the mask's path"); + assert_eq!(crate::canvas::paint_target(&app), json!("pixels")); + assert_eq!(app.session.active().unwrap().active_layer, Some(LayerId(masked)), "the layer stays active"); + click(&mut app, masked, LayerPart::VectorMask); + assert!(vector_mask_targeted(&app), "a third click targets it again"); +} + +#[test] +fn a_double_click_toggles_the_vector_mask_target_with_its_first_click() { + let (s, masked, _) = session(); + let mut app = app_of(s); + double_click(&mut app, masked, LayerPart::VectorMask); + assert!(vector_mask_targeted(&app), "on an untargeted vector mask, the double click targets it"); + double_click(&mut app, masked, LayerPart::VectorMask); + assert!(!app.ui.vector_mask_target && !app.ui.mask_target, "on the targeted one, its first click un-targets it"); + assert_eq!(app.ui.selected_path, None); +} + +#[test] +fn a_second_click_on_the_targeted_layer_mask_keeps_it_targeted() { + let (s, masked, _) = session(); + let mut app = app_of(s); + click(&mut app, masked, LayerPart::LayerMask); + click(&mut app, masked, LayerPart::LayerMask); + assert!(app.ui.mask_target && !app.ui.vector_mask_target); + assert_eq!(crate::canvas::paint_target(&app), json!("mask")); +} + +#[test] +fn the_vector_mask_of_another_layer_is_targeted_while_one_is_targeted() { + let (mut s, masked, _) = session(); + let other = s.execute("layer.new.layer", json!({"name": "Other"})).unwrap()["layer"].as_u64().unwrap(); + let path = json!({"subpaths": [{"knots": [[10, 10], [60, 10], [60, 60]]}]}); + s.execute("layer.vectorMask.add", json!({"layer": other, "path": path})).unwrap(); + s.execute("layer.select", json!({"layer": masked})).unwrap(); + let mut app = app_of(s); + click(&mut app, masked, LayerPart::VectorMask); + click(&mut app, other, LayerPart::VectorMask); + assert_eq!(app.session.active().unwrap().active_layer, Some(LayerId(other))); + assert!(vector_mask_targeted(&app), "the first click on another layer's vector mask targets it"); +} diff --git a/crates/ui-egui/src/panels/options_bar.rs b/crates/ui-egui/src/panels/options_bar.rs index 4fc4946020..a8491771de 100644 --- a/crates/ui-egui/src/panels/options_bar.rs +++ b/crates/ui-egui/src/panels/options_bar.rs @@ -6,9 +6,9 @@ use std::ops::RangeInclusive; use craft::behavior::{EditEvents, IconId, NumberCodec}; use craft::ui::bars::{Bar, BarHome, BarKind, BarOutput, BarTool}; -use craft::ui::buttons::ToggleButton; +use craft::ui::buttons::{IconButton, PopupMark, ToggleButton}; use craft::ui::choice::Checkbox; -use craft::ui::contract::{Bind, Entry, MemoProps, MemoView, Outbox, Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, Entry, MemoProps, MemoView, Outbox, PopupKind, Props as _, Show as _, ShowContainer as _, Trigger}; use craft::ui::display::Divider; use craft::ui::form::Field; use craft::ui::menu::Menu; @@ -100,15 +100,65 @@ pub(crate) fn edit_key(app: &PhotocraftApp) -> (Option, bool) { pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let tool = app.ui.tool; let ending = ending(app, tool); + // The bar's right end stays for every tool. It reads only copies of the app's state: the body holds the app. + let searching = app.ui.palette.open; + let workspaces = crate::workspace_ui::switcher_entries(&app.workspaces.set); + let mut ends = Vec::new(); let mut bar = Bar::new(tl!("Options").to_owned(), BarKind::Options); if let Some(ending) = &ending { bar = bar.commit_cancel(ending.commit.clone(), ending.cancel.clone()); } + bar = bar.trailing(|ui, _| right_end(ui, searching, &workspaces, &mut ends)); // A value control of the bar takes the wheel without a click, as the Mode dropdown and the fields did. let shown = bar.show(ui, |ui, _| with_env(ui, |set| set.wheel = Some(WheelScope::Free), |ui| body(app, ui))); if let Some(ending) = ending { answer(app, ui, tool, ending.end, &shown.output); } + // The bar may run its right end more than once in a pass (it measures it first); each request runs once. + for end in ends { + match end { + RightEnd::Search => run_menu_command(app, ui.ctx(), "edit.search"), + RightEnd::Workspace(pick) => run_menu_command(app, ui.ctx(), &pick.command()), + } + } +} + +/// What the bar's right end asked for this pass. +#[derive(Clone, Debug, PartialEq, Eq)] +enum RightEnd { + /// The Search button was clicked. + Search, + /// A row of the workspace switcher's menu was picked. + Workspace(crate::workspace_ui::SwitcherPick), +} + +/// The bar's right end: the Search button, which opens and closes the search Edit › Search opens, then the workspace +/// switcher, whose menu runs the Window › Workspace commands (`workspaces` are its rows). +fn right_end(ui: &mut egui::Ui, searching: bool, workspaces: &[Entry], ends: &mut Vec) { + let mut send = |end: RightEnd| { + if !ends.contains(&end) { + ends.push(end); + } + }; + let tip = tl!("Search for tools, help, and more"); + let search = IconButton::new(IconId::new("search")).label(tip.to_owned()).tooltip(tip).selected(searching).show(ui); + if search.clicked() { + send(RightEnd::Search); + } + // One button with its arrow: a press on either opens the menu. + let tip = tl!("Choose a Workspace"); + let switcher = IconButton::new(IconId::new("app_window")).label(tip.to_owned()).tooltip(tip).popup(PopupKind::Menu).popup_mark(PopupMark::Menu).show(ui); + if let Some(pick) = Menu::new(tip.to_owned()).opened_by(&switcher.response, Trigger::Press).pick(ui, workspaces).picked { + send(RightEnd::Workspace(pick)); + } +} + +/// Runs menu command `id` as its menu item does; a refusal shows in the status line. +fn run_menu_command(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str) { + if let Err(e) = crate::menus::invoke(app, ctx, id, json!({})) { + app.ui.status = e; + app.ui.status_error = true; + } } /// Runs the ending the bar's commit or cancel button asked for. @@ -361,8 +411,8 @@ pub(super) fn labelled(ui: &mut egui::Ui, label: &str, mut add: impl FnMut(&m } /// A check box named `label` over `value`. -pub(super) fn check(ui: &mut egui::Ui, label: &str, value: &mut bool) { - Checkbox::new(Bind::bound(value)).label(label.to_owned()).show(ui); +pub(super) fn check(ui: &mut egui::Ui, label: &str, value: Bind<'_, bool>) { + Checkbox::new(value).label(label.to_owned()).show(ui); } /// A number field named `label` over `value` (in `unit` when it is not empty), limited to `range`. The events of this @@ -437,3 +487,11 @@ mod art_history_bar_controls_tests; #[cfg(test)] #[path = "../healing_mode_menu_tests.rs"] mod healing_mode_menu_tests; + +#[cfg(test)] +#[path = "../options_bar_search_button_tests.rs"] +mod options_bar_search_button_tests; + +#[cfg(test)] +#[path = "../options_bar_workspace_switcher_tests.rs"] +mod options_bar_workspace_switcher_tests; diff --git a/crates/ui-egui/src/panels/options_bar/fill.rs b/crates/ui-egui/src/panels/options_bar/fill.rs index dffe5fb1f1..4bae6f8d9e 100644 --- a/crates/ui-egui/src/panels/options_bar/fill.rs +++ b/crates/ui-egui/src/panels/options_bar/fill.rs @@ -1,14 +1,16 @@ //! The Paint Bucket's members of the options bar, and the Mode list of the Paint Bucket and the stamp tools. -use craft::ui::contract::{Bind, Entry, Show as _}; +use craft::ui::choice::Checkbox; +use craft::ui::contract::{Bind, Entry, Props as _, Show as _, bind_tracked}; use craft::ui::patterns::blend_keys::{BlendKeyEntry, blend_entries}; use craft::ui::pickers::Select; use photocraft_doc::BlendMode; +use super::labelled; use super::paint::PaintMode; -use super::{check, labelled, number_field}; use crate::PhotocraftApp; use crate::state::Tool; +use crate::tools::option_cells::number; /// The text of a Mode entry. fn label_of(mode: PaintMode) -> String { @@ -80,34 +82,66 @@ pub(crate) fn mode_select<'a>(mode: Bind<'a, PaintMode>, entries: &'a [Entry o.bucket_clear = true, - PaintMode::Blend(blend) => { - o.bucket_clear = false; - o.bucket_blend_mode = blend; + // The Source dropdown stands alone, without a caption, as in the reference. + Select::new(tl!("Source").to_owned(), bind_tracked!(app.ui.tool_options => bucket_fill_pattern), &sources) + .tooltip(tl!("Set source for fill area").to_owned()) + .show(ui); + let o = &app.ui.tool_options; + let shown = if o.bucket_clear { PaintMode::Clear } else { PaintMode::Blend(o.bucket_blend_mode) }; + let mut mode = shown; + labelled(ui, tl!("Mode"), |ui| mode_select(Bind::bound(&mut mode), &entries).tooltip(tl!("Fill Mode").to_owned()).show(ui)); + if mode != shown { + let o = &mut app.ui.tool_options; + match mode { + PaintMode::Clear => o.bucket_clear = true, + PaintMode::Blend(blend) => { + o.bucket_clear = false; + o.bucket_blend_mode = blend; + } + PaintMode::Behind => {} + // Replace belongs to the Healing Brush's list, never the Paint Bucket's. + PaintMode::HealingReplace => {} } - PaintMode::Behind => {} - // Replace belongs to the Healing Brush's list, never the Paint Bucket's. - PaintMode::HealingReplace => {} } - if let Some(opacity) = number_field(ui, tl!("Opacity"), o.fill_opacity, 1.0..=100.0, "%").landed() { - o.fill_opacity = *opacity; + let opacity = number(tl!("Opacity"), bind_tracked!(app.ui.tool_options => fill_opacity), 1.0..=100.0) + .whole() + .unit("%") + .tooltip(tl!("Set opacity for fill")) + .show(ui) + .out_of_range; + let tolerance = number(tl!("Tolerance"), bind_tracked!(app.ui.tool_options => tolerance), 0.0..=255.0) + .whole_alerting_fractions() + .tooltip(tl!("Range of colors to fill")) + .show(ui); + let (anti_alias, contiguous, all_layers) = bind_tracked!(app.ui.tool_options => anti_alias, contiguous, sample_all.paint_bucket); + Checkbox::new(anti_alias).label(tl!("Anti-alias").to_owned()).tooltip(tl!("Smoothes edge transition").to_owned()).show(ui); + Checkbox::new(contiguous).label(tl!("Contiguous").to_owned()).tooltip(tl!("Fill only contiguous pixels").to_owned()).show(ui); + Checkbox::new(all_layers).label(tl!("All Layers").to_owned()).tooltip(tl!("Fill composite image").to_owned()).show(ui); + if opacity.is_some() { + let _ = crate::dialogs::alerts::alert(app, tl!(PAINT_BUCKET_OPACITY_ALERT)); + } else if let Some(alert) = tolerance.out_of_range { + // The framework words a whole-number field without a unit as the reference does: + // "An integer between 0 and 255 is required. Closest value inserted." + crate::tools::option_cells::range_alert(app, ui, &alert); + } else if tolerance.rounded { + let _ = crate::dialogs::alerts::alert(app, tl!(PAINT_BUCKET_TOLERANCE_ALERT)); } - if let Some(tolerance) = number_field(ui, tl!("Tolerance"), o.tolerance, 0.0..=255.0, "").landed() { - o.tolerance = *tolerance; - } - check(ui, tl!("Anti-alias"), &mut o.anti_alias); - check(ui, tl!("Contiguous"), &mut o.contiguous); - check(ui, tl!("All Layers"), &mut o.sample_all.paint_bucket); } diff --git a/crates/ui-egui/src/panels/options_bar/navigate.rs b/crates/ui-egui/src/panels/options_bar/navigate.rs index d05faa82cf..ee64c9e385 100644 --- a/crates/ui-egui/src/panels/options_bar/navigate.rs +++ b/crates/ui-egui/src/panels/options_bar/navigate.rs @@ -1,7 +1,7 @@ //! The options bar's members of the Move, Eyedropper, Zoom, Rotate View and Hand tools. use craft::ui::canvas::{NavigateBar, NavigationOptions}; -use craft::ui::contract::{Bind, Entry, Show as _}; +use craft::ui::contract::{Bind, Entry, Show as _, bind_tracked}; use craft::ui::display::Divider; use craft::ui::pickers::Select; @@ -21,12 +21,12 @@ pub(super) fn members(app: &mut PhotocraftApp, ui: &mut egui::Ui) { /// Auto-Select, its target, Show Transform Controls, then the align strip. fn move_members(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let o = &mut app.ui.tool_options; - check(ui, tl!("Auto-Select:"), &mut o.move_auto_select); + let (auto_select, target, transform) = bind_tracked!(app.ui.tool_options => move_auto_select, move_target, move_show_transform); + check(ui, tl!("Auto-Select:"), auto_select); let targets = [Entry::new("group".to_owned(), tl!("Group").to_owned()), Entry::new("layer".to_owned(), tl!("Layer").to_owned())]; - Select::new(tl!("Auto-Select:").to_owned(), Bind::bound(&mut o.move_target), &targets).show(ui); + Select::new(tl!("Auto-Select:").to_owned(), target, &targets).show(ui); Divider::vertical().show(ui); - check(ui, tl!("Show Transform Controls"), &mut o.move_show_transform); + check(ui, tl!("Show Transform Controls"), transform); Divider::vertical().show(ui); crate::align_bar::show(app, ui); } @@ -60,7 +60,9 @@ fn view_members(app: &mut PhotocraftApp, ui: &mut egui::Ui) { // Zoom Out is the bar's `out`; the tool keeps the direction as `zoom_in`. let mut out = !app.ui.tool_options.zoom_in; let shown = NavigateBar::zoom(Bind::bound(&mut view), target, &mut options, Bind::bound(&mut out)).show(ui); - app.ui.tool_options.zoom_in = !out; + if app.ui.tool_options.zoom_in == out { + app.ui.tool_options.zoom_in = !out; + } crate::chrome_ui::zoom_alert(app, shown.invalid_zoom); write_view(app, index, &view, !shown.view.is_empty()); } else { diff --git a/crates/ui-egui/src/panels/options_bar/paint.rs b/crates/ui-egui/src/panels/options_bar/paint.rs index 765873a3df..e423c91919 100644 --- a/crates/ui-egui/src/panels/options_bar/paint.rs +++ b/crates/ui-egui/src/panels/options_bar/paint.rs @@ -113,10 +113,10 @@ fn paint_values(app: &PhotocraftApp, tool: Tool, b: &BrushSettings) -> PaintValu PaintMode::Blend(b.mode) }; let mut v = PaintValues::new(mode); - v.opacity = f64::from(b.opacity); - v.flow = f64::from(b.flow); + v.opacity = fraction(b.opacity); + v.flow = fraction(b.flow); let mut smoothing = Smoothing::default(); - smoothing.amount = f64::from(b.smoothing.amount); + smoothing.amount = fraction(b.smoothing.amount); smoothing.pulled_string = b.smoothing.pulled_string; smoothing.catch_up = b.smoothing.catch_up; smoothing.catch_up_on_end = b.smoothing.catch_up_on_end; @@ -130,10 +130,10 @@ fn paint_values(app: &PhotocraftApp, tool: Tool, b: &BrushSettings) -> PaintValu let mut mixer = MixerValues::default(); mixer.load_after_stroke = b.mixer.load_after_stroke; mixer.clean_after_stroke = b.mixer.clean_after_stroke; - mixer.wet = f64::from(b.mixer.wet); - mixer.load = f64::from(b.mixer.load); - mixer.mix = f64::from(b.mixer.mix); - mixer.flow = f64::from(b.mixer.flow); + mixer.wet = fraction(b.mixer.wet); + mixer.load = fraction(b.mixer.load); + mixer.mix = fraction(b.mixer.mix); + mixer.flow = fraction(b.mixer.flow); mixer.sample_all_layers = b.mixer.sample_all_layers; mixer.combination = o.mixer_combination; mixer.current_load = mixer_load(app); @@ -142,6 +142,14 @@ fn paint_values(app: &PhotocraftApp, tool: Tool, b: &BrushSettings) -> PaintValu v } +/// A fraction the brush keeps as `f32`, read without its float noise. 0.51 as `f32` reads back as +/// 0.50999999..., which the bar's whole-percent fields take for a value off their step grid, so Up +/// stepped it to 51 again and only the first press moved the value (#16806). Six decimals keep every +/// value the fields can set (a tenth of a percent at the finest). +fn fraction(x: f32) -> f64 { + (f64::from(x) * 1e6).round() / 1e6 +} + /// What the Mixer Brush holds, as the Current Brush Load swatch shows it: the sampled tip image of an Alt-click while /// the foreground stays, else the loaded colour, else nothing (a clean brush). fn mixer_load(app: &PhotocraftApp) -> MixerLoad { @@ -169,14 +177,18 @@ fn apply_values(app: &mut PhotocraftApp, tool: Tool, brush: &mut BrushSettings, // PLAN: PaintBar's Opacity and Flow fields range over 0..=100, so a typed 0 on the Eraser reports no // `out_of_range` and shows no alert (the old bar's range started at 1); pn.C18's owner decides the range. const MIN_FRACTION: f32 = 0.01; - brush.opacity = (after.opacity as f32).max(MIN_FRACTION); - if tool != Tool::MixerBrush { + // The bar shows the fractions rounded (`fraction`), so an untouched one is left as the brush + // holds it rather than written back rounded. + if after.opacity != before.opacity { + brush.opacity = (after.opacity as f32).max(MIN_FRACTION); + } + if tool != Tool::MixerBrush && after.flow != before.flow { brush.flow = (after.flow as f32).max(MIN_FRACTION); } if after.smoothing.amount != before.smoothing.amount { brush.smoothing.enabled = true; + brush.smoothing.amount = after.smoothing.amount as f32; } - brush.smoothing.amount = after.smoothing.amount as f32; brush.smoothing.pulled_string = after.smoothing.pulled_string; brush.smoothing.catch_up = after.smoothing.catch_up; brush.smoothing.catch_up_on_end = after.smoothing.catch_up_on_end; @@ -187,10 +199,16 @@ fn apply_values(app: &mut PhotocraftApp, tool: Tool, brush: &mut BrushSettings, let m = &mut brush.mixer; m.load_after_stroke = after.mixer.load_after_stroke; m.clean_after_stroke = after.mixer.clean_after_stroke; - m.wet = after.mixer.wet as f32; - m.load = after.mixer.load as f32; - m.mix = after.mixer.mix as f32; - m.flow = after.mixer.flow as f32; + for (field, was, now) in [ + (&mut m.wet, before.mixer.wet, after.mixer.wet), + (&mut m.load, before.mixer.load, after.mixer.load), + (&mut m.mix, before.mixer.mix, after.mixer.mix), + (&mut m.flow, before.mixer.flow, after.mixer.flow), + ] { + if now != was { + *field = now as f32; + } + } m.sample_all_layers = after.mixer.sample_all_layers; m.solid_colors_only = after.mixer.solid_colors_only; let o = &mut app.ui.tool_options; @@ -358,6 +376,41 @@ mod mixer_blend_combination_tests; #[path = "../../mixer_load_solid_colors_tests.rs"] mod mixer_load_solid_colors_tests; +#[cfg(test)] +mod apply_values_tests { + use super::{apply_values, paint_values}; + use crate::PhotocraftApp; + use crate::state::Tool; + + /// An edit of an unrelated control (Pressure for Size) leaves the brush's fractions exactly as + /// they were, not rounded to the six decimals the bar shows them with. + #[test] + fn an_unrelated_edit_keeps_the_untouched_fractions_exact() { + for tool in [Tool::Brush, Tool::MixerBrush] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let mut brush = (*app.session.tools.brush).clone(); + let odd = 0.123_456_78_f32; + brush.opacity = odd; + brush.flow = odd; + brush.smoothing.amount = odd; + brush.mixer.wet = odd; + brush.mixer.load = odd; + brush.mixer.mix = odd; + brush.mixer.flow = odd; + let before = paint_values(&app, tool, &brush); + let mut after = before.clone(); + after.pressure_size = !after.pressure_size; + let kept = brush.clone(); + apply_values(&mut app, tool, &mut brush, &before, &after); + assert_eq!(brush.pressure_size, after.pressure_size, "{tool:?}: the edit lands"); + let fractions = + |b: &super::BrushSettings| [b.opacity, b.flow, b.smoothing.amount, b.mixer.wet, b.mixer.load, b.mixer.mix, b.mixer.flow].map(f32::to_bits); + assert_eq!(fractions(&brush), fractions(&kept), "{tool:?}: untouched fractions stay exact"); + assert_eq!(brush.smoothing.enabled, kept.smoothing.enabled, "{tool:?}: smoothing stays as it was"); + } + } +} + #[cfg(test)] mod mixer_load_image_tests { use super::mixer_load_image; diff --git a/crates/ui-egui/src/panels/panel_docking.rs b/crates/ui-egui/src/panels/panel_docking.rs index b58b191e24..b2ebeac752 100644 --- a/crates/ui-egui/src/panels/panel_docking.rs +++ b/crates/ui-egui/src/panels/panel_docking.rs @@ -221,8 +221,7 @@ struct Panels<'a> { } impl DockPanels for Panels<'_> { - /// A panel body is a memoized view keyed by its version (#16118); the canvas shows state that changes without a - /// command (the view, redraw progress, animation and job overlays), so it runs every pass. + /// A panel body is a memoized view keyed by its version (#16118). fn body(&mut self, panel: &String, ui: &mut egui::Ui, _: &mut BodyCx<'_>) { if panel == CANVAS { body(self.app, ui, panel); @@ -231,6 +230,19 @@ impl DockPanels for Panels<'_> { } } + /// The version of what the dock shows for a panel, which keys its column and the docked tree: the canvas's is the + /// document area's, which also keys the area's own view (`region_versions::canvas`). A panel whose body does not show + /// (a tab behind another, in a minimized group or an icon column without its flyout) shows only its title and icon, + /// which every version holds. + fn content(&self, panel: &String) -> Option { + match panel.as_str() { + CANVAS => Some(super::region_versions::canvas(self.app)), + TOOLBAR => Some(super::region_versions::toolbar(self.app)), + id if !is_front(self.app, id) => Some(super::region_versions::hidden_panel(self.app)), + id => Some(super::region_versions::panel(self.app, id)), + } + } + /// The canvas group is the document area: it draws its own tabs and documents in the group's rect. The toolbar's /// group is its rail, which takes the group's full rect and measures its height at a width. fn group_view(&mut self, panels: &[String], _: usize, ui: &mut egui::Ui, at: GroupAt, _: &mut BodyCx<'_>) -> Option { diff --git a/crates/ui-egui/src/panels/preset_browser.rs b/crates/ui-egui/src/panels/preset_browser.rs index 3072d6b245..e495b27645 100644 --- a/crates/ui-egui/src/panels/preset_browser.rs +++ b/crates/ui-egui/src/panels/preset_browser.rs @@ -769,6 +769,15 @@ pub fn finish_custom_shape(app: &mut PhotocraftApp, rect: [f64; 4], keep: bool, "shape.presets.place", json!({"preset": name, "rect": rect, "keepAspect": keep, "fill": fill, "stroke": stroke, "useAlignedRendering": app.ui.tool_options.align_edges}), ); + if let Some(r) = &r { + // Remember which layer this drag placed: the canvas box with its eight handles goes on the + // shape just drawn (#13472). The command's answer names the layer. + let doc = app.session.active().map(|st| st.doc.id); + let layer = r.get("layer").and_then(Value::as_u64); + if let (Some(doc), Some(layer)) = (doc, layer) { + app.ui.presets_ui.placed_custom_shape = Some((doc, layer)); + } + } if r.is_none() && !photocraft_engine::presets::shapes::all_groups(&app.session).iter().any(|g| g.items.iter().any(|s| s.name == name)) { let template = "No custom shape \"{name}\": pick one in the options bar or Window › Shapes"; app.ui.status = crate::i18n::fmt(tl!(template), &[("name", &name)]); diff --git a/crates/ui-egui/src/panels/preset_panels.rs b/crates/ui-egui/src/panels/preset_panels.rs index 7971361605..fa41b34ae3 100644 --- a/crates/ui-egui/src/panels/preset_panels.rs +++ b/crates/ui-egui/src/panels/preset_panels.rs @@ -37,6 +37,10 @@ pub struct PresetUi { pub current_tool_only: bool, /// Custom Shape tool: the shape it draws. pub custom_shape: String, + /// Custom Shape tool: the layer its last drag placed, in that document; with that tool active the + /// canvas box and its eight handles go on that layer alone (#13472). Never restored into another session. + #[serde(skip)] + pub placed_custom_shape: Option<(photocraft_doc::DocId, u64)>, /// Folder/group order per panel, by name (#3658), like the dock's `tabOrder` (#2272). A panel /// with no entry keeps the library's order; unknown names are ignored and groups missing from /// a list follow it in library order. Saved with the UI state. diff --git a/crates/ui-egui/src/panels/preset_panels/tool_presets.rs b/crates/ui-egui/src/panels/preset_panels/tool_presets.rs index 8e8150e76f..69a3b6bd85 100644 --- a/crates/ui-egui/src/panels/preset_panels/tool_presets.rs +++ b/crates/ui-egui/src/panels/preset_panels/tool_presets.rs @@ -39,7 +39,7 @@ pub fn select(app: &mut PhotocraftApp, name: &str) { } } if let Ok(opts) = serde_json::from_value(cur) { - app.ui.tool_options = opts; + *app.ui.tool_options = opts; } } // As the options bar does: a crop preset's ratio (or W x H) fits the frame at once. @@ -132,7 +132,7 @@ mod tests { let mut flipped = serde_json::to_value(&app.ui.tool_options).unwrap(); flip_bools(&mut flipped); flipped["feather"] = json!(0.0); - app.ui.tool_options = serde_json::from_value(flipped.clone()).unwrap(); + *app.ui.tool_options = serde_json::from_value(flipped.clone()).unwrap(); select(&mut app, &name); let after = serde_json::to_value(&app.ui.tool_options).unwrap(); assert_eq!(after["feather"], json!(5.0)); diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 08dd6ac85c..e49b0666d8 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -58,19 +58,20 @@ fn kind_label(layer: &Layer) -> String { /// mask targets, the layer the panel was opened for) keys the inspector, so a field's typing or /// scrub state stays with its layer. pub(super) fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - // A run that shows no adjustment session ends the one kept (`PhotocraftApp::properties_hidden`). - app.properties_tracked = false; - body(app, ui); - if !app.properties_tracked { + // A run that shows no adjustment layer's controls ends the Reset session kept (`PhotocraftApp::properties_hidden`). + // What the run shows decides, not whether the controls' code ran: a pass that reuses the inspector's measurement + // runs none of its content. + if !body(app, ui) { app.properties_hidden = app.properties_hidden.saturating_add(2); } } -fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui) { +/// The panel's inspector; whether it shows an adjustment layer's controls. +fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> bool { let inspector = Inspector::new(tl!("Properties")).empty(tl!("No properties")); let Some(st) = app.session.active() else { inspector.show(ui, |_, _| {}); - return; + return false; }; let doc = st.doc.clone(); let active = st.active_layer; @@ -85,6 +86,7 @@ fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui) { _ if crate::doc_props_ui::shows_document(&doc, active) => Body::Document, _ => Body::Layer, }; + let adjustment = shown == Body::Layer && layer.is_some_and(|l| matches!(l.content, LayerContent::Adjustment(_))); let mut inspector = inspector.target(target); // The Document properties are headed by the document, as production's panel is. inspector = match layer { @@ -108,6 +110,7 @@ fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui) { Body::Layer => layer_body(app, ui, layer), } }); + adjustment } /// The document's properties, with Align and Distribute above them while several layers are selected. diff --git a/crates/ui-egui/src/panels/region_versions.rs b/crates/ui-egui/src/panels/region_versions.rs index 31abdea38b..246559dba9 100644 --- a/crates/ui-egui/src/panels/region_versions.rs +++ b/crates/ui-egui/src/panels/region_versions.rs @@ -1,49 +1,20 @@ -//! The shell's title bar and options bar and every docked panel body as memoized views (#16118). The shell runs a slot -//! every pass and the dock a panel body, and leave memoizing to the app; each reads the whole app, so it is a `MemoView` -//! whose key is a version of what it shows: while the version is the same and no input reaches the slot, the frame adds -//! its last run again instead of running every control in it. The status bar is a memoized view of its own -//! (`status_bar::StatusProps`), over the values it shows. A version covers the app data its slot shows that can change while no -//! input reaches the slot: what a command changes, the active document and layer and the tool in every version; what -//! the slot shows of the canvas view, a job or the brush and colours; and what an edit elsewhere changes without a -//! command, such as a box or pin dragged on the canvas. Input inside a slot runs it whatever its version, and so does a -//! repaint it asks for itself. +//! The versions of what the shell's slots, the docked panels and the document area show (#16118). The shell replays +//! a slot, and PhotoCraft's views a panel body or the document area, while its version holds and no input reaches it: +//! the frame adds its last run again instead of running every control in it. The title bar, the options bar and the +//! status bar are the shell's versioned slots ([`title_bar`], [`options_bar`], [`status_bar`]); each panel body and +//! the document area is a `MemoView` whose key is its version. A version covers the app data its region shows that +//! can change while no input reaches the region: what a command changes, the active document and layer and the tool in +//! every version; what the region shows of the canvas view, a job or the brush and colours; and what an edit elsewhere +//! changes without a command, such as a box or pin dragged on the canvas. Input inside a region runs it whatever its +//! version, and so does a repaint it asks for itself. use std::hash::{Hash, Hasher}; -use craft::ui::contract::{MemoProps, MemoView}; +use craft::ui::contract::{MemoKey, MemoProps, MemoView}; use super::PhotocraftApp; use crate::color_picker_ui::PickWindow; - -/// The props of a shell slot's view: the app the slot reads, which its version stands for. One type per slot, so a -/// trial and the frame's memo log tell the views apart. -macro_rules! slot_props { - ($($name:ident: $what:literal),*) => {$( - #[doc = concat!("The ", $what, "'s view: the app it reads, which its version stands for.")] - #[derive(MemoProps)] - struct $name<'a> { - version: u64, - #[memo_props(covered_by = "version", reason = "the slot's version holds everything the slot shows of the app")] - app: &'a mut PhotocraftApp, - } - )*}; -} -slot_props!(TitleSlot: "title bar", OptionsSlot: "options bar"); - -/// The title bar in its slot, replaying while [`title_bar`]'s version holds. -pub(crate) fn show_title_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let version = title_bar(app); - let _ = MemoView::new("photocraft.title_bar", TitleSlot { version, app }, |slot: &mut TitleSlot<'_>, ui: &mut egui::Ui| super::title_bar(slot.app, ui)) - .show(ui); -} - -/// The options bar in its slot, replaying while [`options_bar`]'s version holds. -pub(crate) fn show_options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let version = options_bar(app); - let _ = - MemoView::new("photocraft.options_bar", OptionsSlot { version, app }, |slot: &mut OptionsSlot<'_>, ui: &mut egui::Ui| super::options_bar(slot.app, ui)) - .show(ui); -} +use crate::state::Tool; /// A docked panel's body: the panel and the app it reads, which its version stands for. #[derive(MemoProps)] @@ -65,22 +36,39 @@ pub(crate) fn show_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: &str) { /// The version of the options bar: every tool option (`app.ui.tool_options`, all of which the bar shows; keys, the /// canvas menu, the canvas and its task bars, panels and presets write them without a command), the commit and cancel /// cells and hints of an edit the canvas opens or ends ([`options_bar::edit_key`](super::options_bar::edit_key)), the -/// Zoom tool's view, an open Free Transform, Puppet Warp or Perspective Warp, which shows its own members in place +/// Zoom and Rotate View tools' zoom and rotation ([`bar_view`]), an open Free Transform, Puppet Warp or Perspective Warp, which shows its own members in place /// of the tool's, with what a drag on the canvas changes (the box, the picked pin, the planes; Escape ends them without -/// a command, #15547), the Crop tool's frame state, the type members' caret or selection, the brush and its presets, the -/// colours, and the vector bar's "Make" row's own two ingredients: the Pen draft's anchor count and the Work Path the +/// a command, #15547), the Crop tool's frame state, the type members' caret or selection and the font families they +/// list ([`families_key`](crate::type_tool::families_key)), the brush and its presets, the colours, and the vector bar's "Make" row's own two ingredients: the Pen draft's anchor count and the Work Path the /// app hides (#12892), which a Pen drawing click by click changes with no History step (#12890). Which path is /// selected is already in [`version`]; the hidden path is held as its document's place, since its content can only /// change with the document's revision, which `version` holds too. pub(crate) fn options_bar(app: &PhotocraftApp) -> u64 { let sessions = (crate::transform_tool::bar_key(app), crate::puppet_ui::bar_key(app), crate::perspective_ui::bar_key(app), crate::crop_ui::bar::bar_key(app)); - let shown = (serialized(&app.ui.tool_options), super::options_bar::edit_key(app), text_target(app)); + let shown = (app.ui.tool_options.revision(), super::options_bar::edit_key(app), text_target(app), crate::type_tool::families_key()); // A canvas gesture's start and end change what the bar enables (the symmetry menu's Transform entry). let gesture = crate::canvas::tools::in_gesture(app); let hidden = app.session.active().map(|st| (st.doc.id.0, app.ui.hidden_work_path.as_ref().map(|(id, _)| *id))); let paths = (app.ui.pen.as_ref().map(|p| p.draft.knots.len()), hidden); - version(app, (view(app), sessions, shown, brush(app), colours(app), gesture, paths)) + // The bar's right end: the Search button shows whether the search is open (Escape closes it without a command), and + // the workspace switcher's menu the workspaces and the current one (the New and Delete dialogs change them without + // a command). + let set = &app.workspaces.set; + let right_end = (app.ui.palette.open, &set.current, set.saved.iter().map(|w| (&w.id, &w.name)).collect::>()); + version(app, (bar_view(app), sessions, shown, brush(app), colours(app), gesture, paths, right_end)) +} + +/// The version of the status bar: the readout's item and the zoom of the active canvas, the status message, the +/// render-path note, and the background redraw's and the job's progress. The readout's document values follow the +/// active document and its revision and name the tool, which every version holds; the language its labels are in +/// reaches the slot's view through its place. +pub(crate) fn status_bar(app: &PhotocraftApp) -> u64 { + let item = MemoKey::of(&super::chrome_ui::status_item(&app.ui.chrome)); + let zoom = crate::canvas::active_view(app).map(|view| view.zoom.to_bits()); + let message = (&app.ui.status, app.ui.status_error); + let progress = MemoKey::of(&(crate::background_redraw::progress(app), crate::jobs_ui::status_job(app).map(|(_, progress)| progress))); + version(app, (item, zoom, message, super::chrome_ui::render_path_label(app), progress)) } /// The version of the toolbar's footer: the colour chips' two colours, whether the active document is in Quick Mask and @@ -91,6 +79,13 @@ pub(crate) fn toolbar_footer(app: &PhotocraftApp) -> u64 { version(app, (colours(app), quick_mask, app.ui.view.screen_mode)) } +/// The version of the toolbar's group view, which the dock keys the toolbar's column by: the rail's slots (in the +/// preferences, which [`version`] holds with the tool), the tools its groups remember, whether the Edit Toolbar drawer +/// is open, and what the footer shows ([`toolbar_footer`]). +pub(crate) fn toolbar(app: &PhotocraftApp) -> u64 { + version(app, (toolbar_footer(app), &app.ui.group_tools, app.ui.toolbar_drawer)) +} + /// The version of the title bar: the title it shows (the active document's name and its unsaved mark), the language /// its menu titles are in, whether the menus are in the bar (not in the macOS menu bar) and whether the bar takes the /// menu keys (F10, Alt, Alt+letter), which a dialog or the shortcut recorder holds back: a dialog closed with Escape @@ -115,7 +110,8 @@ pub(crate) fn title_bar(app: &PhotocraftApp) -> u64 { /// colours, and so do Properties (a shape layer's fill and stroke swatches, a gradient fill's Foreground and /// Background stops, the adjustment editors' swatches) and Character (the colour of new type is the foreground). /// Character and Paragraph show the type defaults, and they and Properties the values at the caret or selection of the -/// type being edited, which Glyphs inserts at. Every other panel shows only what every version holds. +/// type being edited, which Glyphs inserts at; Character, Properties and Glyphs list the font families +/// ([`families_key`](crate::type_tool::families_key)). Every other panel shows only what every version holds. pub(crate) fn panel(app: &PhotocraftApp, id: &str) -> u64 { match id { "navigator" => version(app, (view(app), adjustment_preview(app))), @@ -130,17 +126,25 @@ pub(crate) fn panel(app: &PhotocraftApp, id: &str) -> u64 { } "cloneSource" => version(app, app.ui.presets_ui.clone_cursor.map(|(document, at)| (document, at.map(f64::to_bits)))), "modifierKeys" => version(app, app.ui.shell.latched), - "properties" => version(app, (crate::color_picker_ui::window_picker_state(app, PickWindow::Properties), colours(app), text_target(app))), + "properties" => version( + app, + (crate::color_picker_ui::window_picker_state(app, PickWindow::Properties), colours(app), text_target(app), crate::type_tool::families_key()), + ), "brushSettings" | "brushes" => version(app, brush(app)), "histogram" => version(app, (adjustment_preview(app), histograms(app))), - "character" => version(app, (colours(app), type_defaults(app), text_target(app))), + "character" => version(app, (colours(app), type_defaults(app), text_target(app), crate::type_tool::families_key())), "paragraph" => version(app, (type_defaults(app), text_target(app))), - "glyphs" => version(app, text_target(app)), + "glyphs" => version(app, (text_target(app), crate::type_tool::families_key())), "color" | "swatches" | "gradients" | "gradientEditor" => version(app, colours(app)), _ => version(app, ()), } } +/// The version of a panel in the dock whose body does not show: its title and icon, which every version holds. +pub(crate) fn hidden_panel(app: &PhotocraftApp) -> u64 { + version(app, ()) +} + /// What every slot may show, joined with `extra`: the commands run (any of them may change anything), the active /// document, its revision, its active layers and which part of them is targeted (the layer mask, the vector mask, a /// filter mask, the selected path; the Layers, Channels, Paths and Properties panels and the canvas set it without a @@ -148,7 +152,7 @@ pub(crate) fn panel(app: &PhotocraftApp, id: &str) -> u64 { /// or `prefs.edit`, not as a counted command: units, the language, toolbar slots). /// Whether running command `id` leaves every settling region's version as it is: a view command (zoom, fit, print size, /// rotate) changes only the canvas view, which every region that shows it holds in its version (the Navigator, the Info -/// panel and the options bar through [`view`], the status bar in its own props), so it need not count as a command run +/// panel and the options bar through [`view`] and [`bar_view`], the status bar in its own props), so it need not count as a command run /// and run every panel body in the next frame (#15493). While an action is recorded it counts: the Actions panel lists /// the step it records. pub(crate) fn changes_only_the_view(app: &PhotocraftApp, id: &str) -> bool { @@ -158,7 +162,7 @@ pub(crate) fn changes_only_the_view(app: &PhotocraftApp, id: &str) -> bool { fn version(app: &PhotocraftApp, extra: impl Hash) -> u64 { let mut hasher = std::collections::hash_map::DefaultHasher::new(); app.commands_run.hash(&mut hasher); - app.session.prefs.rev().hash(&mut hasher); + app.session.prefs.settings_rev().hash(&mut hasher); app.session.active_generation().hash(&mut hasher); app.session.active_layer_changes().hash(&mut hasher); app.session.active().map(|st| st.revision).hash(&mut hasher); @@ -182,7 +186,7 @@ fn serialized(value: &impl serde::Serialize) -> u64 { } } let mut hasher = std::collections::hash_map::DefaultHasher::new(); - // Writing to a hasher cannot fail, and every tool option serializes (they are saved). + // Writing to a hasher cannot fail, and the state it hashes serializes (it is saved). let _ = serde_json::to_writer(HashWriter(&mut hasher), value); hasher.finish() } @@ -226,19 +230,127 @@ fn colours(app: &PhotocraftApp) -> [u32; 8] { bits } +/// The part of the active document's view the options bar shows: the Zoom tool's bar the zoom, the Rotate View tool's +/// the rotation, every other tool's none (the Hand tool's bar has no view field). +fn bar_view(app: &PhotocraftApp) -> Option { + let view = crate::canvas::active_view(app)?; + match app.ui.tool { + Tool::Zoom => Some(view.zoom.to_bits()), + Tool::RotateView => Some(view.rotation.to_bits()), + _ => None, + } +} + /// The active document's view as the canvas showed it: its zoom, centre and turn. fn view(app: &PhotocraftApp) -> Option<[u64; 5]> { crate::canvas::active_view(app) .map(|view| [view.zoom.to_bits(), view.center.x.to_bits(), view.center.y.to_bits(), view.rotation.to_bits(), u64::from(view.flip_x)]) } +/// The document area's props: the app it reads, which [`canvas`] stands for. +#[derive(MemoProps)] +struct CanvasSlot<'a> { + version: u64, + #[memo_props(covered_by = "version", reason = "the canvas version holds everything the document area shows of the app")] + app: &'a mut PhotocraftApp, + #[memo_props(covered_by = "version", reason = "the document area's one drawing function, the same in every pass")] + show: fn(&mut PhotocraftApp, &mut egui::Ui), +} + +/// The document area's tabs and documents in `ui`, replaying while [`canvas`] holds. `show` draws them; the per-pass +/// work around them runs before, outside the view (`canvas::document_area`). +pub(crate) fn show_canvas(app: &mut PhotocraftApp, ui: &mut egui::Ui, show: fn(&mut PhotocraftApp, &mut egui::Ui)) { + let version = canvas(app); + let _ = MemoView::new("photocraft.canvas", CanvasSlot { version, app, show }, |slot: &mut CanvasSlot<'_>, ui: &mut egui::Ui| (slot.show)(slot.app, ui)) + .show(ui); +} + +/// The version of the document area, which keys its view and, through `DockPanels::content`, the docked tree it sits +/// in. It holds what the tabs and every shown canvas draw that can change while no input reaches the area and its run +/// asked for no pass: what every slot holds ([`version`]); each document's revision and unsaved mark (the tabs, the +/// arranged panes); each view as stored, with the view commands queued for its next pass and a zoom ease asked; the +/// document windows, the arrangement and its dividers; the View menu's options and the panels shown (the scroll bars +/// go with the screen mode); the tool options and the on-canvas state of the tools (a transform box, a crop frame and whether its crop is pending, a pen draft, the +/// type caret, a picked guide, the samplers, slices, frames and artboards), whose drags and keys change them without a +/// command; the canvas menu and where the Brush Preset picker is open; whether a dialog is open (it holds back the tools and the task bars); the Layers panel's hovered layer, which the Move tool outlines; the previews a dialog or a panel drag shows +/// on the canvas (an adjustment's live values, a filter's or Levels' preview, Color Range's mask); the opening files +/// and their progress; the Batch input shown in place of the documents; the display the window is on; and the blocks a background redraw has landed +/// (`background_redraw::poll`). A run that waits for work of its own (a preview worker, a tile stream) asks for its +/// next pass through the framework, which runs the view then. +pub(crate) fn canvas(app: &PhotocraftApp) -> u64 { + let ui = &app.ui; + let documents: Vec<(u64, u64, bool)> = app.session.documents().iter().map(|st| (st.doc.id.0, st.revision, st.is_dirty())).collect(); + let views: Vec<_> = ui.views.iter().chain(ui.window_views.values()).map(view_key).collect(); + let windows = serialized(&(&ui.view, &ui.panels, &ui.windows, &ui.document_windows, &ui.split_at)); + let tools = serialized(&( + &ui.brush_tool, + &ui.cam_transform, + &ui.transform, + &ui.symmetry_transform, + &ui.layer_picker, + (&ui.clone_source, &ui.clone_offset, &ui.pattern_stamp_phase), + (&ui.canvas_tool_menu, &ui.brush_picker), + &ui.selected_guide, + &ui.direct_selection, + &ui.hidden_work_path, + (&ui.analysis, &ui.slices, &ui.frame_tool, &ui.artboard_tool), + )); + let sessions = + (crate::transform_tool::bar_key(app), crate::puppet_ui::bar_key(app), crate::perspective_ui::bar_key(app), crate::crop_ui::bar::bar_key(app)); + let crop = app.canvas_tools.crop.tool.frame().map(|frame| [frame.rect.x0, frame.rect.y0, frame.rect.x1, frame.rect.y1, frame.angle].map(f64::to_bits)); + let task_bars = ( + crate::transform_task_bar::eligible(app), + crate::crop_task_bar::eligible(app), + crate::crop_ui::pending(app), + app.canvas_tools.crop.tool.straighten_armed(), + ); + let editing = (text_target(app), ui.pen.as_ref().map(|p| p.draft.knots.len()), crate::canvas::tools::in_gesture(app), crop, task_bars); + let previews = ( + adjustment_preview(app), + crate::canvas::filter_preview::canvas_key(app), + crate::levels_clipping::canvas_key(app), + crate::color_range_ui::canvas_key(app), + ); + let opening: Vec<_> = crate::jobs_ui::open_tabs(app).into_iter().map(|(job, _, fraction)| (job, fraction.map(f32::to_bits))).collect(); + let display = crate::monitor_status::view_display(app, app.ctx()); + // The open Brush Preset picker lists the presets and shows the brush. + let picker = ui.brush_picker.map(|_| brush(app)); + let gpu = app.gpu.as_ref().map(|gpu| gpu.canvas_budget()); + version( + app, + ( + documents, + views, + (windows, ui.tool_options.revision(), tools, picker), + sessions, + editing, + previews, + (app.hover_layer, app.dialog_open(), app.jobs.focus, opening, crate::jobs_ui::batch_preview_key(app), display, gpu, app.redraw_landed), + ), + ) +} + +/// A view as its canvas shows it next: the camera, the document size it last showed, how many view commands wait for +/// its next pass (only that pass drains them) and a zoom ease asked. +fn view_key(view: &crate::state::View) -> impl Hash + '_ { + let bits = |[x, y]: [f32; 2]| [x.to_bits(), y.to_bits()]; + ( + [view.zoom.to_bits(), view.rotation.to_bits()], + bits(view.center), + view.doc_size, + view.pending.len(), + view.zoom_animating, + view.zoom_anchor.map(|(doc, screen)| (doc.map(f64::to_bits), bits(screen))), + view.zoom_from.map(|(zoom, center)| (zoom.to_bits(), bits(center))), + ) +} + #[cfg(test)] mod tests { use super::*; - use crate::state::Tool; - /// The brush, the colours, the type defaults, the tool options, the type caret, the Move tool's rollover and an - /// adjustment's live preview move the versions of the bars and panels that show them and of no other, so a drag that + /// The brush, the colours, the type defaults, the tool options, the type caret, the Move tool's rollover, an + /// adjustment's live preview and the status message move the versions of the bars and panels that show them and of no other, so a drag that /// edits one leaves the rest replaying; a version that missed one would replay a stale bar or panel. #[test] fn what_a_region_shows_moves_only_its_version() { @@ -264,7 +376,7 @@ mod tests { .into_iter() .map(|id| (id, panel(app, id))) .collect(); - all.extend([("optionsBar", options_bar(app)), ("titleBar", title_bar(app))]); + all.extend([("optionsBar", options_bar(app)), ("titleBar", title_bar(app)), ("statusBar", status_bar(app))]); all }; let moved = |app: &mut PhotocraftApp, change: &dyn Fn(&mut PhotocraftApp)| -> Vec<&'static str> { @@ -302,6 +414,7 @@ mod tests { app.doc_hist = Some(crate::histogram_panel::PanelHist { key, at: 30.0, hist: Default::default() }); }); assert_eq!(landed, ["histogram"], "a histogram the worker landed"); + assert_eq!(moved(&mut app, &|app| app.ui.status = "Saved".into()), ["statusBar"], "a status message"); } /// Opening or closing a layer's effects list or a group is view state off the document's revision, and a command diff --git a/crates/ui-egui/src/panels/status_bar.rs b/crates/ui-egui/src/panels/status_bar.rs index 8d912e4e52..63a09680b1 100644 --- a/crates/ui-egui/src/panels/status_bar.rs +++ b/crates/ui-egui/src/panels/status_bar.rs @@ -40,8 +40,9 @@ struct StatusProps<'a> { values: StatusValues, item: StatusItem, document: Option, - /// The active document's main canvas as its last pass showed it; a document not yet shown has no readout. - view: Option, + /// The zoom of the active document's main canvas as its last pass showed it, the one view field the readout shows + /// (a pan leaves it as it is); a document not yet shown has no readout. + zoom: Option, message: Option, out: Outbox<'a, StatusEvent>, } @@ -59,8 +60,8 @@ struct TrailingProps<'a> { enum StatusEvent { /// The readout's item was picked. Item(StatusItem), - /// The zoom field edited the view. - View(CanvasView), + /// The zoom field set the zoom, about the view's centre. + Zoom(f64), /// The zoom field cut an entry to its range. InvalidZoom(InvalidZoom), /// The job's Cancel was clicked. @@ -69,15 +70,16 @@ enum StatusEvent { /// The status bar, in the shell's status slot: the zoom readout of the active document and the latest status /// message, and at the far end the render-path note, the background redraw and the background jobs' progress with -/// Cancel (#210). The body and the trailing group are a memoized view each, so a frame where neither changed replays -/// them. The bar itself stays the slot's direct child: it fills the slot's height and centres its content there, where -/// a memoized view around it would be moved down onto the slot row's line and clipped at the window's bottom edge. +/// Cancel (#210). The slot replays while `region_versions::status_bar` holds; when it runs, the body and the trailing +/// group are a memoized view each, so a frame that changed only one runs only that one. The bar itself stays the slot +/// pane's direct child: it fills the slot's height and centres its content there, where a memoized view around it +/// would be moved down onto the slot row's line and clipped at the window's bottom edge. pub fn status_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let job = crate::jobs_ui::status_job(app); let values = chrome_ui::status_values(app); let item = chrome_ui::status_item(&app.ui.chrome); let document = app.session.active().map(|st| Size::new(st.doc.size.width as f64, st.doc.size.height as f64)); - let view = crate::canvas::active_view(app); + let zoom = crate::canvas::active_view(app).map(|view| view.zoom); let message = (!app.ui.status.is_empty()).then(|| StatusMessage::new(app.ui.status.clone()).tone(if app.ui.status_error { Tone::Warn } else { Tone::Neutral })); let render_path = chrome_ui::render_path_label(app) @@ -93,14 +95,14 @@ pub fn status_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let _ = MemoView::new("status-bar-trailing", props, trailing_view).show(ui); }) .show(ui, |ui, _| { - let props = StatusProps { values: values.clone(), item, document, view, message: message.clone(), out: Outbox::new(&mut body_sent) }; + let props = StatusProps { values: values.clone(), item, document, zoom, message: message.clone(), out: Outbox::new(&mut body_sent) }; let _ = MemoView::new("status-bar", props, body_view).show(ui); }); let (mut picked, mut edited, mut invalid_zoom, mut cancelled) = (None, None, None, false); for event in body_sent.into_iter().chain(trailing_sent) { match event { StatusEvent::Item(item) => picked = Some(item), - StatusEvent::View(new) => edited = Some(new), + StatusEvent::Zoom(new) => edited = Some(new), StatusEvent::InvalidZoom(invalid) => invalid_zoom = Some(invalid), StatusEvent::CancelJob => cancelled = true, } @@ -108,11 +110,11 @@ pub fn status_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if let Some(picked) = picked { chrome_ui::set_status_item(&mut app.ui.chrome, picked); } - if let Some(new) = edited + if let Some(zoom) = edited && let Some(i) = app.session.active_index() { let ppp = app.canvas_ppp(); - app.ui.views[i].set_from(&new, ppp); + app.ui.views[i].set_zoom(zoom, ppp); } if cancelled && let Some((id, _)) = &job { crate::jobs_ui::cancel(app, *id); @@ -151,14 +153,14 @@ fn body_view(props: &mut StatusProps<'_>, ui: &mut egui::Ui) { /// The members of the status bar's body: the readout, or "No document", and the status message. fn body_members(props: &mut StatusProps<'_>, ui: &mut egui::Ui) { - match (props.document, props.view) { - (Some(size), Some(view)) => { - let out = StatusReadout::new(Bind::given(view), size, props.item, &props.values).show(ui); + match (props.document, props.zoom) { + (Some(size), Some(zoom)) => { + let out = StatusReadout::new(Bind::given(zoom), size, props.item, &props.values).show(ui); if let Some(picked) = out.item { props.out.send(StatusEvent::Item(picked)); } - if let Some(view) = out.view.value().copied() { - props.out.send(StatusEvent::View(view)); + if let Some(zoom) = out.zoom_edits.value() { + props.out.send(StatusEvent::Zoom(*zoom)); } if let Some(invalid) = out.invalid_zoom { props.out.send(StatusEvent::InvalidZoom(invalid)); @@ -186,9 +188,13 @@ pub(crate) fn document_window_status(app: &mut PhotocraftApp, ui: &mut egui::Ui, let (mut picked, mut edited, mut invalid_zoom) = (None, None, None); Bar::new("", BarKind::Status).show(ui, |ui, _| { if let (Some(size), Some(view)) = (size, view) { - let out = StatusReadout::new(Bind::given(view), size, item, &values).show(ui); + let out = StatusReadout::new(Bind::given(view.zoom), size, item, &values).show(ui); picked = out.item; - edited = out.view.value().copied(); + edited = out.zoom_edits.value().map(|zoom| { + let mut zoomed = view; + zoomed.zoom = *zoom; + zoomed + }); invalid_zoom = out.invalid_zoom; } }); diff --git a/crates/ui-egui/src/pixel_aspect_tests.rs b/crates/ui-egui/src/pixel_aspect_tests.rs index 31a808764e..d0a787c8d1 100644 --- a/crates/ui-egui/src/pixel_aspect_tests.rs +++ b/crates/ui-egui/src/pixel_aspect_tests.rs @@ -23,7 +23,7 @@ fn harness() -> Harness<'static, Box> { if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { return; } - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); }, app, ); diff --git a/crates/ui-egui/src/polygon_lasso_tests.rs b/crates/ui-egui/src/polygon_lasso_tests.rs index 4d970e1345..2318f11295 100644 --- a/crates/ui-egui/src/polygon_lasso_tests.rs +++ b/crates/ui-egui/src/polygon_lasso_tests.rs @@ -22,7 +22,7 @@ fn harness() -> Harness<'static, Box> { if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { return; } - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); }, app, ); diff --git a/crates/ui-egui/src/prefs/prefs_ui/tests.rs b/crates/ui-egui/src/prefs/prefs_ui/tests.rs index 79223c28bb..2c9ecb1840 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/tests.rs @@ -862,7 +862,7 @@ fn restart_cases() -> Vec { assert_eq!(stored["selectedTool"], json!("Eraser")); assert_eq!(app.ui.tool, Tool::Eraser, "restored before the first frame"); assert_eq!(app.ui.group_tool(Tool::Eraser.key()), Some(Tool::Eraser)); - assert_eq!(app.ui.tool_options, crate::state::ToolOptions::default()); + assert_eq!(*app.ui.tool_options, crate::state::ToolOptions::default()); }), }, Case { @@ -1106,7 +1106,7 @@ fn damaged_cases() -> (Vec, Vec) { }, )); cases.push(loaded("tool options: a good value is left alone", json!({"toolOptions": {"feather": 12.5}}), move |app| { - assert_eq!(app.ui.tool_options, crate::state::ToolOptions { feather: 12.5, ..d() }); + assert_eq!(*app.ui.tool_options, crate::state::ToolOptions { feather: 12.5, ..d() }); let mut def = d(); crate::tool_memory::sanitize(&mut def); assert_eq!(def, d(), "in-range defaults never change"); @@ -1436,7 +1436,7 @@ fn reset_tools_clear_the_remembered_options_and_brushes() { |brushes: &[(Tool, photocraft_engine::BrushSettings)]| brushes.iter().all(|(t, b)| *b == crate::paint_mouse::fresh_brush(*t, b) && b.size != 77.0); assert!(starting(&app.ui.tool_brushes), "{saved}"); let app2 = app_on(&store); - assert_eq!(app2.ui.tool_options, crate::state::ToolOptions::default()); + assert_eq!(*app2.ui.tool_options, crate::state::ToolOptions::default()); assert!(!app2.ui.tool_brushes.is_empty() && starting(&app2.ui.tool_brushes), "remembered across a restart"); } diff --git a/crates/ui-egui/src/psd_open_tests.rs b/crates/ui-egui/src/psd_open_tests.rs index 8ccafccb5d..c9863af334 100644 --- a/crates/ui-egui/src/psd_open_tests.rs +++ b/crates/ui-egui/src/psd_open_tests.rs @@ -247,7 +247,7 @@ fn memory_confirmation_dialog_and_cancel_lifecycle() { }) .unwrap(); - crate::open_prompt::arrive_memory(&mut app, preflight_id, "high_mem.psd".into(), None, None, None, 7 * gb, Some(10 * gb), false, false); + crate::open_prompt::arrive_memory(&mut app, preflight_id, "high_mem.psd".into(), None, None, None, None, 7 * gb, Some(10 * gb), false, false); let dlg_id = memory_dialog(&mut app); assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": dlg_id}))["ok"], true); @@ -390,6 +390,7 @@ fn memory_confirmation_refuses_when_source_changed_inline() { Some(path.to_string_lossy().to_string()), None, None, + None, 1000, Some(100_000), false, @@ -441,6 +442,7 @@ fn memory_confirmation_refuses_when_source_changed_async() { Some(path.to_string_lossy().to_string()), None, None, + None, 1000, Some(100_000), false, @@ -490,7 +492,7 @@ fn memory_decline_advances_queue_and_cleans_batch() { }) .unwrap(); - crate::open_prompt::arrive_memory(&mut app, preflight_id, "declined.psd".into(), None, None, Some(order), 1000, Some(4000), false, false); + crate::open_prompt::arrive_memory(&mut app, preflight_id, "declined.psd".into(), None, None, None, Some(order), 1000, Some(4000), false, false); let dlg_id = memory_dialog(&mut app); let res = call(&mut app, "ui.dialog.cancel", json!({"dialog": dlg_id})); @@ -538,8 +540,8 @@ fn batch_single_file_cancel_preserves_other_held_memory_orders() { }) .unwrap(); - crate::open_prompt::arrive_memory(&mut app, p0, "first.psd".into(), None, None, Some(order0), 1000, Some(4000), false, false); - crate::open_prompt::arrive_memory(&mut app, p1, "second.psd".into(), None, None, Some(order1), 1000, Some(4000), false, false); + crate::open_prompt::arrive_memory(&mut app, p0, "first.psd".into(), None, None, None, Some(order0), 1000, Some(4000), false, false); + crate::open_prompt::arrive_memory(&mut app, p1, "second.psd".into(), None, None, None, Some(order1), 1000, Some(4000), false, false); // Cancel first file: let dlg0 = memory_dialog(&mut app); @@ -578,7 +580,7 @@ fn profile_cancel_cancels_whole_queue_including_memory_prompts() { }) .unwrap(); - crate::open_prompt::arrive_memory(&mut app, preflight_id, "high_mem.psd".into(), None, None, None, 7 * gb, Some(10 * gb), false, false); + crate::open_prompt::arrive_memory(&mut app, preflight_id, "high_mem.psd".into(), None, None, None, None, 7 * gb, Some(10 * gb), false, false); crate::open_prompt::arrive( &mut app, @@ -645,7 +647,7 @@ fn mixed_prompts_follow_arrival_order_fifo() { confirm_damage: true, }) .unwrap(); - crate::open_prompt::arrive_memory(&mut app, preflight_id, "second_mem.psd".into(), None, None, None, 7 * gb, Some(10 * gb), false, false); + crate::open_prompt::arrive_memory(&mut app, preflight_id, "second_mem.psd".into(), None, None, None, None, 7 * gb, Some(10 * gb), false, false); // First prompt shown must be damage (since it arrived first)! let dlg_id = damage_dialog(&mut app); @@ -739,6 +741,7 @@ fn memory_prompt_states_unknown_capacity_and_the_eight_gib_warning() { job: photocraft_engine::jobs::JobId(1), name: "unknown.psd".into(), path: Some("/pics/unknown.psd".into()), + error_source: None, slot: None, order: None, }; @@ -761,7 +764,8 @@ fn memory_prompt_states_unknown_capacity_and_the_eight_gib_warning() { // A measured capacity shows the number and drops the uncertainty warning. let id = store_preflight(&mut app, "known.psd", 3 * gb, Some(5 * gb)); - let tab = crate::jobs_ui::OpenTab { job: photocraft_engine::jobs::JobId(2), name: "known.psd".into(), path: None, slot: None, order: None }; + let tab = + crate::jobs_ui::OpenTab { job: photocraft_engine::jobs::JobId(2), name: "known.psd".into(), path: None, error_source: None, slot: None, order: None }; crate::jobs_ui::finish_open_tab( &mut app, &tab, @@ -787,7 +791,8 @@ fn memory_prompt_warns_when_little_memory_would_be_left() { let mut app = app(); let available = 3 * gb + gb / 2; let id = store_preflight(&mut app, "tight.psd", 3 * gb, Some(available)); - let tab = crate::jobs_ui::OpenTab { job: photocraft_engine::jobs::JobId(3), name: "tight.psd".into(), path: None, slot: None, order: None }; + let tab = + crate::jobs_ui::OpenTab { job: photocraft_engine::jobs::JobId(3), name: "tight.psd".into(), path: None, error_source: None, slot: None, order: None }; crate::jobs_ui::finish_open_tab( &mut app, &tab, @@ -808,7 +813,7 @@ fn reopening_a_file_whose_memory_prompt_waits_does_not_queue_a_duplicate() { let gb = 1u64 << 30; let mut app = app(); let id = store_preflight(&mut app, "slow.psd", 3 * gb, Some(5 * gb)); - crate::open_prompt::arrive_memory(&mut app, id, "slow.psd".into(), Some("/pics/slow.psd".into()), None, None, 3 * gb, Some(5 * gb), false, false); + crate::open_prompt::arrive_memory(&mut app, id, "slow.psd".into(), Some("/pics/slow.psd".into()), None, None, None, 3 * gb, Some(5 * gb), false, false); assert_eq!(app.held_memory_prompts.len(), 1); assert!(alerts::prompt_tagged::(&app).is_some()); assert!(app.show_if_open("/pics/slow.psd"), "the waiting prompt is shown"); @@ -817,7 +822,7 @@ fn reopening_a_file_whose_memory_prompt_waits_does_not_queue_a_duplicate() { // The template exception: a repeat open still creates another Untitled. let id = store_preflight(&mut app, "card.psdt", 3 * gb, Some(5 * gb)); - crate::open_prompt::arrive_memory(&mut app, id, "card.psdt".into(), Some("/pics/card.psdt".into()), None, None, 3 * gb, Some(5 * gb), false, false); + crate::open_prompt::arrive_memory(&mut app, id, "card.psdt".into(), Some("/pics/card.psdt".into()), None, None, None, 3 * gb, Some(5 * gb), false, false); assert_eq!(app.held_memory_prompts.len(), 2); assert!(!app.show_if_open("/pics/card.psdt"), "a template reopens instead of reusing the waiting prompt"); assert_eq!(app.held_memory_prompts.len(), 2); @@ -1024,3 +1029,106 @@ fn confirmed_damaged_smart_object_opens_are_admitted_as_smart_objects_with_disti } let _ = std::fs::remove_dir_all(&dir); } + +/// A real inline decode after consent fails on a tiny recognized PSD header. Its raw approval +/// error is unchanged; typed UI confirmation acknowledges delivery. The alert names the source +/// and the next prompt retains its batch. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn failed_inline_memory_approval_alerts_once_and_preserves_the_next_prompt_and_error_reply() { + for (name, file_name) in [("failed.psd", None), ("failed.psd", Some("failed.psd")), ("Untitled-1", Some("template.psdt"))] { + for typed in [false, true] { + check_failed_memory_approval_case(name, file_name, typed); + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn check_failed_memory_approval_case(name: &str, file_name: Option<&str>, typed: bool) { + // File-backed decoding reads the complete 26-byte header before parsing it. Give both + // routes that same header so the unsupported version, rather than EOF, is the failure. + let header = [ + b'8', b'B', b'P', b'S', 0, 0, // unsupported version + 0, 0, 0, 0, 0, 0, // reserved + 0, 3, // channels + 0, 0, 0, 1, // height + 0, 0, 0, 1, // width + 0, 8, // depth + 0, 3, // RGB + ]; + let mut app = app(); + let temp = tempfile::tempdir().unwrap(); + let path = file_name.map(|file| { + let path = temp.path().join(file); + std::fs::write(&path, header).unwrap(); + path.to_string_lossy().into_owned() + }); + let source = path.as_ref().map_or_else( + || photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(header.to_vec())), + |path| photocraft_engine::jobs::OpenSource::Path(path.clone()), + ); + let fingerprint = photocraft_engine::jobs::SourceFingerprint::of(&source).unwrap(); + let first = app + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: name.into(), + source, + fingerprint, + required: 1000, + soft_limit: 500, + hard_limit: 2000, + available_ram: Some(4000), + confirm_damage: true, + }) + .unwrap(); + let second = store_preflight(&mut app, "next.psd", 1000, Some(4000)); + let batch = crate::jobs_ui::begin_batch(&mut app); + let first_order = crate::jobs_ui::OpenOrder { batch, seq: 0 }; + let second_order = crate::jobs_ui::OpenOrder { batch, seq: 1 }; + crate::open_prompt::arrive_memory(&mut app, first, name.into(), path.clone(), None, None, Some(first_order), 1000, Some(4000), false, false); + crate::open_prompt::arrive_memory(&mut app, second, "next.psd".into(), None, None, None, Some(second_order), 1000, Some(4000), false, false); + let dialog = alerts::prompt_tagged::(&app).unwrap(); + if typed { + let reply = call(&mut app, "ui.dialog.confirm", json!({"dialog": dialog.value()})); + assert_eq!(reply["ok"], true, "typed confirmation acknowledges delivery; the real consumer presents the approval failure"); + } else { + let error = crate::open_prompt::answer_memory(&mut app, true).unwrap_err(); + assert_eq!(error, format!("{name}: {name}: PSD: unsupported file version 0"), "keep the approval's original raw error"); + let ctx = app.ctx().clone(); + ctx.run_ui(Default::default(), |ui| crate::dialogs::run(&mut app, ui)).textures_delta.clear(); + } + let source_name = file_name.unwrap_or(name); + let wanted = format!("Couldn't open {source_name}: PSD: unsupported file version 0"); + let errors: Vec<_> = app.framework.dialogs.open_dialogs().into_iter().filter(|d| d.key.as_deref() == Some("alert")).collect(); + assert_eq!(errors.len(), 1); + assert_eq!(errors[0].fields.as_ref().unwrap()["message"], wanted); + let error_id = errors[0].id; + assert_eq!(app.ui.status, wanted); + assert_eq!(app.ui.status.matches(source_name).count(), 1); + if name != source_name { + assert!(!app.ui.status.contains(name)); + } + assert!(app.ui.status_error); + assert!(app.ui.notices.is_empty()); + assert!(app.session.documents().is_empty()); + assert!(app.ui.recent_files.is_empty()); + assert!(app.jobs.opens.is_empty()); + assert!(app.session.take_pending_preflight(first).is_none()); + assert_eq!(app.held_memory_prompts.len(), 1); + assert_eq!(app.held_memory_prompts[0].id, second); + assert_eq!(app.prompt_order.len(), 1); + assert_eq!(app.jobs.batches.len(), 1, "the waiting successor still owns this batch"); + let next = alerts::prompt_tagged::(&app).unwrap(); + crate::open_prompt::advance_memory(&mut app); + assert_eq!(app.framework.dialogs.open_dialogs().len(), 2, "neither the alert nor the successor prompt is duplicated"); + assert_eq!(call(&mut app, "ui.dialog.confirm", json!({"dialog": error_id.value()}))["ok"], true); + assert_eq!(app.framework.dialogs.open_dialogs().len(), 1); + assert_eq!(app.framework.dialogs.open_dialogs()[0].id, next); + assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": next.value()}))["ok"], true); + assert!(app.session.take_pending_preflight(second).is_none()); + assert!(app.framework.dialogs.open_dialogs().is_empty()); + assert!(app.held_memory_prompts.is_empty()); + assert!(app.prompt_order.is_empty()); + assert!(app.jobs.batches.is_empty()); +} diff --git a/crates/ui-egui/src/smudge_bar_pressure_size_tests.rs b/crates/ui-egui/src/smudge_bar_pressure_size_tests.rs new file mode 100644 index 0000000000..a6b9dddede --- /dev/null +++ b/crates/ui-egui/src/smudge_bar_pressure_size_tests.rs @@ -0,0 +1,159 @@ +//! Smudge Pressure for Size (#12961): the bar toggle binds the same brush used by paint.smudge. + +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_engine::BrushSettings; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; + +const PRESSURE: &str = "Always use pressure for size"; +const TOOLTIP: &str = "Always use Pressure for Size. When off, Brush Preset controls pressure"; + +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, 400.0)).with_context(app.ctx().clone()).build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app); + h.run_steps(4); + h +} + +fn toggle(h: &mut Harness<'static, Box>) { + h.get_by_label(PRESSURE).click(); + h.run_steps(3); +} + +fn brush_commands(h: &Harness<'static, Box>) -> usize { + h.state().session.journal.iter().filter(|(id, _)| id == "tools.setBrush").count() +} + +#[test] +fn pressure_is_off_by_default_and_follows_finger_painting_with_the_exact_tooltip() { + let h = bar(Tool::Smudge); + let pressure = h.get_by_label(PRESSURE); + assert!(h.get_by_label("Finger Painting").rect().right() <= pressure.rect().left()); + assert_eq!(pressure.accesskit_node().description().as_deref(), Some(TOOLTIP)); + assert!(!h.state().session.tools.brush.pressure_size); +} + +#[test] +fn the_toggle_updates_the_brush_settings_value_with_one_command_per_click() { + let mut h = bar(Tool::Smudge); + let n = brush_commands(&h); + toggle(&mut h); + assert!(h.state().session.tools.brush.pressure_size); + assert_eq!(h.state_mut().run("brush.get", json!({})).unwrap()["pressureSize"], json!(true)); + assert_eq!(brush_commands(&h), n + 1); + assert_eq!(h.state().session.journal.last().unwrap().1["brush"], json!({"pressureSize": true})); + toggle(&mut h); + assert!(!h.state().session.tools.brush.pressure_size); + assert_eq!(brush_commands(&h), n + 2); + assert_eq!(h.state().session.journal.last().unwrap().1["brush"], json!({"pressureSize": false})); +} + +#[test] +fn reset_tool_turns_pressure_off_and_other_tools_keep_their_own_setting() { + let mut h = bar(Tool::Brush); + h.state_mut().run("tools.setBrush", json!({"brush": {"pressureSize": true}})).unwrap(); + h.run_steps(2); + h.state_mut().ui.tool = Tool::Smudge; + h.run_steps(3); + assert!(!h.state().session.tools.brush.pressure_size, "Smudge starts with its own default"); + toggle(&mut h); + h.state_mut().ui.tool = Tool::Brush; + h.run_steps(3); + assert!(h.state().session.tools.brush.pressure_size, "the Brush setting is retained"); + h.state_mut().ui.tool = Tool::Smudge; + h.run_steps(3); + assert!(h.state().session.tools.brush.pressure_size, "Smudge remembers its value"); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "tool.reset", json!({})).unwrap(); + h.run_steps(2); + assert!(!h.state().session.tools.brush.pressure_size); + h.state_mut().ui.tool = Tool::Brush; + h.run_steps(3); + assert!(h.state().session.tools.brush.pressure_size, "resetting Smudge does not reset the Brush"); +} + +/// Read the actual shared generator's dabs for a pen tap, rather than duplicating its formula. +fn radii(brush: &BrushSettings, pressure: f32) -> Vec { + let mut generator = photocraft_paint::dynamics::DabGenerator::new(brush, 1.0); + let (mut dabs, mut dual) = (Vec::new(), Vec::new()); + generator.push(&[photocraft_paint::StrokePoint::new(28.0, 40.0, pressure)], &mut dabs, &mut dual); + generator.finish(&mut dabs, &mut dual); + assert!(!dabs.is_empty()); + dabs.into_iter().map(|dab| dab.radius).collect() +} + +#[test] +fn the_ui_toggle_changes_generated_dab_size_with_pressure_and_off_restores_the_baseline() { + let mut h = bar(Tool::Smudge); + let original = h.state().session.tools.brush.clone(); + let off_low = radii(&original, 0.25); + let off_full = radii(&original, 1.0); + assert_eq!(off_low, off_full); + toggle(&mut h); + let on = h.state().session.tools.brush.clone(); + assert_eq!(radii(&on, 1.0), off_full); + let low = radii(&on, 0.25); + assert!(low.iter().all(|r| (*r - original.size * 0.25 * 0.5).abs() < 1e-6)); + toggle(&mut h); + assert_eq!(radii(&h.state().session.tools.brush, 0.25), off_low); + assert_eq!(h.state().session.tools.brush.shape_dynamics, original.shape_dynamics, "the toggle does not rewrite preset dynamics"); +} + +/// A red/white edge and a real paint.smudge command, with the UI-selected brush and real point +/// pressures. All comparisons use complete resulting pixels, with no visual threshold. +fn smudged(brush: &BrushSettings, pressure: f32) -> (Vec, Vec) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 80, "depth": 32, "background": "white"})).unwrap(); + app.run("select.rect", json!({"x": 0, "y": 0, "width": 40, "height": 80})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.ui.tool = Tool::Smudge; + crate::paint_mouse::sync_tool_brush(&mut app); + app.run("tools.setBrush", json!({"brush": brush})).unwrap(); + app.ui.tool_options.strength = 100.0; + let read = |app: &PhotocraftApp| { + let state = app.session.active().unwrap(); + state.doc.layer(state.active_layer.unwrap()).unwrap().surface().unwrap().read_region(state.doc.bounds()) + }; + let before = read(&app); + let (command, mut params) = super::dab_params(&app, Tool::Smudge).unwrap(); + assert_eq!(command, "paint.smudge"); + params["points"] = json!([[28.0, 40.0, pressure], [42.0, 40.0, pressure], [58.0, 40.0, pressure]]); + app.run(command, params).unwrap(); + (before, read(&app)) +} + +#[test] +fn actual_smudge_pixels_follow_pressure_on_and_keep_the_existing_result_off() { + let mut h = bar(Tool::Smudge); + h.state_mut().run("tools.setBrush", json!({"brush": {"size": 20, "hardness": 1.0, "spacing": 0.25, "smoothing": {"enabled": false}}})).unwrap(); + h.run_steps(2); + let off = h.state().session.tools.brush.clone(); + let (before, off_low) = smudged(&off, 0.25); + let (_, off_full) = smudged(&off, 1.0); + assert_ne!(off_full, before, "the edge fixture must actually smudge"); + assert_eq!(off_low, off_full, "off keeps today's pressure-independent size"); + toggle(&mut h); + let on = h.state().session.tools.brush.clone(); + let (_, on_low) = smudged(&on, 0.25); + let (_, on_full) = smudged(&on, 1.0); + assert_ne!(on_low, on_full, "the actual command receives pen pressure and the selected brush"); + assert_ne!(on_low, off_low); + assert_eq!(on_full, off_full, "full pressure keeps the full-size result"); + toggle(&mut h); + assert_eq!(smudged(&h.state().session.tools.brush, 0.25).1, off_low); +} + +#[test] +fn the_smudge_change_does_not_add_pressure_controls_to_blur_or_sharpen() { + for tool in [Tool::Blur, Tool::Sharpen] { + assert!(bar(tool).query_by_label(PRESSURE).is_none(), "{tool:?}"); + } +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 78f2ae4726..3fbb67920f 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -52,6 +52,47 @@ pub struct Panels { pub use craft::ui::canvas_controls::TaskBarPlace; +/// What the contextual task bar was last shown for (#16758). A bar shown for another context puts an unpinned +/// place back to automatic placement; a pinned one keeps it. Not saved: it lives for the session. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum TaskBarContext { + /// No bar shown yet. + #[default] + None, + /// Free Transform's bar for one transform session. + Transform { doc: u64, session: u64 }, + /// The Crop tool's bar for one crop frame: `frame` counts the frames applied or discarded so far. + Crop { doc: u64, frame: u64 }, + /// The Frame tool's bar for one frame layer. + Frame { doc: u64, layer: u64 }, +} + +/// The contextual task bar's context bookkeeping (#16758), kept out of saved state. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct TaskBarTrack { + /// The context the bar was last shown for. + pub context: TaskBarContext, + /// The crop frames applied or discarded so far: the next frame is a new context. + pub crop_frame: u64, + /// A crop was pending when the crop bar last showed. + pub crop_pending: bool, +} + +impl UiState { + /// The contextual task bar is about to show for `context` (#16758): on a context change an unpinned bar goes back + /// to automatic placement (its dragged offset and place are cleared); a pinned bar keeps its place. + pub fn enter_task_bar_context(&mut self, context: TaskBarContext) { + if self.task_bar_track.context == context { + return; + } + self.task_bar_track.context = context; + if !self.panels.task_bar.pinned { + self.panels.task_bar.at = None; + self.panels.task_bar.offset = None; + } + } +} + impl Default for Panels { fn default() -> Self { Self { options_bar: true, status_bar: true, menu_bar: true, context_task_bar: true, task_bar: TaskBarPlace::default() } @@ -337,10 +378,13 @@ pub struct UiState { /// Frame tool (see `frame_tool`). #[serde(default)] pub frame_tool: crate::frame_tool::FrameToolUi, - /// The contextual task bar as drawn in the last frame: its screen rect `[x0, y0, x1, y1]` in - /// points, `None` while no bar shows (`ui.inspect` › `taskBar`). + /// The contextual crop task bar as the last canvas run drew it: its screen rect `[x0, y0, x1, y1]` + /// in points, `None` while no bar shows (`ui.inspect` › `taskBar`). #[serde(skip)] pub task_bar_shown: Option<[f32; 4]>, + /// What the contextual task bar was last shown for (#16758). + #[serde(skip)] + pub task_bar_track: TaskBarTrack, /// Artboard tool (see `artboard_tool`). pub artboard_tool: crate::artboard_tool::ArtboardToolUi, /// Modifier Keys panel, custom pixel aspect ratios, workspace dialogs (see `workspace_ui`). @@ -422,7 +466,7 @@ pub struct UiState { #[serde(default)] pub selection_mode: u8, #[serde(default)] - pub tool_options: ToolOptions, + pub tool_options: Tracked, /// The shape Fill / Stroke swatches' recently used gradients, newest first (the Gradient /// tab's Recent row). #[serde(default)] @@ -509,6 +553,7 @@ impl Default for UiState { web_table: Default::default(), frame_tool: Default::default(), task_bar_shown: None, + task_bar_track: TaskBarTrack::default(), artboard_tool: Default::default(), shell: Default::default(), layer_filter: LayerFilter::default(), @@ -546,7 +591,7 @@ impl Default for UiState { brush_curves_open: BTreeSet::new(), brushes_panel: brushes_list(), selection_mode: 0, - tool_options: ToolOptions::default(), + tool_options: Tracked::new(ToolOptions::default()), recent_gradients: Vec::new(), next_id: 1, status: String::new(), @@ -599,7 +644,7 @@ mod tests { let mut s = SampleAllLayers::default(); assert!(s.slot(Tool::Brush).is_none()); for t in [Tool::MagicWand, Tool::PaintBucket, Tool::Blur, Tool::Sharpen, Tool::Smudge, Tool::Remove] { - *s.slot(t).unwrap() = true; + *s.slot_mut(t).unwrap() = true; assert!(s.get(t), "{t:?}"); } assert!(!s.get(Tool::QuickSelection)); diff --git a/crates/ui-egui/src/state/tool_options.rs b/crates/ui-egui/src/state/tool_options.rs index 7d469db67d..463ed44dbe 100644 --- a/crates/ui-egui/src/state/tool_options.rs +++ b/crates/ui-egui/src/state/tool_options.rs @@ -3,11 +3,13 @@ use craft::draw::ui::crop::{CropSettings, CropSizeFields}; use craft::draw::ui::{PathOptionsSettings, TransformSettings, VectorMode}; use craft::imaging::ui::select::MagneticSettings; +use craft::ui::contract::PlainData; + use super::tool::Tool; use super::{Deserialize, Serialize}; /// Object Selection › gear › Object Finder Mode (#12857). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, PlainData)] pub enum ObjectFinderMode { /// Auto Refresh: the finder re-analyses the document after every edit. #[default] @@ -17,7 +19,7 @@ pub enum ObjectFinderMode { } /// Options-bar state for tools (Photoshop keeps these per tool). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, PlainData)] #[serde(default)] pub struct ToolOptions { pub tolerance: f32, @@ -77,6 +79,7 @@ pub struct ToolOptions { /// parameter format. Kept as overrides so saved engine defaults still supply unset fields. /// OpenType features and variable-font axes are merged per tag/axis. #[serde(default)] + #[plain_data(assume = "a JSON map of owned values: no interior mutability")] pub type_style_defaults: serde_json::Map, /// Type tool: paragraph direction of new type, "auto" (from the first strong character), /// "ltr" or "rtl" (TYPE-218-2). @@ -380,7 +383,7 @@ pub(super) fn default_brush_tool() -> Tool { /// tool, all off by default except the Patch tool's Content-Aware Sample All Layers (#5524, /// #12125): turning it on for the Magic Wand must not leave Blur or Smudge copying the composite /// onto the active layer. The Mixer Brush keeps its own with the brush (`MixerSettings`). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, PlainData)] #[serde(default)] pub struct SampleAllLayers { pub magic_wand: bool, @@ -416,29 +419,41 @@ impl Default for SampleAllLayers { } } +/// The field of `SampleAllLayers` that `$tool` keeps, borrowed as `$borrow`. +macro_rules! sample_all_slot { + ($this:ident, $tool:ident, $($borrow:tt)+) => { + Some(match $tool { + Tool::MagicWand => $($borrow)+ $this.magic_wand, + Tool::QuickSelection => $($borrow)+ $this.quick_selection, + Tool::ObjectSelection => $($borrow)+ $this.object_selection, + Tool::PaintBucket => $($borrow)+ $this.paint_bucket, + Tool::MagicEraser => $($borrow)+ $this.magic_eraser, + Tool::SpotHealing => $($borrow)+ $this.spot_healing, + Tool::Patch => $($borrow)+ $this.patch, + Tool::ContentAwareMove => $($borrow)+ $this.content_aware_move, + Tool::Remove => $($borrow)+ $this.remove, + Tool::Blur => $($borrow)+ $this.blur, + Tool::Sharpen => $($borrow)+ $this.sharpen, + Tool::Smudge => $($borrow)+ $this.smudge, + _ => return None, + }) + }; +} + impl SampleAllLayers { /// `tool`'s setting; false for a tool without the option. - pub fn get(mut self, tool: Tool) -> bool { - self.slot(tool).is_some_and(|v| *v) + pub fn get(self, tool: Tool) -> bool { + self.slot(tool).unwrap_or(false) } /// `tool`'s setting, or `None` for a tool without the option. - pub fn slot(&mut self, tool: Tool) -> Option<&mut bool> { - Some(match tool { - Tool::MagicWand => &mut self.magic_wand, - Tool::QuickSelection => &mut self.quick_selection, - Tool::ObjectSelection => &mut self.object_selection, - Tool::PaintBucket => &mut self.paint_bucket, - Tool::MagicEraser => &mut self.magic_eraser, - Tool::SpotHealing => &mut self.spot_healing, - Tool::Patch => &mut self.patch, - Tool::ContentAwareMove => &mut self.content_aware_move, - Tool::Remove => &mut self.remove, - Tool::Blur => &mut self.blur, - Tool::Sharpen => &mut self.sharpen, - Tool::Smudge => &mut self.smudge, - _ => return None, - }) + pub fn slot(&self, tool: Tool) -> Option { + sample_all_slot!(self, tool, &).copied() + } + + /// `tool`'s setting to write, or `None` for a tool without the option. + pub fn slot_mut(&mut self, tool: Tool) -> Option<&mut bool> { + sample_all_slot!(self, tool, &mut) } } diff --git a/crates/ui-egui/src/stroke_timing_tests.rs b/crates/ui-egui/src/stroke_timing_tests.rs index 52b297748a..677bf6c20b 100644 --- a/crates/ui-egui/src/stroke_timing_tests.rs +++ b/crates/ui-egui/src/stroke_timing_tests.rs @@ -19,7 +19,7 @@ fn harness() -> Harness<'static, Box> { if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { return; } - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); }, app, ); @@ -356,7 +356,7 @@ fn the_stroke_trace_times_each_frame_of_a_stroke_and_ends_on_release() { let moves = ctx.input(|i| i.raw.events.iter().filter(|e| matches!(e, egui::Event::PointerMoved(_))).count()); app.perf.stage.start(t0, moves); app.perf.stage.ui_start(t0, Some(0.004)); - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); app.finish_frame(&ctx, crate::gpu_canvas::now_ms() - t0); }, app, diff --git a/crates/ui-egui/src/task_bar_drag_context_tests.rs b/crates/ui-egui/src/task_bar_drag_context_tests.rs new file mode 100644 index 0000000000..df6c270577 --- /dev/null +++ b/crates/ui-egui/src/task_bar_drag_context_tests.rs @@ -0,0 +1,245 @@ +//! A dragged, unpinned contextual task bar goes back to automatic placement on the next context change (#16758). + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::app::framework::BuildApp as _; +use crate::control::{ControlRequest, Reply, handle}; +use crate::state::Tool; +use craft::behavior::geometry::CropBox; +use craft::behavior::kurbo::Rect as DocRect; + +type AppHarness = Harness<'static, Box>; + +fn harness() -> AppHarness { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 100, "y": 100, "width": 100, "height": 60})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.sync_views(); + app.ui.extras.rulers = false; + app.ui.tool = Tool::Move; + let mut h = Harness::builder().with_context(app.ctx().clone()).with_size(egui::vec2(1000.0, 700.0)).build_app( + |ui, app: &mut PhotocraftApp| { + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); + }, + app, + ); + h.run_steps(4); + let v = &mut h.state_mut().ui.views[0]; + v.zoom = 1.0; + v.center = [200.0, 150.0]; + v.clear_pending(); + h.run_steps(2); + h +} + +fn control(h: &mut AppHarness, method: &str, params: Value) -> Value { + let ctx = h.ctx.clone(); + let (request, _reply) = ControlRequest::new(method, params); + let Reply::Done(reply) = handle(h.state_mut(), &ctx, &request) else { panic!("{method} should reply immediately") }; + assert_eq!(reply["ok"], true, "{method}: {reply}"); + reply["result"].clone() +} + +fn bar(h: &mut AppHarness) -> Value { + control(h, "ui.inspect", json!({}))["taskBar"].clone() +} + +fn free_transform(h: &mut AppHarness) { + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransform", json!({})).unwrap(); + h.run_steps(6); +} + +fn drag_grip(h: &mut AppHarness) { + let from = h.get_by_label("Move bar").rect().center(); + let to = from + egui::vec2(80.0, -40.0); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + h.event(egui::Event::PointerMoved(from)); + h.run_steps(1); + h.event(button(from, true)); + h.run_steps(1); + for step in 1..=6 { + h.event(egui::Event::PointerMoved(from + (to - from) * (step as f32 / 6.0))); + h.run_steps(1); + } + h.event(button(to, false)); + h.run_steps(3); +} + +fn crop_frame(h: &mut AppHarness) { + control(h, "ui.set", json!({"tool": "crop"})); + h.run_steps(2); + h.state_mut().canvas_tools.crop.tool.crop_to(CropBox::new(DocRect::new(100.0, 100.0, 200.0, 160.0), 0.0)); + h.run_steps(6); +} + +fn place(h: &AppHarness) -> crate::state::TaskBarPlace { + h.state().ui.panels.task_bar +} + +/// Free Transform with its bar dragged by the grip: the drop is the bar's offset, unpinned. +fn dragged_transform() -> AppHarness { + let mut h = harness(); + free_transform(&mut h); + drag_grip(&mut h); + let p = place(&h); + assert!(!p.pinned && p.at.is_none() && p.offset.is_some(), "an unpinned drag keeps an offset: {p:?}"); + h +} + +fn leave_transform(h: &mut AppHarness) { + crate::transform_tool::cancel(h.state_mut()); + h.run_steps(4); + assert!(h.state().ui.transform.is_none()); +} + +/// Where the crop bar shows with automatic placement for the same frame. +fn automatic_crop_rect() -> Value { + let mut h = harness(); + crop_frame(&mut h); + let shown = bar(&mut h); + assert!(shown["offset"].is_null() && shown["at"].is_null()); + shown["rect"].clone() +} + +/// The transform bar's drag is cleared once the crop bar shows: another bar kind is another context. +#[test] +fn a_dragged_bar_goes_back_to_automatic_placement_for_another_bar() { + let mut h = dragged_transform(); + leave_transform(&mut h); + crop_frame(&mut h); + let crop = bar(&mut h); + assert_eq!(crop["visible"], true); + assert!(crop["offset"].is_null() && crop["at"].is_null(), "the drag is cleared on the context change: {crop}"); + assert_eq!(crop["rect"], automatic_crop_rect(), "the bar shows under the crop frame again"); +} + +/// A new transform box is a new context too. +#[test] +fn a_dragged_bar_goes_back_to_automatic_placement_for_a_new_transform() { + let mut h = dragged_transform(); + leave_transform(&mut h); + free_transform(&mut h); + let p = place(&h); + assert!(p.offset.is_none() && p.at.is_none(), "{p:?}"); +} + +/// Within one context the drop stays: later passes keep the offset and the bar where it was dropped. +#[test] +fn a_dragged_bar_stays_where_it_was_dropped_in_the_same_context() { + let mut h = dragged_transform(); + let (kept, rect) = (place(&h), bar(&mut h)["rect"].clone()); + h.run_steps(6); + assert_eq!(place(&h), kept); + assert_eq!(bar(&mut h)["rect"], rect); +} + +/// A pinned bar keeps its place across contexts. +#[test] +fn a_pinned_bar_keeps_its_place_across_contexts() { + let mut h = dragged_transform(); + h.get_by_label("More options").click(); + h.run_steps(4); + h.get_by_label("Pin bar position").click(); + h.run_steps(4); + let pinned = place(&h); + assert!(pinned.pinned && pinned.at.is_some(), "{pinned:?}"); + leave_transform(&mut h); + crop_frame(&mut h); + assert_eq!(place(&h), pinned, "the pinned place is kept for the crop bar"); + assert_eq!(bar(&mut h)["visible"], true); +} + +/// Reset bar position still puts the bar back to automatic placement, unpinned. +#[test] +fn reset_bar_position_is_unchanged() { + let mut h = dragged_transform(); + h.get_by_label("More options").click(); + h.run_steps(4); + h.get_by_label("Reset bar position").click(); + h.run_steps(4); + assert_eq!(place(&h), crate::state::TaskBarPlace::default()); +} + +/// A crop frame applied or discarded ends the context: the next frame's bar is placed automatically. +#[test] +fn a_new_crop_frame_is_a_new_context() { + let mut h = harness(); + crop_frame(&mut h); + assert!(crate::crop_ui::pending(h.state()), "the frame drawn with crop_to is pending"); + drag_grip(&mut h); + assert!(place(&h).offset.is_some()); + h.run_steps(4); + assert!(place(&h).offset.is_some(), "the same frame keeps the drop"); + crate::crop_ui::discard(h.state_mut()); + h.run_steps(4); + crop_frame(&mut h); + let p = place(&h); + assert!(p.offset.is_none() && p.at.is_none(), "{p:?}"); + assert_eq!(bar(&mut h)["rect"], automatic_crop_rect()); +} + +/// A crop discarded while the bar is hidden still ends that frame's context: the next frame's bar is automatic. +#[test] +fn a_crop_discarded_while_the_bar_is_hidden_is_a_new_context() { + let mut h = harness(); + crop_frame(&mut h); + drag_grip(&mut h); + assert!(place(&h).offset.is_some()); + control(&mut h, "ui.set", json!({"panels": {"context_task_bar": false}})); + h.run_steps(4); + crate::crop_ui::discard(h.state_mut()); + h.run_steps(4); + h.state_mut().canvas_tools.crop.tool.crop_to(CropBox::new(DocRect::new(100.0, 100.0, 200.0, 160.0), 0.0)); + h.run_steps(4); + assert!(crate::crop_ui::pending(h.state()), "a new pending frame while the bar is hidden"); + control(&mut h, "ui.set", json!({"panels": {"context_task_bar": true}})); + h.run_steps(6); + let p = place(&h); + assert!(p.offset.is_none() && p.at.is_none(), "{p:?}"); + assert_eq!(bar(&mut h)["rect"], automatic_crop_rect()); +} + +/// The Frame tool's bar: another frame layer is another context. +#[test] +fn another_frame_layer_is_a_new_context() { + let mut h = harness(); + let a = h.state_mut().run("layer.new.frame", json!({"x": 40, "y": 40, "width": 100, "height": 80})).unwrap()["layer"].as_u64().unwrap(); + let b = h.state_mut().run("layer.new.frame", json!({"x": 220, "y": 120, "width": 100, "height": 80})).unwrap()["layer"].as_u64().unwrap(); + h.state_mut().run("layer.select", json!({"layer": a})).unwrap(); + control(&mut h, "ui.set", json!({"tool": "frame"})); + h.run_steps(6); + drag_grip(&mut h); + assert!(place(&h).offset.is_some(), "the frame bar's drag is kept: {:?}", place(&h)); + h.run_steps(4); + assert!(place(&h).offset.is_some(), "the same frame keeps the drop"); + h.state_mut().run("layer.select", json!({"layer": b})).unwrap(); + h.run_steps(6); + let p = place(&h); + assert!(p.offset.is_none() && p.at.is_none(), "{p:?}"); +} + +/// A pinned bar ignores the context: `enter_task_bar_context` never touches its place, an unpinned one is cleared +/// only when the context differs. +#[test] +fn enter_task_bar_context_clears_only_an_unpinned_place_on_a_change() { + use crate::state::{TaskBarContext, UiState}; + let mut ui = UiState::default(); + let first = TaskBarContext::Transform { doc: 1, session: 7 }; + ui.enter_task_bar_context(first); + ui.panels.task_bar.offset = Some([5.0, 6.0]); + ui.enter_task_bar_context(first); + assert_eq!(ui.panels.task_bar.offset, Some([5.0, 6.0]), "same context: kept"); + ui.enter_task_bar_context(TaskBarContext::Crop { doc: 1, frame: 0 }); + assert_eq!(ui.panels.task_bar.offset, None, "another context: cleared"); + ui.panels.task_bar.pinned = true; + ui.panels.task_bar.at = Some([1.0, 2.0]); + ui.enter_task_bar_context(TaskBarContext::Frame { doc: 1, layer: 3 }); + assert_eq!((ui.panels.task_bar.pinned, ui.panels.task_bar.at), (true, Some([1.0, 2.0])), "pinned: kept"); +} diff --git a/crates/ui-egui/src/tool_memory.rs b/crates/ui-egui/src/tool_memory.rs index 7c4b555616..70ad69cdef 100644 --- a/crates/ui-egui/src/tool_memory.rs +++ b/crates/ui-egui/src/tool_memory.rs @@ -90,7 +90,7 @@ pub fn persist(app: &mut PhotocraftApp, ctx: &egui::Context) { if let Ok(now) = serde_json::to_value(tool) && app.session.prefs().selected_tool != now { - app.session.prefs.edit(|p| p.selected_tool = now); + app.session.prefs.remember(|p| p.selected_tool = now); // prefs_ui::tick ran before the panels; ensure it can flush this new revision. ctx.request_repaint(); } @@ -98,13 +98,13 @@ pub fn persist(app: &mut PhotocraftApp, ctx: &egui::Context) { persist_colors(app, ctx); persist_group_tools(app, ctx, tool); persist_brushes(app); - if app.prefs_rt.tool_options.as_ref() == Some(&app.ui.tool_options) { + if app.prefs_rt.tool_options.as_ref() == Some(&*app.ui.tool_options) { return; } - app.prefs_rt.tool_options = Some(app.ui.tool_options.clone()); + app.prefs_rt.tool_options = Some((*app.ui.tool_options).clone()); let now = changed(&app.ui.tool_options); if app.session.prefs().tool_options != now { - app.session.prefs.edit(|p| p.tool_options = now); + app.session.prefs.remember(|p| p.tool_options = now); } } @@ -138,7 +138,7 @@ fn persist_colors(app: &mut PhotocraftApp, ctx: &egui::Context) { photocraft_engine::prefs::stamp_tool_color_picks(&mut saved, &app.session.prefs().tool_colors); saved }; - app.session.prefs.edit(|p| p.tool_colors = photocraft_engine::prefs::ToolColors(saved)); + app.session.prefs.remember(|p| p.tool_colors = photocraft_engine::prefs::ToolColors(saved)); // Panels and shortcuts can change colours after prefs_ui::tick already ran this frame. ctx.request_repaint(); } @@ -289,7 +289,7 @@ fn persist_group_tools(app: &mut PhotocraftApp, ctx: &egui::Context, tool: Tool) if let Ok(now) = serde_json::to_value(&app.ui.group_tools) && app.session.prefs().group_tools != now { - app.session.prefs.edit(|p| p.group_tools = now); + app.session.prefs.remember(|p| p.group_tools = now); // As for the selected tool: prefs_ui::tick ran before the panels. ctx.request_repaint(); } @@ -322,7 +322,7 @@ fn persist_brushes(app: &mut PhotocraftApp) { }; app.prefs_rt.tool_brushes = Some((owner, brushes.clone())); if app.session.prefs().tool_brushes != now { - app.session.prefs.edit(|p| p.tool_brushes = now); + app.session.prefs.remember(|p| p.tool_brushes = now); } } @@ -422,12 +422,12 @@ pub fn restore(app: &mut PhotocraftApp) { } if let Ok(mut o) = serde_json::from_value(Value::Object(cur)) { sanitize(&mut o); - app.ui.tool_options = o; + *app.ui.tool_options = o; } } else if !saved.is_null() { log::warn!("Preferences: the remembered tool options are not an object; using the defaults"); } - app.prefs_rt.tool_options = Some(app.ui.tool_options.clone()); + app.prefs_rt.tool_options = Some((*app.ui.tool_options).clone()); restore_colors(app); restore_brushes(app); } diff --git a/crates/ui-egui/src/tools/adjustment_brush.rs b/crates/ui-egui/src/tools/adjustment_brush.rs index 04b3cf28d2..e18c508d75 100644 --- a/crates/ui-egui/src/tools/adjustment_brush.rs +++ b/crates/ui-egui/src/tools/adjustment_brush.rs @@ -6,7 +6,7 @@ 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::contract::{Bind, Entry, Props as _, Show as _, bind_tracked}; use craft::ui::display::Divider; use craft::ui::pickers::Select; use photocraft_engine::adjustment_brush_cmds::{self as ab, ENTRIES, INDEXED_ALERT}; @@ -152,7 +152,7 @@ pub fn options_bar(ui: &mut egui::Ui, app: &mut PhotocraftApp, tool: Tool) -> bo 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); // On, the canvas tints what the active adjustment layer's mask reveals (`raster_source::MaskTint`, #12520). - Checkbox::new(Bind::bound(&mut app.ui.tool_options.adjustment_brush_overlay)) + Checkbox::new(bind_tracked!(app.ui.tool_options => adjustment_brush_overlay)) .label(tl!("Overlay").to_owned()) .tooltip(tl!("Show or hide the painted mask areas").to_owned()) .show(ui); @@ -160,7 +160,7 @@ pub fn options_bar(ui: &mut egui::Ui, app: &mut PhotocraftApp, tool: Tool) -> bo 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); + let out = option_cells::number(tl!("Opacity:"), Bind::bound(&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); @@ -173,7 +173,7 @@ pub fn options_bar(ui: &mut egui::Ui, app: &mut PhotocraftApp, tool: Tool) -> bo 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); + let out = option_cells::number(tl!("Flow:"), Bind::bound(&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); diff --git a/crates/ui-egui/src/tools/analysis/bars.rs b/crates/ui-egui/src/tools/analysis/bars.rs index 15d34f36e8..31d2f1d580 100644 --- a/crates/ui-egui/src/tools/analysis/bars.rs +++ b/crates/ui-egui/src/tools/analysis/bars.rs @@ -7,7 +7,7 @@ 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 _, ShowContainer as _}; +use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, bind_tracked}; use craft::ui::display::{Divider, Text}; use craft::ui::form::Field; use craft::ui::pickers::Select; @@ -161,8 +161,8 @@ fn count(app: &mut PhotocraftApp, ui: &mut egui::Ui, doc: &photocraft_doc::Docum Divider::vertical().show(ui); let (marker, label) = (g.marker_size as f32, g.label_size as f32); let (mut new_marker, mut new_label) = (marker, label); - let marker_out = option_cells::number(tl!("Marker Size"), &mut new_marker, MARKER_SIZE).whole().show(ui); - let label_out = option_cells::number(tl!("Label Size"), &mut new_label, LABEL_SIZE).whole().show(ui); + let marker_out = option_cells::number(tl!("Marker Size"), Bind::bound(&mut new_marker), MARKER_SIZE).whole().show(ui); + let label_out = option_cells::number(tl!("Label Size"), Bind::bound(&mut new_label), LABEL_SIZE).whole().show(ui); // A typed size out of range takes the closest value and says so once (#13530). for alert in [&marker_out.out_of_range, &label_out.out_of_range].into_iter().flatten() { option_cells::range_alert(app, ui, alert); @@ -207,7 +207,7 @@ fn sampler(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let n = app.session.active().map_or(0, |d| d.color_samplers.len()); // One Sample Size setting, shared with the Eyedropper (#11732). // PLAN: assumed `SamplerOptions::show(ui)` returns an output with `clear_all: bool`. - let out = SamplerOptions::new(n, Bind::bound(&mut app.ui.tool_options.eyedropper.size)).show(ui); + let out = SamplerOptions::new(n, bind_tracked!(app.ui.tool_options => eyedropper.size)).show(ui); if out.clear_all { run(app, "view.colorSamplers.clear", json!({})); } diff --git a/crates/ui-egui/src/tools/analysis/canvas.rs b/crates/ui-egui/src/tools/analysis/canvas.rs index 2f29a221d1..6c6f2cf9e1 100644 --- a/crates/ui-egui/src/tools/analysis/canvas.rs +++ b/crates/ui-egui/src/tools/analysis/canvas.rs @@ -23,9 +23,6 @@ use crate::canvas::document_display::CanvasHost; use crate::canvas::tools::{FamilyTool, ToolScope}; use crate::state::Tool; -/// A drag of a Count marker that moves less than this, in document units, is a click: nothing moves. -const MOVED: f64 = 0.5; - /// The family's state between passes, kept in `CanvasTools::analysis`. pub(crate) struct AnalysisTools { ruler: RulerTool, @@ -214,6 +211,11 @@ fn dist(a: [f64; 2], b: [f64; 2]) -> f64 { (a[0] - b[0]).hypot(a[1] - b[1]) } +/// The centre of the document pixel that holds `at`, where the Count tool puts a marker (#11761). +fn pixel_centre(at: [f64; 2]) -> [f64; 2] { + [at[0].floor() + 0.5, at[1].floor() + 0.5] +} + /// The ruler line, the sampler marks, the count markers and the note cards over the document, in the canvas body over /// `rect`. The marks show with every tool; the line with its handles only with the Ruler. View › Extras off hides the /// line (View › Show has no Ruler entry, #11987) and the sampler marks, whose points and Info readouts stay (#11741). @@ -290,7 +292,7 @@ enum CountEvent { /// The Count tool's state: the marker a drag holds and the events not yet drained. #[derive(Debug, Default)] pub(crate) struct CountTool { - /// The marker being dragged: group, index and where the press was. + /// The marker being dragged: group, index and where the marker was at the press. moving: Option<(usize, usize, [f64; 2])>, events: Vec, } @@ -335,12 +337,15 @@ impl CanvasTool for CountPass<'_> { ToolAction::Done } Some((group, index)) => { - self.state.moving = Some((group, index, at)); + let marker = + self.scope.with_app(|app| app.session.active().and_then(|st| st.doc.measurement.count_groups.get(group)?.points.get(index).copied())); + let Some(marker) = marker else { return ToolAction::Ignored }; + self.state.moving = Some((group, index, marker)); ToolAction::Claimed } None => { if !pointer.mods.alt { - self.state.events.push(CountEvent::Add { at }); + self.state.events.push(CountEvent::Add { at: pixel_centre(at) }); } ToolAction::Done } @@ -351,8 +356,8 @@ impl CanvasTool for CountPass<'_> { fn release(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) { let Some((group, index, from)) = self.state.moving.take() else { return }; - // A press and release on one spot moves nothing. - if let Some(to) = doc_at(cx, pointer.pos).filter(|to| dist(from, *to) > MOVED) { + // A plain click on a marker re-centres it on the clicked pixel too; a marker already there moves nothing. + if let Some(to) = doc_at(cx, pointer.pos).map(pixel_centre).filter(|to| *to != from) { self.state.events.push(CountEvent::Move { group, index, to }); } } diff --git a/crates/ui-egui/src/tools/analysis/mod.rs b/crates/ui-egui/src/tools/analysis/mod.rs index 220c10e200..488d9499f8 100644 --- a/crates/ui-egui/src/tools/analysis/mod.rs +++ b/crates/ui-egui/src/tools/analysis/mod.rs @@ -48,6 +48,10 @@ mod count_group_name_tests; #[path = "../count_size_alert_tests.rs"] mod count_size_alert_tests; +#[cfg(test)] +#[path = "../count_pixel_centre_tests.rs"] +mod count_pixel_centre_tests; + /// The registry ids of the two panels the menu items toggle. pub(crate) const MEASUREMENT_LOG: &str = "measurementLog"; pub(crate) const NOTES: &str = "notes"; diff --git a/crates/ui-egui/src/tools/analysis/tests.rs b/crates/ui-egui/src/tools/analysis/tests.rs index d96462aee6..bff3b713ec 100644 --- a/crates/ui-egui/src/tools/analysis/tests.rs +++ b/crates/ui-egui/src/tools/analysis/tests.rs @@ -59,17 +59,17 @@ fn count_tool_add_move_remove() { let pts = |app: &PhotocraftApp| app.session.active().unwrap().doc.measurement.count_groups[0].points.clone(); assert_eq!(pts(&app).len(), 2); let past = |app: &PhotocraftApp| app.session.active().unwrap().history.past_len(); - // A move under half a pixel sends no `count.move`: the marker and the history stay. + // A release in the pixel the marker sits on sends no `count.move`: the marker and the history stay. let before = past(&app); down(&mut app, 20.0, 20.0, egui::Modifiers::NONE); mv(&mut app, 20.3, 20.0, egui::Modifiers::NONE); up(&mut app, 20.3, 20.0); - assert_eq!(pts(&app)[0], [20.0, 20.0]); - assert_eq!(past(&app), before, "a sub-pixel move is no step"); + assert_eq!(pts(&app)[0], [20.5, 20.5]); + assert_eq!(past(&app), before, "a move within the marker's pixel is no step"); // A longer drag moves marker 1 in one step. down(&mut app, 20.5, 20.5, egui::Modifiers::NONE); up(&mut app, 30.0, 25.0); - assert_eq!(pts(&app)[0], [30.0, 25.0]); + assert_eq!(pts(&app)[0], [30.5, 25.5]); assert_eq!(past(&app), before + 1, "the move is one step"); // ⌥-click removes. down(&mut app, 50.0, 50.0, egui::Modifiers::ALT); @@ -94,9 +94,9 @@ fn over_a_marker_is_the_clicks_own_hit_test() { let pts = app.session.active().unwrap().doc.measurement.count_groups[0].points.clone(); match hit { Some(_) => { - // The pointer position passes through f32 on its way to the marker. + // The marker lands on the centre of the release pixel (#11761). assert!( - pts.len() == 1 && (pts[0][0] - at[0]).abs() < 1e-4 && (pts[0][1] - (at[1] + 10.0)).abs() < 1e-4, + pts.len() == 1 && pts[0] == [at[0].floor() + 0.5, (at[1] + 10.0).floor() + 0.5], "{dx} px: the press moved the marker the cursor marked: {pts:?}" ); } @@ -444,7 +444,7 @@ fn count_number_height(label_size: u32) -> f32 { app.sync_views(); let mut h = egui_kittest::Harness::builder().with_context(app.ctx().clone()).with_size(egui::vec2(900.0, 600.0)).build_app( |ui, app: &mut PhotocraftApp| { - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); }, app, ); diff --git a/crates/ui-egui/src/tools/brush_feedback.rs b/crates/ui-egui/src/tools/brush_feedback.rs index f0de4f44a7..95f1ae2081 100644 --- a/crates/ui-egui/src/tools/brush_feedback.rs +++ b/crates/ui-egui/src/tools/brush_feedback.rs @@ -32,7 +32,7 @@ pub(crate) fn show(ui: &mut egui::Ui, app: &mut PhotocraftApp, rect: egui::Rect, show_smoothing_string(ui, app, rect); crate::object_finder::show(ui, app, at); if let Some(at) = at { - let shift = craft::ui::runtime::pointer::frame(ui.ctx()).mods.shift; + let shift = craft::ui::runtime::pointer::mods(ui.ctx()).shift; let tool = app.ui.tool; crate::stroke_constraint::show_line_preview(ui, app, at, tool, shift); } @@ -54,7 +54,7 @@ fn show_clone_overlay(ui: &mut egui::Ui, app: &mut PhotocraftApp, at: Option Option<&'static str> { /// The tool's name in the alerts, for the tools whose wording was measured: the Brush, the /// Sharpen tool (#12952), the Sponge (#13030), the Smudge tool (#12965), the Burn tool (#12672), the Healing Brush (#12111), the Art History Brush -/// (#12638) and the Classic gradient (the live Gradient makes a fill layer and isn't measured, #12017). +/// (#12638), the Paint Bucket (#12537) and the Classic gradient (the live Gradient makes a fill layer and isn't measured, #12017). pub fn tool_name(app: &PhotocraftApp, tool: Tool) -> Option<&'static str> { match tool { Tool::Brush => Some(tl!("brush tool")), @@ -53,6 +53,8 @@ pub fn tool_name(app: &PhotocraftApp, tool: Tool) -> Option<&'static str> { Tool::Burn => Some(tl!("burn tool")), Tool::Healing => Some(tl!("healing brush")), Tool::ArtHistoryBrush => Some(tl!("art history brush")), + // The Paint Bucket's click (#12537). + Tool::PaintBucket => Some(tl!("paint bucket")), Tool::Gradient if app.ui.tool_options.gradient_classic => Some(tl!("gradient tool")), _ => None, } @@ -132,11 +134,13 @@ fn layer_refusal(app: &PhotocraftApp, tool: Tool) -> Option<&'static str> { } } -/// Whether `locks` refuse `tool`: Lock All, and for the Sharpen, Sponge, Smudge and Burn tools and the -/// Art History Brush Lock Image Pixels as well (measured for them; the Brush keeps today's -/// behaviour there). +/// Whether `locks` refuse `tool`: Lock All, and for the Sharpen, Sponge, Smudge and Burn tools, the +/// Art History Brush, the Magic Eraser and the Paint Bucket (#12537) Lock Image Pixels as well +/// (measured for them; the Brush keeps today's behaviour there). fn locked(locks: photocraft_doc::Locks, tool: Tool) -> bool { - locks.all || (matches!(tool, Tool::Sharpen | Tool::Sponge | Tool::Smudge | Tool::Burn | Tool::ArtHistoryBrush | Tool::MagicEraser) && locks.pixels) + locks.all + || (matches!(tool, Tool::Sharpen | Tool::Sponge | Tool::Smudge | Tool::Burn | Tool::ArtHistoryBrush | Tool::MagicEraser | Tool::PaintBucket) + && locks.pixels) } /// A Spot Healing press on an empty pixel layer with Sample All Layers off (#12581): when that layer is hidden, the @@ -186,3 +190,7 @@ mod burn_refusal_alert_tests; #[cfg(test)] #[path = "../healing_refusal_alert_tests.rs"] mod healing_refusal_alert_tests; + +#[cfg(test)] +#[path = "../paint_bucket_refusal_alerts_tests.rs"] +mod paint_bucket_refusal_alerts_tests; diff --git a/crates/ui-egui/src/tools/count_pixel_centre_tests.rs b/crates/ui-egui/src/tools/count_pixel_centre_tests.rs new file mode 100644 index 0000000000..f2503e083c --- /dev/null +++ b/crates/ui-egui/src/tools/count_pixel_centre_tests.rs @@ -0,0 +1,71 @@ +//! #11761: a Count marker the tool adds or moves sits on the centre of the pixel under the pointer, also on the +//! pasteboard, and a plain click on a marker re-centres it there as one history state. `count.add` and `count.move` +//! called with coordinates keep them as given. + +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::ToolEvent; +use crate::state::Tool; + +fn app() -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.ui.tool = Tool::Count; + app +} + +fn press(app: &mut PhotocraftApp, x: f64, y: f64) { + crate::canvas::tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, egui::Modifiers::NONE); +} + +fn release(app: &mut PhotocraftApp, x: f64, y: f64) { + crate::canvas::tool_event(app, ToolEvent::Up { x, y }, egui::Modifiers::NONE); +} + +fn points(app: &PhotocraftApp) -> Vec<[f64; 2]> { + app.session.active().unwrap().doc.measurement.count_groups.first().map(|g| g.points.clone()).unwrap_or_default() +} + +fn steps(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.past_len() +} + +#[test] +fn a_click_adds_the_marker_on_the_pixel_centre() { + let mut app = app(); + for (at, centre) in [([99.3, 49.7], [99.5, 49.5]), ([-164.0, 20.2], [-163.5, 20.5])] { + press(&mut app, at[0], at[1]); + release(&mut app, at[0], at[1]); + assert_eq!(points(&app).last(), Some(¢re), "a click at {at:?}"); + } +} + +#[test] +fn a_drag_drops_the_marker_on_the_release_pixel_centre() { + let mut app = app(); + app.run("count.add", json!({"x": 20.5, "y": 20.5})).unwrap(); + let before = steps(&app); + press(&mut app, 20.5, 20.5); + release(&mut app, 60.4, 30.6); + assert_eq!(points(&app), vec![[60.5, 30.5]]); + assert_eq!(steps(&app), before + 1, "the drag is one step"); +} + +#[test] +fn a_click_on_a_marker_re_centres_it_once() { + let mut app = app(); + // Commands keep the coordinates they are given. + app.run("count.add", json!({"x": 40.25, "y": 50.75})).unwrap(); + assert_eq!(points(&app), vec![[40.25, 50.75]]); + let before = steps(&app); + press(&mut app, 43.2, 50.7); + release(&mut app, 43.2, 50.7); + assert_eq!(points(&app), vec![[43.5, 50.5]], "the click moved the marker to the clicked pixel's centre"); + assert_eq!(steps(&app), before + 1, "the re-centring is one step"); + // A click in the pixel the marker already sits on changes nothing. + press(&mut app, 43.9, 50.1); + release(&mut app, 43.9, 50.1); + assert_eq!(points(&app), vec![[43.5, 50.5]]); + assert_eq!(steps(&app), before + 1, "an unchanged centre is no step"); +} diff --git a/crates/ui-egui/src/tools/crop_task_bar.rs b/crates/ui-egui/src/tools/crop_task_bar.rs index 97e8c0bad6..0fc4bdcdc5 100644 --- a/crates/ui-egui/src/tools/crop_task_bar.rs +++ b/crates/ui-egui/src/tools/crop_task_bar.rs @@ -21,7 +21,7 @@ use craft::ui::runtime::env::Label; use crate::PhotocraftApp; use crate::crop_ui; -use crate::state::Tool; +use crate::state::{TaskBarContext, Tool}; /// The bar shows: the Crop tool with a frame, the Window toggle on, no dialog over the canvas. fn wanted(app: &PhotocraftApp) -> bool { @@ -36,11 +36,16 @@ pub fn eligible(app: &PhotocraftApp) -> bool { /// Shows the bar under the active document's crop frame, inside `area` (the canvas body's rect). pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, area: egui::Rect) { + // The canvas run that shows the bar reports where; a replay of that run shows it there still. + app.ui.task_bar_shown = None; + // A crop applied or discarded while the bar is hidden still ends that frame's context. + track_crop_frame(app); if !wanted(app) { return; } let Some(frame) = app.canvas_tools.crop.tool.frame() else { return }; let corners = frame.corners(); + enter_context(app); // The body borrows `app`, so the place lives in a local while the bar is shown. let mut place = app.ui.panels.task_bar; let output = TaskBar::new(label(tl!("Contextual Task Bar")), &corners, Bind::bound(&mut place)).show(ui, area, |ui, cx| { @@ -73,3 +78,24 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, area: egui::Rect) { fn label(text: &str) -> Label { Label::from(text.to_string()) } + +/// Counts the crop frames that end (applied or discarded) on every pass, whether the bar shows or not. +fn track_crop_frame(app: &mut PhotocraftApp) { + let pending = app.canvas_tools.crop.tool.session().pending(); + let track = &mut app.ui.task_bar_track; + if track.crop_pending && !pending { + track.crop_frame = track.crop_frame.wrapping_add(1); + } + track.crop_pending = pending; +} + +/// A new crop frame (the last one applied or discarded) or another document is a new context for the bar (#16758). +fn enter_context(app: &mut PhotocraftApp) { + let Some(doc) = app.session.active().map(|d| d.doc.id.0) else { return }; + let frame = app.ui.task_bar_track.crop_frame; + app.ui.enter_task_bar_context(TaskBarContext::Crop { doc, frame }); +} + +#[cfg(test)] +#[path = "../task_bar_drag_context_tests.rs"] +mod task_bar_drag_context_tests; diff --git a/crates/ui-egui/src/tools/direct_select/tests.rs b/crates/ui-egui/src/tools/direct_select/tests.rs index f849a9d613..805529af71 100644 --- a/crates/ui-egui/src/tools/direct_select/tests.rs +++ b/crates/ui-egui/src/tools/direct_select/tests.rs @@ -245,7 +245,7 @@ fn a_curvature_pen_double_click_through_the_canvas_rounds_a_corner() { app.ui.extras.rulers = false; let mut h = Harness::builder().with_context(app.ctx().clone()).with_size(vec2(1000.0, 700.0)).with_step_dt(1.0 / 60.0).build_ui_state( |ui, app: &mut Box| { - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); }, app, ); diff --git a/crates/ui-egui/src/tools/eraser_ui.rs b/crates/ui-egui/src/tools/eraser_ui.rs index 12fd03a433..c3a701c0a9 100644 --- a/crates/ui-egui/src/tools/eraser_ui.rs +++ b/crates/ui-egui/src/tools/eraser_ui.rs @@ -7,7 +7,7 @@ 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 _, ShowContainer as _}; +use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, bind_tracked}; use craft::ui::display::Divider; use craft::ui::form::Field; use craft::ui::pickers::Select; @@ -148,8 +148,8 @@ pub(crate) fn stored_tolerance(v: f32) -> f32 { } /// A check box named `label` over `value`. -fn check(ui: &mut egui::Ui, label: &str, value: &mut bool, tip: Option<&str>) { - let mut checkbox = Checkbox::new(Bind::bound(value)).label(label.to_owned()); +fn check(ui: &mut egui::Ui, label: &str, value: Bind<'_, bool>, tip: Option<&str>) { + let mut checkbox = Checkbox::new(value).label(label.to_owned()); if let Some(tip) = tip { checkbox = checkbox.tooltip(tip.to_owned()); } @@ -168,28 +168,27 @@ pub fn options_bar(ui: &mut egui::Ui, app: &mut PhotocraftApp, tool: Tool) -> bo } fn magic_eraser_members(ui: &mut egui::Ui, app: &mut PhotocraftApp) { - let o = &mut app.ui.tool_options; // The field clamps without an alert, as the reference's Magic Eraser Tolerance does. - let _ = option_cells::number(tl!("Tolerance:"), &mut o.tolerance, 0.0..=255.0).show(ui); - check(ui, tl!("Anti-alias"), &mut o.anti_alias, None); - check(ui, tl!("Contiguous"), &mut o.contiguous, None); - check(ui, tl!("Sample All Layers"), &mut o.sample_all.magic_eraser, None); + let _ = option_cells::number(tl!("Tolerance:"), bind_tracked!(app.ui.tool_options => tolerance), 0.0..=255.0).show(ui); + let (anti_alias, contiguous, sample_all) = bind_tracked!(app.ui.tool_options => anti_alias, contiguous, sample_all.magic_eraser); + check(ui, tl!("Anti-alias"), anti_alias, None); + check(ui, tl!("Contiguous"), contiguous, None); + check(ui, tl!("Sample All Layers"), sample_all, None); Divider::vertical().show(ui); - let _ = option_cells::number(tl!("Opacity:"), &mut o.magic_eraser_opacity, 1.0..=100.0).unit("%").show(ui); + let _ = option_cells::number(tl!("Opacity:"), bind_tracked!(app.ui.tool_options => magic_eraser_opacity), 1.0..=100.0).unit("%").show(ui); } fn background_eraser_members(ui: &mut egui::Ui, app: &mut PhotocraftApp) { let mut alerts = Vec::new(); { - let o = &mut app.ui.tool_options; let sampling = [ Entry::new("continuous".to_string(), tl!("Sampling: Continuous")).icon(IconId::new("eyedropper")), Entry::new("once".to_string(), tl!("Sampling: Once")).icon(IconId::new("target")), Entry::new("backgroundSwatch".to_string(), tl!("Sampling: Background Swatch")).icon(IconId::new("square")), ]; - let picked = Segmented::new(tl!("Sampling"), Bind::given(o.bg_sampling.clone()), &sampling).show(ui).value().cloned(); + let picked = Segmented::new(tl!("Sampling"), Bind::given(app.ui.tool_options.bg_sampling.clone()), &sampling).show(ui).value().cloned(); if let Some(sampling) = picked { - o.bg_sampling = sampling; + app.ui.tool_options.bg_sampling = sampling; } Divider::vertical().show(ui); @@ -201,7 +200,7 @@ fn background_eraser_members(ui: &mut egui::Ui, app: &mut PhotocraftApp) { // 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) + Select::new(tl!("Limits:"), Bind::given(app.ui.tool_options.bg_limits.clone()), &limits) .tooltip(tl!("How far to let the erasing spread").to_owned()) .show(ui) .events @@ -211,20 +210,20 @@ fn background_eraser_members(ui: &mut egui::Ui, app: &mut PhotocraftApp) { .inner .flatten(); if let Some(limits) = picked { - o.bg_limits = limits; + app.ui.tool_options.bg_limits = limits; } // Shown as the stroke reads it; written back only when the user edits it. - let shown = stored_tolerance(o.bg_tolerance); + let shown = stored_tolerance(app.ui.tool_options.bg_tolerance); let mut tolerance = shown; - let alert = option_cells::number(tl!("Tolerance:"), &mut tolerance, 1.0..=100.0) + let alert = option_cells::number(tl!("Tolerance:"), Bind::bound(&mut tolerance), 1.0..=100.0) .whole() .unit("%") .tooltip(tl!("Erase range of similar colors")) .show(ui) .out_of_range; if tolerance != shown { - o.bg_tolerance = tolerance; + app.ui.tool_options.bg_tolerance = tolerance; } alerts.extend(alert); } @@ -233,7 +232,7 @@ fn background_eraser_members(ui: &mut egui::Ui, app: &mut PhotocraftApp) { let before = (*app.session.tools.brush).clone(); let mut brush = before.clone(); let mut angle = brush.angle; - let angle_out = option_cells::number(tl!("Angle"), &mut angle, -180.0..=180.0) + let angle_out = option_cells::number(tl!("Angle"), Bind::bound(&mut angle), -180.0..=180.0) .whole() .unit("°") .icon(IconSpec::svg(IconId::new("rotate_cw"))) @@ -244,7 +243,7 @@ fn background_eraser_members(ui: &mut egui::Ui, app: &mut PhotocraftApp) { brush.angle = angle; alerts.extend(angle_out.out_of_range); - check(ui, tl!("Protect Foreground Color"), &mut app.ui.tool_options.bg_protect_fg, Some(tl!("Do not erase the foreground swatch color"))); + check(ui, tl!("Protect Foreground Color"), bind_tracked!(app.ui.tool_options => bg_protect_fg), Some(tl!("Do not erase the foreground swatch color"))); let pressure = ToggleButton::new(tl!("Always use pressure for size"), Bind::given(brush.pressure_size)) .icon(IconId::new("target")) diff --git a/crates/ui-egui/src/tools/eyedropper_ui.rs b/crates/ui-egui/src/tools/eyedropper_ui.rs index d9da168205..a745abf2a2 100644 --- a/crates/ui-egui/src/tools/eyedropper_ui.rs +++ b/crates/ui-egui/src/tools/eyedropper_ui.rs @@ -10,7 +10,11 @@ use crate::PhotocraftApp; /// The options bar for the Eyedropper tool. pub fn options(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - EyedropperBar::new(&mut app.ui.tool_options.eyedropper).show(ui); + let mut options = app.ui.tool_options.eyedropper; + EyedropperBar::new(&mut options).show(ui); + if options != app.ui.tool_options.eyedropper { + app.ui.tool_options.eyedropper = options; + } } #[cfg(test)] diff --git a/crates/ui-egui/src/tools/frame_tool/task_bar.rs b/crates/ui-egui/src/tools/frame_tool/task_bar.rs index 573e54cca6..fa828a5127 100644 --- a/crates/ui-egui/src/tools/frame_tool/task_bar.rs +++ b/crates/ui-egui/src/tools/frame_tool/task_bar.rs @@ -3,7 +3,7 @@ use super::{Target, report, select, selected, visible}; use crate::PhotocraftApp; -use crate::state::Tool; +use crate::state::{TaskBarContext, Tool}; use craft::behavior::kurbo::Point; use craft::ui::buttons::Button; use craft::ui::canvas_controls::TaskBar; @@ -27,6 +27,9 @@ pub(crate) fn show(ui: &mut egui::Ui, app: &mut PhotocraftApp, at: egui::Rect) { let (x0, y0, x1, y1) = (f64::from(b.x0), f64::from(b.y0), f64::from(b.x1), f64::from(b.y1)); let anchor = [Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)]; + if let Some(doc) = app.session.active().map(|d| d.doc.id.0) { + app.ui.enter_task_bar_context(TaskBarContext::Frame { doc, layer: id.0 }); + } let mut import = false; let mut fit = false; let shown = TaskBar::new(tl!("Frame"), &anchor, Bind::bound(&mut app.ui.panels.task_bar)).show(ui, at, |ui, _| { diff --git a/crates/ui-egui/src/tools/frame_tool/tests.rs b/crates/ui-egui/src/tools/frame_tool/tests.rs index 45063f1cd4..b3b4688d96 100644 --- a/crates/ui-egui/src/tools/frame_tool/tests.rs +++ b/crates/ui-egui/src/tools/frame_tool/tests.rs @@ -55,7 +55,7 @@ fn harness(app: Box) -> egui_kittest::Harness<'static, Box| crate::canvas::document_area(app, ui), app); + .build_ui_state(|ui, app: &mut Box| crate::canvas::testing::document_area(app, ui), app); h.run_steps(4); h diff --git a/crates/ui-egui/src/tools/gradient_ui/bar.rs b/crates/ui-egui/src/tools/gradient_ui/bar.rs index 0f9a30ed4e..2a389f1be8 100644 --- a/crates/ui-egui/src/tools/gradient_ui/bar.rs +++ b/crates/ui-egui/src/tools/gradient_ui/bar.rs @@ -3,7 +3,7 @@ use craft::draw::ui::gradient::{GradientFillWords, GradientStyle, GradientSwatch}; use craft::ui::choice::{Checkbox, Segmented}; -use craft::ui::contract::{Bind, Entry, LabelKind, Props as _, Show as _, ShowContainer as _, SideLabel}; +use craft::ui::contract::{Bind, Entry, LabelKind, Props as _, Show as _, ShowContainer as _, SideLabel, bind_tracked}; use craft::ui::display::Divider; use craft::ui::form::Field; use craft::ui::patterns::blend_keys::{BlendKeyEntry, blend_entries}; @@ -51,37 +51,40 @@ pub(crate) fn bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let blends = blend_modes(); let open_editor; { - let o = &mut app.ui.tool_options; - let mut classic = o.gradient_classic && !locked_live; + let mut classic = app.ui.tool_options.gradient_classic && !locked_live; Field::new(tl!("Gradient mode").to_owned()).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| { Select::new(tl!("Gradient mode").to_owned(), Bind::bound(&mut classic), &modes).enabled(!locked_live).show(ui); }); - if !locked_live { - o.gradient_classic = classic; + if !locked_live && classic != app.ui.tool_options.gradient_classic { + app.ui.tool_options.gradient_classic = classic; } open_editor = GradientSwatch::new(tl!("Gradient picker").to_string(), &tool_stops).sampler(&sampler).show(ui).clicked; Divider::vertical().show(ui); - let style = stops::style_named(&o.gradient_style); + let style = stops::style_named(&app.ui.tool_options.gradient_style); if let Some(next) = Segmented::new(Label::from(tl!("Gradient style").to_string()), Bind::given(style), &styles).show(ui).value().copied() { - o.gradient_style = stops::style_name(next).to_owned(); + app.ui.tool_options.gradient_style = stops::style_name(next).to_owned(); } if classic { - labelled(ui, tl!("Mode"), |ui| { - Select::new(tl!("Blend Mode").to_owned(), Bind::bound(&mut o.gradient_blend_mode), &blends).show(ui); - }); + let fill_opacity = app.ui.tool_options.fill_opacity; + { + let mut blend = bind_tracked!(app.ui.tool_options => gradient_blend_mode); + labelled(ui, tl!("Mode"), |ui| { + Select::new(tl!("Blend Mode").to_owned(), blend.reborrowed(), &blends).show(ui); + }); + } labelled(ui, tl!("Opacity"), |ui| { let field = - NumberField::new(tl!("Opacity").to_owned(), Bind::given(Some(f64::from(o.fill_opacity)))).range(1.0..=100.0).unit("%").scrub_by_label(); + NumberField::new(tl!("Opacity").to_owned(), Bind::given(Some(f64::from(fill_opacity)))).range(1.0..=100.0).unit("%").scrub_by_label(); if let Some(next) = field.show(ui).value().copied().flatten() { - o.fill_opacity = next as f32; + app.ui.tool_options.fill_opacity = next as f32; } }); } - if let Some(on) = Checkbox::new(Bind::given(o.gradient_reverse)).label(tl!("Reverse").to_owned()).show(ui).value().copied() { - o.gradient_reverse = on; + if let Some(on) = Checkbox::new(Bind::given(app.ui.tool_options.gradient_reverse)).label(tl!("Reverse").to_owned()).show(ui).value().copied() { + app.ui.tool_options.gradient_reverse = on; } - if let Some(on) = Checkbox::new(Bind::given(o.gradient_dither)).label(tl!("Dither").to_owned()).show(ui).value().copied() { - o.gradient_dither = on; + if let Some(on) = Checkbox::new(Bind::given(app.ui.tool_options.gradient_dither)).label(tl!("Dither").to_owned()).show(ui).value().copied() { + app.ui.tool_options.gradient_dither = on; } } if open_editor { diff --git a/crates/ui-egui/src/tools/gradient_ui/live_overlay.rs b/crates/ui-egui/src/tools/gradient_ui/live_overlay.rs index d568fb803d..b99722e785 100644 --- a/crates/ui-egui/src/tools/gradient_ui/live_overlay.rs +++ b/crates/ui-egui/src/tools/gradient_ui/live_overlay.rs @@ -58,7 +58,7 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut Ui, at: Rect) -> Option<(La return None; } // ⌘ is the Move tool (`hold_keys::cmd_moves`): the overlay steps aside while it is held. - if craft::ui::runtime::pointer::frame(ui.ctx()).mods.cmd && crate::canvas::tools::takes_command_stand_in(Tool::Gradient) { + if craft::ui::runtime::pointer::mods(ui.ctx()).cmd && crate::canvas::tools::takes_command_stand_in(Tool::Gradient) { return None; } let (layer, frame, canvas) = active_gradient(app)?; diff --git a/crates/ui-egui/src/tools/line_wh_fields_tests.rs b/crates/ui-egui/src/tools/line_wh_fields_tests.rs new file mode 100644 index 0000000000..d75317e1dd --- /dev/null +++ b/crates/ui-egui/src/tools/line_wh_fields_tests.rs @@ -0,0 +1,268 @@ +//! #13250: the Line tool's options bar shows W, a link button and H after the stroke controls. With +//! no line active they read 0 px and the link is off; with a line active W is its length and H its +//! thickness (the weight, or the arrowhead width when wider). Typing W or H resizes the line in its +//! own rotated frame as one "Scale Paths" step, keeping it a live line; the tool's own Weight and +//! arrowhead options for the next line do not change. +//! +//! H follows the measured numbers: the start of a 15 px thick line moves from 400,300 to +//! 398.88,302.24 for H 20, a scale about the edge of the line's box on the start's side, not its +//! centre line (a scale about the centre line would keep the start at 400,300). + +use egui::accesskit::{Role, Toggled}; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_doc::{LayerContent, LayerId, LiveShape}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +type H = Harness<'static, Box>; + +/// An 800 x 600 document with the Line tool picked, its options bar in a harness; `drawn` drags a +/// line from 400,300 to 600,400 with the tool first. +fn bar(drawn: bool) -> H { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::Line; + if drawn { + let none = egui::Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 400.0, y: 300.0, pressure: 1.0 }, none); + tool_event(&mut app, ToolEvent::Move { x: 500.0, y: 350.0, pressure: 1.0 }, none); + tool_event(&mut app, ToolEvent::Move { x: 600.0, y: 400.0, pressure: 1.0 }, none); + tool_event(&mut app, ToolEvent::Up { x: 600.0, y: 400.0 }, none); + } + let mut h = + Harness::builder().with_context(app.ctx().clone()).with_size(vec2(2400.0, 300.0)).build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app); + h.run_steps(4); + h +} + +/// The drawn line with the End arrowhead on, 15 px wide and 10 px long, set as the Properties panel sets it. +fn arrow_bar() -> (H, LayerId) { + let mut h = bar(true); + let id = active(&h); + h.state_mut().run("shape.edit", json!({"layer": id.0, "arrowEnd": true, "arrowWidth": 15, "arrowLength": 10})).unwrap(); + h.run_steps(3); + (h, id) +} + +fn active(h: &H) -> LayerId { + h.state().session.active().unwrap().active_layer.unwrap() +} + +/// The SpinButton labelled `label`. +fn field<'h>(h: &'h H, label: &'h str) -> egui_kittest::Node<'h> { + h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some(label)).unwrap_or_else(|| panic!("the {label} field")) +} + +/// The number the field labelled `label` shows. +fn shown(h: &H, label: &str) -> f64 { + let text = field(h, label).value().unwrap_or_else(|| panic!("the {label} field shows a value")); + // The decimal mark follows the locale the test runs in. + let number = text.trim_end_matches("px").trim().replace(',', "."); + number.parse().unwrap_or_else(|e| panic!("the {label} field shows a number, not {text:?} ({e})")) +} + +/// Types `text` into the field labelled `label`, then Tabs out of it. +fn type_into(h: &mut H, label: &str, text: &str) { + field(h, label).click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +/// Whether the link button is on. +fn link_on(h: &H) -> bool { + h.get_by_role_and_label(Role::Button, "Maintain aspect ratio").accesskit_node().toggled() == Some(Toggled::True) +} + +/// The live arrow line of layer `id`: from, to, weight, width, length. +fn arrow(h: &H, id: LayerId) -> ([f64; 2], [f64; 2], f64, f64, f64) { + match &h.state().session.active().unwrap().doc.layer(id).unwrap().content { + LayerContent::Shape(sh) => match &sh.live { + Some(LiveShape::ArrowLine { from, to, weight, width, length, end: true, .. }) => (*from, *to, *weight, *width, *length), + other => panic!("a live line with its End arrowhead, got {other:?}"), + }, + _ => panic!("a shape layer"), + } +} + +fn steps(h: &H) -> usize { + h.state().session.active().unwrap().history.past_len() +} + +fn undo_label(h: &H) -> Option { + h.state().session.active().unwrap().history.undo_label().map(str::to_owned) +} + +fn near(a: f64, b: f64, tol: f64) -> bool { + (a - b).abs() <= tol +} + +fn assert_pt(got: [f64; 2], want: [f64; 2], what: &str) { + assert!(near(got[0], want[0], 0.01) && near(got[1], want[1], 0.01), "{what}: {got:?}, want {want:?}"); +} + +/// The tool's own settings the next line is drawn with. +fn tool_settings(h: &H) -> (f32, bool, bool, f32, f32) { + let o = &h.state().ui.tool_options; + (o.line_weight, o.arrow_start, o.arrow_end, o.arrow_width, o.arrow_length) +} + +#[test] +fn no_line_reads_zero_and_the_link_is_off() { + let h = bar(false); + assert_eq!(shown(&h, "W:"), 0.0); + assert_eq!(shown(&h, "H:"), 0.0); + assert!(!link_on(&h), "the link is off"); +} + +#[test] +fn a_drawn_line_reads_its_length_and_thickness() { + let h = bar(true); + assert!(near(shown(&h, "W:"), 223.61, 0.006), "W {}", shown(&h, "W:")); + assert_eq!(shown(&h, "H:"), 1.0); + assert!(!link_on(&h), "the link is off"); +} + +#[test] +fn w_then_h_scale_the_line_in_its_own_frame_as_scale_paths_steps() { + let (mut h, id) = arrow_bar(); + let tool = tool_settings(&h); + assert_eq!(shown(&h, "H:"), 15.0, "the thickness includes the 15 px arrowhead"); + let before_w = (arrow(&h, id), steps(&h)); + + type_into(&mut h, "W:", "300"); + let (from, to, weight, width, length) = arrow(&h, id); + assert_pt(from, [400.0, 300.0], "W keeps the start"); + assert_pt(to, [668.33, 434.16], "W moves the end along the line"); + assert!(near(length, 13.416, 0.001), "arrowhead length {length}"); + assert!(near(weight, 1.0, 1e-9) && near(width, 15.0, 1e-9), "weight {weight}, width {width}"); + assert_eq!(steps(&h), before_w.1 + 1, "one step"); + assert_eq!(undo_label(&h).as_deref(), Some("Scale Paths")); + assert!(near(shown(&h, "W:"), 300.0, 0.006)); + + let before_h = (arrow(&h, id), steps(&h)); + type_into(&mut h, "H:", "20"); + let (from, to, weight, width, length) = arrow(&h, id); + assert!(near(weight, 1.333, 0.001), "weight {weight}"); + assert!(near(width, 20.0, 1e-9), "arrowhead width {width}"); + assert!(near(length, 13.416, 0.001), "arrowhead length {length}"); + assert_pt(from, [398.88, 302.24], "H moves the start across the line"); + assert!(near((to[0] - from[0]).hypot(to[1] - from[1]), 300.0, 1e-6), "H keeps the length"); + assert_eq!(steps(&h), before_h.1 + 1, "one step"); + assert_eq!(undo_label(&h).as_deref(), Some("Scale Paths")); + assert_eq!(shown(&h, "H:"), 20.0); + + assert_eq!(tool_settings(&h), tool, "the tool's Weight and arrowhead options are unchanged"); + + // Each edit undoes in one step. + h.state_mut().session.undo(); + h.run_steps(2); + assert_eq!((arrow(&h, id), steps(&h)), before_h); + h.state_mut().session.undo(); + h.run_steps(2); + assert_eq!((arrow(&h, id), steps(&h)), before_w); +} + +#[test] +fn zero_negative_or_no_number_changes_nothing() { + let (mut h, id) = arrow_bar(); + let before = (arrow(&h, id), steps(&h)); + for typed in ["0", "-5", "abc", "NaN", "inf"] { + for label in ["W:", "H:"] { + type_into(&mut h, label, typed); + assert_eq!((arrow(&h, id), steps(&h)), before, "{label} {typed}"); + } + } +} + +#[test] +fn typing_without_a_line_edits_nothing() { + let mut h = bar(false); + let n = h.state().session.active().unwrap().doc.layers.len(); + type_into(&mut h, "W:", "300"); + type_into(&mut h, "H:", "20"); + assert_eq!(h.state().session.active().unwrap().doc.layers.len(), n); + assert_eq!((shown(&h, "W:"), shown(&h, "H:")), (0.0, 0.0)); +} + +#[test] +fn the_frame_scale_helper_refuses_sizes_that_are_not_positive_and_finite() { + use photocraft_engine::vector_cmds::{line_frame_scale, line_frame_size}; + let line = + LiveShape::ArrowLine { from: [400.0, 300.0], to: [600.0, 400.0], weight: 1.0, start: false, end: true, width: 15.0, length: 10.0, concavity: 0.0 }; + let (len, thick) = line_frame_size(&line).unwrap(); + assert!(near(len, 223.607, 0.001) && thick == 15.0); + for (l, t) in [(0.0, 15.0), (300.0, 0.0), (f64::NAN, 15.0), (300.0, f64::INFINITY), (-1.0, 15.0)] { + assert!(line_frame_scale(&line, l, t).is_none(), "{l} x {t}"); + } + let flat = LiveShape::ArrowLine { from: [1.0, 1.0], to: [1.0, 1.0], weight: 1.0, start: false, end: false, width: 15.0, length: 10.0, concavity: 0.0 }; + assert!(line_frame_size(&flat).is_none() && line_frame_scale(&flat, 300.0, 20.0).is_none()); + let rect = LiveShape::Rect { rect: [0.0, 0.0, 10.0, 10.0], radii: [0.0; 4] }; + assert!(line_frame_size(&rect).is_none() && line_frame_scale(&rect, 300.0, 20.0).is_none()); + // A plain line's thickness is its weight, whatever the (hidden) arrowhead width. + let plain = + LiveShape::ArrowLine { from: [400.0, 300.0], to: [600.0, 400.0], weight: 1.0, start: false, end: false, width: 15.0, length: 10.0, concavity: 0.0 }; + assert_eq!(line_frame_size(&plain).map(|s| s.1), Some(1.0)); +} + +#[test] +fn another_transform_of_a_line_keeps_its_history_name() { + let (mut h, id) = arrow_bar(); + // A rotation is no scale in the line's frame. + let (s, c) = 0.3f64.sin_cos(); + h.state_mut().run("shape.edit", json!({"layer": id.0, "transform": [c, s, -s, c, 0.0, 0.0]})).unwrap(); + assert_ne!(undo_label(&h).as_deref(), Some("Scale Paths")); + // A move is none either. + h.state_mut().run("shape.edit", json!({"layer": id.0, "transform": [1.0, 0.0, 0.0, 1.0, 5.0, 5.0]})).unwrap(); + assert_ne!(undo_label(&h).as_deref(), Some("Scale Paths")); +} + +/// The live plain line (no arrow parameters) of layer `id`: from, to, weight. +fn plain(h: &H, id: LayerId) -> ([f64; 2], [f64; 2], f64) { + match &h.state().session.active().unwrap().doc.layer(id).unwrap().content { + LayerContent::Shape(sh) => match &sh.live { + Some(LiveShape::Line { from, to, weight }) => (*from, *to, *weight), + other => panic!("a live plain line, got {other:?}"), + }, + _ => panic!("a shape layer"), + } +} + +#[test] +fn w_then_h_keep_a_diagonal_plain_line_live() { + // `shape.create` without arrow keys (or an imported line) makes a plain `LiveShape::Line`. + let mut h = bar(false); + h.state_mut().run("shape.create", json!({"kind": "line", "from": [0, 0], "to": [200, 100], "weight": 4})).unwrap(); + h.run_steps(3); + let id = active(&h); + plain(&h, id); + assert!(near(shown(&h, "W:"), 223.61, 0.006), "W {}", shown(&h, "W:")); + assert_eq!(shown(&h, "H:"), 4.0); + + type_into(&mut h, "W:", "300"); + let (from, to, weight) = plain(&h, id); + assert_pt(from, [0.0, 0.0], "W keeps the start"); + assert_pt(to, [268.33, 134.16], "W moves the end along the line"); + assert!(near(weight, 4.0, 1e-9), "weight {weight}"); + assert_eq!(undo_label(&h).as_deref(), Some("Scale Paths")); + assert!(near(shown(&h, "W:"), 300.0, 0.006)); + + type_into(&mut h, "H:", "8"); + let (from, to, weight) = plain(&h, id); + assert!(near(weight, 8.0, 1e-9), "weight {weight}"); + assert!(near((to[0] - from[0]).hypot(to[1] - from[1]), 300.0, 1e-6), "H keeps the length"); + // The pivot is the box edge 2 px off the start; doubling the thickness moves the start 2 px + // along the normal (-0.447, 0.894). + assert_pt(from, [-0.894, 1.789], "H moves the start across the line"); + assert_eq!(undo_label(&h).as_deref(), Some("Scale Paths")); + assert_eq!(shown(&h, "H:"), 8.0); +} diff --git a/crates/ui-egui/src/tools/magnetic_lasso_ui.rs b/crates/ui-egui/src/tools/magnetic_lasso_ui.rs index e2a7bb9c9d..6d059cf504 100644 --- a/crates/ui-egui/src/tools/magnetic_lasso_ui.rs +++ b/crates/ui-egui/src/tools/magnetic_lasso_ui.rs @@ -68,7 +68,9 @@ pub(crate) fn prepare(app: &PhotocraftApp, tool: &mut MagneticLassoTool /// Writes the tool's settings back after the run, so `[` and `]` reach the options store. pub(crate) fn store(app: &mut PhotocraftApp, tool: &MagneticLassoTool) { - app.ui.tool_options.magnetic = *tool.settings(); + if app.ui.tool_options.magnetic != *tool.settings() { + app.ui.tool_options.magnetic = *tool.settings(); + } } /// Selects the closed border as drawn, in `mode` (the family's operation-to-mode name). Fewer than diff --git a/crates/ui-egui/src/tools/move_distance.rs b/crates/ui-egui/src/tools/move_distance.rs index 82a09ffc04..5dfdd0bb43 100644 --- a/crates/ui-egui/src/tools/move_distance.rs +++ b/crates/ui-egui/src/tools/move_distance.rs @@ -93,7 +93,7 @@ fn duplicate_drag(app: &PhotocraftApp) -> Option<(Rect, Rect)> { /// Shows the measurements over the canvas `rect`, in the Smart Guides colour. `pointer` is the /// screen hover position. pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, canvas: egui::Rect, pointer: Option) { - let command = craft::ui::runtime::pointer::frame(ui.ctx()).mods.cmd; + let command = craft::ui::runtime::pointer::mods(ui.ctx()).cmd; let pressed = crate::canvas::tools::in_gesture(app); let at = pointer.and_then(|p| crate::canvas::document_display::doc_point_at(app, p)).map(|p| [p.x, p.y]); let Some((a, b)) = current(app, at, command, pressed) else { return }; diff --git a/crates/ui-egui/src/tools/move_hover.rs b/crates/ui-egui/src/tools/move_hover.rs index 75fd55aeff..af59be78e4 100644 --- a/crates/ui-egui/src/tools/move_hover.rs +++ b/crates/ui-egui/src/tools/move_hover.rs @@ -111,7 +111,7 @@ pub(crate) fn active_outline(app: &mut PhotocraftApp, at: Option<[f64; 2]>, comm /// position. The Layers panel reads `canvas_hover_layer`, so a change of it asks for a repaint. pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, canvas: egui::Rect, pointer: Option) { let prev_canvas_hover = app.canvas_hover_layer; - let command = craft::ui::runtime::pointer::frame(ui.ctx()).mods.cmd; + let command = craft::ui::runtime::pointer::mods(ui.ctx()).cmd; let pressed = crate::canvas::tools::in_gesture(app); let at = pointer.and_then(|p| crate::canvas::document_display::doc_point_at(app, p)).map(|p| [p.x, p.y]); let outline = active_outline(app, at, command, pressed); diff --git a/crates/ui-egui/src/tools/object_finder.rs b/crates/ui-egui/src/tools/object_finder.rs index 2ab9a34f5b..7daec81c82 100644 --- a/crates/ui-egui/src/tools/object_finder.rs +++ b/crates/ui-egui/src/tools/object_finder.rs @@ -185,7 +185,7 @@ pub(crate) fn update(app: &mut PhotocraftApp, at: Option<[f64; 2]>, pressed: boo } let resting = f.shown.is_none() && !missed && now - f.since < DEBOUNCE; if resting { - ctx.request_repaint_after(std::time::Duration::from_secs_f64(DEBOUNCE - (now - f.since))); + craft::ui::runtime::frame::request_repaint_after(ctx, DEBOUNCE - (now - f.since)); } #[cfg(test)] let busy = f.job.is_some() || resting; diff --git a/crates/ui-egui/src/tools/option_cells.rs b/crates/ui-egui/src/tools/option_cells.rs index 159203d9c7..4e2c189a06 100644 --- a/crates/ui-egui/src/tools/option_cells.rs +++ b/crates/ui-egui/src/tools/option_cells.rs @@ -2,8 +2,9 @@ //! `NumberField` whose out-of-range commit comes back as a [`RangeAlert`] for the caller to show. use std::ops::RangeInclusive; +use std::sync::Arc; -use craft::behavior::{EditEvents, NumberCodec}; +use craft::behavior::{EditEvent, EditEvents, Mixed, NumberCodec}; use craft::ui::contract::{Bind, FieldLayout, Props as _, Show as _, ShowContainer as _, SideLabel, Sizing}; use craft::ui::dialog::Alert; use craft::ui::display::{Elide, Shade, Text}; @@ -18,10 +19,11 @@ use crate::PhotocraftApp; /// commits, so showing a bar never rounds a fraction another tool shares. pub(crate) struct NumberCell<'a> { caption: Label, - value: &'a mut f32, + value: Bind<'a, f32>, range: RangeInclusive, unit: Option