Merge origin/main into fix/contact-sheet-load-save-reset-13698

This commit is contained in:
David Mann committed 2026-11-28 22:38:37 +01:00
commit 17fcf4483a
287 files changed
+13749 -1082

No files matched your search

+1 -1
View File
@@ -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
+3 -11
View File
@@ -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",
+8 -8
View File
@@ -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 }}
+3 -3
View File
@@ -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
+18 -5
View File
@@ -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 }}
+3 -2
View File
@@ -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"]'
+20
View File
@@ -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 }}
+1 -1
View File
@@ -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 }}
+1
View File
@@ -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`.
Generated
+213 -116
View File
File diff suppressed because it is too large. Load diff
+56 -56
View File
@@ -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" }
+8 -2
View File
@@ -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(());
}
+3
View File
@@ -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());
+7 -2
View File
@@ -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") {
+71
View File
@@ -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 <args>` in `dir`; its trimmed output when it succeeds.
fn git(dir: &Path, args: &[&str]) -> Option<String> {
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/<crate> → 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<PathBuf> {
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<PathBuf> {
path.ancestors().take_while(|p| p.starts_with(stop)).find(|p| p.exists()).map(Path::to_path_buf)
}
+2
View File
@@ -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();
+79 -1
View File
@@ -150,9 +150,17 @@ fn private_subdirectory(root: &Path, name: impl AsRef<Path>, 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();
@@ -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()));
}
+152
View File
@@ -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<PathBuf> {
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<PathBuf> {
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);
}
+1
View File
@@ -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.
+14
View File
@@ -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 {
+2
View File
@@ -246,6 +246,8 @@ impl FxMaps {
}
}
#[cfg(test)]
mod drop_shadow_anti_alias_tests;
#[cfg(test)]
mod inner_shadow_anti_alias_tests;
#[cfg(test)]
@@ -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<f32>; 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"
);
}
@@ -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
+4 -4
View File
@@ -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);
+1 -1
View File
@@ -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 }
+39 -4
View File
@@ -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<String> = 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]
+2
View File
@@ -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;
+66 -13
View File
@@ -369,9 +369,19 @@ fn artboard_from_group(s: &mut Session, p: &Value) -> Result<Value> {
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<Value> {
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<Rect> {
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<Value> {
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<Value> {
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<Document> {
/// `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<f64>, cmd: &str) -> Result<Vec<u8>> {
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<f64>, masked: bool, cmd: &str) -> Result<(Vec<u8>, Option<Vec<u8>>)> {
/// [`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<f64>, zip: bool, masked: bool, cmd: &str) -> Result<(Vec<u8>, Option<Vec<u8>>)> {
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<f64>, masked: bool, cmd: &st
let mut surf = Surface::new(fmt);
let vals: Vec<f32> = 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<u8> = 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<u8>)]) -> Vec<u8> {
let pages: Vec<PdfPage> = 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<u8> {
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<Value> {
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<Value> {
// 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<CommandSpec> {
"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<CommandSpec> {
"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, "<dir>/<prefix><artboard name>.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, "<dir>/<prefix><artboard name>.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;
@@ -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<Value> {
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");
}
@@ -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<i64> = 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}");
}
@@ -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);
@@ -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<Vec<u8>> {
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<usize> {
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<u8> {
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<usize> = 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);
}
+4 -1
View File
@@ -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<CommandSpec> {
vec![
@@ -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<Value> {
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<Value> {
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" => {
@@ -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<Value> {
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<Value> {
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 }))
}
@@ -285,6 +285,18 @@ pub(super) fn source(s: &Session, p: &Value, cmd: &str, gray: bool) -> Result<Ve
if st.doc.size != target.doc.size {
return Err(bad(cmd, format!("source document \"{}\" is {}×{}; it must match the target size", st.doc.name, st.doc.size.width, st.doc.size.height)));
}
// Apply Image reads only a source of the target's bit depth (#14480); its dialog lists no other.
if cmd == "image.applyImage" && st.doc.depth != target.doc.depth {
return Err(bad(
cmd,
format!(
"source document \"{}\" is {} bit; it must match the target's bit depth ({} bit)",
st.doc.name,
st.doc.depth.bits(),
target.doc.depth.bits()
),
));
}
let r = if p.get("channel") == Some(&serde_json::json!({"targeted": true})) {
// Resolve on replay, before the calculation creates a channel. A string selector would
// collide with an existing alpha named "targeted".
@@ -60,6 +60,23 @@ pub(super) fn save_selection(s: &mut Session, p: &Value) -> Result<Value> {
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<Value> {
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<Value> {
// 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())
@@ -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);
}
}
@@ -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<u64>) {
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);
}
+45
View File
@@ -759,6 +759,51 @@ pub fn working_profile(mode: ColorMode) -> Arc<Profile> {
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<Arc<Profile>> {
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<Vec<u8>>) -> std::result::Result<Arc<Profile>, craft_cms::CmsError> {
type Cache = Mutex<Vec<(Weak<Vec<u8>>, Arc<Profile>)>>;
+10 -1
View File
@@ -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<Value> {
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 };
@@ -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).
@@ -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");
}
@@ -370,7 +370,12 @@ pub(crate) fn duplicate_to_new_document(s: &mut Session, p: &Value) -> Result<Va
if !layered(sdoc.mode) {
return Err(EngineError::Other(format!("layers can't be duplicated with a {:?} document", sdoc.mode)));
}
let doc_name = p.get("documentName").and_then(Value::as_str).filter(|n| !n.is_empty()).map(str::to_string).unwrap_or_else(|| format!("{} copy", sdoc.name));
let doc_name = p
.get("documentName")
.and_then(Value::as_str)
.filter(|n| !n.is_empty())
.map(str::to_string)
.unwrap_or_else(|| crate::cmd::file_cmds::untitled_name("Untitled", |n| s.documents().iter().any(|d| d.doc.name == n) || s.held_open_named(n)));
let mut nd = Document::new(doc_name, sdoc.size, sdoc.mode, sdoc.depth);
nd.resolution_dpi = sdoc.resolution_dpi;
nd.icc_profile.clone_from(&sdoc.icc_profile);
@@ -0,0 +1,50 @@
//! #14608: Duplicate Layer… with Document = New and an empty Name makes an "Untitled-N"
//! document, as the reference application does, not "<source> 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");
}
@@ -158,8 +158,8 @@ pub fn specs() -> Vec<CommandSpec> {
&["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;
@@ -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<LayerId>, Option<LayerId>, Vec<String>) {
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<LayerId> {
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]);
}
@@ -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<Value> {
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.
@@ -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 [
+3 -3
View File
@@ -99,7 +99,8 @@ fn set_mask_with(s: &mut Session, p: &Value, label: &str, mask: Option<LayerMask
/// Drag a layer mask's thumbnail onto another layer or group in the Layers panel: the mask moves
/// there (⌥: a copy goes there and the original stays), as in Photoshop (#10485). A layer that
/// already has a mask keeps it unless `replace` (Photoshop asks first). One history step.
/// already has a mask keeps it unless `replace` (Photoshop asks first). One history step, named
/// `Add Layer Mask` for a move and a copy alike, as Photoshop names the drop (#16786).
pub(super) fn move_mask(s: &mut Session, p: &Value) -> Result<Value> {
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<Value> {
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`)"));
+1 -1
View File
@@ -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 {
@@ -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<LineFrame> {
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<Affine> {
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<Value> {
/// 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,
}
}
@@ -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<Value> {
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<Value> {
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<Value> {
})?;
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)
}
@@ -119,6 +119,10 @@ pub(super) fn quick_export(s: &mut Session, p: &Value) -> Result<Value> {
// 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);
@@ -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);
@@ -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");
}
+4
View File
@@ -31,6 +31,9 @@ pub struct DocState {
pub coalesce: Option<String>,
/// 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<LayerId>,
/// 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(),
+1
View File
@@ -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);
+19 -3
View File
@@ -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<Vec<u8>> {
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<Effect> {
let shadow = |inner: bool| Shadow {
@@ -598,7 +606,10 @@ fn fresh_effect(kind: &str) -> Option<Effect> {
}),
"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<Effect> {
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<Value> {
Ok(Value::Null)
}
#[cfg(test)]
mod gradient_overlay_defaults_tests;
#[cfg(test)]
mod satin_defaults_tests;
@@ -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);
}
}
@@ -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<i32> = 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))]);
}
+13 -1
View File
@@ -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<String, u64>,
}
@@ -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<R>(&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<R>(&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
@@ -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();
+11 -7
View File
@@ -249,18 +249,22 @@ fn red_eye(s: &mut Session, p: &Value) -> Result<Value> {
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<CommandSpec> {
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,
@@ -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();
@@ -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.
+1 -1
View File
@@ -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::*;
@@ -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<f32> = (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<f32> = (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:?}");
}
@@ -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<f32> {
(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<f32> {
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<f32> = 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<f32> = 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::<Vec<_>>()).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);
}
@@ -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)
};
@@ -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<ToneRange> {
match string(p, "range", "midtones") {
"shadows" => Ok(ToneRange::Shadows),
@@ -198,7 +243,7 @@ fn tone_range(p: &Value, cmd: &str) -> Result<ToneRange> {
/// 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;
@@ -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<f32> = (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<f32> = (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:?}");
}
@@ -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);
}
@@ -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<Value> {
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<Value> {
#[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;
@@ -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<f32> = (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);
}
@@ -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}");
}
}
}
+1
View File
@@ -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;
@@ -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());
+10 -10
View File
@@ -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())
+67 -4
View File
@@ -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
+76
View File
@@ -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<f32>; 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}"));
}
}
+1 -1
View File
@@ -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
@@ -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");
}
@@ -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<StrokePoint> {
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));
}
+14 -11
View File
@@ -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]
+4
View File
@@ -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;
+6
View File
@@ -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;
+3 -2
View File
@@ -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);
+2 -2
View File
@@ -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);
+63 -3
View File
@@ -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;
+2 -1
View File
@@ -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)?;
+1 -1
View File
@@ -14,7 +14,7 @@ use craft::keymap::Mods;
pub(crate) fn harness(app: Box<PhotocraftApp>) -> Harness<'static, Box<PhotocraftApp>> {
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,
);
+1 -1
View File
@@ -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,
+6 -1
View File
@@ -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
+5 -5
View File
@@ -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 {
+2
View File
@@ -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);
}
}
@@ -52,7 +52,7 @@ fn type_into(h: &mut Harness<'static, Box<PhotocraftApp>>, 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] = [
@@ -22,7 +22,7 @@ fn harness() -> Harness<'static, Box<PhotocraftApp>> {
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,
);
@@ -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"))));
Loaded 100 of 287 files, more files were not shown because too many files have changed in this diff. Show more