mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-03 06:31:42 +01:00
Merge remote-tracking branch 'upstream/main' into fix/delete-anchor-shown-only-12769
This commit is contained in:
commit
63644ce5a1
197 files changed
+5905
-554
No files matched your search
+92
-24
@@ -82,6 +82,10 @@ jobs:
|
||||
windows: ${{ steps.pick.outputs.windows }}
|
||||
web: ${{ steps.pick.outputs.web }}
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
@@ -197,6 +201,10 @@ jobs:
|
||||
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
|
||||
CRAFT_FONTS_REQUIRED: "1"
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
@@ -214,15 +222,16 @@ jobs:
|
||||
- name: Check out craft-i18n
|
||||
uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main
|
||||
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
components: clippy
|
||||
|
||||
# Only main saves caches; PRs restore main's, so the repo's 10 GB cache budget keeps main's.
|
||||
# A failing test still saves: the cache holds compiled dependencies, not test results.
|
||||
# Both legs share one key (same dependencies); the integration leg saves it, because it also
|
||||
# runs Clippy and so leaves Clippy's dependency metadata in it.
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
- uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2
|
||||
with:
|
||||
save-if: ${{ github.ref == 'refs/heads/main' && matrix.part == 'integration' }}
|
||||
cache-on-failure: true
|
||||
@@ -232,7 +241,7 @@ jobs:
|
||||
# main's entries); a full set is ~90 MB, so it barely touches the 10 GB budget (#2688).
|
||||
# Test executables can't be cached, so a PR still links its tests.
|
||||
- name: Install sccache
|
||||
uses: Mozilla-Actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11
|
||||
uses: step-security/sccache-action@ae2d64c53dbae979f387673f0aae7ebb52087f6b # v0.0.11
|
||||
with:
|
||||
version: v0.18.0
|
||||
|
||||
@@ -253,7 +262,7 @@ jobs:
|
||||
if: matrix.part == 'integration'
|
||||
run: cargo xtask layers
|
||||
|
||||
- uses: taiki-e/install-action@3a3daafd3b7f23b8f65d9f5ba2db203fb59b79e2 # v2.90.2
|
||||
- uses: step-security/taiki-e-install-action@76747d22a7567cc4438546a84f11bdf18e670ab8 # v2.87.32
|
||||
with:
|
||||
tool: [email protected]
|
||||
|
||||
@@ -290,6 +299,10 @@ jobs:
|
||||
CARGO_INCREMENTAL: 0
|
||||
CARGO_NET_RETRY: 10
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
@@ -306,16 +319,18 @@ jobs:
|
||||
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev
|
||||
libgtk-3-dev
|
||||
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
|
||||
# gate.yml keys its cache `<cache-version>-rust-<hash of Cargo.toml>-gate`.
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
- uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2
|
||||
with:
|
||||
prefix-key: v1-rust
|
||||
shared-key: ${{ hashFiles('Cargo.toml') }}-gate
|
||||
save-if: false
|
||||
|
||||
- uses: taiki-e/install-action@3a3daafd3b7f23b8f65d9f5ba2db203fb59b79e2 # v2.90.2
|
||||
- uses: step-security/taiki-e-install-action@76747d22a7567cc4438546a84f11bdf18e670ab8 # v2.87.32
|
||||
with:
|
||||
tool: [email protected]
|
||||
|
||||
@@ -339,11 +354,17 @@ jobs:
|
||||
CARGO_PROFILE_RELEASE_LTO: "false"
|
||||
CARGO_PROFILE_RELEASE_CODEGEN_UNITS: "16"
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
- uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2
|
||||
with:
|
||||
key: corpus
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
@@ -369,6 +390,10 @@ jobs:
|
||||
# Match release.yml so PR results reflect what would actually ship.
|
||||
TRUNK_VERSION: 0.21.14
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
@@ -378,10 +403,11 @@ jobs:
|
||||
- name: Check out craft-i18n
|
||||
uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main
|
||||
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
targets: wasm32-unknown-unknown
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
- uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2
|
||||
with:
|
||||
key: ci-web
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
@@ -446,11 +472,17 @@ jobs:
|
||||
- { crate: affinity, name: import_preview, args: "--features io" }
|
||||
- { crate: format, name: load }
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # nightly
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
- uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2
|
||||
with:
|
||||
workspaces: crates/${{ matrix.target.crate }}/fuzz
|
||||
- name: Install cargo-fuzz
|
||||
@@ -474,6 +506,10 @@ jobs:
|
||||
env:
|
||||
RAYON_NUM_THREADS: "4"
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
@@ -483,8 +519,10 @@ jobs:
|
||||
packages: >-
|
||||
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev
|
||||
libgtk-3-dev
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
- uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2
|
||||
with:
|
||||
key: color-range-perf
|
||||
- name: Compare exact outputs and release timings on 24 MP
|
||||
@@ -504,6 +542,10 @@ jobs:
|
||||
env:
|
||||
RAYON_NUM_THREADS: "4"
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
@@ -513,8 +555,10 @@ jobs:
|
||||
packages: >-
|
||||
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev
|
||||
libgtk-3-dev
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
- uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2
|
||||
with:
|
||||
key: selection-morphology-perf
|
||||
- name: Compare exact outputs and release timings on 36 MP
|
||||
@@ -539,11 +583,17 @@ jobs:
|
||||
runs-on: macos-15
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
- uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2
|
||||
with:
|
||||
key: perf-release
|
||||
- name: Quick performance suite
|
||||
@@ -563,11 +613,17 @@ jobs:
|
||||
env:
|
||||
RAYON_NUM_THREADS: "4"
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
- uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2
|
||||
with:
|
||||
key: selection-combining-perf
|
||||
- name: Compare exact outputs and release timings on 36 MP
|
||||
@@ -587,6 +643,10 @@ jobs:
|
||||
env:
|
||||
RAYON_NUM_THREADS: "4"
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
@@ -596,8 +656,10 @@ jobs:
|
||||
persist-credentials: false
|
||||
ref: ${{ inputs.brush_tip_base }}
|
||||
path: before
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
- uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2
|
||||
with:
|
||||
workspaces: |
|
||||
before -> target
|
||||
@@ -633,6 +695,10 @@ jobs:
|
||||
CARGO_PROFILE_RELEASE_LTO: "false"
|
||||
CARGO_PROFILE_RELEASE_CODEGEN_UNITS: "16"
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
@@ -647,7 +713,9 @@ jobs:
|
||||
git worktree add --detach "$RUNNER_TEMP/photocraft-baseline" "$base"
|
||||
mkdir -p "$RUNNER_TEMP/photocraft-baseline/crates/engine/examples"
|
||||
cp crates/engine/examples/bench_dry_mixer.rs "$RUNNER_TEMP/photocraft-baseline/crates/engine/examples/bench_dry_mixer.rs"
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
- name: Install Linux build dependencies
|
||||
uses: storytold/craft-common-actions/actions/install-apt-packages@main
|
||||
with:
|
||||
|
||||
@@ -31,8 +31,14 @@ jobs:
|
||||
name: mdBook build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@v7
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
- name: Install mdBook
|
||||
run: cargo install mdbook --version 0.4.52 --locked
|
||||
- name: Build documentation
|
||||
|
||||
@@ -29,6 +29,10 @@ jobs:
|
||||
name: Verified AppImage inputs
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- run: bash packaging/linux/verified-download-test.sh
|
||||
|
||||
@@ -37,6 +41,10 @@ jobs:
|
||||
name: Windows installation policy (no app build)
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
@@ -43,13 +43,19 @@ jobs:
|
||||
runs-on: macos-15
|
||||
timeout-minutes: 120
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
- uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2
|
||||
with:
|
||||
key: perf-release
|
||||
|
||||
|
||||
@@ -118,7 +118,7 @@ People trust PhotoCraft with their work, and a crash loses it. A malformed file,
|
||||
3. **Clean-room.** We studied Photoshop and other proprietary editors for *behaviour and look only*. Never copy their code, shaders, profiles or assets. Implement from public specs (Adobe PSD spec, ICC, ISO 32000 blend modes, papers) and observation. Third-party assets must be permissively licensed, keep their license file next to them, and get a row in `ATTRIBUTION.md` (path, title, author, source, license) in the same change; so do original assets. The ArtCraft logos in `docs/brand/` are not open source (`docs/brand/LICENSE-brand.txt`). **Never commit font files:** fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts). PhotoCraft uses it through the optional build input `CRAFT_FONTS_DIR=<craft-fonts checkout>` (read by `crates/text/build.rs`, exposed as `photocraft_text::CRAFT_FONTS`; empty without it, and everything must still work). Build with it: `CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo build`; details in `docs/development.md` › Fonts.
|
||||
4. **Tests are the gate.** Every change comes with tests. Format crates use round-trip, synthetic-generator, oracle and fuzz tests. Keep the PSD corpus results and the parity floor (`crates/ui-egui/src/parity.rs`) from regressing.
|
||||
5. **The UI is thin and data-driven.** UI state lives in `ui-egui/src/state.rs` (serde), so the control channel can read and drive it. Colours and radii come from `theme::Tokens`, never hard-coded.
|
||||
6. **Verify UI changes visually.** Render offscreen with `cargo run -p photocraft-ui-egui --example snapshot` (no window, no focus stealing), or launch with `--control` and take `ui.screenshot`. Look at the PNG. Demo images must be public-domain art, never personal photos. When fetching assets, never put a person's name, email or other personal details in requests (User-Agent, headers, URLs); use a generic `Photocraft-dev` User-Agent.
|
||||
6. **Verify UI changes visually.** Render offscreen with `cargo run -p photocraft-ui-egui --example snapshot` (no window, no focus stealing), or launch with `--control` and take `ui.screenshot`. Look at the PNG. **Screenshots that show a PR's change (before/after evidence) go in the PR description, never in the repo:** `docs/images/` holds only images the README or a doc displays (a doc's own before/after comparison included), so a PR adds an image there only together with the doc that shows it. Demo images must be public-domain art, never personal photos. When fetching assets, never put a person's name, email or other personal details in requests (User-Agent, headers, URLs); use a generic `Photocraft-dev` User-Agent.
|
||||
7. **Never break wasm.** L0–L6 must `cargo check --target wasm32-unknown-unknown` (run `cargo xtask wasm`). File-system code is `cfg(not(target_arch = "wasm32"))` or goes through the platform services.
|
||||
8. **Performance is a feature.** Benchmark heavy operations on a 24–36 MP image in release. Work per tile in parallel (rayon), skip empty tiles, never scan a full surface per frame (cache per revision), and record before/after timings in the dev log.
|
||||
|
||||
|
||||
+2
-5
@@ -15,8 +15,9 @@ next to them.
|
||||
| `epaint_default_fonts::EGUI_ICONS` (build input; deflated into `OUT_DIR/egui_fonts/egui-icons.ttf.deflate`, registered by `crates/ui-egui/src/text/egui_fonts.rs`) | egui-icons, five-glyph subset of emoji-icon-font | John Slegers | [egui fork at 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [original](https://github.com/jslegers/emoji-icon-font); egui subset, unmodified here | MIT; Copyright (c) 2014 John Slegers; full upstream notice in [NOTICE](NOTICE) |
|
||||
| `assets/fonts/Inter-Regular.ttf`, `Inter-Medium.ttf`, `Inter-SemiBold.ttf` | Inter 4.001 (UI font) | The Inter Project Authors (Rasmus Andersson) | <https://github.com/rsms/inter> | SIL OFL 1.1, [`assets/fonts/OFL-Inter.txt`](assets/fonts/OFL-Inter.txt) |
|
||||
| `assets/fonts/JetBrainsMono-Regular.ttf` | JetBrains Mono 2.305 (numeric font) | The JetBrains Mono Project Authors | <https://github.com/JetBrains/JetBrainsMono> | SIL OFL 1.1, [`assets/fonts/OFL-JetBrainsMono.txt`](assets/fonts/OFL-JetBrainsMono.txt) |
|
||||
| `assets/icons/*.svg` except `slice-knife.svg`, `slice-select.svg`, `font-similar.svg`, `font-variable.svg`, `sampler.svg`, `artboard.svg`, `perspective-crop.svg`, `frame-placeholder.svg`, `ellipse-dashed.svg`, `gradient.svg`, `type-mask.svg`, `type-mask-vertical.svg`, `text-warp.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `history-brush.svg`, `quick-selection.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `convert-point.svg`, `pen-add-anchor.svg`, `pen-delete-anchor.svg`, `pen-freeform.svg`, `pen-curvature.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg`, `path-op-*.svg` and `marquee-{row,column}.svg`, `align-edge-*.svg` and `distribute-*.svg`, `crop-overlay-*.svg`, `vertical-align-*.svg`, `spirit-level.svg` (116 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
| `assets/icons/*.svg` except `vector-shape.svg`, `slice-knife.svg`, `slice-select.svg`, `font-similar.svg`, `font-variable.svg`, `sampler.svg`, `artboard.svg`, `perspective-crop.svg`, `frame-placeholder.svg`, `ellipse-dashed.svg`, `gradient.svg`, `type-mask.svg`, `type-mask-vertical.svg`, `text-warp.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `history-brush.svg`, `quick-selection.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `convert-point.svg`, `pen-add-anchor.svg`, `pen-delete-anchor.svg`, `pen-freeform.svg`, `pen-curvature.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg`, `path-op-*.svg` and `marquee-{row,column}.svg`, `align-edge-*.svg` and `distribute-*.svg`, `crop-overlay-*.svg`, `vertical-align-*.svg`, `spirit-level.svg` (116 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
| `assets/icons/{check,chevron-down,chevron-left,chevron-right,chevron-up,chevrons-left,chevrons-right,circle,clock,compass,info,link,link-2,lock,minus,monitor,moon,move,navigation,plus,search,square,trash,triangle,type,x,zoom-in}.svg` | Lucide icons derived from Feather (subset of the row above) | Cole Bemis (Feather), Lucide Contributors | <https://github.com/feathericons/feather> via Lucide | MIT (Feather) and ISC (Lucide), [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
| `assets/icons/vector-shape.svg` | Vector path shape-layer glyph with four anchor points | @superplay2021 | Original work for PhotoCraft | MIT OR Apache-2.0 |
|
||||
| `assets/icons/slice-knife.svg` | Slice tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `assets/icons/slice-select.svg` | Slice Select tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `assets/icons/crop-overlay-*.svg` | Crop overlay glyphs: Rule of Thirds, Grid, Diagonal, Triangle, Golden Ratio and Golden Spiral inside the crop-mark frame | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
@@ -80,12 +81,8 @@ The other built-in ICC profiles and the generated LUT looks are produced by code
|
||||
|---|---|---|---|---|
|
||||
| `docs/brand/` (all files) | ArtCraft name, wordmark and mark | ArtCraft Team | getartcraft.com | Not open source; trademarks of the ArtCraft Team, [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt) |
|
||||
| `docs/images/photocraft-*.jpg` | PhotoCraft screenshots | PhotoCraft contributors (UI) | Rendered offscreen with the `snapshot` example | MIT OR Apache-2.0 (UI); the artwork in each is public domain, listed below |
|
||||
| `docs/images/native-pipette-macos-*.png` | Text Color Picker on macOS before and after the native pipette fix (synthetic text, no artwork) | PhotoCraft contributors (UI); @SvenCarstensen (captures) | Local macOS screenshot and PhotoCraft control-channel capture | MIT OR Apache-2.0 |
|
||||
| `docs/images/preferences-apply-*.png` | Preferences before and after adding Apply (no artwork) | PhotoCraft contributors | PhotoCraft control-channel capture and offscreen `snapshot` example | MIT OR Apache-2.0 |
|
||||
| `docs/images/guide-position-*-tab.png` | New Guide before and after focusing Position with Tab (no artwork) | PhotoCraft contributors | Offscreen `snapshot` example with `ui.key Tab` | MIT OR Apache-2.0 |
|
||||
| `docs/images/embedded-vector-editor-en.png` | Embedded AI/PDF/EPS conversion warning and editor chooser (no artwork) | Don Omondi | Offscreen `smart_svg_ui::tests::capture_embedded_vector_conversion_prompt` with authored bytes and mock services | MIT OR Apache-2.0 |
|
||||
| `docs/images/embedded-vector-tabs-linux.png` | Shared VectorCraft window after a portal editor save and ordinary document launch | Don Omondi | Local Linux GUI acceptance with authored orange rectangle/blue circle SVGs; no private artwork | MIT OR Apache-2.0 |
|
||||
| `docs/images/gradient-overlay-method-*.png` | Gradient Overlay Method selector, before and after (synthetic gradient) | @oRE-o | Rendered offscreen with the `snapshot` example; no external artwork | MIT OR Apache-2.0 |
|
||||
| `docs/images/preset-invalid-choice-before.png` | Gradient preset import before validation, with the collision dialog closed | @yoriswind | Offscreen PhotoCraft capture with the synthetic `Fire.grd` gradient fixture | MIT OR Apache-2.0 |
|
||||
| `docs/images/preset-invalid-choice-after.png` | Gradient preset import after validation, with the collision dialog still open | @yoriswind | Offscreen PhotoCraft capture with the synthetic `Fire.grd` gradient fixture | MIT OR Apache-2.0 |
|
||||
| `docs/images/cpu-pixel-alignment/*.png` | CPU canvas pixel alignment, before and after #8321 | PhotoCraft contributors | Original synthetic noise rendered with the offscreen `snapshot` example; see the adjacent README | MIT OR Apache-2.0, adjacent `LICENSE-MIT` and `LICENSE-APACHE` |
|
||||
|
||||
Generated
+45
-43
@@ -1406,12 +1406,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
|
||||
[[package]]
|
||||
name = "craft-heif"
|
||||
@@ -1425,7 +1425,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
dependencies = [
|
||||
"fixed_decimal",
|
||||
"icu_decimal",
|
||||
@@ -1448,7 +1448,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1466,7 +1466,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"hayro",
|
||||
@@ -1478,7 +1478,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
dependencies = [
|
||||
"craft-winprint-gdi",
|
||||
"log",
|
||||
@@ -1492,7 +1492,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
dependencies = [
|
||||
"craft-fonts-build",
|
||||
"craft-i18n",
|
||||
@@ -1513,7 +1513,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"dunce",
|
||||
@@ -1523,6 +1523,7 @@ dependencies = [
|
||||
"image",
|
||||
"log",
|
||||
"plist",
|
||||
"rustix 1.1.5",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -2974,7 +2975,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro"
|
||||
version = "0.7.1"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"hayro-interpret",
|
||||
@@ -3004,7 +3005,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-interpret"
|
||||
version = "0.7.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"hayro-cmap",
|
||||
@@ -3022,7 +3023,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
"hayro-ccitt",
|
||||
@@ -3046,7 +3047,7 @@ checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f"
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
version = "0.7.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
@@ -5323,7 +5324,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"arboard",
|
||||
"async-io",
|
||||
@@ -5378,7 +5379,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-affinity"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
@@ -5388,7 +5389,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-algo"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"photocraft-color",
|
||||
@@ -5403,7 +5404,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-automation"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"cap-std",
|
||||
@@ -5436,7 +5437,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-cli"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"clap_complete",
|
||||
@@ -5462,7 +5463,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-cms"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"moxcms",
|
||||
"rayon",
|
||||
@@ -5470,7 +5471,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-codecs"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"craft-heif",
|
||||
"craft-jpeg",
|
||||
@@ -5494,7 +5495,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-color"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"photocraft-cms",
|
||||
"serde",
|
||||
@@ -5502,7 +5503,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-compose"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"photocraft-cms",
|
||||
@@ -5518,7 +5519,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-doc"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"photocraft-color",
|
||||
"photocraft-geom",
|
||||
@@ -5529,7 +5530,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-engine"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -5572,7 +5573,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-format"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"craft-pcraft-format",
|
||||
@@ -5596,14 +5597,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-geom"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-gpu"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"half",
|
||||
@@ -5624,7 +5625,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-io"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"craft-docpath",
|
||||
@@ -5664,18 +5665,18 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-ipp"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-ops"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"photocraft-doc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-paint"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"photocraft-cms",
|
||||
"photocraft-color",
|
||||
@@ -5689,7 +5690,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-plugins"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"photocraft-color",
|
||||
"photocraft-geom",
|
||||
@@ -5705,7 +5706,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-psd"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
@@ -5717,7 +5718,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-raster"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"lz4_flex",
|
||||
@@ -5733,7 +5734,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-raw"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"image",
|
||||
@@ -5748,7 +5749,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-tablet"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"log",
|
||||
@@ -5763,7 +5764,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-testkit"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"memory-stats",
|
||||
"serde_json",
|
||||
@@ -5771,7 +5772,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-text"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"parley",
|
||||
@@ -5786,7 +5787,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-ui-egui"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"chrono",
|
||||
@@ -5835,7 +5836,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-vector"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"photocraft-color",
|
||||
"photocraft-doc",
|
||||
@@ -5846,7 +5847,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-web"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"eframe",
|
||||
"egui",
|
||||
@@ -5869,7 +5870,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-web-boot"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"js-sys",
|
||||
@@ -9488,7 +9489,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "winprint"
|
||||
version = "0.2.1"
|
||||
source = "git+https://github.com/storytold/winprint.rs?rev=51934db382f225454cf152a8657eb03789be63c4#51934db382f225454cf152a8657eb03789be63c4"
|
||||
source = "git+https://github.com/storytold/winprint.rs?rev=bc06a7c48b768eb27a828c7986f6d2868b245ee0#bc06a7c48b768eb27a828c7986f6d2868b245ee0"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"fmt-derive",
|
||||
@@ -9503,6 +9504,7 @@ dependencies = [
|
||||
"windows",
|
||||
"windows-core",
|
||||
"windows-implement",
|
||||
"windows-numerics",
|
||||
"xml",
|
||||
]
|
||||
|
||||
@@ -9754,7 +9756,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-i18n",
|
||||
|
||||
+12
-12
@@ -4,13 +4,13 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
default-members = ["crates/*", "apps/photocraft", "apps/photocraft-cli", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["serde"] }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["serde"] }
|
||||
# internal
|
||||
photocraft-geom = { path = "crates/geom" }
|
||||
photocraft-color = { path = "crates/color" }
|
||||
@@ -39,19 +39,19 @@ photocraft-tablet = { path = "crates/tablet" }
|
||||
photocraft-ipp = { path = "crates/ipp" }
|
||||
|
||||
# external
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" }
|
||||
# HEIC/HEIF: the shared decoder (replaces crates/heif; craft-libs#784).
|
||||
craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "081078bb1b44aeedfa5bef3d4f13d978dc77510a" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["raster"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
|
||||
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["raster"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" }
|
||||
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" }
|
||||
craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "b8f7d93b00dfb8f172938f3d2d796ae62dcfe123" }
|
||||
# Interface translations: lookup, fallback, CLDR plurals and language names over the craft-i18n
|
||||
# catalogs that `crates/ui-egui/build.rs` embeds from `CRAFT_I18N_DIR` (storytold/craft-i18n, at
|
||||
# the commit in `craft-i18n.rev`). Already in the tree through craft-ui.
|
||||
craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
|
||||
craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" }
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] }
|
||||
thiserror = "2"
|
||||
serde = { version = "1", features = ["derive", "rc"] }
|
||||
serde_json = "1"
|
||||
@@ -211,7 +211,7 @@ egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc7
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
# craft-pdf's vendored Hayro trees: consumers patch the same craft-libs revision (crates/pdf README).
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" }
|
||||
@@ -244,6 +244,17 @@ pub struct LogFile {
|
||||
/// One formatted log line: `<timestamp> <LEVEL> [<thread>] <target>: <message>\n`.
|
||||
pub fn format_line(ts: &str, level: log::Level, thread: &str, target: &str, message: &str) -> String {
|
||||
let message = message.strip_suffix('\n').unwrap_or(message);
|
||||
// A message cannot forge a record or inject terminal controls: continuation lines are
|
||||
// indented (a record starts with a timestamp) and other control characters are escaped.
|
||||
let message: String = message
|
||||
.chars()
|
||||
.flat_map(|c| match c {
|
||||
'\n' => "\n ".chars().collect::<Vec<_>>(),
|
||||
'\r' => vec!['\\', 'r'],
|
||||
c if c.is_control() && c != '\t' => c.escape_default().collect(),
|
||||
c => vec![c],
|
||||
})
|
||||
.collect();
|
||||
format!("{ts} {level:<5} [{thread}] {target}: {message}\n")
|
||||
}
|
||||
|
||||
@@ -560,8 +571,10 @@ mod tests {
|
||||
format_line("2026-10-08T07:59:17.728Z", log::Level::Warn, "main", "photocraft::gpu_startup", "GPU startup marker: denied"),
|
||||
"2026-10-08T07:59:17.728Z WARN [main] photocraft::gpu_startup: GPU startup marker: denied\n"
|
||||
);
|
||||
// A multi-line message (a panic with a backtrace) keeps its lines; the record still ends in one newline.
|
||||
assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\nb\n"));
|
||||
// A multi-line message (a panic with a backtrace) keeps its lines, indented; the record still ends in one newline.
|
||||
assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\n b\n"));
|
||||
let forged = format_line("t", log::Level::Error, "w", "x", "a\r\n2026 INFO forged\x1b[2J");
|
||||
assert!(forged.lines().all(|l| !l.starts_with("2026")) && !forged.contains('\x1b') && !forged.contains('\r'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75">
|
||||
<path d="M8 6H16 M18 8V16 M16 18H8 M6 16V8"/>
|
||||
<rect x="4" y="4" width="4" height="4"/>
|
||||
<rect x="16" y="4" width="4" height="4"/>
|
||||
<rect x="4" y="16" width="4" height="4"/>
|
||||
<rect x="16" y="16" width="4" height="4"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 368 B |
@@ -447,7 +447,7 @@ pub(crate) fn effect_reach(e: &GalleryEffect) -> i32 {
|
||||
F::Plaster => gs(0.5 + g("smoothness") * 0.8) + gs(1.5) + 2,
|
||||
F::Stamp => gs(0.3 + g("smoothness") * 0.3),
|
||||
F::TornEdges => gs(1.0),
|
||||
F::WaterPaper => 2 * (g("fiberLength") / 6.0) as i32 + 2,
|
||||
F::WaterPaper => 2 * (fiber_length(e) / 6.0) as i32 + 2,
|
||||
F::GlowingEdges => gs(0.3 + g("smoothness") * 0.25) + gs(g("edgeWidth") * 0.4) + 2,
|
||||
F::Craquelure => 0,
|
||||
F::Patchwork => patch_size(e).ceil() as i32 + 2,
|
||||
@@ -518,6 +518,12 @@ fn plastic_sigma(e: &GalleryEffect) -> f32 {
|
||||
fn watercolor_radius(e: &GalleryEffect) -> usize {
|
||||
1 + ((15.0 - e.get("brushDetail")) / 2.5) as usize
|
||||
}
|
||||
/// Water Paper's fiber length within its parameter range (3..=50): raw gallery values bypass the
|
||||
/// setter's clamp, and the reach estimate and the blur radius must agree on one bounded value.
|
||||
fn fiber_length(e: &GalleryEffect) -> f32 {
|
||||
e.get("fiberLength").clamp(3.0, 50.0)
|
||||
}
|
||||
|
||||
fn basrelief_sigma(e: &GalleryEffect) -> f32 {
|
||||
0.3 + e.get("smoothness") * 0.5 + (15.0 - e.get("detail")) * 0.12
|
||||
}
|
||||
@@ -1178,7 +1184,7 @@ fn apply_sketch(e: &GalleryEffect, win: &mut Win, ctx: &Ctx) -> bool {
|
||||
}
|
||||
}
|
||||
F::WaterPaper => {
|
||||
let fl = g("fiberLength");
|
||||
let fl = fiber_length(e);
|
||||
let (br, co) = (g("brightness") / 100.0, g("contrast") / 100.0);
|
||||
let r = (fl / 6.0) as usize;
|
||||
line_blur3(&mut win.c, w, h, (1, 0), r);
|
||||
@@ -1360,6 +1366,17 @@ mod tests {
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gallery_window_budget_counts_working_temporaries() {
|
||||
// A 6300 px square RGBA window is 159 M samples for the source read alone, 476 M with the old
|
||||
// 3x factor, and over the 512 Mi-sample budget once the working window and temporaries count.
|
||||
// The check runs before any window is read, so nothing that large is allocated.
|
||||
let s = pattern(SampleType::F32);
|
||||
let big = Rect::new(0, 0, 6300, 6300);
|
||||
let fp = FilterParams::FilterGallery { effects: vec![GalleryEffect::new(crate::GalleryFilter::ALL[0])] };
|
||||
assert!(crate::apply_tiled_with(&s, &fp, big, big, None, 6300, None, &photocraft_raster::Interrupt::NONE).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_effect_changes_pixels_and_is_tile_independent() {
|
||||
let b = Rect::new(0, 0, 56, 40);
|
||||
|
||||
@@ -168,13 +168,18 @@ fn boxes_for_gauss(sigma: f32, n: usize) -> Vec<usize> {
|
||||
(0..n).map(|i| if i < m { wl as usize } else { wu as usize }).collect()
|
||||
}
|
||||
|
||||
/// Largest box-blur radius run (far beyond any real use).
|
||||
const MAX_BOX_RADIUS: f32 = 16384.0;
|
||||
|
||||
/// The box widths (odd) a blur runs as running-sum passes along each axis, or `None` when it uses a
|
||||
/// direct kernel (small radii, where the kernel is quicker).
|
||||
pub(crate) fn box_widths(params: &FilterParams) -> Option<Vec<usize>> {
|
||||
match *params {
|
||||
FilterParams::GaussianBlur { radius } if radius > 4.0 => Some(boxes_for_gauss(radius, 3)),
|
||||
FilterParams::BoxBlur { radius } => {
|
||||
let r = radius.max(0.0).round() as usize;
|
||||
// Capped: the line scratch grows with the radius, and `2 * r + 1` must not overflow
|
||||
// (Photoshop's largest Box Blur radius is 999).
|
||||
let r = radius.clamp(0.0, MAX_BOX_RADIUS).round() as usize;
|
||||
(r > 4).then(|| vec![2 * r + 1])
|
||||
}
|
||||
_ => None,
|
||||
|
||||
@@ -1029,23 +1029,25 @@ fn dehaze(px: &mut [[f32; 4]], w: usize, h: usize, d: &Dehaze) {
|
||||
}
|
||||
|
||||
fn detail(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, ps: f32) {
|
||||
// The controls' documented 0..=100 range: raw values drive the filter radii below.
|
||||
let [nl, nld, nc, ncd] = [p.noise_luminance, p.noise_luminance_detail, p.noise_color, p.noise_color_detail].map(|v| v.clamp(0.0, 100.0));
|
||||
// Work in Y + chroma (BT.709 luma, B−Y, R−Y).
|
||||
let mut y: Vec<f32> = px.iter().map(|q| luma([q[0], q[1], q[2]])).collect();
|
||||
let mut cb: Vec<f32> = px.iter().zip(&y).map(|(q, l)| q[2] - l).collect();
|
||||
let mut cr: Vec<f32> = px.iter().zip(&y).map(|(q, l)| q[0] - l).collect();
|
||||
if p.noise_luminance > 0.0 {
|
||||
let n = p.noise_luminance / 100.0;
|
||||
if nl > 0.0 {
|
||||
let n = nl / 100.0;
|
||||
let r = ((1.0 + 3.0 * n) * ps).round().max(1.0) as usize;
|
||||
let smooth = guided(&y, &y, w, h, r, (n * 0.06).powi(2) + 1e-6);
|
||||
let keep = p.noise_luminance_detail / 100.0 * 0.5;
|
||||
let keep = nld / 100.0 * 0.5;
|
||||
for i in 0..w * h {
|
||||
y[i] = smooth[i] + (y[i] - smooth[i]) * keep;
|
||||
}
|
||||
}
|
||||
if p.noise_color > 0.0 {
|
||||
let sigma = (p.noise_color / 100.0 * 6.0 * ps).max(0.3);
|
||||
if nc > 0.0 {
|
||||
let sigma = (nc / 100.0 * 6.0 * ps).max(0.3);
|
||||
let (bcb, bcr) = (gauss(&cb, w, h, sigma), gauss(&cr, w, h, sigma));
|
||||
let keep = p.noise_color_detail / 100.0 * 0.3;
|
||||
let keep = ncd / 100.0 * 0.3;
|
||||
for i in 0..w * h {
|
||||
cb[i] = bcb[i] + (cb[i] - bcb[i]) * keep;
|
||||
cr[i] = bcr[i] + (cr[i] - bcr[i]) * keep;
|
||||
@@ -1306,6 +1308,12 @@ mod tests {
|
||||
let mut nr = noisy.clone();
|
||||
develop(&mut nr, w, h, &CameraRaw { noise_luminance: 80.0, ..Default::default() }, false);
|
||||
assert!(var(&nr) < var(&noisy) * 0.5);
|
||||
// Out-of-range noise settings are held to their 0..=100 range, not turned into huge radii.
|
||||
let mut wild = noisy.clone();
|
||||
let hostile =
|
||||
CameraRaw { noise_luminance: 1.0e30, noise_color: 1.0e30, noise_luminance_detail: 1.0e30, noise_color_detail: 1.0e30, ..Default::default() };
|
||||
develop(&mut wild, w, h, &hostile, false);
|
||||
assert!(wild.iter().all(|q| q[0].is_finite()));
|
||||
let mut sh = noisy.clone();
|
||||
develop(&mut sh, w, h, &CameraRaw { sharpen_amount: 100.0, ..Default::default() }, false);
|
||||
assert!(var(&sh) > var(&noisy));
|
||||
|
||||
+34
-2
@@ -30,9 +30,14 @@ impl CameraInfo {
|
||||
}
|
||||
}
|
||||
|
||||
/// Text bytes decoded per EXIF read (real Make/Model/Lens/Date strings are a few dozen bytes).
|
||||
const MAX_TEXT_BYTES: usize = 1 << 20;
|
||||
|
||||
struct Tiff<'a> {
|
||||
b: &'a [u8],
|
||||
le: bool,
|
||||
/// Text bytes this read may still decode: duplicate tags can share one large blank value.
|
||||
text_left: std::cell::Cell<usize>,
|
||||
}
|
||||
|
||||
impl Tiff<'_> {
|
||||
@@ -93,7 +98,9 @@ impl Tiff<'_> {
|
||||
return None;
|
||||
}
|
||||
let at = self.data_at(typ, count, field)?;
|
||||
let s = self.b.get(at..at.checked_add(usize::try_from(count).ok()?)?)?;
|
||||
let n = usize::try_from(count).ok()?;
|
||||
self.text_left.set(self.text_left.get().checked_sub(n)?);
|
||||
let s = self.b.get(at..at.checked_add(n)?)?;
|
||||
let s = String::from_utf8_lossy(s).trim_end_matches('\0').trim().to_string();
|
||||
(!s.is_empty()).then_some(s)
|
||||
}
|
||||
@@ -111,7 +118,7 @@ pub fn read(exif: &[u8]) -> CameraInfo {
|
||||
Some([b'M', b'M', 0, 42]) => false,
|
||||
_ => return info,
|
||||
};
|
||||
let t = Tiff { b, le };
|
||||
let t = Tiff { b, le, text_left: std::cell::Cell::new(MAX_TEXT_BYTES) };
|
||||
let Some(ifd0) = t.u32(4) else { return info };
|
||||
let mut queue = vec![ifd0 as usize];
|
||||
let mut seen = Vec::new();
|
||||
@@ -259,6 +266,31 @@ mod tests {
|
||||
|
||||
/// Hostile payloads: huge counts, offsets near `u32::MAX`, self-referencing IFDs and random
|
||||
/// bytes read as `None` fields instead of panicking or overflowing (usize is 32 bits on wasm).
|
||||
#[test]
|
||||
fn blank_duplicate_text_tags_share_one_decode_budget() {
|
||||
// Blank values never fill `make`, so every duplicate would decode the same 1 MiB again;
|
||||
// the per-read budget stops after the first, so the later real value is not reached.
|
||||
let blank = MAX_TEXT_BYTES;
|
||||
let entry = |count: u32, off: u32| {
|
||||
let mut e = Vec::new();
|
||||
e.extend_from_slice(&0x010Fu16.to_le_bytes());
|
||||
e.extend_from_slice(&2u16.to_le_bytes());
|
||||
e.extend_from_slice(&count.to_le_bytes());
|
||||
e.extend_from_slice(&off.to_le_bytes());
|
||||
e
|
||||
};
|
||||
let mut b = b"II*\0".to_vec();
|
||||
b.extend_from_slice(&8u32.to_le_bytes());
|
||||
b.extend_from_slice(&3u16.to_le_bytes());
|
||||
b.extend(entry(blank as u32, 50));
|
||||
b.extend(entry(blank as u32, 50));
|
||||
b.extend(entry(2, u32::from_le_bytes(*b"M\0\0\0")));
|
||||
b.extend_from_slice(&0u32.to_le_bytes());
|
||||
assert_eq!(b.len(), 50);
|
||||
b.extend(std::iter::repeat_n(b' ', blank));
|
||||
assert_eq!(read(&b).make, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_text_tags_keep_the_first_value_without_copying_large_duplicates() {
|
||||
let value = vec![b'X'; 2 * 1024 * 1024];
|
||||
|
||||
@@ -115,7 +115,7 @@ pub fn complete_with(
|
||||
p: &CompleteParams,
|
||||
ctl: &photocraft_raster::Interrupt,
|
||||
) -> Result<Option<Vec<f32>>, photocraft_raster::Cancelled> {
|
||||
assert_eq!(hole.len(), w * h);
|
||||
assert_eq!(w.checked_mul(h), Some(hole.len()));
|
||||
let px: Vec<Px> = hole.iter().map(|h| if *h { Px::Hole } else { Px::Source }).collect();
|
||||
complete_masked(w, h, ch, img, &px, p, ctl)
|
||||
}
|
||||
@@ -159,8 +159,13 @@ fn complete_cow<'a>(
|
||||
p: &CompleteParams,
|
||||
ctl: &photocraft_raster::Interrupt,
|
||||
) -> Result<Result<Vec<f32>, Cow<'a, [f32]>>, photocraft_raster::Cancelled> {
|
||||
assert_eq!(img.len(), w * h * ch);
|
||||
assert_eq!(px.len(), w * h);
|
||||
// Checked: wrapped products must not let tiny buffers pass for a huge `h`.
|
||||
assert_eq!(w.checked_mul(h), Some(px.len()));
|
||||
assert_eq!(w.checked_mul(h).and_then(|n| n.checked_mul(ch)), Some(img.len()));
|
||||
if w == 0 || h == 0 {
|
||||
// Nothing to fill; no per-row tables for a zero-width image of any height.
|
||||
return Ok(Ok(img.into_owned()));
|
||||
}
|
||||
let Some(hb0) = hole_bounds(w, h, px) else { return Ok(Ok(img.into_owned())) };
|
||||
if ch == 0 {
|
||||
return Ok(Ok(Vec::new()));
|
||||
|
||||
@@ -261,7 +261,8 @@ pub fn best_offset(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool], ri
|
||||
pub fn synthesize(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool], block: usize, seed: u64) -> Vec<f32> {
|
||||
let mut out = img.to_vec();
|
||||
let Some((bx0, by0, bx1, by1)) = hole_bbox(w, h, hole) else { return out };
|
||||
let b = block.max(4) as i32;
|
||||
// A block larger than the image fits no candidate either way: the clamp keeps the i32 math in range.
|
||||
let b = block.clamp(4, w.max(h).max(4)) as i32;
|
||||
let ov = (b / 3).max(1);
|
||||
let hs = integral(w, h, hole);
|
||||
// Candidate block origins: whole block (with overlap) inside the grid and outside the hole.
|
||||
|
||||
@@ -23,6 +23,24 @@ fn zero_width_images_complete_without_sizing_by_height() {
|
||||
assert_eq!(complete(1 << 40, 0, 3, &[], &[], &p), Some(Vec::new()));
|
||||
}
|
||||
|
||||
/// Dimensions whose product wraps must be refused, not matched against tiny buffers.
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn wrapping_dimension_products_are_refused() {
|
||||
let _ = complete(1 << 40, 1 << 40, 1, &[], &[], &CompleteParams::default());
|
||||
}
|
||||
|
||||
/// A block size beyond `i32` falls back to the membrane fill instead of looping on a zero step.
|
||||
#[test]
|
||||
fn a_huge_synthesis_block_does_not_hang() {
|
||||
let (w, h) = (8, 8);
|
||||
let img = vec![0.5f32; w * h];
|
||||
let mut hole = vec![false; w * h];
|
||||
hole[27] = true;
|
||||
let out = synthesize(w, h, 1, &img, &hole, usize::MAX, 1);
|
||||
assert_eq!(out.len(), w * h);
|
||||
}
|
||||
|
||||
/// Smooth gradient plus deterministic fine noise.
|
||||
fn texture(w: usize, h: usize) -> Vec<f32> {
|
||||
let mut rng = Rng::new(7);
|
||||
|
||||
+15
-1
@@ -1317,6 +1317,15 @@ fn coverage_operation(params: &FilterParams) -> Option<coverage::Operation<'_>>
|
||||
}
|
||||
}
|
||||
|
||||
/// Working-copy samples per pixel a Filter Gallery stack holds beside the source read: none for an
|
||||
/// empty stack, which returns the cropped source.
|
||||
fn gallery_working_samples(params: &FilterParams) -> usize {
|
||||
match params {
|
||||
FilterParams::FilterGallery { effects } if !effects.is_empty() => 12,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
/// Dispatch checked whole-domain filters or bounded native tiles, publishing a result only after successful processing
|
||||
/// and cancellation checks.
|
||||
@@ -1390,7 +1399,12 @@ fn apply_tiled_with_impl(
|
||||
// caller-supplied, so a short parameter set can ask for a huge source window per tile.
|
||||
if let Halo::Radius(reach) = halo {
|
||||
let (w, h) = (area.width().min(tile as u32) as usize, area.height().min(tile as u32) as usize);
|
||||
let read_samples = w.checked_add(2 * reach as usize)?.checked_mul(h.checked_add(2 * reach as usize)?)?.checked_mul(fmt.channels())?;
|
||||
// A Filter Gallery applies every effect to one working window. Beside the source read (`channels`
|
||||
// samples per pixel) one effect holds the three-channel window plus its worst temporaries: two more
|
||||
// three-channel copies and a plane or gradient set, 12 samples per pixel however many effects there
|
||||
// are. An empty stack makes no working window (it returns the cropped source), so it is not charged.
|
||||
let per_pixel = fmt.channels().checked_add(gallery_working_samples(params))?;
|
||||
let read_samples = w.checked_add(2 * reach as usize)?.checked_mul(h.checked_add(2 * reach as usize)?)?.checked_mul(per_pixel)?;
|
||||
let tile_count = u64::from(area.width()).div_ceil(tile as u64).checked_mul(u64::from(area.height()).div_ceil(tile as u64))?;
|
||||
// Reject hostile source-window sizes before Image::read allocates them.
|
||||
// Ordinary filter parameters and automatic tiles fit these bounds.
|
||||
|
||||
@@ -896,6 +896,16 @@ mod tests {
|
||||
assert!(pv.vignette[0].abs() < 0.1, "{pv:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_oversized_level_count_is_clamped() {
|
||||
let (w, h) = (4, 4);
|
||||
let img = RoiImage { x0: 0, y0: 0, w, h, ch: 1, px: vec![0.5; w * h], alpha: vec![1.0; w * h] };
|
||||
let (out, cov) = multiband(w, h, &[img], &[vec![1.0; w * h]], usize::MAX).unwrap();
|
||||
assert_eq!(out.len(), w * h);
|
||||
assert!(out.iter().all(|v| (v - 0.5).abs() < 1e-5), "{out:?}");
|
||||
assert!(cov.iter().all(|c| *c == 1.0), "{cov:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seams_avoid_disagreement_and_multiband_is_seamless() {
|
||||
// Two images over a 120×40 strip, overlapping in 40..80; the second has a bright
|
||||
|
||||
@@ -555,7 +555,8 @@ pub fn try_multiband_batched(
|
||||
max_band_budget: Option<usize>,
|
||||
) -> Result<(Vec<f32>, Vec<f32>), AllocationError> {
|
||||
let ch = imgs.first().map_or(1, |i| i.ch);
|
||||
let levels = levels.max(1);
|
||||
// Levels past 1x1 add nothing; 16 (real use is at most 7) keeps the shifts below in range.
|
||||
let levels = levels.clamp(1, 16);
|
||||
let cost = |im: &RoiImage| band_cost(im, w, h, ch, levels);
|
||||
if let Some(limit) = max_band_budget {
|
||||
for im in imgs {
|
||||
|
||||
@@ -233,6 +233,10 @@ fn weights(o: i32, scale: f64, kernel: Kernel, edge: Option<(i32, i32)>, content
|
||||
let sum: f64 = w.iter().sum();
|
||||
(lo, w.into_iter().map(|v| v / sum).collect())
|
||||
}
|
||||
// Past a 4096x reduction Lanczos would build a weight per covered source sample (tens of
|
||||
// thousands per output sample); the box average that folds the beyond-edge weights is
|
||||
// indistinguishable at that scale.
|
||||
Kernel::Lanczos if scale < 1.0 / 4096.0 => weights(o, scale, Kernel::Bilinear, edge, content),
|
||||
Kernel::Lanczos => {
|
||||
let stretch = if scale < 1.0 { 1.0 / scale } else { 1.0 };
|
||||
let u = (o as f64 + 0.5) / scale - 0.5;
|
||||
|
||||
@@ -401,6 +401,18 @@ fn nearest_neighbor_reduction_does_not_average() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A reduction beyond 4096x by Lanczos must not build a weight per covered source sample.
|
||||
#[test]
|
||||
fn a_tiny_lanczos_scale_keeps_its_weights_small() {
|
||||
let scale = 1.0e-7;
|
||||
for o in [0, 1] {
|
||||
let (_, w) = weights(o, scale, Kernel::Lanczos, None, (0, 63));
|
||||
assert!(w.len() < 1024, "{} weights", w.len());
|
||||
let sum: f64 = w.iter().sum();
|
||||
assert!((sum - 1.0).abs() < 1e-6, "{sum}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #9212: a bicubic shrink of both axes stores the image between its passes with one axis at the
|
||||
/// old size, larger than the result; single-pass filters and growing axes store nothing larger.
|
||||
#[test]
|
||||
|
||||
@@ -46,6 +46,8 @@ impl Fold<'_> {
|
||||
/// Most subsamples per axis when a warp shrinks the source; also the longest source step per
|
||||
/// destination pixel the filter follows (bounds the footprint each tile reads).
|
||||
const MAX_SS: f64 = 8.0;
|
||||
/// Bounding-box pixels scanned per destination pixel of a tile, across all its triangles.
|
||||
const MAX_SCAN_PER_PIXEL: usize = 256;
|
||||
|
||||
/// Places a smart object's source image (`src`, its pixels in `src_rect`) in the document:
|
||||
/// through `warp` (source space) and then the affine `t` (source → document) in one resampling
|
||||
@@ -462,6 +464,11 @@ fn triangles(
|
||||
let by0 = ps.iter().map(|p| p[1]).fold(f64::MAX, f64::min).floor() as i32;
|
||||
let bx1 = ps.iter().map(|p| p[0]).fold(f64::MIN, f64::max).ceil() as i32;
|
||||
let by1 = ps.iter().map(|p| p[1]).fold(f64::MIN, f64::max).ceil() as i32;
|
||||
// Degenerate triangles draw nothing (`work` skips them the same way): do not bin them.
|
||||
let det = (ps[1][0] - ps[0][0]) * (ps[2][1] - ps[0][1]) - (ps[2][0] - ps[0][0]) * (ps[1][1] - ps[0][1]);
|
||||
if det.is_nan() || det.abs() < 1e-12 {
|
||||
continue;
|
||||
}
|
||||
let (cx0, cy0) = ((bx0.max(dst.x0) - tx0).div_euclid(ts), (by0.max(dst.y0) - ty0).div_euclid(ts));
|
||||
let (cx1, cy1) = ((bx1.min(dst.x1 - 1) - tx0).div_euclid(ts), (by1.min(dst.y1 - 1) - ty0).div_euclid(ts));
|
||||
for cy in cy0.max(0)..=cy1 {
|
||||
@@ -515,6 +522,9 @@ fn triangles(
|
||||
let mut under_at: Vec<u32> = Vec::new();
|
||||
let mut jac: Vec<([f64; 4], usize, usize)> = Vec::with_capacity(order.len());
|
||||
'pass: loop {
|
||||
// Folded warps pile thousands of triangles over the same pixels: the bounding boxes
|
||||
// scanned per tile are capped (a sound warp scans a small multiple of the tile's area).
|
||||
let mut scan_left = w * h * MAX_SCAN_PER_PIXEL + (1 << 16);
|
||||
for (k, tri) in order.iter().enumerate() {
|
||||
let [(p0, s0), (p1, s1), (p2, s2)] = tri.map(|v| verts[v]);
|
||||
let det = (p1[0] - p0[0]) * (p2[1] - p0[1]) - (p2[0] - p0[0]) * (p1[1] - p0[1]);
|
||||
@@ -538,6 +548,12 @@ fn triangles(
|
||||
let bx1 = (p0[0].max(p1[0]).max(p2[0]) + 0.5).ceil().min(f64::from(t.x1)) as i32;
|
||||
let by1 = (p0[1].max(p1[1]).max(p2[1]) + 0.5).ceil().min(f64::from(t.y1)) as i32;
|
||||
let eps = -1e-9;
|
||||
let scan = (bx1 - bx0).max(0) as usize * (by1 - by0).max(0) as usize;
|
||||
// A triangle that no longer fits is skipped, not the end of the tile: later (smaller) ones still draw.
|
||||
if scan > scan_left {
|
||||
continue;
|
||||
}
|
||||
scan_left -= scan;
|
||||
for y in by0..by1 {
|
||||
let py = f64::from(y) + 0.5;
|
||||
for x in bx0..bx1 {
|
||||
|
||||
@@ -203,7 +203,9 @@ pub fn save_bytes_with_renderer(
|
||||
}
|
||||
return Ok((bytes, warnings));
|
||||
}
|
||||
let result = photocraft_io::export_with_renderer(doc, &ext, opts, &photocraft_raster::Interrupt::NONE, renderer)?;
|
||||
// No ambient authority: a linked path inside the document must not be read and embedded.
|
||||
let opts = ExportOptions { read_linked_files: false, ..opts.clone() };
|
||||
let result = photocraft_io::export_with_renderer(doc, &ext, &opts, &photocraft_raster::Interrupt::NONE, renderer)?;
|
||||
Ok((result.bytes, result.warnings))
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
//! `files::save_bytes` is the capability-scoped encoder: a linked path inside the document must
|
||||
//! not be read through ambient filesystem authority and embedded in the returned bytes.
|
||||
|
||||
use photocraft_automation::files;
|
||||
use photocraft_doc::{Document, Layer, LayerContent, SmartContentsId, SmartObject, SmartSource};
|
||||
|
||||
#[test]
|
||||
fn a_linked_smart_object_is_not_read_into_the_bytes() {
|
||||
let mut doc = Document::new("linked", photocraft_doc::Size::new(8, 6), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8);
|
||||
let linked = std::env::current_exe().unwrap();
|
||||
let smart = SmartObject {
|
||||
contents_id: SmartContentsId::fresh(),
|
||||
source: SmartSource::Linked { path: linked.to_string_lossy().into_owned() },
|
||||
transform: photocraft_geom::Affine::IDENTITY,
|
||||
smart_filters: vec![],
|
||||
cache: Some(photocraft_raster::Surface::new(doc.pixel_format())),
|
||||
psd_raw: None,
|
||||
filters_enabled: true,
|
||||
filter_mask: None,
|
||||
warp: None,
|
||||
stack_mode: None,
|
||||
perspective: None,
|
||||
vector_preview: None,
|
||||
};
|
||||
doc.layers.push(Layer::new("Linked", LayerContent::Smart(smart)));
|
||||
let (bytes, warnings) = files::save_bytes(&doc, "out.psd", None, &Default::default()).unwrap();
|
||||
assert!(warnings.iter().any(|w| w.contains("not read for this export")), "{warnings:?}");
|
||||
assert!(bytes.len() < 1 << 20, "the test executable was not embedded");
|
||||
}
|
||||
@@ -9,6 +9,7 @@ mod gpu_backend;
|
||||
mod inactive_save;
|
||||
mod krita;
|
||||
mod layered_save_dirty;
|
||||
mod linked_save_bytes;
|
||||
mod mcp;
|
||||
mod mcp_wire;
|
||||
mod missing_font_warnings;
|
||||
|
||||
@@ -185,6 +185,7 @@ impl Profile {
|
||||
/// Parses ICC profile bytes.
|
||||
pub fn parse(bytes: &[u8]) -> Result<Profile, CmsError> {
|
||||
CURVE_SAMPLES_LEFT.with(|left| left.set(MAX_CURVE_SAMPLES));
|
||||
CLUT_VALUES_LEFT.with(|left| left.set(MAX_PROFILE_CLUT_VALUES));
|
||||
let mut p = parse_profile(bytes)?;
|
||||
p.bytes = Some(Arc::new(bytes.to_vec()));
|
||||
Ok(p)
|
||||
@@ -595,6 +596,24 @@ thread_local! {
|
||||
static CURVE_SAMPLES_LEFT: std::cell::Cell<usize> = const { std::cell::Cell::new(MAX_CURVE_SAMPLES) };
|
||||
}
|
||||
|
||||
/// CLUT values one profile may decode in all (128 MB of `f32`): the twelve LUT tags can alias
|
||||
/// one table, and each reference decodes its own copy.
|
||||
const MAX_PROFILE_CLUT_VALUES: usize = 32 << 20;
|
||||
|
||||
thread_local! {
|
||||
/// What is left of [`MAX_PROFILE_CLUT_VALUES`] for the profile being parsed on this thread.
|
||||
static CLUT_VALUES_LEFT: std::cell::Cell<usize> = const { std::cell::Cell::new(MAX_PROFILE_CLUT_VALUES) };
|
||||
}
|
||||
|
||||
/// Charges `n` decoded CLUT values to the profile being parsed.
|
||||
fn charge_clut_values(n: usize) -> Result<(), CmsError> {
|
||||
CLUT_VALUES_LEFT.with(|left| {
|
||||
let rest = left.get().checked_sub(n).ok_or_else(|| CmsError::Invalid("the profile's lookup tables hold too many values".into()))?;
|
||||
left.set(rest);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Charges `n` decoded curve samples to the profile being parsed.
|
||||
fn charge_curve_samples(n: usize) -> Result<(), CmsError> {
|
||||
CURVE_SAMPLES_LEFT.with(|left| {
|
||||
@@ -698,6 +717,7 @@ fn parse_lut(d: &[u8], a2b: bool) -> Result<Lut, CmsError> {
|
||||
return Err(CmsError::Invalid("CLUT too large".into()));
|
||||
}
|
||||
let total = nodes as usize * o;
|
||||
charge_clut_values(total)?;
|
||||
let s = r.slice(off, total * bps)?;
|
||||
let data: Vec<f32> = if wide {
|
||||
s.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]]) as f32 / 65535.0).collect()
|
||||
@@ -803,6 +823,7 @@ fn lut_ab_clut(r: &Reader, off: usize, cin: usize, cout: usize) -> Result<Stage,
|
||||
return Err(CmsError::Invalid("CLUT too large".into()));
|
||||
}
|
||||
let total = nodes as usize * cout;
|
||||
charge_clut_values(total)?;
|
||||
let samples = extent(off, 20, 1)?;
|
||||
let data: Vec<f32> = match prec {
|
||||
1 => r.slice(samples, total)?.iter().map(|b| *b as f32 / 255.0).collect(),
|
||||
@@ -984,6 +1005,22 @@ mod tests {
|
||||
mod curve_budget_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn aliased_cluts_are_charged_for_each_decoded_table() {
|
||||
// A 255³ × 1 CLUT (within one table's limit) referenced by LUT tags three times.
|
||||
let mut element = vec![255u8, 255, 255];
|
||||
element.resize(16, 0);
|
||||
element.extend([1, 0, 0, 0]);
|
||||
element.extend(std::iter::repeat_n(0u8, 255 * 255 * 255));
|
||||
let r = Reader { b: &element };
|
||||
CLUT_VALUES_LEFT.with(|left| left.set(MAX_PROFILE_CLUT_VALUES));
|
||||
assert!(lut_ab_clut(&r, 0, 3, 1).is_ok());
|
||||
assert!(lut_ab_clut(&r, 0, 3, 1).is_ok());
|
||||
assert!(lut_ab_clut(&r, 0, 3, 1).is_err(), "the third decoded copy passes the profile's allowance");
|
||||
CLUT_VALUES_LEFT.with(|left| left.set(MAX_PROFILE_CLUT_VALUES));
|
||||
assert!(lut_ab_clut(&r, 0, 3, 1).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aliased_curves_are_charged_for_each_decoded_table() {
|
||||
// One 1M-sample `curv` element referenced seventeen times decodes 17M samples.
|
||||
|
||||
@@ -296,9 +296,14 @@ pub(crate) fn decode_channels(bytes: &[u8], index: usize, names: &[&str], limits
|
||||
let (w, h) = (layer.size.0, layer.size.1);
|
||||
let channels = &layer.channel_data.list;
|
||||
let npx = w * h;
|
||||
// More names than channels can only repeat one: refuse before the per-name lookups multiply.
|
||||
if names.len() > channels.len() {
|
||||
return Err(err("more channel names than the part has channels"));
|
||||
}
|
||||
let have: Vec<String> = channels.iter().map(|c| c.name.to_string()).collect();
|
||||
let mut picked: Vec<&AnyChannel<FlatSamples>> = Vec::with_capacity(names.len());
|
||||
for name in names {
|
||||
let c = channels.iter().find(|c| c.name.to_string() == *name).ok_or_else(|| err(format!("the part has no channel {name}")))?;
|
||||
let c = have.iter().position(|n| n == name).map(|i| &channels[i]).ok_or_else(|| err(format!("the part has no channel {name}")))?;
|
||||
if c.sample_data.len() != npx {
|
||||
return Err(err("channel sample count mismatch (subsampled channels are unsupported)"));
|
||||
}
|
||||
|
||||
@@ -124,25 +124,33 @@ fn parse_manifest(json: &str) -> Vec<(f32, String)> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The stream channel names of a layer (`crypto_asset00`, `crypto_asset01`, …, exactly as
|
||||
/// the file spells them), matched leniently: the channel prefix and the `name` attribute
|
||||
/// differ in case or `_`/`-` between renderers (`CryptoAsset` vs `crypto_asset`).
|
||||
fn layer_streams(header: &exr::meta::header::Header, name: &str) -> Vec<String> {
|
||||
let normalize = |s: &str| s.to_ascii_lowercase().replace(['_', '-'], "");
|
||||
let want = normalize(name);
|
||||
let mut found: Vec<(u32, String)> = header
|
||||
.channels
|
||||
.list
|
||||
.iter()
|
||||
.filter_map(|c| {
|
||||
let s = split_stream(&c.name.to_string())?;
|
||||
(!s.coverage).then_some((s.index, s.stream))
|
||||
/// How a layer name compares with a stream's channel prefix: the channel prefix and the `name`
|
||||
/// attribute differ in case or `_`/`-` between renderers (`CryptoAsset` vs `crypto_asset`).
|
||||
fn normalize_layer(s: &str) -> String {
|
||||
s.to_ascii_lowercase().replace(['_', '-'], "")
|
||||
}
|
||||
|
||||
/// The stream channel names of every layer of a header (`crypto_asset00`, `crypto_asset01`, …,
|
||||
/// exactly as the file spells them), keyed by [`normalize_layer`] of their prefix. Built in one
|
||||
/// pass over the channels, so looking up each `cryptomatte/<key>/name` costs no channel scan.
|
||||
fn layer_streams(header: &exr::meta::header::Header) -> std::collections::HashMap<String, Vec<String>> {
|
||||
let mut found: std::collections::HashMap<String, Vec<(u32, String)>> = std::collections::HashMap::new();
|
||||
for c in &header.channels.list {
|
||||
let Some(s) = split_stream(&c.name.to_string()) else { continue };
|
||||
if s.coverage {
|
||||
continue;
|
||||
}
|
||||
let layer = normalize_layer(s.stream.trim_end_matches(|c: char| c.is_ascii_digit()));
|
||||
found.entry(layer).or_default().push((s.index, s.stream));
|
||||
}
|
||||
found
|
||||
.into_iter()
|
||||
.map(|(layer, mut streams)| {
|
||||
streams.sort();
|
||||
streams.dedup();
|
||||
(layer, streams.into_iter().map(|(_, stream)| stream).collect())
|
||||
})
|
||||
.filter(|(_, stream)| normalize(stream.trim_end_matches(|c: char| c.is_ascii_digit())) == want)
|
||||
.collect();
|
||||
found.sort();
|
||||
found.dedup();
|
||||
found.into_iter().map(|(_, stream)| stream).collect()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Lists every Cryptomatte layer of the file from the headers alone: what a Cryptomatte
|
||||
@@ -157,41 +165,56 @@ pub(crate) fn layers(bytes: &[u8], limits: &Limits) -> Result<Vec<CryptomatteLay
|
||||
let size = header.layer_size;
|
||||
let (w, h) = (u32::try_from(size.0).unwrap_or(u32::MAX), u32::try_from(size.1).unwrap_or(u32::MAX));
|
||||
limits.check_bytes(w, h, 8)?;
|
||||
// Cache stream lists by resolved layer name: layer_streams() rescans every channel,
|
||||
// and distinct file-controlled keys can all name the same layer, which would turn
|
||||
// channel discovery into O(keys * channels) work and allocate a fresh list each time.
|
||||
let mut streams_for: std::collections::HashMap<String, Vec<String>> = std::collections::HashMap::new();
|
||||
for key in cryptomatte_keys(&header.own_attributes.other) {
|
||||
let Some(name) = attribute(&header.own_attributes.other, &key, "name") else { continue };
|
||||
let channels = streams_for.entry(name.clone()).or_insert_with(|| layer_streams(header, name.as_str())).clone();
|
||||
if channels.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let manifest = attribute(&header.own_attributes.other, &key, "manifest")
|
||||
.filter(|m| m.len() <= MANIFEST_CAP)
|
||||
.map(|m| parse_manifest(m.as_str()))
|
||||
.unwrap_or_default();
|
||||
// Every channel's stream, indexed once by layer. Each layer's list is moved into the
|
||||
// first key that names it: file-controlled keys can all name the same layer (in any
|
||||
// case or `_`/`-` spelling), and copying its list for each of them would make the
|
||||
// result grow with keys * channels. A second key naming a listed layer is skipped;
|
||||
// `decode` resolves a name to its first layer anyway.
|
||||
let mut streams_for = layer_streams(header);
|
||||
// A key whose manifest is missing or unparseable only stands in for its layer when no later
|
||||
// key naming it has a usable one.
|
||||
let mut fallback: std::collections::HashMap<String, (String, String)> = std::collections::HashMap::new();
|
||||
let other = &header.own_attributes.other;
|
||||
let mut push = |name: String, key: String, manifest: Vec<_>, channels: Vec<String>| {
|
||||
out.push(CryptomatteLayer {
|
||||
part,
|
||||
name,
|
||||
key: key.clone(),
|
||||
conversion: attribute(&header.own_attributes.other, &key, "conversion"),
|
||||
conversion: attribute(other, &key, "conversion"),
|
||||
manifest,
|
||||
sidecar_manifest: attribute(&header.own_attributes.other, &key, "manif_file"),
|
||||
sidecar_manifest: attribute(other, &key, "manif_file"),
|
||||
key,
|
||||
channels,
|
||||
});
|
||||
};
|
||||
for key in cryptomatte_keys(other) {
|
||||
let Some(name) = attribute(other, &key, "name") else { continue };
|
||||
let norm = normalize_layer(&name);
|
||||
if streams_for.get(&norm).is_none_or(|c| c.is_empty()) {
|
||||
continue;
|
||||
}
|
||||
let manifest = attribute(other, &key, "manifest").filter(|m| m.len() <= MANIFEST_CAP).map(|m| parse_manifest(m.as_str())).unwrap_or_default();
|
||||
if manifest.is_empty() {
|
||||
fallback.entry(norm).or_insert((name, key));
|
||||
} else if let Some(channels) = streams_for.remove(&norm) {
|
||||
push(name, key, manifest, channels);
|
||||
}
|
||||
}
|
||||
for (norm, (name, key)) in fallback {
|
||||
if let Some(channels) = streams_for.remove(&norm) {
|
||||
push(name, key, Vec::new(), channels);
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| (&a.part, &a.name).cmp(&(&b.part, &b.name)));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Every `cryptomatte/<key>/` key of a header, in file order, without duplicates.
|
||||
/// Every `cryptomatte/<key>/` key of a header, sorted, without duplicates.
|
||||
fn cryptomatte_keys(other: &std::collections::HashMap<exr::meta::attribute::Text, exr::meta::attribute::AttributeValue>) -> Vec<String> {
|
||||
let mut keys = Vec::new();
|
||||
// Track seen keys in a set: the attribute names are file-controlled, so membership with
|
||||
// keys.iter().any() is O(n^2) in the number of distinct `cryptomatte/<key>/<field>`
|
||||
// groups. The Vec still records file order; the set only answers "seen before".
|
||||
// groups. The set only answers "seen before"; the result is sorted below.
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for name in other.keys() {
|
||||
let full = name.to_string();
|
||||
@@ -201,6 +224,7 @@ fn cryptomatte_keys(other: &std::collections::HashMap<exr::meta::attribute::Text
|
||||
keys.push(key.to_string());
|
||||
}
|
||||
}
|
||||
keys.sort(); // HashMap order varies per call; layer names must stay stable
|
||||
keys
|
||||
}
|
||||
|
||||
@@ -210,9 +234,11 @@ fn cryptomatte_keys(other: &std::collections::HashMap<exr::meta::attribute::Text
|
||||
/// other flat part decoders.
|
||||
pub(crate) fn decode(bytes: &[u8], layer_name: &str, limits: &Limits) -> Result<CryptomatteBuffer, CodecError> {
|
||||
let found = layers(bytes, limits)?;
|
||||
// An exact name wins, so layers whose names only differ after normalising can each be asked for.
|
||||
let layer = found
|
||||
.iter()
|
||||
.find(|l| l.name.eq_ignore_ascii_case(layer_name))
|
||||
.find(|l| l.name == layer_name)
|
||||
.or_else(|| found.iter().find(|l| normalize_layer(&l.name) == normalize_layer(layer_name)))
|
||||
.ok_or_else(|| CodecError::unsupported(F, format!("no Cryptomatte layer named {layer_name}")))?;
|
||||
// Also caps all parts' declared sizes together, like every other flat decode.
|
||||
let meta = super::exr::read_meta(bytes, limits)?;
|
||||
@@ -240,9 +266,12 @@ pub(crate) fn decode(bytes: &[u8], layer_name: &str, limits: &Limits) -> Result<
|
||||
// Two (ID, coverage) ranks per set: rank `slot * 2 + stream.rank`.
|
||||
let mut ids: Vec<Vec<f32>> = vec![Vec::new(); ranks];
|
||||
let mut coverages: Vec<Vec<f32>> = vec![Vec::new(); ranks];
|
||||
// Stream name -> its slot, built once: a linear search per decoded channel is quadratic in
|
||||
// the file's stream count.
|
||||
let slots: std::collections::HashMap<&str, usize> = layer.channels.iter().enumerate().rev().map(|(i, s)| (s.as_str(), i)).collect();
|
||||
for c in &ex_layer.channel_data.list {
|
||||
let Some(stream) = split_stream(&c.name.to_string()) else { continue };
|
||||
let Some(slot) = layer.channels.iter().position(|s| *s == stream.stream) else { continue };
|
||||
let Some(&slot) = slots.get(stream.stream.as_str()) else { continue };
|
||||
let values: Vec<f32> = c.sample_data.values_as_f32().collect();
|
||||
if values.len() != npx {
|
||||
return Err(CodecError::malformed(F, "a Cryptomatte channel is smaller than its layer"));
|
||||
|
||||
@@ -381,6 +381,8 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError>
|
||||
match out16 {
|
||||
Some(out) => Image::from_u16(w, hgt, layout, &out)?,
|
||||
None => {
|
||||
// Admission above assumed 16-bit samples; the float fallback is twice that.
|
||||
limits.check(w, hgt, layout, SampleType::F32)?;
|
||||
let max = (0..n).filter_map(physical).fold(0.0f64, f64::max);
|
||||
let white = if max <= 2.0 {
|
||||
1.0
|
||||
|
||||
@@ -1598,7 +1598,7 @@ pub fn encode_indexed(
|
||||
dpi: Option<(f32, f32)>,
|
||||
stereo: Option<PngStereo>,
|
||||
) -> Result<Vec<u8>, CodecError> {
|
||||
if width == 0 || height == 0 || indices.len() != width as usize * height as usize {
|
||||
if width == 0 || height == 0 || (width as usize).checked_mul(height as usize) != Some(indices.len()) {
|
||||
return Err(CodecError::InvalidImage("index data does not match the size".into()));
|
||||
}
|
||||
if palette.is_empty() || palette.len() > 256 || indices.iter().any(|&i| usize::from(i) >= palette.len()) {
|
||||
|
||||
@@ -448,7 +448,9 @@ impl<'a> Encoder<'a> {
|
||||
let whole_cost = best_sse + 3 * lambda;
|
||||
|
||||
// B_PRED: sub-blocks in raster order, each predicted from the reconstruction so far.
|
||||
let saved_y = self.rec_y.data.clone();
|
||||
// B_PRED writes only this macroblock's 16 rows: save those, not the whole plane.
|
||||
let rows = |p: &Plane| -> [[u8; 16]; 16] { std::array::from_fn(|r| p.data[(y0 + r) * p.width + x0..][..16].try_into().unwrap_or([0; 16])) };
|
||||
let saved_y = rows(&self.rec_y);
|
||||
let mut b_modes = [B_DC_PRED; 16];
|
||||
let mut b_blocks: Vec<Block> = Vec::with_capacity(16);
|
||||
let mut b_sse = 0u64;
|
||||
@@ -490,7 +492,10 @@ impl<'a> Encoder<'a> {
|
||||
(B_PRED, None, b_blocks)
|
||||
} else {
|
||||
// Whole-block mode: undo the B_PRED reconstruction, code 16 blocks + Y2.
|
||||
self.rec_y.data = saved_y;
|
||||
let w = self.rec_y.width;
|
||||
for (r, row) in saved_y.iter().enumerate() {
|
||||
self.rec_y.data[(y0 + r) * w + x0..][..16].copy_from_slice(row);
|
||||
}
|
||||
let mut dcs = [0i32; 16];
|
||||
let mut ac_blocks: Vec<[i32; 16]> = Vec::with_capacity(16);
|
||||
let mut deq_blocks: Vec<[i32; 16]> = Vec::with_capacity(16);
|
||||
|
||||
@@ -526,18 +526,118 @@ pub fn xmp_with_resolution(xmp: &str, ppi: (f32, f32)) -> Cow<'_, str> {
|
||||
fn exif_without_thumbnail(exif: &[u8]) -> Option<Vec<u8>> {
|
||||
let body = tiff_body(exif);
|
||||
let prefix = exif.len() - body.len();
|
||||
let (_, first, count, entry_bytes, big_tiff) = ifd0_entries(body)?;
|
||||
let (order, first, count, entry_bytes, big_tiff) = ifd0_entries(body)?;
|
||||
let next = prefix.checked_add(first)?.checked_add(count.checked_mul(entry_bytes)?)?;
|
||||
let width = if big_tiff { 8 } else { 4 };
|
||||
// In bounds: `ifd0_entries` checked that the whole pointer is present.
|
||||
if exif.get(next..next.checked_add(width)?)?.iter().all(|b| *b == 0) {
|
||||
return None;
|
||||
}
|
||||
// Classic TIFF: also blank the thumbnail JPEG itself (IFD1's JPEGInterchangeFormat/Length),
|
||||
// which stays recoverable in the block once nothing points at it.
|
||||
// Only a range clear of the TIFF header, IFD0's table and values, and its Exif/GPS sub-IFDs: one
|
||||
// that covers them is not a thumbnail.
|
||||
let thumb = (!big_tiff)
|
||||
.then(|| thumbnail_range(order, body, next - prefix))
|
||||
.flatten()
|
||||
.filter(|&(off, len)| off >= 8 && !overlaps_ifd0(order, body, first - 2, count, off, len));
|
||||
let mut out = exif.to_vec();
|
||||
out.get_mut(next..next + width)?.fill(0);
|
||||
if let Some((off, len)) = thumb
|
||||
&& let Some(jpeg) = prefix.checked_add(off).and_then(|a| out.get_mut(a..a.checked_add(len)?))
|
||||
{
|
||||
jpeg.fill(0);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Most IFD entries `overlaps_ifd0` examines in total: a hostile block with thousands of Exif/GPS
|
||||
/// pointers to large sub-IFDs would otherwise cost billions of checks.
|
||||
const MAX_OVERLAP_ENTRIES: usize = 1 << 20;
|
||||
|
||||
/// Whether `off..off + len` of `body` covers part of classic IFD0 (`ifd0` is its entry count's
|
||||
/// offset) or of its Exif / GPS sub-IFDs. Past [`MAX_OVERLAP_ENTRIES`] checks it answers `true`
|
||||
/// (the range is not trusted as a thumbnail, so its bytes stay).
|
||||
fn overlaps_ifd0(order: Order, body: &[u8], ifd0: usize, count: usize, off: usize, len: usize) -> bool {
|
||||
let mut budget = MAX_OVERLAP_ENTRIES;
|
||||
overlaps_ifd(order, body, ifd0, count, off, len, &mut budget)
|
||||
|| (0..count).any(|i| {
|
||||
let e = ifd0 + 2 + i * 12;
|
||||
// A LONG pointer (tag 0x8769 ExifIFD, 0x8825 GPSIFD) to a sub-IFD, whose own count says its size.
|
||||
matches!(order.u16(body, e), Some(0x8769 | 0x8825))
|
||||
&& order.u32(body, e + 8).and_then(|v| usize::try_from(v).ok()).is_some_and(|sub| overlaps_sub_ifd(order, body, sub, off, len, &mut budget))
|
||||
})
|
||||
}
|
||||
|
||||
/// [`overlaps_ifd`] for the Exif / GPS sub-IFD at `sub`, and for the Interoperability IFD (tag
|
||||
/// 0xA005) it points to, which `jpeg.fill(0)` would otherwise erase from under its pointer.
|
||||
fn overlaps_sub_ifd(order: Order, body: &[u8], sub: usize, off: usize, len: usize, budget: &mut usize) -> bool {
|
||||
let Some(n) = order.u16(body, sub).map(usize::from) else { return false };
|
||||
if overlaps_ifd(order, body, sub, n, off, len, budget) {
|
||||
return true;
|
||||
}
|
||||
(0..n).any(|i| {
|
||||
let Some(left) = budget.checked_sub(1) else { return true };
|
||||
*budget = left;
|
||||
let e = sub + 2 + i * 12;
|
||||
matches!(order.u16(body, e), Some(0xA005))
|
||||
&& order
|
||||
.u32(body, e + 8)
|
||||
.and_then(|v| usize::try_from(v).ok())
|
||||
.is_some_and(|interop| order.u16(body, interop).is_some_and(|m| overlaps_ifd(order, body, interop, usize::from(m), off, len, budget)))
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `off..off + len` of `body` covers the table of the classic IFD at `ifd` (its entry
|
||||
/// count's offset) with the next-IFD pointer, or an out-of-line value of one of its entries. Each
|
||||
/// entry examined is charged to `budget`; when it runs out the answer is `true`.
|
||||
fn overlaps_ifd(order: Order, body: &[u8], ifd: usize, count: usize, off: usize, len: usize, budget: &mut usize) -> bool {
|
||||
let end = off.saturating_add(len);
|
||||
let hits = |a: usize, size: usize| a < end && off < a.saturating_add(size);
|
||||
if hits(ifd, 2 + count * 12 + 4) {
|
||||
return true;
|
||||
}
|
||||
(0..count).any(|i| {
|
||||
let Some(left) = budget.checked_sub(1) else { return true };
|
||||
*budget = left;
|
||||
let e = ifd + 2 + i * 12;
|
||||
let unit = match order.u16(body, e + 2) {
|
||||
Some(1 | 2 | 6 | 7) => 1,
|
||||
Some(3 | 8) => 2,
|
||||
Some(4 | 9 | 11) => 4,
|
||||
Some(5 | 10 | 12) => 8,
|
||||
_ => return false,
|
||||
};
|
||||
let size = usize::try_from(order.u32(body, e + 4).unwrap_or(0)).unwrap_or(usize::MAX).saturating_mul(unit);
|
||||
size > 4 && order.u32(body, e + 8).and_then(|v| usize::try_from(v).ok()).is_some_and(|v| hits(v, size))
|
||||
})
|
||||
}
|
||||
|
||||
/// IFD1's thumbnail JPEG as (offset, length) in `body`, from the next-IFD pointer at `ptr`.
|
||||
fn thumbnail_range(order: Order, body: &[u8], ptr: usize) -> Option<(usize, usize)> {
|
||||
let ifd1 = usize::try_from(order.u32(body, ptr)?).ok()?;
|
||||
let (mut off, mut len) = (None, None);
|
||||
for i in 0..usize::from(order.u16(body, ifd1)?) {
|
||||
let e = ifd1.checked_add(2)?.checked_add(i.checked_mul(12)?)?;
|
||||
let tag = order.u16(body, e)?;
|
||||
if !matches!(tag, 0x0201 | 0x0202) {
|
||||
continue;
|
||||
}
|
||||
// One SHORT or LONG value; anything else holds an unrelated number.
|
||||
let ty = order.u16(body, e + 2)?;
|
||||
if order.u32(body, e + 4)? != 1 || !matches!(ty, 3 | 4) {
|
||||
return None;
|
||||
}
|
||||
let value = if ty == 3 { usize::from(order.u16(body, e + 8)?) } else { usize::try_from(order.u32(body, e + 8)?).ok()? };
|
||||
if tag == 0x0201 {
|
||||
off = Some(value);
|
||||
} else {
|
||||
len = Some(value);
|
||||
}
|
||||
}
|
||||
Some((off?, len?))
|
||||
}
|
||||
|
||||
/// The EXIF to write next to upright pixels at resolution `ppi`: Orientation 1 (see
|
||||
/// [`upright_exif`]), no thumbnail of the source image (see [`exif_without_thumbnail`]) and,
|
||||
/// when `ppi` is known, the resolution (see [`exif_with_resolution`]).
|
||||
|
||||
@@ -227,7 +227,7 @@ fn put_multibyte(out: &mut Vec<u8>, v: u32) {
|
||||
/// WBMP type 0 (1 bit per pixel, rows padded to bytes, 1 = white). `white[i]` per pixel.
|
||||
pub fn encode_wbmp(width: u32, height: u32, white: &[bool]) -> Result<Vec<u8>, CodecError> {
|
||||
let (w, h) = (width as usize, height as usize);
|
||||
if width == 0 || height == 0 || white.len() != w * h {
|
||||
if width == 0 || height == 0 || w.checked_mul(h) != Some(white.len()) {
|
||||
return Err(CodecError::InvalidImage("WBMP size must match the pixel data".into()));
|
||||
}
|
||||
let mut out = vec![0u8, 0u8];
|
||||
@@ -304,7 +304,7 @@ pub fn encode_jpeg_rgb8(
|
||||
let (Ok(w16), Ok(h16)) = (u16::try_from(width), u16::try_from(height)) else {
|
||||
return Err(CodecError::encode(Format::Jpeg, "JPEG dimensions are limited to 65535"));
|
||||
};
|
||||
if rgb.len() != width as usize * height as usize * 3 {
|
||||
if (width as usize).checked_mul(height as usize).and_then(|n| n.checked_mul(3)) != Some(rgb.len()) {
|
||||
return Err(CodecError::InvalidImage("RGB data does not match the size".into()));
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
|
||||
@@ -269,3 +269,59 @@ fn hostile_input_never_panics() {
|
||||
let e = cryptomatte_layers(&bytes, &Limits { max_alloc: 8, ..Limits::default() }).unwrap_err();
|
||||
assert!(e.to_string().contains("exceed"), "{e}");
|
||||
}
|
||||
|
||||
/// Many keys naming the same layer (in different spellings) list it once, so the listing
|
||||
/// stays proportional to the channels rather than keys * channels.
|
||||
#[test]
|
||||
fn keys_naming_one_layer_list_it_once() {
|
||||
let (w, h) = (4usize, 4usize);
|
||||
let mk = |n: &str, v: f32| AnyChannel::new(n, FlatSamples::F32(vec![v; w * h]));
|
||||
let list = vec![mk("crypto_asset00.red", cryptomatte_id("cube")), mk("crypto_asset00.green", 1.0)];
|
||||
let mut attrs = LayerAttributes::named("crypto_asset");
|
||||
let spellings = ["CryptoAsset", "crypto_asset", "Crypto-Asset", "CRYPTO_ASSET", "crypto__asset"];
|
||||
for i in 0..200 {
|
||||
let name = spellings[i % spellings.len()];
|
||||
attrs.other.insert(text(&format!("cryptomatte/k{i:04}/name")), AttributeValue::Text(text(name)));
|
||||
}
|
||||
let layer = Layer::new(
|
||||
(w, h),
|
||||
attrs,
|
||||
Encoding { compression: Compression::Uncompressed, blocks: Blocks::ScanLines, line_order: LineOrder::Increasing },
|
||||
AnyChannels::sort(list.into_iter().collect()),
|
||||
);
|
||||
let image = exr::image::Image::from_layers(ImageAttributes::new(IntegerBounds::new((0, 0), (w, h))), vec![layer]);
|
||||
let mut out = std::io::Cursor::new(Vec::new());
|
||||
image.write().to_buffered(&mut out).expect("synthetic cryptomatte exr writes");
|
||||
let bytes = out.into_inner();
|
||||
let found = cryptomatte_layers(&bytes, &Limits::default()).unwrap();
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(found[0].channels, ["crypto_asset00"]);
|
||||
let buf = decode_cryptomatte(&bytes, &found[0].name, &Limits::default()).unwrap();
|
||||
assert_eq!(buf.at(0, 0).len(), 1);
|
||||
}
|
||||
|
||||
/// Of keys naming one layer, the first with a usable manifest lists it, not an earlier one
|
||||
/// whose manifest is missing.
|
||||
#[test]
|
||||
fn a_later_key_with_a_manifest_beats_an_earlier_one_without() {
|
||||
let (w, h) = (4usize, 4usize);
|
||||
let mk = |n: &str, v: f32| AnyChannel::new(n, FlatSamples::F32(vec![v; w * h]));
|
||||
let list = vec![mk("crypto_asset00.red", cryptomatte_id("cube")), mk("crypto_asset00.green", 1.0)];
|
||||
let mut attrs = LayerAttributes::named("crypto_asset");
|
||||
attrs.other.insert(text("cryptomatte/a/name"), AttributeValue::Text(text("CryptoAsset")));
|
||||
attrs.other.insert(text("cryptomatte/b/name"), AttributeValue::Text(text("crypto_asset")));
|
||||
attrs.other.insert(text("cryptomatte/b/manifest"), AttributeValue::Text(text("{\"cube\":\"3f800000\"}")));
|
||||
let layer = Layer::new(
|
||||
(w, h),
|
||||
attrs,
|
||||
Encoding { compression: Compression::Uncompressed, blocks: Blocks::ScanLines, line_order: LineOrder::Increasing },
|
||||
AnyChannels::sort(list.into_iter().collect()),
|
||||
);
|
||||
let image = exr::image::Image::from_layers(ImageAttributes::new(IntegerBounds::new((0, 0), (w, h))), vec![layer]);
|
||||
let mut out = std::io::Cursor::new(Vec::new());
|
||||
image.write().to_buffered(&mut out).expect("synthetic cryptomatte exr writes");
|
||||
let found = cryptomatte_layers(&out.into_inner(), &Limits::default()).unwrap();
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(found[0].key, "b");
|
||||
assert_eq!(found[0].manifest.len(), 1);
|
||||
}
|
||||
@@ -511,10 +511,12 @@ fn exports_drop_the_source_exif_thumbnail() {
|
||||
assert!(out.windows(6).any(|w| w == b"NIKON\0"), "the rest of the EXIF is kept");
|
||||
near(exif_resolution(&out), ppi.map_or(300.0, |p| p.0));
|
||||
}
|
||||
// Only the pointer changes.
|
||||
// Only the pointer and the thumbnail's own bytes (the JPEG at the end) change.
|
||||
let out = export_exif(&exif, None);
|
||||
let thumb_len = b"\xFF\xD8stale thumbnail\xFF\xD9".len();
|
||||
let differing: Vec<usize> = (0..exif.len()).filter(|&i| exif[i] != out[i]).collect();
|
||||
assert!(differing.iter().all(|&i| (8 + 2 + 4 * 12..8 + 2 + 4 * 12 + 4).contains(&i)), "{differing:?}");
|
||||
assert!(differing.iter().all(|&i| (8 + 2 + 4 * 12..8 + 2 + 4 * 12 + 4).contains(&i) || i >= exif.len() - thumb_len), "{differing:?}");
|
||||
assert!(!out.windows(5).any(|w| w == b"stale"), "the thumbnail bytes are blanked, not just unlinked");
|
||||
// With a JPEG-style prefix too.
|
||||
let prefixed = [b"Exif\0\0".as_slice(), &exif].concat();
|
||||
assert_eq!(next_ifd(e, &export_exif(&prefixed, None)[6..]), 0);
|
||||
@@ -534,6 +536,44 @@ fn exports_drop_the_source_exif_thumbnail() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A thumbnail range that covers IFD0, or tags that are not one SHORT/LONG value, are not blanked.
|
||||
#[test]
|
||||
fn thumbnail_blanking_keeps_ifd0_and_ignores_malformed_tags() {
|
||||
for e in [&LE, &BE] {
|
||||
let exif = exif_with_thumbnail(e);
|
||||
let ifd1 = camera_exif(e).len();
|
||||
let table = 8..8 + 2 + 4 * 12;
|
||||
// Offset 8, length 60: the range covers IFD0's table.
|
||||
let mut over = exif.clone();
|
||||
over[ifd1 + 2 + 8..ifd1 + 2 + 12].copy_from_slice(&e.u32(8));
|
||||
over[ifd1 + 2 + 12 + 8..ifd1 + 2 + 12 + 12].copy_from_slice(&e.u32(60));
|
||||
let out = export_exif(&over, None);
|
||||
assert_eq!(next_ifd(e, &out), 0, "IFD1 is still unlinked");
|
||||
assert_eq!(out[table.start..table.end], over[table.start..table.end], "IFD0's table is untouched");
|
||||
// Offset 0, length 8: the range covers the TIFF header, which must stay parseable.
|
||||
let mut header = exif.clone();
|
||||
header[ifd1 + 2 + 8..ifd1 + 2 + 12].copy_from_slice(&e.u32(0));
|
||||
header[ifd1 + 2 + 12 + 8..ifd1 + 2 + 12 + 12].copy_from_slice(&e.u32(8));
|
||||
let out = export_exif(&header, None);
|
||||
assert_eq!(out[..8], header[..8], "the TIFF header is untouched");
|
||||
// IFD0's last entry (Unit) turned into an ExifIFD pointer at IFD1's table: that range is not a thumbnail.
|
||||
let mut sub = exif.clone();
|
||||
let entry = 8 + 2 + 3 * 12;
|
||||
sub[entry..entry + 2].copy_from_slice(&e.u16(0x8769));
|
||||
sub[entry + 2..entry + 4].copy_from_slice(&e.u16(LONG));
|
||||
sub[entry + 4..entry + 8].copy_from_slice(&e.u32(1));
|
||||
sub[entry + 8..entry + 12].copy_from_slice(&e.u32(ifd1 as u32));
|
||||
sub[ifd1 + 2 + 8..ifd1 + 2 + 12].copy_from_slice(&e.u32(ifd1 as u32 + 2));
|
||||
sub[ifd1 + 2 + 12 + 8..ifd1 + 2 + 12 + 12].copy_from_slice(&e.u32(4));
|
||||
let out = export_exif(&sub, None);
|
||||
assert_eq!(out[ifd1 + 2..ifd1 + 6], sub[ifd1 + 2..ifd1 + 6], "the sub-IFD's table is untouched");
|
||||
// A count of 2 on the offset tag: the thumbnail bytes are not blanked.
|
||||
let mut counted = exif.clone();
|
||||
counted[ifd1 + 2 + 4..ifd1 + 2 + 8].copy_from_slice(&e.u32(2));
|
||||
assert!(export_exif(&counted, None).windows(5).any(|w| w == b"stale"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thumbnail_removal_never_panics_on_truncated_exif() {
|
||||
for e in [&LE, &BE] {
|
||||
@@ -544,3 +584,75 @@ fn thumbnail_removal_never_panics_on_truncated_exif() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Many Exif pointers to one huge sub-IFD must not cost a full scan each: past the scan budget the
|
||||
/// thumbnail bytes are left alone (the IFD1 pointer is still cleared).
|
||||
#[test]
|
||||
fn thumbnail_overlap_scan_is_bounded_by_a_budget() {
|
||||
let e = &LE;
|
||||
let (pointers, sub_entries) = (100usize, 65_535usize);
|
||||
let sub = 8 + 2 + pointers * 12 + 4;
|
||||
let ifd1 = sub + 2 + sub_entries * 12 + 4;
|
||||
let thumb = b"\xFF\xD8stale thumbnail\xFF\xD9";
|
||||
let mut v = b"II*\0".to_vec();
|
||||
v.extend_from_slice(&e.u32(8));
|
||||
v.extend_from_slice(&e.u16(pointers as u16));
|
||||
for _ in 0..pointers {
|
||||
v.extend_from_slice(&[e.u16(0x8769), e.u16(LONG)].concat());
|
||||
v.extend_from_slice(&[e.u32(1), e.u32(sub as u32)].concat());
|
||||
}
|
||||
v.extend_from_slice(&e.u32(ifd1 as u32));
|
||||
v.extend_from_slice(&e.u16(sub_entries as u16));
|
||||
v.resize(ifd1, 0); // the sub-IFD's entries are type 0: nothing to hit
|
||||
v.extend_from_slice(&e.u16(2));
|
||||
for (tag, value) in [(0x0201u16, (ifd1 + 2 + 2 * 12 + 4) as u32), (0x0202, thumb.len() as u32)] {
|
||||
v.extend_from_slice(&[e.u16(tag), e.u16(LONG)].concat());
|
||||
v.extend_from_slice(&[e.u32(1), e.u32(value)].concat());
|
||||
}
|
||||
v.extend_from_slice(&e.u32(0));
|
||||
v.extend_from_slice(thumb);
|
||||
let out = export_exif(&v, None);
|
||||
assert_eq!(next_ifd_at(e, &out, 8 + 2 + pointers * 12), 0, "IFD1 is unlinked");
|
||||
assert!(out.windows(5).any(|w| w == b"stale"), "over the scan budget the thumbnail bytes stay");
|
||||
}
|
||||
|
||||
fn next_ifd_at(e: &Exif, exif: &[u8], at: usize) -> u32 {
|
||||
let b: [u8; 4] = exif[at..at + 4].try_into().unwrap();
|
||||
if e.big { u32::from_be_bytes(b) } else { u32::from_le_bytes(b) }
|
||||
}
|
||||
|
||||
/// A thumbnail range that covers the Interoperability IFD (an Exif sub-IFD's 0xA005 target) is not
|
||||
/// blanked: its pointer would stay behind, aimed at zeroes.
|
||||
#[test]
|
||||
fn thumbnail_blanking_keeps_the_interoperability_ifd() {
|
||||
for e in [&LE, &BE] {
|
||||
let (ifd0, sub, interop, ifd1) = (8usize, 8 + 2 + 12 + 4, 8 + 2 + 12 + 4 + 2 + 12 + 4, 8 + 2 + 12 + 4 + 2 + 12 + 4 + 2 + 12 + 4);
|
||||
let mut v = if e.big { b"MM\0*".to_vec() } else { b"II*\0".to_vec() };
|
||||
v.extend_from_slice(&e.u32(ifd0 as u32));
|
||||
// IFD0: one ExifIFD pointer, then IFD1.
|
||||
v.extend_from_slice(&e.u16(1));
|
||||
v.extend_from_slice(&[e.u16(0x8769), e.u16(LONG)].concat());
|
||||
v.extend_from_slice(&[e.u32(1), e.u32(sub as u32)].concat());
|
||||
v.extend_from_slice(&e.u32(ifd1 as u32));
|
||||
// The Exif IFD: one Interoperability pointer.
|
||||
v.extend_from_slice(&e.u16(1));
|
||||
v.extend_from_slice(&[e.u16(0xA005), e.u16(LONG)].concat());
|
||||
v.extend_from_slice(&[e.u32(1), e.u32(interop as u32)].concat());
|
||||
v.extend_from_slice(&e.u32(0));
|
||||
// The Interoperability IFD: one inline ASCII entry (InteroperabilityIndex).
|
||||
v.extend_from_slice(&e.u16(1));
|
||||
v.extend_from_slice(&[e.u16(1), e.u16(ASCII)].concat());
|
||||
v.extend_from_slice(&[e.u32(4), b"R98\0".to_vec().try_into().unwrap_or([0; 4])].concat());
|
||||
v.extend_from_slice(&e.u32(0));
|
||||
assert_eq!(v.len(), ifd1);
|
||||
// IFD1: a thumbnail whose range is the Interoperability IFD.
|
||||
v.extend_from_slice(&e.u16(2));
|
||||
for (tag, value) in [(0x0201u16, interop as u32), (0x0202, 18)] {
|
||||
v.extend_from_slice(&[e.u16(tag), e.u16(LONG)].concat());
|
||||
v.extend_from_slice(&[e.u32(1), e.u32(value)].concat());
|
||||
}
|
||||
v.extend_from_slice(&e.u32(0));
|
||||
let out = export_exif(&v, None);
|
||||
assert_eq!(out[interop..interop + 18], v[interop..interop + 18], "the Interoperability IFD is untouched");
|
||||
}
|
||||
}
|
||||
@@ -158,7 +158,9 @@ impl Dt1Scratch {
|
||||
pub(super) fn edt_nearest(inside: &[bool], w: usize, h: usize) -> (Vec<f32>, Vec<u32>) {
|
||||
const INF: f32 = 1e20;
|
||||
let total = w.saturating_mul(h);
|
||||
if total != inside.len() || total > u32::MAX as usize {
|
||||
// No pixels: nothing to transform, and the scratch below is sized from the larger
|
||||
// dimension, which a zero-by-huge plane would still allocate.
|
||||
if total != inside.len() || total > u32::MAX as usize || total == 0 {
|
||||
return (vec![INF; inside.len()], vec![0; inside.len()]);
|
||||
}
|
||||
let n = w.max(h);
|
||||
|
||||
@@ -180,7 +180,11 @@ struct PreparedGradient {
|
||||
|
||||
impl PreparedGradient {
|
||||
fn new(g: &Gradient) -> Self {
|
||||
Self { color: g.stops.iter().map(|(p, c)| (*p, rgb(c))).collect(), opacity: g.opacity_stops.iter().map(|(p, a)| (*p, [*a; 3])).collect() }
|
||||
let mut color: Vec<_> = g.stops.iter().map(|(p, c)| (*p, rgb(c))).collect();
|
||||
color.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let mut opacity: Vec<_> = g.opacity_stops.iter().map(|(p, a)| (*p, [*a; 3])).collect();
|
||||
opacity.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
Self { color, opacity }
|
||||
}
|
||||
|
||||
fn sample(&self, t: f32) -> [f32; 4] {
|
||||
@@ -198,13 +202,15 @@ fn sample_stops(stops: &[(f32, [f32; 3])], t: f32) -> [f32; 3] {
|
||||
if t <= stops[0].0 {
|
||||
return stops[0].1;
|
||||
}
|
||||
for w in stops.windows(2) {
|
||||
if t <= w[1].0 {
|
||||
let k = if w[1].0 > w[0].0 { (t - w[0].0) / (w[1].0 - w[0].0) } else { 0.0 };
|
||||
return std::array::from_fn(|i| w[0].1[i] + (w[1].1[i] - w[0].1[i]) * k);
|
||||
}
|
||||
// Sorted in `new`: bisect rather than scan the stops for every covered pixel.
|
||||
let j = stops.partition_point(|s| s.0 < t);
|
||||
// j == 0 for a NaN position: the last stop, as a scan gave.
|
||||
if j >= stops.len() || j == 0 {
|
||||
return stops[stops.len() - 1].1;
|
||||
}
|
||||
stops[stops.len() - 1].1
|
||||
let (a, b) = (&stops[j - 1], &stops[j]);
|
||||
let k = if b.0 > a.0 { (t - a.0) / (b.0 - a.0) } else { 0.0 };
|
||||
std::array::from_fn(|i| a.1[i] + (b.1[i] - a.1[i]) * k)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1048,6 +1048,14 @@ fn shifting_by_hostile_distances_does_not_overflow() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A plane with no pixels but a huge other dimension must not size scratch from it.
|
||||
#[test]
|
||||
fn an_empty_distance_transform_allocates_nothing() {
|
||||
let (d, n) = edt_nearest(&[], 0, 1 << 30);
|
||||
assert!(d.is_empty() && n.is_empty());
|
||||
assert!(edt(&[], 1 << 30, 0).is_empty());
|
||||
}
|
||||
|
||||
/// #8639 review: a Stroke Emboss whose stroke lies wholly inside shades with the layer, so its
|
||||
/// non-Normal highlight or shadow counts as an interior blend, as an Inner Bevel's does; with the
|
||||
/// stroke reaching outside, or no stroke, it doesn't.
|
||||
|
||||
@@ -275,6 +275,13 @@ fn evict_fx_cache_over_budget(key: u64) {
|
||||
c.bytes = c.bytes.saturating_sub(s.get().map_or(0, |e| e.bytes));
|
||||
}
|
||||
}
|
||||
// The current entry alone over the budget: its callers hold the maps, the cache must not.
|
||||
if c.bytes > budget
|
||||
&& let Some(s) = c.map.remove(&key)
|
||||
{
|
||||
c.order.retain(|k| *k != key);
|
||||
c.bytes = c.bytes.saturating_sub(s.get().map_or(0, |e| e.bytes));
|
||||
}
|
||||
}
|
||||
|
||||
/// The layer's effect maps from the global cache, built on a miss.
|
||||
|
||||
@@ -72,15 +72,17 @@ fn sample_color<const N: usize>(stops: &[(f32, [f32; N])], mids: &[f32], t: f32)
|
||||
if t <= first.0 {
|
||||
return first.1;
|
||||
}
|
||||
for (i, w) in stops.windows(2).enumerate() {
|
||||
let (a, b) = (&w[0], &w[1]);
|
||||
if t <= b.0 {
|
||||
let u = if b.0 > a.0 { (t - a.0) / (b.0 - a.0) } else { 0.0 };
|
||||
let k = midpoint_remap(u, mids.get(i).copied().unwrap_or(0.5));
|
||||
return std::array::from_fn(|c| a.1[c] + (b.1[c] - a.1[c]) * k);
|
||||
}
|
||||
// The stops are sorted: the segment is found by bisection, not a scan per pixel (a
|
||||
// document can carry thousands of stops).
|
||||
let j = stops.partition_point(|s| s.0 < t);
|
||||
// A NaN position leaves `j` at 0 (no stop compares below it): the last stop, as a scan gave.
|
||||
if j >= stops.len() || j == 0 {
|
||||
return last.1;
|
||||
}
|
||||
last.1
|
||||
let (a, b) = (&stops[j - 1], &stops[j]);
|
||||
let u = if b.0 > a.0 { (t - a.0) / (b.0 - a.0) } else { 0.0 };
|
||||
let k = midpoint_remap(u, mids.get(j - 1).copied().unwrap_or(0.5));
|
||||
std::array::from_fn(|c| a.1[c] + (b.1[c] - a.1[c]) * k)
|
||||
}
|
||||
|
||||
fn sample_opacity(stops: &[(f32, f32)], t: f32) -> f32 {
|
||||
@@ -88,13 +90,13 @@ fn sample_opacity(stops: &[(f32, f32)], t: f32) -> f32 {
|
||||
if t <= first.0 {
|
||||
return first.1;
|
||||
}
|
||||
for w in stops.windows(2) {
|
||||
if t <= w[1].0 {
|
||||
let u = if w[1].0 > w[0].0 { (t - w[0].0) / (w[1].0 - w[0].0) } else { 0.0 };
|
||||
return w[0].1 + (w[1].1 - w[0].1) * u;
|
||||
}
|
||||
let j = stops.partition_point(|s| s.0 < t);
|
||||
if j >= stops.len() || j == 0 {
|
||||
return last.1;
|
||||
}
|
||||
last.1
|
||||
let (a, b) = (&stops[j - 1], &stops[j]);
|
||||
let u = if b.0 > a.0 { (t - a.0) / (b.0 - a.0) } else { 0.0 };
|
||||
a.1 + (b.1 - a.1) * u
|
||||
}
|
||||
|
||||
/// Adds one level of the shared dither noise to a colour (as the Gradient tool does).
|
||||
@@ -248,6 +250,38 @@ pub fn from_handles(style: GradientStyle, from: [f32; 2], to: [f32; 2], frame: R
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A NaN position (from a non-finite angle in a file) returns the last stop and does not panic.
|
||||
#[test]
|
||||
fn nan_position_gives_the_last_stop() {
|
||||
let stops = [(0.0f32, [1.0f32]), (1.0, [2.0])];
|
||||
assert_eq!(sample_color(&stops, &[], f32::NAN), [2.0]);
|
||||
assert_eq!(sample_opacity(&[(0.0, 0.25), (1.0, 0.75)], f32::NAN), 0.75);
|
||||
}
|
||||
|
||||
/// Bisection over many stops picks the same segment as a scan, including repeated positions.
|
||||
#[test]
|
||||
fn bisected_stop_lookup_matches_a_scan() {
|
||||
let stops: Vec<(f32, [f32; 1])> = (0..1000).map(|i| ((i / 2) as f32 / 500.0, [i as f32])).collect();
|
||||
let scan = |t: f32| {
|
||||
if t <= stops[0].0 {
|
||||
return stops[0].1;
|
||||
}
|
||||
for w in stops.windows(2) {
|
||||
if t <= w[1].0 {
|
||||
let u = if w[1].0 > w[0].0 { (t - w[0].0) / (w[1].0 - w[0].0) } else { 0.0 };
|
||||
return [w[0].1[0] + (w[1].1[0] - w[0].1[0]) * u];
|
||||
}
|
||||
}
|
||||
stops[stops.len() - 1].1
|
||||
};
|
||||
for k in 0..=2000 {
|
||||
let t = k as f32 / 2000.0 * 1.1 - 0.05;
|
||||
assert_eq!(sample_color(&stops, &[], t), scan(t), "t = {t}");
|
||||
}
|
||||
let opacity: Vec<(f32, f32)> = stops.iter().map(|(p, c)| (*p, c[0])).collect();
|
||||
assert_eq!(sample_opacity(&opacity, 0.5), sample_color(&stops, &[], 0.5)[0]);
|
||||
}
|
||||
use photocraft_doc::Color;
|
||||
|
||||
const STYLES: [GradientStyle; 5] = [GradientStyle::Linear, GradientStyle::Radial, GradientStyle::Angle, GradientStyle::Reflected, GradientStyle::Diamond];
|
||||
|
||||
@@ -15,6 +15,23 @@ pub(crate) fn filled<T: Clone>(len: usize, value: T, purpose: &str) -> Result<Ve
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Reads a regular file of at most `max` bytes. The opened handle must be a regular file (a
|
||||
/// device such as `/dev/zero` never ends) and reading stops one byte past `max`, so neither a
|
||||
/// special file nor one that grows after a size check can fill memory.
|
||||
pub(crate) fn read_file_within(path: impl AsRef<std::path::Path>, max: u64) -> std::io::Result<Vec<u8>> {
|
||||
use std::io::{Error, ErrorKind, Read};
|
||||
let file = std::fs::File::open(path)?;
|
||||
if !file.metadata()?.is_file() {
|
||||
return Err(Error::new(ErrorKind::InvalidInput, "not a regular file"));
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
file.take(max.saturating_add(1)).read_to_end(&mut out)?;
|
||||
if out.len() as u64 > max {
|
||||
return Err(Error::new(ErrorKind::InvalidData, format!("file is larger than {max} bytes")));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Reserve a vector for a known number of operation results.
|
||||
pub(crate) fn capacity<T>(len: usize, purpose: &str) -> Result<Vec<T>> {
|
||||
let bytes = len.checked_mul(std::mem::size_of::<T>()).ok_or_else(|| error(purpose, "requested size overflowed"))?;
|
||||
@@ -61,6 +78,29 @@ pub(crate) fn read_region(surface: &photocraft_raster::Surface, area: photocraft
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Most bytes of dense working buffers one command may hold while it expands sparse content (or
|
||||
/// the canvas) into flat arrays: the allowance Image Size resamples within. A document stores
|
||||
/// only the tiles it holds, so two distant tiles, or a huge empty canvas, make a small file whose
|
||||
/// content bounds would need far more than any machine has.
|
||||
pub(crate) const MAX_DENSE_BYTES: u64 = crate::image_cmds::MAX_RESAMPLE_BYTES;
|
||||
|
||||
/// Refuses, before anything is allocated, an operation that would hold `bytes_per_px` bytes of
|
||||
/// dense buffers for every pixel of `area` at once.
|
||||
pub(crate) fn check_dense(area: photocraft_geom::Rect, bytes_per_px: u64, purpose: &str) -> Result<()> {
|
||||
let px = u64::from(area.width()).saturating_mul(u64::from(area.height()));
|
||||
let bytes = px.saturating_mul(bytes_per_px);
|
||||
if bytes <= MAX_DENSE_BYTES {
|
||||
return Ok(());
|
||||
}
|
||||
Err(EngineError::Other(format!(
|
||||
"{purpose} would need {} MB of working memory for a {} x {} px area (limit {} MB); the document was not changed",
|
||||
bytes >> 20,
|
||||
area.width(),
|
||||
area.height(),
|
||||
MAX_DENSE_BYTES >> 20
|
||||
)))
|
||||
}
|
||||
|
||||
pub(crate) fn error(purpose: &str, detail: &str) -> EngineError {
|
||||
EngineError::Other(format!("not enough memory for {purpose} ({detail}); the document was not changed"))
|
||||
}
|
||||
@@ -102,6 +142,17 @@ fn failpoint_hits() -> bool {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn dense_area_past_the_budget_is_refused() {
|
||||
use photocraft_geom::Rect;
|
||||
assert!(check_dense(Rect::from_xywh(0, 0, 4096, 4096), 16, "test").is_ok());
|
||||
// Two tiles a million pixels apart: content bounds of a trillion pixels.
|
||||
let far = Rect::new(0, 0, 1 << 20, 1 << 20);
|
||||
assert!(check_dense(far, 16, "test").is_err_and(|e| e.to_string().contains("working memory")));
|
||||
// Overflowing sizes saturate instead of wrapping into a small number.
|
||||
assert!(check_dense(Rect::new(i32::MIN, i32::MIN, i32::MAX, i32::MAX), u64::MAX, "test").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allocation_failure_is_reported_without_panicking() {
|
||||
fail_next_for_test();
|
||||
@@ -131,4 +182,30 @@ mod tests {
|
||||
assert!(filled::<u8>(4, 0, "counted").is_err_and(|e| e.to_string().contains("not enough memory for counted")));
|
||||
assert!(filled::<u8>(4, 0, "done").is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_file_within_bounds_the_bytes_and_refuses_special_files() {
|
||||
let path = std::env::temp_dir().join(format!("pc-read-within-{}", std::process::id()));
|
||||
std::fs::write(&path, [7u8; 10]).unwrap();
|
||||
let p = path.to_str().unwrap();
|
||||
assert_eq!(read_file_within(p, 10).unwrap(), vec![7u8; 10]);
|
||||
assert!(read_file_within(p, 9).is_err_and(|e| e.kind() == std::io::ErrorKind::InvalidData));
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
// A directory (and on unix a device that never ends) is not a regular file.
|
||||
assert!(read_file_within(std::env::temp_dir().to_str().unwrap(), 10).is_err());
|
||||
#[cfg(unix)]
|
||||
assert!(read_file_within("/dev/zero", 1 << 30).is_err_and(|e| e.kind() == std::io::ErrorKind::InvalidInput));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn read_file_within_reads_a_path_that_is_not_utf8() {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
let dir = std::env::temp_dir().join(format!("pc-read-within-nonutf8-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join(std::ffi::OsStr::from_bytes(b"frame-\xff.png"));
|
||||
std::fs::write(&path, [3u8; 4]).unwrap();
|
||||
assert_eq!(read_file_within(&path, 10).unwrap(), vec![3u8; 4]);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -136,6 +136,9 @@ pub struct ActionsFile {
|
||||
|
||||
pub const MAX_PLAYBACK_STEPS: u64 = 100_000;
|
||||
|
||||
/// How deep batches and droplets may run inside one another (a droplet whose steps run a droplet).
|
||||
pub const MAX_BATCH_DEPTH: u8 = 4;
|
||||
|
||||
/// Actions list and the recording / playback flags. Only `list` is persisted.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
@@ -156,6 +159,14 @@ pub struct ActionState {
|
||||
/// Number of steps executed by the current top-level playback tree.
|
||||
#[serde(skip)]
|
||||
pub playback_steps: u64,
|
||||
/// Set for a batch nested in a played action or another batch: the playback counter it carries
|
||||
/// is shared by every input, so a played action inside it does not restart the count.
|
||||
#[serde(skip)]
|
||||
pub budget_shared: bool,
|
||||
/// How many batches (`file.automate.batch`, and droplets through it) are running inside one
|
||||
/// another: each runs its steps in a scratch session that carries this on, plus one.
|
||||
#[serde(skip)]
|
||||
pub batch_depth: u8,
|
||||
/// How many scripts (`file.scripts.browse`) are running inside one another.
|
||||
#[serde(skip)]
|
||||
pub script_depth: u8,
|
||||
@@ -303,6 +314,22 @@ pub fn consume_playback_step(s: &mut Session) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Steps of the playback tree the next `actions.play` starts in has charged so far: a top-level
|
||||
/// call starts a new tree ([`begin_playback`] resets the counter).
|
||||
fn playback_steps_used(s: &Session) -> u64 {
|
||||
if s.actions.playing > 0 || s.actions.budget_shared { s.actions.playback_steps } else { 0 }
|
||||
}
|
||||
|
||||
/// Steps of `action` playback walks past without running them: the ones before `from` and the
|
||||
/// disabled ones after it. [`begin_playback`] charges them, so every stored step costs one unit
|
||||
/// of the playback budget once per call, run or not.
|
||||
fn skipped_steps(action: &Action, from: usize) -> u64 {
|
||||
let len = action.steps.len();
|
||||
let from = from.min(len);
|
||||
let disabled = action.disabled.range(from..len).count();
|
||||
u64::try_from(from.saturating_add(disabled)).unwrap_or(u64::MAX)
|
||||
}
|
||||
/// View-only menu commands recorded by the desktop shell. Headless playback reports
|
||||
/// them as unsupported instead of silently dropping them; Batch and droplets skip them.
|
||||
pub fn shell_view_command(id: &str) -> bool {
|
||||
@@ -315,6 +342,14 @@ pub fn playback_plan(s: &Session, p: &Value) -> Result<(Action, usize)> {
|
||||
return Err(bad("actions.play", "an action is already playing"));
|
||||
}
|
||||
let idx = resolve(&s.actions.list, p, "actions.play")?;
|
||||
// Every stored step of the call is charged to the playback tree (run, disabled or skipped),
|
||||
// so refuse a call whose steps no longer fit before copying it: repeated calls to a large
|
||||
// action would otherwise copy and walk it each time for free.
|
||||
let len = s.actions.list.get(idx).map_or(0, |a| a.steps.len());
|
||||
if playback_steps_used(s).saturating_add(u64::try_from(len).unwrap_or(u64::MAX)) > MAX_PLAYBACK_STEPS {
|
||||
// A limit, not a bad parameter: an enclosing batch must fail the input instead of saving it.
|
||||
return Err(EngineError::BatchLimit(format!("invalid parameters for `actions.play`: action playback exceeded the {MAX_PLAYBACK_STEPS}-step limit")));
|
||||
}
|
||||
let action = s.actions.list.get(idx).cloned().ok_or_else(|| bad("actions.play", "no such action"))?;
|
||||
if s.actions.playback_stack.iter().any(|name| name == &action.name) || s.actions.recording.is_some_and(|(_, i)| i == idx) {
|
||||
return Err(bad("actions.play", format!("recursive action call to `{}`", action.name)));
|
||||
@@ -751,7 +786,7 @@ fn run_recorded(s: &mut Session, action: &Action, from: usize) -> (u64, Option<V
|
||||
let mut failed = None;
|
||||
for (i, (id, params)) in action.enabled_steps().skip_while(|(i, _)| *i < from) {
|
||||
if !consume_playback_step(s) {
|
||||
failed = Some(json!({"step": i, "id": id, "error": format!("action playback exceeded the {}-step limit", MAX_PLAYBACK_STEPS)}));
|
||||
failed = Some(json!({"step": i, "id": id, "error": format!("action playback exceeded the {}-step limit", MAX_PLAYBACK_STEPS), "limit": true}));
|
||||
break;
|
||||
}
|
||||
let effective = crate::file_cmds::batch_open_params(s, id, params);
|
||||
@@ -768,6 +803,14 @@ fn run_recorded(s: &mut Session, action: &Action, from: usize) -> (u64, Option<V
|
||||
}
|
||||
match playback_params(s, id, params).and_then(|p| if saves_smart_contents(s, id) { s.execute(SAVE_CONTENTS, json!({})) } else { s.execute(id, p) }) {
|
||||
Ok(value) => {
|
||||
// A nested batch or action that stopped at a limit stops this action too.
|
||||
if let Some(error) = limit_stop(&value) {
|
||||
// The child result stays, so the files a nested batch wrote before the stop are visible.
|
||||
let mut failure = json!({"step": i, "id": id, "error": error, "limit": true});
|
||||
failure["result"] = value;
|
||||
failed = Some(failure);
|
||||
break;
|
||||
}
|
||||
if let Some(error) = nested_failure(id, &value) {
|
||||
// Like Scripts, retain the child result so partial Batch outputs remain visible.
|
||||
let mut failure = json!({"step": i, "id": id, "error": error});
|
||||
@@ -779,6 +822,11 @@ fn run_recorded(s: &mut Session, action: &Action, from: usize) -> (u64, Option<V
|
||||
}
|
||||
Err(e) => {
|
||||
failed = Some(json!({"step": i, "id": id, "error": e.to_string()}));
|
||||
if matches!(e, EngineError::BatchLimit(_))
|
||||
&& let Some(f) = failed.as_mut()
|
||||
{
|
||||
f["limit"] = json!(true);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -789,10 +837,31 @@ fn run_recorded(s: &mut Session, action: &Action, from: usize) -> (u64, Option<V
|
||||
/// Suspend recording while a called action executes. Keep its commands in the journal
|
||||
/// for diagnostics, but record just the named call in the parent action.
|
||||
pub fn begin_playback(s: &mut Session, action: &Action) -> Result<Option<(usize, usize)>> {
|
||||
begin_playback_from(s, action, 0)
|
||||
}
|
||||
|
||||
/// [`begin_playback`] for a call that starts at step `from`: the steps before it are charged to the
|
||||
/// playback budget too.
|
||||
pub fn begin_playback_from(s: &mut Session, action: &Action, from: usize) -> Result<Option<(usize, usize)>> {
|
||||
flush_recording(s)?;
|
||||
// The steps that run are charged one by one as they run; the ones walked past are charged
|
||||
// here ([`playback_plan`] checked that the whole action fits). Refused before the history
|
||||
// scope opens, so a rejected call leaves none behind.
|
||||
let skipped = skipped_steps(action, from);
|
||||
let max = crate::automate_cmds::MAX_SCRIPT_STEPS;
|
||||
if s.actions.script_depth > 0 && s.actions.script_steps.saturating_add(skipped) > max {
|
||||
return Err(bad("actions.play", format!("the script ran more than {max} steps in all")));
|
||||
}
|
||||
if s.actions.playing == 0 {
|
||||
history::begin(s, &action.name);
|
||||
s.actions.playback_steps = 0;
|
||||
// A batch nested in a played action or another batch carries the shared count on.
|
||||
if !s.actions.budget_shared {
|
||||
s.actions.playback_steps = 0;
|
||||
}
|
||||
}
|
||||
s.actions.playback_steps = s.actions.playback_steps.saturating_add(skipped);
|
||||
if s.actions.script_depth > 0 {
|
||||
s.actions.script_steps = s.actions.script_steps.saturating_add(skipped);
|
||||
}
|
||||
let recording = s.actions.recording.take();
|
||||
s.actions.playing = s.actions.playing.saturating_add(1);
|
||||
@@ -822,6 +891,16 @@ pub fn restore_recording(s: &mut Session, idx: usize, action: &str, from: usize)
|
||||
s.journal.push(("actions.play".into(), params));
|
||||
}
|
||||
|
||||
/// The message of a nesting or playback-limit stop reported by `value`, the result of a step: an
|
||||
/// input of a nested batch or droplet marked `"limit": true` in `errors`, or a played action whose
|
||||
/// failed step carries it. Such a stop fails the enclosing input rather than being swallowed.
|
||||
pub fn limit_stop(value: &Value) -> Option<String> {
|
||||
let flagged = |v: &Value| v.get("limit") == Some(&json!(true));
|
||||
let found =
|
||||
value.get("errors").and_then(Value::as_array).and_then(|a| a.iter().find(|e| flagged(e))).or_else(|| value.get("failed").filter(|f| flagged(f)))?;
|
||||
Some(found.get("error").and_then(Value::as_str).unwrap_or("batch limit reached").to_string())
|
||||
}
|
||||
|
||||
/// What stops the caller of a Batch even where per-file errors don't (a direct Batch in a script
|
||||
/// or a CLI command list): the script ran out of steps inside it, it was cancelled, or its
|
||||
/// requested error log could not be written.
|
||||
@@ -874,7 +953,7 @@ pub fn nested_failure(id: &str, value: &Value) -> Option<String> {
|
||||
/// recording while a gate is installed marks the recorded action ([`note_automation_step`]).
|
||||
fn play(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (action, from) = playback_plan(s, p)?;
|
||||
let recording = begin_playback(s, &action)?;
|
||||
let recording = begin_playback_from(s, &action, from)?;
|
||||
// Nested calls and commands the steps run on their own behalf see the kept gate too.
|
||||
let kept = kept_gate(s, &action);
|
||||
if kept.is_some() {
|
||||
@@ -1319,4 +1398,62 @@ mod security_tests {
|
||||
assert!(consume_playback_step(&mut session));
|
||||
assert!(!consume_playback_step(&mut session));
|
||||
}
|
||||
|
||||
/// A played action inside a nested batch (no enclosing playback) continues the shared count the
|
||||
/// batch carries instead of restarting it for each input.
|
||||
#[test]
|
||||
fn a_nested_batch_input_does_not_reset_the_shared_playback_count() {
|
||||
let mut session = Session::new();
|
||||
session.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
|
||||
session.actions.list.push(Action::new("A", vec![("select.all".to_string(), json!({}))]));
|
||||
session.actions.budget_shared = true;
|
||||
session.actions.playback_steps = MAX_PLAYBACK_STEPS;
|
||||
let r = session.execute("actions.play", json!({"action": "A"}));
|
||||
assert!(matches!(r, Err(EngineError::BatchLimit(_))), "the carried count leaves no room for the action: {r:?}");
|
||||
session.actions.budget_shared = false;
|
||||
let r = session.execute("actions.play", json!({"action": "A"})).unwrap();
|
||||
assert_eq!(r["ran"], 1, "a top-level call starts its own count");
|
||||
}
|
||||
|
||||
/// An action of mostly disabled steps, called over and over from a parent, is charged for
|
||||
/// every step it stores, so the calls stop at the shared limit instead of each copying and
|
||||
/// walking the whole action for free.
|
||||
#[test]
|
||||
fn disabled_steps_are_charged_to_the_playback_budget() {
|
||||
let mut session = Session::new();
|
||||
let mut child = Action::new("Child", (0..1000).map(|_| ("select.all".to_string(), json!({}))).collect());
|
||||
child.disabled = (0..1000).collect();
|
||||
let calls = MAX_PLAYBACK_STEPS as usize / 1000 * 2;
|
||||
let parent = Action::new("Parent", (0..calls).map(|_| ("actions.play".to_string(), json!({"action": "Child"}))).collect());
|
||||
session.actions.list.push(child);
|
||||
session.actions.list.push(parent);
|
||||
let r = session.execute("actions.play", json!({"action": "Parent"})).unwrap();
|
||||
let failed = r["failed"]["error"].as_str().unwrap();
|
||||
assert!(failed.contains("step limit"), "{failed}");
|
||||
// Each call charges its 1000 stored steps plus the Play step itself.
|
||||
let ran = r["ran"].as_u64().unwrap();
|
||||
assert!(ran < MAX_PLAYBACK_STEPS / 1000, "{ran}");
|
||||
}
|
||||
|
||||
/// Limit stops are recognised from a nested batch's `errors` and from a played action's `failed`;
|
||||
/// an ordinary failure is not one.
|
||||
#[test]
|
||||
fn limit_stops_are_found_in_nested_results() {
|
||||
let batch = json!({"files": [], "errors": [{"file": "a", "error": "x"}, {"file": "b", "error": "too deep", "limit": true}]});
|
||||
assert_eq!(limit_stop(&batch).as_deref(), Some("too deep"));
|
||||
let played = json!({"action": "A", "failed": {"step": 2, "id": "x", "error": "over", "limit": true}});
|
||||
assert_eq!(limit_stop(&played).as_deref(), Some("over"));
|
||||
assert_eq!(limit_stop(&json!({"errors": [{"file": "a", "error": "x"}], "failed": {"step": 0, "error": "y"}})), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steps_before_from_are_charged() {
|
||||
let action = Action::new("A", (0..10).map(|_| ("select.all".to_string(), json!({}))).collect());
|
||||
assert_eq!(skipped_steps(&action, 7), 7);
|
||||
assert_eq!(skipped_steps(&action, 50), 10);
|
||||
let mut disabled = action.clone();
|
||||
disabled.disabled = [1, 8, 9, 40].into_iter().collect();
|
||||
assert_eq!(skipped_steps(&disabled, 7), 9);
|
||||
assert_eq!(skipped_steps(&disabled, 0), 3);
|
||||
}
|
||||
}
|
||||
@@ -1601,6 +1601,18 @@ fn record_keeps_an_empty_loaded_sets_exact_name() {
|
||||
assert_eq!(s.execute("actions.save", json!({"set": " Web "})).unwrap()["actions"], json!(["First"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skipped_steps_count_against_the_script_limit() {
|
||||
let mut s = Session::new();
|
||||
s.actions.list.push(Action::new("A", (0..3).map(|_| ("select.all".to_string(), json!({}))).collect()));
|
||||
s.actions.script_depth = 1;
|
||||
s.actions.script_steps = crate::automate_cmds::MAX_SCRIPT_STEPS - 1;
|
||||
let e = s.execute("actions.play", json!({"action": "A", "from": 3})).err().map(|e| e.to_string());
|
||||
assert!(e.is_some_and(|e| e.contains("the script ran more than")));
|
||||
assert_eq!(s.actions.playing, 0);
|
||||
assert!(s.action_history.is_none(), "a rejected call leaves no history scope open");
|
||||
}
|
||||
|
||||
/// A droplet capturing two actions of one name (sets A and B) keeps each call on the action it
|
||||
/// reached: an index or set-qualified call to B's action still reaches B's copy, a name-only call
|
||||
/// still reaches A's, and a call to a uniquely named action stays a name.
|
||||
|
||||
@@ -245,7 +245,7 @@ pub fn folder_luts(_: &str) -> Vec<(String, String)> {
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn read_file(path: &str) -> Option<Vec<u8>> {
|
||||
std::fs::read(path).ok()
|
||||
crate::allocation::read_file_within(path, MAX_FOLDER_LUT_BYTES).ok()
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn read_file(_: &str) -> Option<Vec<u8>> {
|
||||
@@ -266,19 +266,23 @@ pub fn update_adjustment(existing: &Adjustment, p: &Value) -> Option<Result<Adju
|
||||
// ---------- destructive helpers ----------
|
||||
|
||||
/// Runs `f` on the target surface's content as straight RGBA (`w × h` = content bounds), blending
|
||||
/// the result through the selection.
|
||||
fn process_surface(surf: &mut Surface, selection: Option<&Surface>, f: &mut dyn FnMut(&mut Vec<[f32; 4]>, Rect)) {
|
||||
/// the result through the selection. Refused before reading when the dense buffers over the
|
||||
/// content bounds (which span the gaps between distant tiles) would pass the working budget.
|
||||
fn process_surface(surf: &mut Surface, selection: Option<&Surface>, f: &mut dyn FnMut(&mut Vec<[f32; 4]>, Rect)) -> Result<()> {
|
||||
let r = surf.content_bounds();
|
||||
if r.is_empty() {
|
||||
return;
|
||||
return Ok(());
|
||||
}
|
||||
let fmt = surf.format();
|
||||
let n = fmt.channels();
|
||||
// The native read and the blended output (`n` f32 each), and the edited and original RGBA.
|
||||
crate::allocation::check_dense(r, (n as u64).saturating_mul(8).saturating_add(32), "this adjustment")?;
|
||||
let raw = surf.read_region(r);
|
||||
let mut px: Vec<[f32; 4]> = raw.chunks_exact(n).map(|q| to_rgba(&fmt, q)).collect();
|
||||
let orig = px.clone();
|
||||
f(&mut px, r);
|
||||
surf.write_region(r, &crate::pixels::mix_through_selection(&fmt, r, &orig, &px, selection));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One history step running `f` on the active pixel layer (or targeted channel or layer mask).
|
||||
@@ -288,7 +292,7 @@ fn rgba_edit(s: &mut Session, label: &str, p: &Value, mut f: impl FnMut(&mut Vec
|
||||
return s.edit(label, |doc, _| {
|
||||
let sel = doc.selection.clone();
|
||||
if let Some(surf) = crate::channel_cmds::channel_surface_for_filter(doc, id, p)? {
|
||||
process_surface(surf, sel.as_ref(), &mut f);
|
||||
process_surface(surf, sel.as_ref(), &mut f)?;
|
||||
surf.prune();
|
||||
}
|
||||
Ok(Value::Null)
|
||||
@@ -298,7 +302,7 @@ fn rgba_edit(s: &mut Session, label: &str, p: &Value, mut f: impl FnMut(&mut Vec
|
||||
s.edit(label, |doc, _| {
|
||||
let sel = doc.selection.clone();
|
||||
let surf = crate::commands::paint_surface(doc, id, &Value::Null)?;
|
||||
process_surface(surf, sel.as_ref(), &mut f);
|
||||
process_surface(surf, sel.as_ref(), &mut f)?;
|
||||
Ok(Value::Null)
|
||||
})
|
||||
}
|
||||
@@ -372,14 +376,15 @@ fn has_doc(s: &Session) -> std::result::Result<(), String> {
|
||||
|
||||
/// Image › Adjustments run as a smart filter (`image.adjustments.<kind>` recorded on a smart
|
||||
/// object): the adjustment applied to a copy of `surf`. `None` for kinds or params it can't run.
|
||||
pub(crate) fn adjust_as_filter(kind: &str, p: &Value, surf: &Surface) -> Option<Surface> {
|
||||
pub(crate) fn adjust_as_filter(kind: &str, p: &Value, surf: &Surface) -> Result<Option<Surface>> {
|
||||
// A Color Lookup filter re-reads its LUT `file`, a path stored in the document: followed only
|
||||
// as `doc_path` allows, else the filter can't run (like a missing file).
|
||||
let resolved;
|
||||
let p = match p.get("file").and_then(Value::as_str).filter(|f| kind == "colorLookup" && !f.is_empty()) {
|
||||
Some(file) => {
|
||||
let mut q = p.clone();
|
||||
q["file"] = json!(crate::doc_path::resolve(file).ok()?.to_str()?);
|
||||
let Some(path) = crate::doc_path::resolve(file).ok().and_then(|p| p.to_str().map(str::to_owned)) else { return Ok(None) };
|
||||
q["file"] = json!(path);
|
||||
resolved = q;
|
||||
&resolved
|
||||
}
|
||||
@@ -388,14 +393,16 @@ pub(crate) fn adjust_as_filter(kind: &str, p: &Value, surf: &Surface) -> Option<
|
||||
let mut out = surf.clone();
|
||||
if kind == "shadowsHighlights" {
|
||||
let sh = shadows_highlights_params(p);
|
||||
process_surface(&mut out, None, &mut |px, r| tone::shadows_highlights(px, r.width() as usize, r.height() as usize, &sh));
|
||||
process_surface(&mut out, None, &mut |px, r| tone::shadows_highlights(px, r.width() as usize, r.height() as usize, &sh))?;
|
||||
} else {
|
||||
let mode = surf.format().mode;
|
||||
let adj = crate::adjust_params::from_params(kind, p, None, mode).ok()?;
|
||||
crate::pixels::adjust_surface(&mut out, &adj, None, mode).ok()?;
|
||||
let Ok(adj) = crate::adjust_params::from_params(kind, p, None, mode) else { return Ok(None) };
|
||||
if crate::pixels::adjust_surface(&mut out, &adj, None, mode).is_err() {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
out.prune();
|
||||
Some(out)
|
||||
Ok(Some(out))
|
||||
}
|
||||
|
||||
fn shadows_highlights(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -171,9 +171,12 @@ fn auto_align(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const MAX_BLEND_BYTES: u64 = 4 << 30;
|
||||
|
||||
/// What Auto-Blend's buffers hold per work-area pixel, as f32: each layer's pixels, luminance,
|
||||
/// alpha and mask weight, plus the merged picture and the depth map.
|
||||
fn blend_bytes_per_pixel(layers: u64, channels: u64) -> u64 {
|
||||
layers.saturating_mul(channels.saturating_add(3)).saturating_add(channels.saturating_mul(2)).saturating_mul(4)
|
||||
/// alpha and mask weight, plus the merged picture and the depth map. A `stack` blend also holds
|
||||
/// `fuse_stack`'s pyramids when `fuse` (a `stack` blend with Seamless Tones; 4/3 of a level 0
|
||||
/// each): the accumulated and the current image's (`channels` each), and about seven single-channel ones (luma, alpha, energies, winners, halo).
|
||||
fn blend_bytes_per_pixel(layers: u64, channels: u64, fuse: bool) -> u64 {
|
||||
let pyramids = if fuse { channels.saturating_mul(2).saturating_add(7).saturating_mul(4).div_ceil(3) } else { 0 };
|
||||
layers.saturating_mul(channels.saturating_add(3)).saturating_add(channels.saturating_mul(2)).saturating_add(pyramids).saturating_mul(4)
|
||||
}
|
||||
|
||||
/// Auto-Blend's buffers, for allocation errors.
|
||||
@@ -218,12 +221,23 @@ fn auto_blend(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// whose buffers would exceed `MAX_BLEND_BYTES`, keep to the canvas.
|
||||
let canvas = doc.bounds();
|
||||
let channels = ids.iter().filter_map(|id| doc.layer(*id).and_then(|l| l.surface()).map(|s| s.channels() as u64)).max().unwrap_or(4);
|
||||
let per_px = blend_bytes_per_pixel(ids.len() as u64, channels);
|
||||
let per_px = blend_bytes_per_pixel(ids.len() as u64, channels, method == "stack" && seamless);
|
||||
let fits = px_of(&union).saturating_mul(per_px) <= MAX_BLEND_BYTES && px_of(&union) <= content_px.max(px_of(&canvas)).saturating_mul(2);
|
||||
let area = if fits { union } else { union.intersect(&canvas) };
|
||||
if area.is_empty() {
|
||||
return Err(EngineError::Other("the selected layers are empty".into()));
|
||||
}
|
||||
// The fallback (the canvas) can still be past the budget: a huge canvas, or sparse layers
|
||||
// whose content bounds fill it. Refuse before any layer is expanded into dense buffers.
|
||||
if px_of(&area).saturating_mul(per_px) > MAX_BLEND_BYTES {
|
||||
return Err(EngineError::Other(format!(
|
||||
"Auto-Blend would need more than {} MB for {} layers over {} x {} px; blend fewer or smaller layers",
|
||||
MAX_BLEND_BYTES >> 20,
|
||||
ids.len(),
|
||||
area.width(),
|
||||
area.height()
|
||||
)));
|
||||
}
|
||||
let (w, h) = (area.width() as usize, area.height() as usize);
|
||||
let mut imgs: Vec<Vec<f32>> = Vec::new();
|
||||
let mut luma: Vec<Vec<f32>> = Vec::new();
|
||||
|
||||
@@ -357,11 +357,17 @@ fn auto_blend_sparse_huge_bounds_keep_to_the_canvas() {
|
||||
#[test]
|
||||
fn auto_blend_budget_counts_layers_and_channels() {
|
||||
// Two RGBA layers: 4 bytes × (2 layers × (4 channels + luma, alpha, weight) + merged + depth).
|
||||
assert_eq!(blend_bytes_per_pixel(2, 4), 88);
|
||||
assert!(blend_bytes_per_pixel(5, 4) > blend_bytes_per_pixel(2, 4));
|
||||
assert_eq!(blend_bytes_per_pixel(2, 4, false), 88);
|
||||
assert!(blend_bytes_per_pixel(5, 4, false) > blend_bytes_per_pixel(2, 4, false));
|
||||
// A stack blend adds the fusion pyramids: (2 × 4 + 7) × 4/3 = 20 more f32 per pixel.
|
||||
assert_eq!(blend_bytes_per_pixel(2, 4, true), 88 + 80);
|
||||
// Without Seamless Tones `fuse_stack` never runs, so its pyramids are not budgeted: two RGBA
|
||||
// layers over 6000 x 6000 px fit the limit only then.
|
||||
assert!(36_000_000 * blend_bytes_per_pixel(2, 4, false) <= MAX_BLEND_BYTES);
|
||||
assert!(36_000_000 * blend_bytes_per_pixel(2, 4, true) > MAX_BLEND_BYTES);
|
||||
// A 2^27-pixel area would need about 11 GiB for just two RGBA layers: it keeps to the canvas.
|
||||
assert!((1u64 << 27).saturating_mul(blend_bytes_per_pixel(2, 4)) > MAX_BLEND_BYTES);
|
||||
assert_eq!(blend_bytes_per_pixel(u64::MAX, 4), u64::MAX, "saturates instead of overflowing");
|
||||
assert!((1u64 << 27).saturating_mul(blend_bytes_per_pixel(2, 4, false)) > MAX_BLEND_BYTES);
|
||||
assert_eq!(blend_bytes_per_pixel(u64::MAX, 4, true), u64::MAX, "saturates instead of overflowing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1179,6 +1179,18 @@ fn log_delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn csv_field(v: &Value) -> String {
|
||||
let s = match v {
|
||||
// A text cell a spreadsheet would read as a formula gets a leading apostrophe (OWASP CSV
|
||||
// injection); plain numbers in text keep their sign.
|
||||
// Leading spaces do not hide it: a spreadsheet that trims them still reads a formula.
|
||||
Value::String(s)
|
||||
if {
|
||||
let t = s.trim_start_matches(' ');
|
||||
t.starts_with(['=', '@', '\t', '\r', '\n', '\u{ff1d}', '\u{ff20}'])
|
||||
|| (t.starts_with(['+', '-', '\u{ff0b}', '\u{ff0d}']) && t.parse::<f64>().is_err())
|
||||
} =>
|
||||
{
|
||||
format!("'{s}")
|
||||
}
|
||||
Value::String(s) => s.clone(),
|
||||
Value::Array(a) => a.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(" "),
|
||||
Value::Null => String::new(),
|
||||
|
||||
@@ -556,6 +556,28 @@ fn iso_from_unix_matches_the_old_cycle_conversion_including_beyond_chrono() {
|
||||
assert_eq!(iso_from_unix(i64::MIN), "-292277022657-01-27T08:29:52Z");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_text_cells_that_read_as_formulas_are_neutralised() {
|
||||
for (cell, want) in [
|
||||
("=1+1", "'=1+1"),
|
||||
("@SUM(A1)", "'@SUM(A1)"),
|
||||
("-2+3", "'-2+3"),
|
||||
("+cmd|x", "'+cmd|x"),
|
||||
("-5.5", "-5.5"),
|
||||
("px", "px"),
|
||||
("\n=1+1", "\"'\n=1+1\""),
|
||||
("\u{ff1d}1+1", "'\u{ff1d}1+1"),
|
||||
("\u{ff0b}1", "'\u{ff0b}1"),
|
||||
("\u{ff20}SUM(A1)", "'\u{ff20}SUM(A1)"),
|
||||
(" =1+1", "' =1+1"),
|
||||
(" -2+3", "' -2+3"),
|
||||
(" -5.5", " -5.5"),
|
||||
] {
|
||||
assert_eq!(csv_field(&json!(cell)), want, "{cell}");
|
||||
}
|
||||
assert_eq!(csv_field(&json!(-5.5)), "-5.5", "numbers are not text cells");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn geometric_features_match_full_measurements_without_gray() {
|
||||
let mask = [true, true, false, false, false, false, false, true, true];
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::convert::{UniqueNames, export, import_with_encoding};
|
||||
use super::convert::{UniqueNames, clip_name, export, import_with_encoding};
|
||||
use super::{Action, DEFAULT_SET, EngineError, Result, Session, Value, bad, json};
|
||||
|
||||
/// `actions.load`: add the actions of an `.atn` file (`path` or `data`) to the list, retargeting
|
||||
@@ -22,7 +22,8 @@ pub(super) fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
match p.get("set") {
|
||||
None | Some(Value::Null) => {}
|
||||
Some(Value::String(n)) if !n.trim().is_empty() => {
|
||||
imp.set = n.trim().to_string();
|
||||
// Held to the importer's name limit: the set name is copied into every action.
|
||||
imp.set = clip_name(n.trim()).trim_end().to_string();
|
||||
for a in &mut imp.actions {
|
||||
a.set = Some(imp.set.clone());
|
||||
}
|
||||
|
||||
@@ -508,6 +508,21 @@ fn load_renames_play_targets_longer_than_the_name_limit() {
|
||||
assert_eq!(caller.steps[0].1["action"], renamed.as_str());
|
||||
}
|
||||
|
||||
/// The `set` override is copied into every loaded action, so it is held to the same limit as a
|
||||
/// set name read from the file.
|
||||
#[test]
|
||||
fn load_clips_an_overlong_set_override() {
|
||||
let mut s = Session::new();
|
||||
let actions: Vec<Action> = (0..3).map(|i| Action::new(format!("A{i}"), vec![])).collect();
|
||||
let refs: Vec<&Action> = actions.iter().collect();
|
||||
let (bytes, _) = export("File", &refs, &[], false).unwrap();
|
||||
let long = "s".repeat(super::convert::MAX_NAME_CHARS * 4);
|
||||
s.execute("actions.load", json!({"data": b64(&bytes), "set": long})).unwrap();
|
||||
let clipped = "s".repeat(super::convert::MAX_NAME_CHARS);
|
||||
assert_eq!(s.actions.list.len(), 3);
|
||||
assert!(s.actions.list.iter().all(|a| a.set.as_deref() == Some(clipped.as_str())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_many_duplicate_names_get_sequential_suffixes() {
|
||||
// Several actions share one base name. Deduplication must stay O(n) overall and produce
|
||||
|
||||
@@ -433,6 +433,8 @@ fn write_shim(_: &str) -> Result<String> {
|
||||
/// Runs a droplet file on inputs (files and/or folders).
|
||||
fn run_droplet(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "file.automate.runDroplet";
|
||||
// Checked before the droplet file is read, so a droplet that runs itself stops at the limit.
|
||||
crate::file_cmds::check_batch_depth(s, cmd)?;
|
||||
let path = p.get("droplet").or_else(|| p.get("path")).and_then(Value::as_str).ok_or_else(|| bad(cmd, "missing \"droplet\""))?;
|
||||
let v: Value = serde_json::from_slice(&read_file(path)?).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
|
||||
if v.get("photocraftDroplet").is_none() {
|
||||
|
||||
@@ -913,7 +913,7 @@ fn color_replacement(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let sel = doc.selection.clone();
|
||||
let lock = doc.effective_locks(id).transparency;
|
||||
let surf = paint_surface(doc, id, &json!({}))?;
|
||||
Ok(apply_color_replacement(surf, &stroke, &rs, sel.as_ref(), lock))
|
||||
apply_color_replacement(surf, &stroke, &rs, sel.as_ref(), lock).map_err(|e| bad("paint.colorReplacement", e.to_string()))
|
||||
})?;
|
||||
Ok(damage_json(s, dmg))
|
||||
}
|
||||
|
||||
@@ -110,7 +110,8 @@ fn mixer_live_current_layer_matches_reference_and_cancels() {
|
||||
&mut state,
|
||||
None,
|
||||
false,
|
||||
);
|
||||
)
|
||||
.unwrap();
|
||||
let live = LiveMixer::begin(&s, &p).unwrap();
|
||||
let id = s.active().unwrap().active_layer.unwrap();
|
||||
let actual = live.doc.layer(id).unwrap().surface().unwrap().read_region(s.active().unwrap().doc.bounds());
|
||||
|
||||
@@ -93,6 +93,10 @@ pub(super) fn native_pixels(doc: &Document, layer: Option<LayerId>) -> Result<(V
|
||||
let r = doc.bounds();
|
||||
let fmt = doc.pixel_format();
|
||||
let n = fmt.channels();
|
||||
// The source is read as dense samples over the whole canvas, whatever tiles it stores, then
|
||||
// returned as `n` native f32 samples per pixel. Refuse a canvas past the working budget
|
||||
// before reading (an empty canvas can be 300000 px a side).
|
||||
let out = (n as u64).saturating_mul(4);
|
||||
match layer {
|
||||
Some(id) => {
|
||||
let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?;
|
||||
@@ -105,6 +109,7 @@ pub(super) fn native_pixels(doc: &Document, layer: Option<LayerId>) -> Result<(V
|
||||
return Err(EngineError::Other(format!("layer \"{}\" has no pixels", l.name)));
|
||||
}
|
||||
};
|
||||
crate::allocation::check_dense(r, (s.channels() as u64).saturating_mul(4).saturating_add(out), "reading this channel source")?;
|
||||
if s.format() == fmt {
|
||||
return Ok((s.read_region(r), n));
|
||||
}
|
||||
@@ -113,6 +118,8 @@ pub(super) fn native_pixels(doc: &Document, layer: Option<LayerId>) -> Result<(V
|
||||
Ok((raw.chunks_exact(sf.channels()).flat_map(|p| from_rgba(&fmt, to_rgba(&sf, p))).collect(), n))
|
||||
}
|
||||
None => {
|
||||
// The composite is straight RGBA f32.
|
||||
crate::allocation::check_dense(r, 16u64.saturating_add(out), "reading this channel source")?;
|
||||
let buf = photocraft_compose::render(doc, r);
|
||||
Ok((buf.px.iter().flat_map(|p| from_rgba(&fmt, *p)).collect(), n))
|
||||
}
|
||||
@@ -152,6 +159,13 @@ fn ref_planes(doc: &Document, layer: Option<LayerId>, active: Option<LayerId>, r
|
||||
let colors = color_count(doc);
|
||||
Ok(match r {
|
||||
ChanRef::Composite | ChanRef::Color(_) => {
|
||||
// After `native_pixels` returns its `n` samples per pixel, the colour planes (and for
|
||||
// one channel the toned plane) are built beside them: check that peak first, as
|
||||
// `native_pixels` only checks its own.
|
||||
let n = doc.pixel_format().channels() as u64;
|
||||
let toned = u64::from(matches!(r, ChanRef::Color(_)));
|
||||
let planes = (colors as u64).saturating_add(toned).saturating_mul(4);
|
||||
crate::allocation::check_dense(area, n.saturating_mul(4).saturating_add(planes), "reading this channel source")?;
|
||||
let (px, n) = native_pixels(doc, layer)?;
|
||||
let planes: Vec<Vec<f32>> = (0..colors).map(|c| px.chunks_exact(n).map(|p| p[c]).collect()).collect();
|
||||
match r {
|
||||
|
||||
@@ -47,7 +47,9 @@ fn named(c: Contour, name: &str) -> Contour {
|
||||
/// `base`, or `base 2`, `base 3`… so a name is neither a standard contour's nor a user contour's
|
||||
/// (a name alone selects a standard contour, so a user contour may not shadow one).
|
||||
fn unique(lib: &[Contour], base: &str) -> String {
|
||||
let taken = |n: &str| builtin_contour(n).is_some() || lib.iter().any(|c| name_of(c) == n);
|
||||
// One pass over the library, not one per suffix tried.
|
||||
let used: std::collections::HashSet<&str> = lib.iter().map(name_of).collect();
|
||||
let taken = |n: &str| builtin_contour(n).is_some() || used.contains(n);
|
||||
if !taken(base) {
|
||||
return base.to_string();
|
||||
}
|
||||
|
||||
@@ -160,14 +160,24 @@ fn interp(p: &Value) -> Interp {
|
||||
// ---------- pixel operations ----------
|
||||
|
||||
/// Mixes `new` over `old` by the selection's coverage (premultiplied when there is alpha).
|
||||
fn mix_by_selection(old: &Surface, new: &Surface, sel: &Surface) -> Surface {
|
||||
let area = old.content_bounds().union(&new.content_bounds());
|
||||
let mut out = new.clone();
|
||||
///
|
||||
/// Where the selection covers nothing the result is `old`, so only the part of the content
|
||||
/// bounds the selection reaches is blended into a copy of `old`: a small selection over distant
|
||||
/// sparse content no longer expands the empty space between them. Refused, before any dense
|
||||
/// buffer, when that part would still pass the working budget.
|
||||
fn mix_by_selection(old: &Surface, new: &Surface, sel: &Surface) -> Result<Surface> {
|
||||
let content = old.content_bounds().union(&new.content_bounds());
|
||||
// Outside its tiles the selection's coverage is its default: an empty default lets the
|
||||
// blend keep to the selection's bounds.
|
||||
let sel_default_empty = sel.default_pixel().first().is_none_or(|v| *v <= 0.0);
|
||||
let area = if sel_default_empty { content.intersect(&sel.content_bounds()) } else { content };
|
||||
let mut out = old.clone();
|
||||
if area.is_empty() {
|
||||
return out;
|
||||
return Ok(out);
|
||||
}
|
||||
let fmt = old.format();
|
||||
let n = fmt.channels();
|
||||
crate::allocation::check_dense(area, (n as u64).saturating_mul(12), "blending Liquify through the selection")?;
|
||||
let (o, w) = (old.read_region(area), new.read_region(area));
|
||||
let mut r = vec![0.0f32; o.len()];
|
||||
let aw = area.width() as usize;
|
||||
@@ -189,7 +199,7 @@ fn mix_by_selection(old: &Surface, new: &Surface, sel: &Surface) -> Surface {
|
||||
}
|
||||
out.write_region(area, &r);
|
||||
out.prune();
|
||||
out
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Liquifies a surface over `canvas` (the field's extent).
|
||||
@@ -344,7 +354,7 @@ fn liquify(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
&|surf, sel, _| {
|
||||
let out = apply_liquify(surf, &field);
|
||||
Ok(match sel {
|
||||
Some(sel) => mix_by_selection(surf, &out, sel),
|
||||
Some(sel) => mix_by_selection(surf, &out, sel)?,
|
||||
None => out,
|
||||
})
|
||||
},
|
||||
|
||||
@@ -187,9 +187,10 @@ fn background_eraser(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let surf = l.surface_mut().ok_or_else(|| bad(CMD, "not a pixel layer"))?;
|
||||
if let Some(colors) = colors {
|
||||
let effect = selected_background_effect(surf, &bs, colors, bg);
|
||||
Ok(photocraft_paint::retouch::apply_dab_stroke(surf, &background_eraser_stroke(&stroke), selection.as_ref(), false, 0, effect))
|
||||
photocraft_paint::retouch::apply_dab_stroke(surf, &background_eraser_stroke(&stroke), selection.as_ref(), false, 0, effect)
|
||||
.map_err(|e| bad(CMD, e.to_string()))
|
||||
} else {
|
||||
Ok(apply_background_eraser(surf, &stroke, &bs, selection.as_ref()))
|
||||
apply_background_eraser(surf, &stroke, &bs, selection.as_ref()).map_err(|e| bad(CMD, e.to_string()))
|
||||
}
|
||||
})?;
|
||||
Ok(damage(s, dmg, true))
|
||||
|
||||
@@ -28,6 +28,9 @@ pub fn detect(px: &[[f32; 4]], w: usize, h: usize, min_score: f32) -> Result<Vec
|
||||
/// `all_layers` is off. Coordinates are document pixels.
|
||||
pub fn faces_in(doc: &Document, active: Option<LayerId>, all_layers: bool, min_score: f32) -> Result<Vec<Face>> {
|
||||
let area = doc.bounds();
|
||||
// Both paths hold the whole canvas as straight RGBA f32, however few tiles the layers store:
|
||||
// refuse a canvas past the working budget before allocating it.
|
||||
crate::allocation::check_dense(area, 16, "face detection")?;
|
||||
let (w, h) = (area.width() as usize, area.height() as usize);
|
||||
let surface = active.and_then(|id| doc.layer(id)).and_then(|l| l.surface()).filter(|_| !all_layers);
|
||||
let px = match surface {
|
||||
|
||||
@@ -33,6 +33,7 @@ mod save;
|
||||
|
||||
pub use batch_naming::plan as plan_batch_names;
|
||||
use batch_run::batch;
|
||||
pub(crate) use batch_run::check_batch_depth;
|
||||
pub use batch_run::same_format as batch_same_format;
|
||||
use batch_run::same_format;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
@@ -222,6 +222,10 @@ impl FileFailure {
|
||||
fn value(&self, key: &str, input: &str) -> Value {
|
||||
let mut failure = json!({"error": self.error.to_string()});
|
||||
failure[key] = json!(input);
|
||||
// Marks a nesting or playback-budget stop, which an enclosing batch step must not swallow.
|
||||
if matches!(self.error, EngineError::BatchLimit(_)) {
|
||||
failure["limit"] = json!(true);
|
||||
}
|
||||
if let Some(result) = &self.result {
|
||||
failure["result"] = result.clone();
|
||||
}
|
||||
@@ -239,10 +243,13 @@ fn process_outputs<'a>(
|
||||
// The scratch sessions have default preferences; a raw opens at the user's Raw Defaults.
|
||||
let raw_ppi = s.prefs().raw_defaults.resolution;
|
||||
let action_prefs = s.prefs().actions.clone();
|
||||
let authorize = s.authorize;
|
||||
let mut files = Vec::new();
|
||||
let mut errors = Vec::new();
|
||||
let mut written = OutputClaims::default();
|
||||
let run = |scratch: &mut Session, out: &str| {
|
||||
// Nested commands answer to the initiating session's authorization hook.
|
||||
scratch.authorize = authorize;
|
||||
scratch.prefs.edit(|prefs| prefs.actions = action_prefs.clone());
|
||||
f(scratch, out).map_err(FileFailure::from)
|
||||
};
|
||||
@@ -661,6 +668,18 @@ pub(crate) fn batch_keeps_step(id: &str) -> bool {
|
||||
(batch_save_point(id) || !crate::actions_cmds::shell_save_command(id)) && !crate::actions_cmds::shell_view_command(id)
|
||||
}
|
||||
|
||||
/// Refuses a batch or droplet nested past [`MAX_BATCH_DEPTH`](crate::actions_cmds::MAX_BATCH_DEPTH),
|
||||
/// before it reads or decodes anything: each level keeps its parent's scratch document open.
|
||||
pub(crate) fn check_batch_depth(s: &Session, cmd: &str) -> Result<()> {
|
||||
if s.actions.batch_depth >= crate::actions_cmds::MAX_BATCH_DEPTH {
|
||||
return Err(EngineError::BatchLimit(format!(
|
||||
"invalid parameters for `{cmd}`: batches and droplets are nested more than {} deep",
|
||||
crate::actions_cmds::MAX_BATCH_DEPTH
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn batch_action(list: &[crate::actions_cmds::Action], p: &Value) -> Result<usize> {
|
||||
const CMD: &str = "file.automate.batch";
|
||||
if let Some(set) = p.get("set").filter(|v| !v.is_null()) {
|
||||
@@ -680,6 +699,7 @@ pub(crate) fn batch_action(list: &[crate::actions_cmds::Action], p: &Value) -> R
|
||||
/// Named actions carry their recursion context and both routes normalize recorded parameters.
|
||||
pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "file.automate.batch";
|
||||
check_batch_depth(s, cmd)?;
|
||||
let quiet_raw = match p.get("suppressOpenOptions") {
|
||||
None | Some(Value::Null) => false,
|
||||
Some(Value::Bool(value)) => *value,
|
||||
@@ -810,17 +830,19 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A batch inside a played action charges its inputs × steps (at least one each: an input is read,
|
||||
// decoded and saved even with no steps) to the playback tree it is in and
|
||||
// hands the count on, so nested batches cannot multiply past the limit. A top-level named
|
||||
// action starts fresh; standalone explicit steps retain their existing behavior.
|
||||
// action starts fresh; standalone explicit steps retain their existing behavior. A batch nested
|
||||
// in another batch (a droplet a droplet runs) is charged the same way, so the levels share one budget.
|
||||
let named = called_name.is_some();
|
||||
let nested = s.actions.playing > 0 || s.actions.batch_depth > 0;
|
||||
let mut playback_steps = 0;
|
||||
if s.actions.playing > 0 || named {
|
||||
let spent = if s.actions.playing > 0 { s.actions.playback_steps } else { 0 };
|
||||
if nested || named {
|
||||
let spent = if nested { s.actions.playback_steps } else { 0 };
|
||||
playback_steps =
|
||||
spent.saturating_add((steps.len().max(1) as u64).saturating_mul(if source == "open" { s.documents().len() } else { inputs.len() } as u64));
|
||||
if playback_steps > crate::actions_cmds::MAX_PLAYBACK_STEPS {
|
||||
return Err(EngineError::BadParams { cmd: cmd.into(), msg: "this batch would exceed the action playback step limit".into() });
|
||||
return Err(EngineError::BatchLimit(format!("invalid parameters for `{cmd}`: this batch would exceed the action playback step limit")));
|
||||
}
|
||||
if s.actions.playing > 0 {
|
||||
if nested {
|
||||
s.actions.playback_steps = playback_steps;
|
||||
}
|
||||
}
|
||||
@@ -833,6 +855,8 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
playback_steps,
|
||||
script_depth: s.actions.script_depth,
|
||||
script_steps: s.actions.script_steps,
|
||||
budget_shared: nested,
|
||||
batch_depth: s.actions.batch_depth.saturating_add(1),
|
||||
..Default::default()
|
||||
};
|
||||
if source == "open" {
|
||||
@@ -849,6 +873,9 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let previous_playing = std::mem::replace(&mut s.actions.playing, actions.playing);
|
||||
let previous_stack = std::mem::replace(&mut s.actions.playback_stack, actions.playback_stack);
|
||||
let previous_steps = std::mem::replace(&mut s.actions.playback_steps, actions.playback_steps);
|
||||
// The nesting depth and shared budget of the levels above travel with the run too.
|
||||
let previous_shared = std::mem::replace(&mut s.actions.budget_shared, actions.budget_shared);
|
||||
let previous_depth = std::mem::replace(&mut s.actions.batch_depth, actions.batch_depth);
|
||||
let previous_list = p.get("calledActions").is_some_and(|value| !value.is_null()).then(|| std::mem::replace(&mut s.actions.list, actions.list));
|
||||
let owns_history = s.action_history.is_none() && s.prefs().actions.create_single_history_state;
|
||||
if owns_history {
|
||||
@@ -860,10 +887,12 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
s.actions.playing = previous_playing;
|
||||
s.actions.playback_stack = previous_stack;
|
||||
s.actions.budget_shared = previous_shared;
|
||||
s.actions.batch_depth = previous_depth;
|
||||
if let Some(previous) = previous_list {
|
||||
s.actions.list = previous;
|
||||
}
|
||||
if previous_playing == 0 {
|
||||
if previous_playing == 0 && !previous_shared {
|
||||
s.actions.playback_steps = previous_steps;
|
||||
}
|
||||
if named {
|
||||
@@ -902,7 +931,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
validate_flat_outputs(&outputs)?;
|
||||
validate_error_log(&policy, outputs.iter().map(|(path, _)| path.clone()), outputs.iter().map(|(_, path)| path.clone()))?;
|
||||
let was_playing = s.actions.playing > 0;
|
||||
let was_playing = nested;
|
||||
#[cfg(test)]
|
||||
let history_observer = s.batch_history_observer;
|
||||
crate::jobs::run(
|
||||
@@ -1027,6 +1056,10 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A recorded Save is a step too: Batch writes the output for it.
|
||||
charge_script_step(scratch)?;
|
||||
if batch_save_point(id) {
|
||||
// The scratch session never executes a save point, so the gate would not see it.
|
||||
if let Some(gate) = scratch.authorize {
|
||||
gate(id, params)?;
|
||||
}
|
||||
let st = scratch.active_mut().ok_or(EngineError::NoDocument)?;
|
||||
saved = Some(st.doc.clone());
|
||||
// Batch performs the action's Save / Save As (to its destination), so the
|
||||
@@ -1040,6 +1073,12 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let params = crate::actions_cmds::playback_params(scratch, id, params)?;
|
||||
let r = scratch.execute(id, params)?;
|
||||
// A nested batch, droplet or played action that hit the nesting or shared playback
|
||||
// limit fails this input too, instead of saving it unprocessed.
|
||||
if let Some(limit) = crate::actions_cmds::limit_stop(&r) {
|
||||
// The child result stays, so the files it wrote before the stop are reported.
|
||||
return Err(FileFailure { error: EngineError::BatchLimit(limit), result: Some(r) });
|
||||
}
|
||||
ctx.publish_batch_preview(&source_path, scratch.active().map(|state| state.doc.clone()));
|
||||
// A failed step inside a called action makes this file an error, not a saved result.
|
||||
if let Some(error) = crate::actions_cmds::nested_failure(id, &r) {
|
||||
|
||||
@@ -44,6 +44,10 @@ pub struct LayerExportReport {
|
||||
pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result<LayerExportReport> {
|
||||
let cmd = "file.export.layersToFiles";
|
||||
let format = p.get("format").and_then(Value::as_str).unwrap_or("png").trim_start_matches('.').to_ascii_lowercase();
|
||||
// The format becomes the file extension inside one filename component handed to `write`.
|
||||
if format.is_empty() || !format.chars().all(|c| c.is_ascii_alphanumeric()) {
|
||||
return Err(EngineError::BadParams { cmd: cmd.into(), msg: "`format` must be a file extension such as png".into() });
|
||||
}
|
||||
let trim = p.get("trim").and_then(Value::as_bool).unwrap_or(false);
|
||||
let visible_only = p.get("visibleOnly").and_then(Value::as_bool).unwrap_or(true);
|
||||
// Callers outside `Session::execute` (headless workspace exports) carry the session's gate
|
||||
|
||||
@@ -171,6 +171,19 @@ impl PlaceSteps {
|
||||
Some(c) if c.len() == 2 => (c[0].as_f64().unwrap_or(cw / 2.0), c[1].as_f64().unwrap_or(ch / 2.0)),
|
||||
_ => (cw / 2.0, ch / 2.0),
|
||||
};
|
||||
// `scale` is the caller's: bound the resampled size before allocating it (a frame's image
|
||||
// renders through its smart object, which has its own budget). Resampling rounds the far
|
||||
// output edges outward; an unresampled placement keeps its size.
|
||||
if self.input.frame.is_none() {
|
||||
let (ow, oh) = if (scale - 1.0).abs() > 1e-9 { ((w * scale).ceil(), (h * scale).ceil()) } else { (w, h) };
|
||||
let scaled = ow * oh;
|
||||
if scaled.is_nan() || scaled > photocraft_compose::MAX_RENDER_PIXELS as f64 {
|
||||
return Err(EngineError::BadParams {
|
||||
cmd: self.input.command().into(),
|
||||
msg: format!("scaling {w}×{h} by {scale} makes an image too large to place"),
|
||||
});
|
||||
}
|
||||
}
|
||||
let (dx, dy) = ((center.0 - w * scale / 2.0).round(), (center.1 - h * scale / 2.0).round());
|
||||
self.plan = Plan { w, h, scale, dx, dy };
|
||||
// A frame's image renders through its smart object, which refuses a placement past the
|
||||
|
||||
@@ -1785,6 +1785,17 @@ fn dds_params_are_none_until_one_is_given() {
|
||||
assert_eq!(dds_param(&json!({"ddsCompression": "bc2"}), "file.saveAs").unwrap(), Some(DdsOptions { compression: DdsCompression::Bc2, mipmaps: false }));
|
||||
}
|
||||
|
||||
/// The layer export's `format` is an extension, never a path: separators and `..` are refused.
|
||||
#[test]
|
||||
fn layer_export_format_cannot_carry_path_components() {
|
||||
let dir = tmp("fmt-path");
|
||||
let mut s = session(8, 8, 8);
|
||||
for bad in ["png/../../x", "..\\x", "a/b", ""] {
|
||||
let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "format": bad}));
|
||||
assert!(matches!(r, Err(EngineError::BadParams { .. })), "{bad}: {r:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A `tgaBits` other than 24 or 32 is a bad parameter, reported before anything is written.
|
||||
#[test]
|
||||
fn bad_targa_bits_are_refused_before_writing() {
|
||||
@@ -2004,6 +2015,21 @@ fn place_embedded_centres_fits_and_embeds() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A caller-chosen placement scale cannot ask for an image beyond the render limit.
|
||||
#[test]
|
||||
fn placing_refuses_a_scale_that_would_exceed_the_pixel_limit() {
|
||||
let dir = tmp("place-huge-scale");
|
||||
let small = png(&dir, "small.png", 200, 100, "#ff0000");
|
||||
let mut s = session(100, 100, 8);
|
||||
for scale in [1e9, 1e300, 1e308, 23170.25] {
|
||||
assert!(matches!(s.execute("file.placeEmbedded", json!({"path": small, "scale": scale})), Err(EngineError::BadParams { .. })), "{scale}");
|
||||
}
|
||||
assert!(s.execute("file.placeEmbedded", json!({"path": small, "scale": 50})).is_ok());
|
||||
// The error names the command that asked.
|
||||
let linked = s.execute("file.placeLinked", json!({"path": small, "scale": 1e9}));
|
||||
assert!(matches!(linked, Err(EngineError::BadParams { ref cmd, .. }) if cmd == "file.placeLinked"), "{linked:?}");
|
||||
}
|
||||
|
||||
/// Preferences ▸ General ▸ Always Create Smart Objects When Placing: unchecked, an embedded place
|
||||
/// lands as a plain pixel layer; a linked place is always a smart object and `"smartObject"` wins.
|
||||
#[test]
|
||||
@@ -2723,6 +2749,41 @@ fn trimming_an_empty_layer_keeps_a_valid_nonzero_canvas() {
|
||||
assert_eq!((back.size.width, back.size.height), (6, 7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_processor_scratch_sessions_answer_to_the_authorization_gate() {
|
||||
fn deny_image(id: &str, _: &Value) -> Result<()> {
|
||||
if id.starts_with("image.") { Err(EngineError::Other(format!("automation command `{id}` is disabled"))) } else { Ok(()) }
|
||||
}
|
||||
let dir = tmp("proc-gate");
|
||||
let input = join(&dir, "in");
|
||||
std::fs::create_dir_all(&input).unwrap();
|
||||
png(&input, "a.png", 40, 20, "#ff0000");
|
||||
let mut s = Session::new();
|
||||
s.authorize = Some(deny_image);
|
||||
let out = join(&dir, "out");
|
||||
let r = s.execute("file.scripts.imageProcessor", json!({"input": input, "output": out, "format": "jpg", "width": 20, "height": 20})).unwrap();
|
||||
assert!(r["files"].as_array().unwrap().is_empty(), "{r}");
|
||||
assert_eq!(r["errors"].as_array().unwrap().len(), 1, "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_save_points_answer_to_the_authorization_gate() {
|
||||
fn deny_save(id: &str, _: &Value) -> Result<()> {
|
||||
if id == "file.save" { Err(EngineError::Other(format!("automation command `{id}` is disabled"))) } else { Ok(()) }
|
||||
}
|
||||
let dir = tmp("batch-save-gate");
|
||||
let input = join(&dir, "in");
|
||||
std::fs::create_dir_all(&input).unwrap();
|
||||
png(&input, "a.png", 8, 8, "#ff0000");
|
||||
let mut s = Session::new();
|
||||
s.authorize = Some(deny_save);
|
||||
let out = join(&dir, "out");
|
||||
let r = s.execute("file.automate.batch", json!({"steps": [["file.save", {}]], "input": input, "output": out, "format": "png"})).unwrap();
|
||||
assert!(r["files"].as_array().unwrap().is_empty(), "{r}");
|
||||
assert_eq!(r["errors"].as_array().unwrap().len(), 1, "{r}");
|
||||
assert!(!std::path::Path::new(&join(&out, "a.png")).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_files_into_stack_and_image_processor_and_batch() {
|
||||
let dir = tmp("batch");
|
||||
@@ -3900,6 +3961,33 @@ fn sanitize_keeps_windows_device_names_off_the_disk() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A droplet whose steps run the same droplet stops at the nesting limit with an error for the
|
||||
/// input, rather than opening documents until the stack or memory runs out.
|
||||
#[test]
|
||||
fn a_droplet_that_runs_itself_stops_at_the_nesting_limit() {
|
||||
let dir = tmp("droplet-recursion");
|
||||
let input = png(&dir, "a.png", 4, 4, "#ff0000");
|
||||
let droplet = join(&dir, "self.pcdroplet");
|
||||
let out = join(&dir, "out");
|
||||
let step = json!(["file.automate.runDroplet", {"droplet": droplet, "input": [input], "output": out}]);
|
||||
std::fs::write(&droplet, json!({"photocraftDroplet": 1, "name": "self", "action": {"steps": [step]}, "options": {"format": "png"}}).to_string()).unwrap();
|
||||
let mut s = Session::new();
|
||||
// Each level runs the next in a scratch session; the innermost is refused, so this returns.
|
||||
let r = s.execute("file.automate.runDroplet", json!({"droplet": droplet, "input": [input], "output": out})).unwrap();
|
||||
assert_eq!(s.actions.batch_depth, 0);
|
||||
// The limit reaches the outermost result: the input failed, nothing was saved unprocessed.
|
||||
assert!(r["errors"][0]["error"].as_str().unwrap().contains("nested more than"), "{r}");
|
||||
assert_eq!(r["files"], json!([]), "{r}");
|
||||
assert!(!std::path::Path::new(&out).join("a.png").exists());
|
||||
// At the limit, the droplet is refused before its file is read (this one doesn't exist).
|
||||
s.actions.batch_depth = crate::actions_cmds::MAX_BATCH_DEPTH;
|
||||
let missing = join(&dir, "missing.pcdroplet");
|
||||
let e = s.execute("file.automate.runDroplet", json!({"droplet": missing, "input": [input], "output": out})).unwrap_err();
|
||||
assert!(e.to_string().contains("nested more than"), "{e}");
|
||||
let e = s.execute("file.automate.batch", json!({"steps": [], "input": [input], "output": out})).unwrap_err();
|
||||
assert!(e.to_string().contains("nested more than"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn approve_memory_validates_parameters_and_unknown_ids() {
|
||||
let mut s = session(4, 4, 8);
|
||||
|
||||
@@ -163,8 +163,22 @@ fn cut_piece(base: &Surface, sel: &Surface, b: photocraft_geom::Rect, with_alpha
|
||||
let alpha_off = dst_bpp - sb;
|
||||
let src_empty_default = same_fmt && base.default_bytes().iter().all(|&v| v == 0);
|
||||
let oom = |e| EngineError::Other(format!("not enough memory while floating selection ({e}); the document was not changed"));
|
||||
let mut coords = crate::allocation::capacity(b.tiles().count(), "floating selection")?;
|
||||
coords.extend(b.tiles());
|
||||
// Only tiles that can hold a piece of the result are visited. With an empty source default,
|
||||
// that is the source's stored tiles; with an empty selection default, the selection's. Two
|
||||
// distant tiles make `b` a grid of millions of tiles that hold nothing, so the full grid is
|
||||
// walked only when neither default is empty, after checking what it could produce.
|
||||
let sel_default_empty = sel.default_pixel().first().is_none_or(|v| *v <= 0.0);
|
||||
let stored = |s: &Surface| s.tiles().map(|(c, _)| *c).filter(|c| !c.rect().intersect(&b).is_empty()).collect::<Vec<_>>();
|
||||
let coords: Vec<TileCoord> = if src_empty_default {
|
||||
stored(base)
|
||||
} else if sel_default_empty {
|
||||
stored(sel)
|
||||
} else {
|
||||
crate::allocation::check_dense(b, dst_bpp as u64, "floating selection")?;
|
||||
let mut coords = crate::allocation::capacity(usize::try_from(b.tile_count()).unwrap_or(usize::MAX), "floating selection")?;
|
||||
coords.extend(b.tiles());
|
||||
coords
|
||||
};
|
||||
let tiles = coords
|
||||
.into_par_iter()
|
||||
.map(|tc| -> Result<Option<(TileCoord, Arc<Tile>)>> {
|
||||
|
||||
@@ -131,6 +131,17 @@ fn apply_mask(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// displays. LayerMask::values_into accounts for density but not feather (#3044).
|
||||
let feathered = {
|
||||
let layer = doc.layer(id).ok_or(EngineError::NoLayer(id))?;
|
||||
// The pixels are read over their content bounds (distant tiles span the gaps between
|
||||
// them) as native samples, straight RGBA, the mask's coverage and the re-encoded
|
||||
// output; a feathered mask is also rendered over the canvas and those bounds.
|
||||
if let Some(surf) = layer.surface() {
|
||||
let r = surf.content_bounds();
|
||||
let n = surf.channels() as u64;
|
||||
crate::allocation::check_dense(r, n.saturating_mul(8).saturating_add(20), "applying the layer mask")?;
|
||||
if layer.mask.as_ref().is_some_and(|m| m.enabled && photocraft_compose::masks::feather_sigma(m.feather) > 0.0) {
|
||||
crate::allocation::check_dense(doc.bounds().union(&r), 8, "applying the feathered layer mask")?;
|
||||
}
|
||||
}
|
||||
if layer.mask.as_ref().is_some_and(|m| m.enabled && photocraft_compose::masks::feather_sigma(m.feather) > 0.0) {
|
||||
// Do not bake an independent vector mask that remains attached after Apply.
|
||||
let mut mask_only = layer.clone();
|
||||
|
||||
@@ -124,6 +124,19 @@ fn to_multichannel(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
return Err(EngineError::NoDocument);
|
||||
};
|
||||
let names = s.edit("Multichannel", |doc, active| {
|
||||
// Every ink is built as dense planes over the whole canvas (the flattened image, its
|
||||
// colour planes, the inverted densities and each clamped channel), however few tiles
|
||||
// the document stores: refuse a canvas past the working budget before allocating.
|
||||
// Per pixel: the flattened image (16 B), its colour planes (4 B each), and per ink an f32
|
||||
// density and the stored plane (up to 4 B at F32). A Duotone has one colour channel but
|
||||
// as many inks as it lists.
|
||||
let cc = doc.pixel_format().mode.color_channels() as u64;
|
||||
let inks = match (&doc.duotone, doc.mode) {
|
||||
(Some(d), ColorMode::Duotone) if !d.inks.is_empty() => d.inks.len() as u64,
|
||||
_ => cc,
|
||||
};
|
||||
let per_px = cc.saturating_mul(4).saturating_add(inks.saturating_mul(8)).saturating_add(16);
|
||||
crate::allocation::check_dense(doc.bounds(), per_px, "converting to Multichannel")?;
|
||||
let inks = inks_of(doc);
|
||||
let mut channels: Vec<AlphaChannel> = inks
|
||||
.iter()
|
||||
@@ -189,8 +202,16 @@ pub(crate) fn convert_from(s: &mut Session, mode: ColorMode, _p: &Value) -> Resu
|
||||
let how = s.edit("Mode Change", |doc, active| {
|
||||
let (inks, others): (Vec<AlphaChannel>, Vec<AlphaChannel>) = std::mem::take(&mut doc.channels).into_iter().partition(|c| c.spot.is_some());
|
||||
let canvas = doc.bounds();
|
||||
let n = canvas.width() as usize * canvas.height() as usize;
|
||||
// The interleaved output, the rendered look (straight RGBA f32) and one ink plane at a
|
||||
// time, all over the canvas: refuse a canvas past the working budget before allocating.
|
||||
// The appearance branch also holds the stored surface (up to 4 B per sample) while `shown`
|
||||
// and the interleaved output are alive; the reinterpret branch drops each plane first.
|
||||
let out_cc = mode.color_channels() as u64;
|
||||
let reinterpret = matches!((mode, inks.len()), (ColorMode::Rgb | ColorMode::Lab, 3) | (ColorMode::Cmyk, 4) | (ColorMode::Grayscale, 1));
|
||||
let samples = out_cc.saturating_add(1).saturating_mul(4);
|
||||
let stored = if reinterpret { 0 } else { samples };
|
||||
crate::allocation::check_dense(canvas, samples.saturating_add(20).saturating_add(stored), "converting from Multichannel")?;
|
||||
let n = canvas.width() as usize * canvas.height() as usize;
|
||||
// The printed look, rendered before the inks leave the document.
|
||||
let shown = (!reinterpret).then(|| {
|
||||
let mut d = doc.clone();
|
||||
|
||||
@@ -55,6 +55,9 @@ fn fill_mode(p: &Value) -> Result<FillMode> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The reference's alert for a Paint Bucket click in a Bitmap document (#12536).
|
||||
pub const BITMAP_REFUSAL: &str = "Could not use the paint bucket because it does not work with Bitmap images (convert image to Grayscale mode to edit).";
|
||||
|
||||
fn bucket(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let fg = s.tools.foreground;
|
||||
let c = color(p.get("color"), fg);
|
||||
@@ -63,6 +66,10 @@ fn bucket(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let opacity = opacity(p, "paint.bucket")?;
|
||||
let mode = fill_mode(p)?;
|
||||
let all = b(p, "sampleAllLayers", false) && crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::Pixels;
|
||||
// Before the region, the target and the document copy: a Bitmap click changes nothing.
|
||||
if s.active().is_some_and(|d| d.doc.mode == photocraft_color::ColorMode::Bitmap) {
|
||||
return Err(EngineError::Other(BITMAP_REFUSAL.into()));
|
||||
}
|
||||
// Other visible layers can define the region, but the fill still writes only to the target.
|
||||
let region = if all {
|
||||
let (area, img) = crate::selection_cmds::sample_rgba8(s, true)?;
|
||||
@@ -212,3 +219,6 @@ mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod bucket_no_op_history_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod bucket_bitmap_tests;
|
||||
@@ -0,0 +1,95 @@
|
||||
//! #12536: the Paint Bucket refuses a Bitmap document with the reference's alert text, before
|
||||
//! anything else, and leaves the document and History unchanged. Grayscale, RGB, CMYK, Lab and
|
||||
//! Indexed Color documents still fill; Duotone and Multichannel were not measured and keep
|
||||
//! today's behaviour (no refusal).
|
||||
|
||||
use super::*;
|
||||
|
||||
fn bitmap() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 64, "height": 64, "background": "white"})).unwrap();
|
||||
s.execute("image.mode.grayscale", json!({})).unwrap();
|
||||
s.execute("image.mode.bitmap", json!({})).unwrap();
|
||||
assert_eq!(s.active().unwrap().doc.mode, photocraft_color::ColorMode::Bitmap);
|
||||
s.execute("tools.setColors", json!({"foreground": "#00ff00"})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn assert_refused(s: &mut Session, params: Value, case: &str) {
|
||||
let (doc, steps) = (s.active().unwrap().doc.clone(), s.active().unwrap().history.past_len());
|
||||
let err = s.execute("paint.bucket", params).unwrap_err().to_string();
|
||||
assert_eq!(err, BITMAP_REFUSAL, "{case}");
|
||||
assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc), "{case}: document unchanged");
|
||||
assert_eq!(s.active().unwrap().history.past_len(), steps, "{case}: no history state");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_refusal_is_the_reference_alert_text() {
|
||||
assert_eq!(BITMAP_REFUSAL, "Could not use the paint bucket because it does not work with Bitmap images (convert image to Grayscale mode to edit).");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bitmap_document_is_refused() {
|
||||
let mut s = bitmap();
|
||||
assert_refused(&mut s, json!({"x": 32, "y": 32}), "foreground");
|
||||
assert_refused(&mut s, json!({"x": 32, "y": 32, "color": "#000000", "mode": "clear"}), "black, Clear");
|
||||
assert_refused(&mut s, json!({"x": 32, "y": 32, "contents": "pattern"}), "a pattern");
|
||||
assert_refused(&mut s, json!({"x": 32, "y": 32, "sampleAllLayers": true}), "all layers");
|
||||
}
|
||||
|
||||
/// The mode comes first: a click that would fill nothing, or a target that would be refused,
|
||||
/// gets the Bitmap alert as well.
|
||||
#[test]
|
||||
fn the_refusal_comes_before_the_click_and_the_target() {
|
||||
let mut s = bitmap();
|
||||
assert_refused(&mut s, json!({"x": -5, "y": 32}), "off the canvas");
|
||||
assert_refused(&mut s, json!({"x": 32, "y": 32, "layer": 999_999}), "a missing layer");
|
||||
assert_refused(&mut s, json!({"x": 32, "y": 32, "target": "mask"}), "a missing mask");
|
||||
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 8, "antiAlias": false})).unwrap();
|
||||
assert_refused(&mut s, json!({"x": 32, "y": 32}), "outside the selection");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_modes_still_fill() {
|
||||
for (mode, depth) in [
|
||||
("grayscale", 8),
|
||||
("grayscale", 16),
|
||||
("grayscale", 32),
|
||||
("rgb", 8),
|
||||
("rgb", 16),
|
||||
("rgb", 32),
|
||||
("cmyk", 8),
|
||||
("cmyk", 16),
|
||||
("lab", 8),
|
||||
("lab", 16),
|
||||
("indexed", 8),
|
||||
] {
|
||||
let mut s = Session::new();
|
||||
let new_mode = if mode == "indexed" { "rgb" } else { mode };
|
||||
s.execute("file.new", json!({"width": 64, "height": 64, "mode": new_mode, "depth": depth, "background": "white"})).unwrap();
|
||||
if mode == "indexed" {
|
||||
s.execute("image.mode.indexedColor", json!({})).unwrap();
|
||||
assert_eq!(s.active().unwrap().doc.mode, photocraft_color::ColorMode::Indexed);
|
||||
}
|
||||
s.execute("tools.setColors", json!({"foreground": "#000000"})).unwrap();
|
||||
let steps = s.active().unwrap().history.past_len();
|
||||
let r = s.execute("paint.bucket", json!({"x": 32, "y": 32})).unwrap_or_else(|e| panic!("{mode} {depth}: {e}"));
|
||||
assert_eq!(r["filled"], true, "{mode} {depth}: {r}");
|
||||
assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "{mode} {depth}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unmeasured_modes_are_not_refused() {
|
||||
let mut multi = Session::new();
|
||||
multi.execute("file.new", json!({"width": 64, "height": 64, "background": "white"})).unwrap();
|
||||
multi.execute("image.mode.multichannel", json!({})).unwrap();
|
||||
let mut duotone = Session::new();
|
||||
duotone.execute("file.new", json!({"width": 64, "height": 64, "mode": "grayscale", "background": "white"})).unwrap();
|
||||
duotone.execute("image.mode.duotone", json!({"type": "monotone"})).unwrap();
|
||||
for (mut s, mode) in [(multi, photocraft_color::ColorMode::Multichannel), (duotone, photocraft_color::ColorMode::Duotone)] {
|
||||
assert_eq!(s.active().unwrap().doc.mode, mode);
|
||||
let r = s.execute("paint.bucket", json!({"x": 32, "y": 32}));
|
||||
assert!(r.as_ref().err().is_none_or(|e| e.to_string() != BITMAP_REFUSAL), "{mode:?}: {r:?}");
|
||||
}
|
||||
}
|
||||
@@ -1525,6 +1525,12 @@ fn package(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
// ---------- Paths to Illustrator ----------
|
||||
|
||||
/// `s` with line terminators and other control characters replaced by spaces, so a name stays
|
||||
/// inside its one PostScript comment line instead of ending it and adding instructions.
|
||||
fn ps_comment_text(s: &str) -> String {
|
||||
s.chars().map(|c| if c.is_control() { ' ' } else { c }).collect()
|
||||
}
|
||||
|
||||
/// The document's paths as an Illustrator 3 PostScript file. `which`: "all", "work" or a path
|
||||
/// name. Coordinates are points (pixels at the document resolution), y up.
|
||||
pub fn paths_to_ai(doc: &Document, which: &str) -> Result<(String, usize)> {
|
||||
@@ -1544,7 +1550,7 @@ pub fn paths_to_ai(doc: &Document, which: &str) -> Result<(String, usize)> {
|
||||
}
|
||||
let mut s = String::new();
|
||||
s.push_str("%!PS-Adobe-2.0 EPSF-1.2\n%%Creator: PhotoCraft\n");
|
||||
s.push_str(&format!("%%Title: ({})\n", doc.name.replace([')', '('], "_")));
|
||||
s.push_str(&format!("%%Title: ({})\n", ps_comment_text(&doc.name).replace([')', '('], "_")));
|
||||
s.push_str(&format!(
|
||||
"%%BoundingBox: 0 0 {} {}\n%%HiResBoundingBox: 0 0 {w:.4} {h:.4}\n%AI3_Cropmarks: 0 0 {w:.4} {h:.4}\n",
|
||||
w.ceil() as i64,
|
||||
@@ -1559,7 +1565,7 @@ pub fn paths_to_ai(doc: &Document, which: &str) -> Result<(String, usize)> {
|
||||
continue;
|
||||
}
|
||||
n += 1;
|
||||
s.push_str(&format!("%%Note: {name}\n"));
|
||||
s.push_str(&format!("%%Note: {}\n", ps_comment_text(name)));
|
||||
let compound = subs.len() > 1;
|
||||
if compound {
|
||||
s.push_str("*u\n");
|
||||
|
||||
@@ -1561,3 +1561,8 @@ fn printed_pdf_uses_winansi_for_labels_and_descriptions() {
|
||||
assert!(content.contains(r"(Price: \20020 \(proof\)) Tj"), "{content}");
|
||||
assert!(content.is_ascii(), "encoded bytes are escaped, never UTF-8 text operands");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postscript_comment_text_cannot_end_its_line() {
|
||||
assert_eq!(ps_comment_text("a\nshowpage\r%x"), "a showpage %x");
|
||||
}
|
||||
@@ -13,6 +13,9 @@ pub(super) fn clone_mapping(s: &mut Session, p: &Value, stroke: &Stroke, cmd: &s
|
||||
crate::presets::clone_source::mapping(s, p, (f.x, f.y), cmd)
|
||||
}
|
||||
|
||||
/// Most source pixels one clone sample may read (a 8192 x 8192 window); real strokes stay far below.
|
||||
const MAX_CLONE_SOURCE_PIXELS: u64 = 1 << 26;
|
||||
|
||||
/// Source pixels for destination `rect`: a translated read, or a bilinear resample when the
|
||||
/// clone source is scaled, rotated or flipped.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -41,7 +44,13 @@ pub(super) fn clone_sample(
|
||||
r.rect = rect;
|
||||
return Ok(r);
|
||||
}
|
||||
let src = read(map.source_rect(rect))?;
|
||||
// A small W/H scale makes the source window enormous for a bounded destination: refuse it
|
||||
// before the dense read allocates width x height x channels floats.
|
||||
let sr = map.source_rect(rect);
|
||||
if u64::from(sr.width()) * u64::from(sr.height()) > MAX_CLONE_SOURCE_PIXELS {
|
||||
return Err(bad(cmd, "the scaled clone source covers too large an area; raise the clone source's W/H or use a smaller brush"));
|
||||
}
|
||||
let src = read(sr)?;
|
||||
Ok(crate::presets::clone_source::resample(&src, rect, map, alpha_index(&surf.format())))
|
||||
}
|
||||
|
||||
|
||||
@@ -316,10 +316,11 @@ pub(super) fn dab_cmd(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
|
||||
let fmt = surf.format();
|
||||
let mut effect = tool.effect(fmt, stroke.brush.spacing);
|
||||
let mut sampler = all.then(|| AllLayers::new(pre, fmt));
|
||||
Ok(apply_dab_stroke(surf, &stroke, sel, lock, tool.neighborhood().halo(), |work, fp| match &mut sampler {
|
||||
apply_dab_stroke(surf, &stroke, sel, lock, tool.neighborhood().halo(), |work, fp| match &mut sampler {
|
||||
Some(all) => all.dab(work, fp, |w, f| effect(w, f)),
|
||||
None => effect(work, fp),
|
||||
}))
|
||||
})
|
||||
.map_err(|e| bad(cmd, e.to_string()))
|
||||
})?;
|
||||
let mut r = json!({ "damage": damage_json(dmg) });
|
||||
if from_live {
|
||||
|
||||
@@ -163,7 +163,7 @@ pub(super) fn run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if st.impressionist {
|
||||
// Halo is the dab footprint only: Impressionist jitters phase, it does not blur.
|
||||
let effect = st.impressionist_effect(surf.format());
|
||||
Ok(apply_dab_stroke(surf, &st.stroke, sel, lock, 0, effect))
|
||||
apply_dab_stroke(surf, &st.stroke, sel, lock, 0, effect).map_err(|e| bad(CMD, e.to_string()))
|
||||
} else {
|
||||
paint_aligned(surf, &st, sel, lock, CMD)
|
||||
}
|
||||
|
||||
@@ -67,6 +67,22 @@ fn periodic_clone_projection_is_disjoint_and_matches_pixel_modulo() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hugely_scaled_clone_source_is_refused_before_the_dense_read() {
|
||||
use super::clone::clone_sample;
|
||||
use super::sampling::sample_layers;
|
||||
use crate::presets::clone_source::Mapping;
|
||||
let s = session(32, 24, 8, "rgb");
|
||||
let d = s.active().unwrap();
|
||||
let id = d.active_layer.unwrap();
|
||||
let surf = d.doc.layer(id).unwrap().surface().unwrap();
|
||||
let which = sample_layers(&json!({"sampleLayer": "current"}), "paint.cloneStamp").unwrap();
|
||||
// 1000x: a 100x100 destination asks for a ~100000x100000 source window.
|
||||
let map = Mapping { source: (0.0, 0.0), anchor: (0.0, 0.0), m: [1000.0, 0.0, 0.0, 1000.0] };
|
||||
let r = clone_sample(&d.doc, Some(id), surf, which, Rect::new(0, 0, 100, 100), &map, false, "paint.cloneStamp");
|
||||
assert!(r.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn periodic_clone_preview_interpolates_across_transformed_source_seam() {
|
||||
use crate::presets::clone_source::Mapping;
|
||||
|
||||
@@ -99,7 +99,8 @@ pub(super) fn export_contents(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Ok(json!({"path": path, "fileName": name, "bytes": bytes.len(), "converted": false}));
|
||||
}
|
||||
let contents = decode_source(&name, &bytes)?;
|
||||
let r = photocraft_io::export(&contents, path, &Default::default()).map_err(|e| other(format!("can't export the contents as {}: {e}", base_name(path))))?;
|
||||
let r = photocraft_io::export(&contents, path, &photocraft_io::ExportOptions { read_linked_files: s.authorize.is_none(), ..Default::default() })
|
||||
.map_err(|e| other(format!("can't export the contents as {}: {e}", base_name(path))))?;
|
||||
crate::file_cmds::write_file(path, &r.bytes)?;
|
||||
Ok(json!({"path": path, "fileName": name, "bytes": r.bytes.len(), "converted": true, "warnings": r.warnings}))
|
||||
}
|
||||
|
||||
@@ -542,13 +542,13 @@ pub fn read_file(bytes: &[u8], format: Format, group: &str) -> std::result::Resu
|
||||
AseEntry::Swatch(s) => loose.extend(conv(s)),
|
||||
AseEntry::Group { name, swatches } => {
|
||||
let items: Vec<Swatch> = swatches.iter().filter_map(&mut conv).collect();
|
||||
let name = if name.trim().is_empty() { group.to_string() } else { clip(name.trim()) };
|
||||
let name = if name.trim().is_empty() { clip(group) } else { clip(name.trim()) };
|
||||
out.push(Group::new(&name, items));
|
||||
}
|
||||
}
|
||||
}
|
||||
if !loose.is_empty() || out.is_empty() {
|
||||
out.insert(0, Group::new(group, loose));
|
||||
out.insert(0, Group::new(&clip(group), loose));
|
||||
}
|
||||
if skipped > 0 {
|
||||
warnings.push(format!("{skipped} swatches in an unknown colour model were skipped"));
|
||||
|
||||
@@ -433,7 +433,7 @@ fn load_frames(path: &str, fmt: photocraft_color::PixelFormat, opts: &photocraft
|
||||
Ok(())
|
||||
};
|
||||
for f in &files {
|
||||
let bytes = std::fs::read(f).map_err(|e| EngineError::Other(format!("read `{}`: {e}", f.display())))?;
|
||||
let bytes = crate::allocation::read_file_within(f, max_footage_bytes).map_err(|e| EngineError::Other(format!("read `{}`: {e}", f.display())))?;
|
||||
let name = f.to_string_lossy();
|
||||
// A GIF (a still one is its only frame) or an animated WebP brings every frame.
|
||||
let animation = match photocraft_codecs::detect(&bytes) {
|
||||
|
||||
@@ -114,7 +114,12 @@ pub(super) fn quick_export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// WebP uses the regular exporter. Its optional quality is in the Photoshop-style
|
||||
// 0–12 save scale: invert that mapping so the codec receives the chosen 1–100.
|
||||
// Keeping quality absent preserves the historical lossless Quick Export behavior.
|
||||
let (wdoc, _, _) = web_document(&doc, &json!({}), &WebSettings { convert_to_srgb: prefs.convert_to_srgb, ..Default::default() })?;
|
||||
let st = WebSettings::from_params(&Value::Object(o.clone()), cmd)?;
|
||||
let (mut wdoc, _, _) = web_document(&doc, &json!({}), &st)?;
|
||||
// The regular exporter embeds the document's XMP and EXIF as they are: give it only
|
||||
// what the metadata choice keeps, as the Save for Web formats get.
|
||||
wdoc.metadata.xmp = web_xmp(&doc, st.metadata).map(std::sync::Arc::from);
|
||||
wdoc.metadata.exif = web_exif(&doc, st.metadata).map(|e| std::sync::Arc::new(e.to_vec()));
|
||||
let quality = if prefs.webp_lossless { None } else { Some((f64::from(prefs.webp_quality.clamp(1, 100)) - 1.0) * 12.0 / 99.0) };
|
||||
let warnings = crate::file_cmds::save_doc(&wdoc, &path, quality)?;
|
||||
crate::automate_cmds::fire_event(s, "export");
|
||||
|
||||
@@ -1396,6 +1396,25 @@ fn embed_color_profile_tags_an_untagged_document_srgb() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Quick Export as WebP goes through the regular exporter, which embeds a document's XMP and
|
||||
/// EXIF whole: the export preferences' metadata choice must still apply to it.
|
||||
#[test]
|
||||
fn quick_export_webp_keeps_only_the_chosen_metadata() {
|
||||
let dir = tmp("quick_webp_metadata");
|
||||
let mut s = session(8);
|
||||
s.execute("file.fileInfo", json!({"copyright": "© Example", "description": "secret notes"})).unwrap();
|
||||
let has = |b: &[u8], needle: &[u8]| b.windows(needle.len()).any(|w| w == needle);
|
||||
for (choice, lossless) in [("none", true), ("copyright", false)] {
|
||||
s.execute("file.export.exportPreferences", json!({"quickExportFormat": "png", "metadata": choice, "webpLossless": lossless})).unwrap();
|
||||
let path = format!("{dir}/{choice}.webp");
|
||||
s.execute("file.export.quickExport", json!({"path": path})).unwrap();
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
assert!(!has(&bytes, b"secret notes"), "{choice}: the description is not {choice}");
|
||||
assert_eq!(has(&bytes, b"Example"), choice == "copyright", "{choice}");
|
||||
}
|
||||
s.execute("prefs.reset", json!({"path": "export"})).unwrap();
|
||||
}
|
||||
|
||||
/// #5305: `folder` writes the whole image there under the document's own name, so an action
|
||||
/// recorded with the suggested name saves each document it is played on under that name; it is
|
||||
/// a destination, never a remembered setting.
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
//! Commands that expand a layer into dense buffers over its content bounds (or the canvas) refuse,
|
||||
//! before allocating, when those buffers would pass the working budget: a few distant tiles in a
|
||||
//! small document, or a huge empty canvas, would otherwise ask for terabytes.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use photocraft_doc::{LayerId, LayerMask};
|
||||
use photocraft_geom::Rect;
|
||||
use photocraft_raster::Surface;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
/// Two 10 px blocks two billion pixels apart: two stored tiles, trillions of pixels of bounds.
|
||||
fn distant_blocks(s: &Surface) -> Surface {
|
||||
let fmt = s.format();
|
||||
let mut out = Surface::with_default(fmt, &s.default_pixel());
|
||||
out.fill_rect(Rect::new(0, 0, 10, 10), &vec![1.0; fmt.channels()]);
|
||||
out.fill_rect(Rect::new(2_000_000_000, 2_000_000_000, 2_000_000_010, 2_000_000_010), &vec![1.0; fmt.channels()]);
|
||||
out
|
||||
}
|
||||
|
||||
/// A small document whose active layer holds [`distant_blocks`].
|
||||
fn sparse_session() -> (Session, LayerId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 64, "height": 64})).unwrap();
|
||||
let id = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap());
|
||||
let doc = Arc::make_mut(&mut s.active_mut().unwrap().doc);
|
||||
let surf = doc.layer_mut(id).unwrap().surface_mut().unwrap();
|
||||
*surf = distant_blocks(surf);
|
||||
(s, id)
|
||||
}
|
||||
|
||||
fn refused(s: &mut Session, cmd: &str, p: serde_json::Value) {
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let e = s.execute(cmd, p).unwrap_err().to_string();
|
||||
assert!(e.contains("working memory"), "{cmd}: {e}");
|
||||
assert!(Arc::ptr_eq(&before, &s.active().unwrap().doc), "{cmd} left the document as it was");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_layer_mask_over_distant_tiles_is_refused() {
|
||||
let (mut s, id) = sparse_session();
|
||||
Arc::make_mut(&mut s.active_mut().unwrap().doc).layer_mut(id).unwrap().mask = Some(LayerMask::reveal_all());
|
||||
refused(&mut s, "layer.layerMask.apply", json!({"layer": id.0}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shadows_highlights_over_distant_tiles_is_refused() {
|
||||
let (mut s, id) = sparse_session();
|
||||
refused(&mut s, "image.adjustments.shadowsHighlights", json!({"layer": id.0}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_size_without_distant_tiles_still_resamples() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 64, "height": 64, "background": "white"})).unwrap();
|
||||
s.execute("image.imageSize", json!({"width": 128, "height": 128})).unwrap();
|
||||
assert_eq!(s.active().unwrap().doc.size.width, 128);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn face_detection_on_a_huge_empty_canvas_is_refused() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 300_000, "height": 300_000, "background": "transparent"})).unwrap();
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
let e = s.execute("image.detectFaces", json!({"sampleAllLayers": false})).unwrap_err().to_string();
|
||||
assert!(e.contains("working memory"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multichannel_on_a_huge_empty_canvas_is_refused() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 300_000, "height": 300_000, "background": "transparent"})).unwrap();
|
||||
refused(&mut s, "image.mode.multichannel", json!({}));
|
||||
}
|
||||
|
||||
/// A quadtone keeps an f32 density and a stored plane for each of its four inks beside the
|
||||
/// flattened image: 52 B per pixel, past the budget at 15,000 × 15,000 px where one colour
|
||||
/// channel's 28 B would have passed.
|
||||
#[test]
|
||||
fn multichannel_counts_every_duotone_ink() {
|
||||
use photocraft_color::ColorMode;
|
||||
use photocraft_doc::{Duotone, DuotoneInk};
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 15_000, "height": 15_000, "background": "transparent"})).unwrap();
|
||||
let doc = Arc::make_mut(&mut s.active_mut().unwrap().doc);
|
||||
doc.mode = ColorMode::Duotone;
|
||||
doc.duotone = Some(Duotone { inks: (0..4).map(|i| DuotoneInk::new(format!("ink {i}"), [0.0; 3])).collect(), psd_raw: None });
|
||||
refused(&mut s, "image.mode.multichannel", json!({}));
|
||||
}
|
||||
@@ -37,6 +37,10 @@ pub enum EngineError {
|
||||
SourceChanged { name: String },
|
||||
#[error("{0}")]
|
||||
Other(String),
|
||||
/// A batch or droplet stopped at its nesting or shared playback-step limit. A batch whose
|
||||
/// step hits one fails that input instead of saving it unprocessed.
|
||||
#[error("{0}")]
|
||||
BatchLimit(String),
|
||||
/// A background job was cancelled (see [`jobs`]); nothing changed.
|
||||
#[error("cancelled")]
|
||||
Cancelled,
|
||||
|
||||
@@ -213,7 +213,7 @@ pub(crate) fn apply_filter_to_surface_in(
|
||||
}
|
||||
// Image › Adjustments recorded as smart filters (Levels, Curves, Shadows/Highlights… from PSD).
|
||||
if let Some(kind) = id.strip_prefix("image.adjustments.") {
|
||||
return Ok(crate::adjust_cmds::adjust_as_filter(kind, params, surf));
|
||||
return crate::adjust_cmds::adjust_as_filter(kind, params, surf);
|
||||
}
|
||||
// WebAssembly plug-in smart filters (plugin_cmds).
|
||||
if id == crate::plugin_cmds::RUN {
|
||||
|
||||
@@ -567,9 +567,13 @@ pub(crate) fn map_document(p: &Value) -> Option<&Value> {
|
||||
p.get("mapDocument").filter(|d| !d.is_null() && d.as_i64().is_none_or(|i| i >= 0))
|
||||
}
|
||||
|
||||
/// Largest displacement-map file read (the same cap as imported presets).
|
||||
const MAX_MAP_FILE_BYTES: u64 = 512 << 20;
|
||||
|
||||
/// Displace's map read from a file (flattened, or its `mapLayer`).
|
||||
fn map_from_path(path: &str, layer: Option<u64>) -> Result<Option<algo::Image>> {
|
||||
let bytes = std::fs::read(path).map_err(|e| EngineError::Other(format!("cannot read displacement map `{path}`: {e}")))?;
|
||||
let bytes =
|
||||
crate::allocation::read_file_within(path, MAX_MAP_FILE_BYTES).map_err(|e| EngineError::Other(format!("cannot read displacement map `{path}`: {e}")))?;
|
||||
let imported = crate::file_cmds::import(path, &bytes).map_err(|e| EngineError::Other(format!("cannot open displacement map `{path}`: {e}")))?;
|
||||
Ok(map_from_document(&imported, layer))
|
||||
}
|
||||
|
||||
@@ -372,6 +372,9 @@ mod tests;
|
||||
#[cfg(test)]
|
||||
mod fx_mode_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod dense_budget_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod brush_clear_background_tests;
|
||||
pub mod command_hints;
|
||||
|
||||
@@ -537,12 +537,16 @@ pub fn remap_surface(s: &Surface, map: impl Fn(i32, i32) -> (i32, i32)) -> Surfa
|
||||
let r = s.content_bounds();
|
||||
let mut out = Surface::with_default(s.format(), &s.default_pixel());
|
||||
let n = s.channels();
|
||||
let raw = s.read_region(r);
|
||||
let w = r.width() as usize;
|
||||
for (i, px) in raw.chunks_exact(n).enumerate() {
|
||||
let (x, y) = (r.x0 + (i % w) as i32, r.y0 + (i / w) as i32);
|
||||
let (nx, ny) = map(x, y);
|
||||
out.write_pixel(nx, ny, px);
|
||||
// Tile by tile: unstored pixels read as the default `out` already has, and the content
|
||||
// bounds of a sparse surface can span a grid of mostly nothing.
|
||||
for tr in s.tiles().map(|(c, _)| c.rect().intersect(&r)).filter(|t| !t.is_empty()) {
|
||||
let raw = s.read_region(tr);
|
||||
let w = tr.width() as usize;
|
||||
for (i, px) in raw.chunks_exact(n).enumerate() {
|
||||
let (x, y) = (tr.x0 + (i % w) as i32, tr.y0 + (i / w) as i32);
|
||||
let (nx, ny) = map(x, y);
|
||||
out.write_pixel(nx, ny, px);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -468,3 +468,17 @@ fn full_coverage_keeps_the_edit_over_huge_hdr_values() {
|
||||
assert_eq!(out[..3], [a, a, a], "{a} over {o}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Remapping walks the stored tiles, not the dense rectangle around them: two pixels a million
|
||||
/// pixels apart (a ~4 TB rectangle) flip to their mirrored places.
|
||||
#[test]
|
||||
fn remap_surface_of_distant_tiles_does_not_densify_the_gap() {
|
||||
let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::U8, true);
|
||||
let mut s = Surface::new(fmt);
|
||||
let (a, b) = ([1.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 1.0]);
|
||||
s.write_pixel(-500_000, 3, &from_rgba(&fmt, a));
|
||||
s.write_pixel(500_000, 9, &from_rgba(&fmt, b));
|
||||
let out = remap_surface(&s, |x, y| (-x - 1, y));
|
||||
assert_eq!(out.pixel(499_999, 3), from_rgba(&fmt, a));
|
||||
assert_eq!(out.pixel(-500_001, 9), from_rgba(&fmt, b));
|
||||
}
|
||||
@@ -222,7 +222,14 @@ impl PresetBackend for DirBackend {
|
||||
let path = self.path(name)?;
|
||||
let dir = path.parent().ok_or_else(|| format!("{name}: no parent directory"))?;
|
||||
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
photocraft_format::atomic_write(&path, bytes).map_err(|e| format!("{name}: {e}"))
|
||||
// The document writer follows a symlink to the file it points at on purpose; a preset
|
||||
// entry is managed by this store, and a link someone put there would carry the write
|
||||
// outside the directory the store confines itself to.
|
||||
if std::fs::symlink_metadata(&path).is_ok_and(|m| m.file_type().is_symlink()) {
|
||||
return Err(format!("{name}: a symbolic link is not a preset file"));
|
||||
}
|
||||
// No-follow: a link swapped in after the check above is replaced, never written through.
|
||||
photocraft_format::atomic_write_no_follow(&path, bytes).map_err(|e| format!("{name}: {e}"))
|
||||
}
|
||||
fn remove(&self, name: &str) -> Result<(), String> {
|
||||
match std::fs::remove_file(self.path(name)?) {
|
||||
|
||||
@@ -1136,3 +1136,21 @@ fn migration_preserves_duplicate_names_but_refuses_duplicate_ids() {
|
||||
assert!(mem.read(PATTERNS_FILE, 1 << 20).is_err());
|
||||
assert_eq!(mem.read(LEGACY_PATTERNS_FILE, MAX_PATTERNS_BYTES).unwrap(), old);
|
||||
}
|
||||
|
||||
/// A symlink planted among the presets must not carry a managed write to its target: the
|
||||
/// document writer follows links on purpose, the store confines itself to its directory.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_symlinked_preset_entry_is_refused_not_written_through() {
|
||||
let dir = TempDir::new("symlink");
|
||||
std::fs::create_dir_all(&dir.0).unwrap();
|
||||
let outside = dir.0.join("outside.txt");
|
||||
std::fs::write(&outside, b"victim").unwrap();
|
||||
std::os::unix::fs::symlink(&outside, dir.0.join("planted.json")).unwrap();
|
||||
let be = DirBackend::new(&dir.0);
|
||||
let e = be.write("planted.json", b"{}").unwrap_err();
|
||||
assert!(e.contains("symbolic link"), "{e}");
|
||||
assert_eq!(std::fs::read(&outside).unwrap(), b"victim");
|
||||
be.write("fresh.json", b"{}").unwrap();
|
||||
assert_eq!(be.read("fresh.json", 1024).unwrap(), b"{}");
|
||||
}
|
||||
@@ -435,5 +435,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
pub(crate) fn call(s: &mut Session, id: &str, p: Value) -> Result<Value> {
|
||||
let spec = crate::commands::find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
|
||||
(spec.enabled)(s).map_err(|why| EngineError::Disabled(id.to_string(), why))?;
|
||||
// A nested command answers to the session's authorization hook like a direct call.
|
||||
if let Some(gate) = s.authorize {
|
||||
gate(id, &p)?;
|
||||
}
|
||||
(spec.run)(s, &p)
|
||||
}
|
||||
@@ -995,3 +995,20 @@ fn export_presets_survive_a_presets_json_round_trip() {
|
||||
assert_eq!(restored.presets.export_presets[0].name, "Web");
|
||||
assert_eq!(restored.presets.export_presets[0].settings.format, "jpg");
|
||||
}
|
||||
|
||||
/// A nested command a preset command runs answers to the session's authorization hook: a denied one
|
||||
/// does not run, an ungated call still succeeds.
|
||||
#[test]
|
||||
fn nested_preset_commands_answer_to_the_authorization_gate() {
|
||||
fn deny_select_all(id: &str, _: &Value) -> crate::Result<()> {
|
||||
if id == "select.all" { Err(crate::EngineError::Other(format!("automation command `{id}` is disabled"))) } else { Ok(()) }
|
||||
}
|
||||
let mut s = session(8);
|
||||
s.authorize = Some(deny_select_all);
|
||||
let e = super::call(&mut s, "select.all", json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("is disabled"), "{e}");
|
||||
assert!(s.active().unwrap().doc.selection.is_none(), "the denied command did not run");
|
||||
s.authorize = None;
|
||||
super::call(&mut s, "select.all", json!({})).unwrap();
|
||||
assert!(s.active().unwrap().doc.selection.is_some());
|
||||
}
|
||||
@@ -157,7 +157,7 @@ fn smudge_pickup_matches_full_neighborhood_when_pressure_expands() {
|
||||
points: points.iter().map(|q| StrokePoint::new(q[0], q[1], q[2] as f32)).collect(),
|
||||
};
|
||||
let mut effect = Smudge::new(0.8, None, 40.0).with_alpha(Some(3));
|
||||
apply_dab_stroke(&mut expected, &stroke, None, lock, 40, |work, fp| effect.dab(work, fp));
|
||||
apply_dab_stroke(&mut expected, &stroke, None, lock, 40, |work, fp| effect.dab(work, fp)).unwrap();
|
||||
let bounds = s.active().unwrap().doc.bounds();
|
||||
let want = expected.read_region(bounds);
|
||||
s.execute("paint.smudge", params.clone()).unwrap();
|
||||
|
||||
@@ -236,7 +236,14 @@ pub fn atomic_write_with(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, byt
|
||||
|
||||
/// [`atomic_write_with`] reporting write progress (see [`atomic_write_progress`]).
|
||||
pub fn atomic_write_with_progress(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, bytes: &[u8], progress: &dyn Fn(f32)) -> io::Result<()> {
|
||||
replace_with(fs, retry, path, &mut |tmp| fs.write_new_progress(tmp, bytes, progress))
|
||||
replace_with(fs, retry, path, true, &mut |tmp| fs.write_new_progress(tmp, bytes, progress))
|
||||
}
|
||||
|
||||
/// [`atomic_write`] that never follows a symlink at `path`: a link there is replaced by the new
|
||||
/// file (the rename swaps the directory entry), so a link planted between a caller's own check
|
||||
/// and this write cannot carry it outside the folder (a store managing its own entries).
|
||||
pub fn atomic_write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
replace_with(&RealFs, RenameRetry::platform(), path, false, &mut |tmp| RealFs.write_new_progress(tmp, bytes, &|_| {}))
|
||||
}
|
||||
|
||||
/// [`atomic_write`] for a file serialized as it is written (#6607): `write` fills the temporary
|
||||
@@ -261,7 +268,7 @@ pub fn atomic_write_stream_progress(path: &Path, expected_len: u64, progress: &d
|
||||
|
||||
/// [`atomic_write_stream`] through an explicit file system and retry policy.
|
||||
pub fn atomic_write_stream_with(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, write: &mut StreamWriter<'_>) -> io::Result<()> {
|
||||
replace_with(fs, retry, path, &mut |tmp| fs.write_new_stream(tmp, write))
|
||||
replace_with(fs, retry, path, true, &mut |tmp| fs.write_new_stream(tmp, write))
|
||||
}
|
||||
|
||||
/// A stream reporting how far it has got (see [`atomic_write_stream_progress`]), every
|
||||
@@ -304,8 +311,8 @@ impl Seek for Progress<'_, '_> {
|
||||
|
||||
/// The steps every atomic write shares: `write_tmp` fills a fresh temporary file beside the
|
||||
/// target, which is then renamed over it.
|
||||
fn replace_with(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, write_tmp: &mut dyn FnMut(&Path) -> io::Result<()>) -> io::Result<()> {
|
||||
let target = resolve_symlink(path).map_err(|e| context(e, format!("cannot save {}", path.display())))?;
|
||||
fn replace_with(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, follow: bool, write_tmp: &mut dyn FnMut(&Path) -> io::Result<()>) -> io::Result<()> {
|
||||
let target = if follow { resolve_symlink(path).map_err(|e| context(e, format!("cannot save {}", path.display())))? } else { path.to_path_buf() };
|
||||
let name = target.file_name().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("{}: not a file path", path.display())))?;
|
||||
let dir = match target.parent() {
|
||||
Some(d) if !d.as_os_str().is_empty() => d.to_path_buf(),
|
||||
@@ -340,7 +347,10 @@ fn replace_with(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, write_tmp: &
|
||||
// default, its extended attributes, and its ACL. Best effort, and before the swap, so the
|
||||
// file the user ends up with never passes through a more permissive state.
|
||||
let replacing = target.exists();
|
||||
if replacing {
|
||||
// A link that is replaced rather than followed has nothing to carry over: reading the target's
|
||||
// attributes would open whatever it points at (a FIFO with no writer blocks there).
|
||||
let replaced_link = !follow && std::fs::symlink_metadata(&target).is_ok_and(|m| m.file_type().is_symlink());
|
||||
if replacing && !replaced_link {
|
||||
let _ = fs.copy_metadata(&target, &tmp);
|
||||
}
|
||||
|
||||
|
||||
@@ -51,6 +51,16 @@ const XATTR_CHUNK: usize = 4 << 10;
|
||||
/// Errors are the caller's to ignore: each piece is attempted on its own, and the first failure
|
||||
/// is returned only so a caller that wants to log one can.
|
||||
pub fn copy_metadata(from: &Path, to: &Path) -> io::Result<()> {
|
||||
// The group first: on Linux `chown` drops `security.capability`, so it must not follow the
|
||||
// extended-attribute copy.
|
||||
#[cfg(unix)]
|
||||
let metadata = std::fs::metadata(from);
|
||||
#[cfg(unix)]
|
||||
let group = match &metadata {
|
||||
Ok(m) => restore_group(m, to),
|
||||
Err(_) => Ok(true),
|
||||
};
|
||||
|
||||
// The permission bits go on last. Writing an attribute needs the destination open for
|
||||
// writing, and replacing a read-only (0444) file would copy that mode onto the temporary
|
||||
// file and then be unable to touch it again.
|
||||
@@ -72,9 +82,41 @@ pub fn copy_metadata(from: &Path, to: &Path) -> io::Result<()> {
|
||||
let acl = Ok(());
|
||||
|
||||
// A save over a 0600 file must not widen it to whatever the process default is.
|
||||
// A failed group lookup counts as "group not kept": the mode is still copied, minus the group bits.
|
||||
#[cfg(unix)]
|
||||
let permissions = metadata.and_then(|m| set_permissions_keeping_group(&m, to, group.as_ref().copied().unwrap_or(false)));
|
||||
#[cfg(not(unix))]
|
||||
let permissions = std::fs::metadata(from).and_then(|m| std::fs::set_permissions(to, m.permissions()));
|
||||
#[cfg(unix)]
|
||||
let group = group.map(drop);
|
||||
#[cfg(not(unix))]
|
||||
let group = Ok(());
|
||||
|
||||
attributes.and(acl).and(created).and(permissions)
|
||||
attributes.and(acl).and(created).and(group).and(permissions)
|
||||
}
|
||||
|
||||
/// Give `to` the group of the replaced file (`from`) when it has another: group bits are access
|
||||
/// for *that* group, so on a replacement owned by a different one (a setgid folder, say) they
|
||||
/// would hand the file to people the original never named. `false` when the group cannot be
|
||||
/// restored (the owner is not a member): [`set_permissions_keeping_group`] then leaves the group
|
||||
/// bits off.
|
||||
#[cfg(unix)]
|
||||
fn restore_group(from: &std::fs::Metadata, to: &Path) -> io::Result<bool> {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
Ok(std::fs::metadata(to)?.gid() == from.gid() || std::os::unix::fs::chown(to, None, Some(from.gid())).is_ok())
|
||||
}
|
||||
|
||||
/// Give `to` the permission bits of the replaced file (`from`), without the group bits when
|
||||
/// [`restore_group`] could not give it the original's group.
|
||||
#[cfg(unix)]
|
||||
fn set_permissions_keeping_group(from: &std::fs::Metadata, to: &Path, group_kept: bool) -> io::Result<()> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mut permissions = from.permissions();
|
||||
if !group_kept {
|
||||
permissions.set_mode(permissions.mode() & !0o070);
|
||||
}
|
||||
// After the chown, which clears setuid/setgid.
|
||||
std::fs::set_permissions(to, permissions)
|
||||
}
|
||||
|
||||
/// The creation time ("Created" in Finder) of the file being replaced, onto the file replacing
|
||||
|
||||
@@ -311,6 +311,34 @@ mod windows {
|
||||
}
|
||||
}
|
||||
|
||||
/// A replacement owned by another group does not give that group the file: the original's group
|
||||
/// is restored, or its group bits are dropped when it cannot be.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_replacement_in_another_group_does_not_widen_group_access() {
|
||||
use std::os::unix::fs::{MetadataExt, PermissionsExt};
|
||||
let d = TempDir::new("group");
|
||||
let original = d.join("a");
|
||||
let replacement = d.join("b");
|
||||
std::fs::write(&original, b"old").unwrap();
|
||||
std::fs::write(&replacement, b"new").unwrap();
|
||||
std::fs::set_permissions(&original, std::fs::Permissions::from_mode(0o660)).unwrap();
|
||||
// Another group this process belongs to; without one there is nothing to test.
|
||||
let status = std::fs::read_to_string("/proc/self/status").unwrap_or_default();
|
||||
let own = std::fs::metadata(&original).unwrap().gid();
|
||||
let groups: Vec<u32> =
|
||||
status.lines().find_map(|l| l.strip_prefix("Groups:")).unwrap_or_default().split_whitespace().filter_map(|g| g.parse().ok()).collect();
|
||||
// The original's group must be one this process can assign; a setgid parent can give it another.
|
||||
let Some(other) = groups.iter().copied().find(|g| *g != own).filter(|_| groups.contains(&own)) else {
|
||||
return;
|
||||
};
|
||||
std::os::unix::fs::chown(&replacement, None, Some(other)).unwrap();
|
||||
super::copy_metadata(&original, &replacement).unwrap();
|
||||
let after = std::fs::metadata(&replacement).unwrap();
|
||||
assert_eq!(after.gid(), own, "the original's group is restored");
|
||||
assert_eq!(after.permissions().mode() & 0o777, 0o660);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- MOVE_REPLACEMENT_2 ladder (#11178)
|
||||
//
|
||||
// The Windows `ReplaceFileW` cannot be made to return `ERROR_UNABLE_TO_MOVE_REPLACEMENT_2` on
|
||||
|
||||
@@ -496,6 +496,43 @@ fn writes_through_a_symlink() {
|
||||
assert_eq!(std::fs::read(&real).unwrap(), b"new");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn no_follow_replaces_a_symlink_and_leaves_its_target() {
|
||||
let d = TempDir::new("nofollow");
|
||||
let real = d.0.join("real.psd");
|
||||
let link = d.0.join("link.psd");
|
||||
std::fs::write(&real, ORIGINAL).unwrap();
|
||||
std::os::unix::fs::symlink(&real, &link).unwrap();
|
||||
crate::atomic::atomic_write_no_follow(&link, b"new").unwrap();
|
||||
assert!(!std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink());
|
||||
assert_eq!(std::fs::read(&link).unwrap(), b"new");
|
||||
assert_eq!(std::fs::read(&real).unwrap(), ORIGINAL);
|
||||
}
|
||||
|
||||
/// Replacing a link that points at a FIFO with no writer must not open the FIFO to copy its attributes.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn no_follow_never_opens_the_target_of_a_replaced_link() {
|
||||
let d = TempDir::new("nofollow-fifo");
|
||||
let fifo = d.0.join("pipe");
|
||||
let link = d.0.join("link.psd");
|
||||
let Ok(made) = std::process::Command::new("mkfifo").arg(&fifo).status() else { return };
|
||||
if !made.success() {
|
||||
return;
|
||||
}
|
||||
std::os::unix::fs::symlink(&fifo, &link).unwrap();
|
||||
// Run apart, so a regression fails the test instead of hanging it.
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let path = link.clone();
|
||||
std::thread::spawn(move || {
|
||||
let _ = tx.send(crate::atomic::atomic_write_no_follow(&path, b"new"));
|
||||
});
|
||||
let r = rx.recv_timeout(std::time::Duration::from_secs(20)).expect("the write does not block on the FIFO");
|
||||
r.unwrap();
|
||||
assert_eq!(std::fs::read(&link).unwrap(), b"new");
|
||||
}
|
||||
|
||||
/// #6605: saving onto a dangling symlink writes through to its target instead of replacing the
|
||||
/// link with a regular file, even when a folder on the way to the target doesn't exist yet.
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -33,6 +33,7 @@ mod finite;
|
||||
mod import_conversion;
|
||||
pub mod manifest;
|
||||
mod migrate;
|
||||
mod noreplace;
|
||||
pub mod read;
|
||||
mod store;
|
||||
pub mod zip;
|
||||
@@ -42,12 +43,13 @@ use std::path::Path;
|
||||
use photocraft_doc::Document;
|
||||
use photocraft_raster::Rgba8Image;
|
||||
|
||||
pub use atomic::{atomic_write, atomic_write_progress, atomic_write_stream, atomic_write_stream_progress};
|
||||
pub use atomic::{atomic_write, atomic_write_no_follow, atomic_write_progress, atomic_write_stream, atomic_write_stream_progress};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use autosave::RecoveryStore;
|
||||
pub use autosave::{Autosaver, RecoveryEntry, discard_recovery, list_recovery, recover};
|
||||
pub use convert::MAX_GROUP_DEPTH;
|
||||
pub use manifest::{FORMAT_VERSION, Manifest};
|
||||
pub use noreplace::{PublishNewError, rename_noreplace, write_noreplace};
|
||||
pub use read::{read_file, read_file_limited};
|
||||
pub use store::{ByteSource, DEFAULT_REVERIFY_BUDGET, PcraftWriter, SaveStats, read_entry};
|
||||
|
||||
|
||||
@@ -0,0 +1,378 @@
|
||||
//! Exclusive publication and rename for files in one directory.
|
||||
//!
|
||||
//! Prefer a native exclusive rename, with atomic hard-link publication when that operation is
|
||||
//! unavailable. The caller handles failures between separate file operations. Never replace
|
||||
//! an exclusive operation with an existence check followed by an overwriting rename.
|
||||
|
||||
use std::{
|
||||
ffi::OsStr,
|
||||
fs::{File, OpenOptions},
|
||||
io::{self, Write},
|
||||
path::{Path, PathBuf},
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
};
|
||||
|
||||
/// Publication failure distinguishes an unchanged destination from a published file whose cleanup or directory flush failed.
|
||||
///
|
||||
/// With `published: false` the destination is unchanged (for example `AlreadyExists` when another
|
||||
/// file got there first), so the caller may pick another name or retry. With `published: true` the
|
||||
/// destination already holds the complete, flushed bytes; only cleanup or the directory flush
|
||||
/// failed. Don't retry that as unpublished: a retry would fail with `AlreadyExists` against the
|
||||
/// caller's own file. Report the write as done but not confirmed durable instead.
|
||||
#[derive(Debug)]
|
||||
pub struct PublishNewError {
|
||||
/// Whether the destination name now exists with the complete bytes despite the error.
|
||||
pub published: bool,
|
||||
/// The failed operation: staging, writing or the rename when `published` is false; source
|
||||
/// cleanup or the directory flush when it is true.
|
||||
pub error: io::Error,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for PublishNewError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
if self.published { write!(f, "file published; completion unconfirmed: {}", self.error) } else { std::fmt::Display::fmt(&self.error, f) }
|
||||
}
|
||||
}
|
||||
impl std::error::Error for PublishNewError {}
|
||||
|
||||
/// Publish a complete, flushed file only if its destination is still absent.
|
||||
/// Uses an exclusive staging file beside the destination. The caller must use a stable parent
|
||||
/// directory where untrusted writers cannot replace the staging entry.
|
||||
/// On Windows, non-Unicode paths require a filesystem that supports hard links.
|
||||
pub fn write_noreplace(path: &Path, bytes: &[u8]) -> Result<(), PublishNewError> {
|
||||
use crate::atomic::{AtomicFs, RealFs};
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let before = |error| PublishNewError { published: false, error };
|
||||
let dir = path.parent().ok_or_else(|| before(io::Error::new(io::ErrorKind::InvalidInput, "missing publication directory")))?;
|
||||
// A bare filename still needs a real directory path for the final flush.
|
||||
let dir = if dir.as_os_str().is_empty() { Path::new(".") } else { dir };
|
||||
let name = path.file_name().ok_or_else(|| before(io::Error::new(io::ErrorKind::InvalidInput, "missing publication filename")))?;
|
||||
let (temp, mut file) = create_stage(dir, name, &NEXT).map_err(before)?;
|
||||
let written = file.write_all(bytes).and_then(|_| crate::atomic::sync_file(&file));
|
||||
drop(file);
|
||||
let published = written
|
||||
.map_err(before)
|
||||
.and_then(|()| move_noreplace(&temp, path, platform, |from, to| std::fs::hard_link(from, to), |path| std::fs::remove_file(path)));
|
||||
let published = published.map_err(|failure| retry_stage_cleanup(failure, &temp, |path| std::fs::remove_file(path)));
|
||||
finish_publication(published, || RealFs.sync_dir(dir))
|
||||
}
|
||||
|
||||
/// Retry removing the staging name after a failure; if that fails too, name the leftover
|
||||
/// staging file in the error so the caller can report or remove it.
|
||||
fn retry_stage_cleanup(failure: PublishNewError, temp: &Path, remove: impl FnOnce(&Path) -> io::Result<()>) -> PublishNewError {
|
||||
match remove(temp) {
|
||||
Err(cleanup) if cleanup.kind() != io::ErrorKind::NotFound => PublishNewError {
|
||||
published: failure.published,
|
||||
error: io::Error::new(failure.error.kind(), format!("{}; staging file {} remains", failure.error, temp.display())),
|
||||
},
|
||||
_ => failure,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a staging entry whose name cannot be the destination's native filename.
|
||||
fn create_stage(dir: &Path, destination: &OsStr, next: &AtomicU64) -> io::Result<(PathBuf, File)> {
|
||||
// Ignore a Windows stream suffix. A different last ASCII digit stays distinct across
|
||||
// case folding and trailing-dot/space normalization. An uppercase 8.3 staging name
|
||||
// already satisfies DOS short-name rules, so it needs no second name.
|
||||
let name = destination.as_encoded_bytes().split(|&byte| byte == b':').next().unwrap_or_default();
|
||||
let extension = if name.iter().rev().find(|byte| byte.is_ascii_digit()) == Some(&b'1') { "TM2" } else { "TM1" };
|
||||
for _ in 0..32 {
|
||||
let sequence = next.fetch_add(1, Ordering::Relaxed);
|
||||
let nonce = (u64::from(std::process::id()) << 8).wrapping_add(sequence) & 0xff_ffff;
|
||||
let temp = dir.join(format!("PC{nonce:06X}.{extension}"));
|
||||
match OpenOptions::new().write(true).create_new(true).open(&temp) {
|
||||
Ok(file) => return Ok((temp, file)),
|
||||
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
// Not `AlreadyExists`: that means the destination is taken, and callers may pick another name.
|
||||
Err(io::Error::other("no unused publication temp name"))
|
||||
}
|
||||
|
||||
/// Rename a file within one stable directory, refusing an existing destination atomically.
|
||||
/// Directories are not supported: the hard-link fallback cannot link them.
|
||||
/// The caller must ensure untrusted writers cannot replace the source entry.
|
||||
/// Unsupported rename primitives use a hard link followed by unlink, never an overwriting
|
||||
/// rename or cross-volume copy. If unlink fails, both names retain the same bytes and this
|
||||
/// returns an error, so the caller reports retirement as incomplete.
|
||||
/// The caller must flush the directory before reporting crash-durable migration completion;
|
||||
/// the existing `atomic::AtomicFs::sync_dir` provides that separately fallible operation.
|
||||
pub fn rename_noreplace(from: &Path, to: &Path) -> io::Result<()> {
|
||||
if from == to || from.parent().is_none() || from.parent() != to.parent() {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "no-replace retirement requires distinct names in one directory"));
|
||||
}
|
||||
move_noreplace(from, to, platform, |from, to| std::fs::hard_link(from, to), |path| std::fs::remove_file(path)).map_err(|failure| failure.error)
|
||||
}
|
||||
|
||||
/// Use fallback only when the exclusive rename primitive itself is unsupported.
|
||||
fn unsupported_rename(error: &io::Error) -> bool {
|
||||
if error.kind() == io::ErrorKind::Unsupported {
|
||||
return true;
|
||||
}
|
||||
#[cfg(unix)]
|
||||
if matches!(error.raw_os_error(), Some(code) if code == rustix::io::Errno::INVAL.raw_os_error() || code == rustix::io::Errno::NOSYS.raw_os_error()) {
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Linking claims an absent destination atomically; a later unlink failure is already published.
|
||||
fn move_noreplace(
|
||||
from: &Path,
|
||||
to: &Path,
|
||||
rename: impl FnOnce(&Path, &Path) -> io::Result<()>,
|
||||
link: impl FnOnce(&Path, &Path) -> io::Result<()>,
|
||||
remove: impl FnOnce(&Path) -> io::Result<()>,
|
||||
) -> Result<(), PublishNewError> {
|
||||
match rename(from, to) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(error) if unsupported_rename(&error) => {
|
||||
link(from, to).map_err(|error| PublishNewError { published: false, error })?;
|
||||
remove(from).map_err(|error| PublishNewError { published: true, error })
|
||||
}
|
||||
Err(error) => Err(PublishNewError { published: false, error }),
|
||||
}
|
||||
}
|
||||
|
||||
/// A successful name change is durable only after the separately fallible directory flush.
|
||||
fn finish_publication(result: Result<(), PublishNewError>, sync: impl FnOnce() -> io::Result<()>) -> Result<(), PublishNewError> {
|
||||
match result {
|
||||
Ok(()) => sync().map_err(|error| PublishNewError { published: true, error }),
|
||||
Err(failure) => {
|
||||
if failure.published {
|
||||
let _ = sync();
|
||||
}
|
||||
Err(failure)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Prefer the native exclusive rename when the Windows wrapper can represent both paths.
|
||||
#[cfg(windows)]
|
||||
fn platform(from: &Path, to: &Path) -> io::Result<()> {
|
||||
let (Some(from), Some(to)) = (from.to_str(), to.to_str()) else {
|
||||
// The existing hard-link fallback takes native paths, including unpaired surrogates.
|
||||
return Err(io::ErrorKind::Unsupported.into());
|
||||
};
|
||||
if from.contains('\0') || to.contains('\0') {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "file path contains a NUL character"));
|
||||
}
|
||||
// MoveFile (unlike MoveFileEx with REPLACE_EXISTING) fails if the destination exists.
|
||||
// The same-directory restriction above also excludes its cross-volume copy behavior.
|
||||
winsafe::MoveFile(from, to).map_err(|error| io::Error::from_raw_os_error(error.raw() as i32))
|
||||
}
|
||||
|
||||
#[cfg(all(unix, any(target_os = "linux", target_os = "android", target_os = "redox", target_vendor = "apple")))]
|
||||
fn platform(from: &Path, to: &Path) -> io::Result<()> {
|
||||
// rustix maps NOREPLACE to Linux renameat2 or Apple's RENAME_EXCL, without unsafe FFI here.
|
||||
rustix::fs::renameat_with(rustix::fs::CWD, from, rustix::fs::CWD, to, rustix::fs::RenameFlags::NOREPLACE).map_err(io::Error::from)
|
||||
}
|
||||
|
||||
#[cfg(not(any(windows, all(unix, any(target_os = "linux", target_os = "android", target_os = "redox", target_vendor = "apple")))))]
|
||||
fn platform(_from: &Path, _to: &Path) -> io::Result<()> {
|
||||
Err(io::Error::new(io::ErrorKind::Unsupported, "this platform has no supported no-replace retirement primitive"))
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
struct Dir(PathBuf);
|
||||
impl Dir {
|
||||
fn new() -> io::Result<Self> {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let path = std::env::temp_dir().join(format!("pc-noreplace-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
// Never clean a preexisting directory to make the fixture pass.
|
||||
std::fs::create_dir(&path)?;
|
||||
Ok(Self(path))
|
||||
}
|
||||
}
|
||||
impl Drop for Dir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retirement_moves_the_original_bytes_without_overwriting_a_backup() {
|
||||
let dir = Dir::new().unwrap();
|
||||
let from = dir.0.join("legacy");
|
||||
let to = dir.0.join("retained");
|
||||
std::fs::write(&from, b"exact original bytes").unwrap();
|
||||
std::fs::write(&to, b"existing backup").unwrap();
|
||||
assert_eq!(rename_noreplace(&from, &to).unwrap_err().kind(), io::ErrorKind::AlreadyExists);
|
||||
assert_eq!(std::fs::read(&from).unwrap(), b"exact original bytes");
|
||||
assert_eq!(std::fs::read(&to).unwrap(), b"existing backup");
|
||||
std::fs::remove_file(&to).unwrap();
|
||||
rename_noreplace(&from, &to).unwrap();
|
||||
assert!(!from.exists());
|
||||
assert_eq!(std::fs::read(&to).unwrap(), b"exact original bytes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retirement_refuses_same_name_and_missing_source_without_changing_existing_data() {
|
||||
let dir = Dir::new().unwrap();
|
||||
let from = dir.0.join("legacy");
|
||||
let to = dir.0.join("retained");
|
||||
std::fs::write(&to, b"existing backup").unwrap();
|
||||
assert!(rename_noreplace(&from, &to).is_err());
|
||||
assert_eq!(std::fs::read(&to).unwrap(), b"existing backup");
|
||||
assert_eq!(rename_noreplace(&to, &to).unwrap_err().kind(), io::ErrorKind::InvalidInput);
|
||||
assert_eq!(std::fs::read(&to).unwrap(), b"existing backup");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn publication_keeps_an_existing_destination_and_leaves_no_owned_temp() {
|
||||
let dir = Dir::new().unwrap();
|
||||
let path = dir.0.join("actions.atn");
|
||||
std::fs::write(&path, b"existing ATN").unwrap();
|
||||
let error = write_noreplace(&path, b"replacement").unwrap_err();
|
||||
assert!(!error.published);
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"existing ATN");
|
||||
assert_eq!(std::fs::read_dir(&dir.0).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn publication_creates_complete_bytes_then_removes_its_temp_name() {
|
||||
let dir = Dir::new().unwrap();
|
||||
let path = dir.0.join("actions.atn");
|
||||
write_noreplace(&path, b"complete ATN").unwrap();
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"complete ATN");
|
||||
assert_eq!(std::fs::read_dir(&dir.0).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
/// Even the first generated candidate cannot create the destination before publication.
|
||||
#[test]
|
||||
fn staging_does_not_create_a_destination_alias() {
|
||||
let dir = Dir::new().unwrap();
|
||||
let (first, file) = create_stage(&dir.0, OsStr::new("actions.atn"), &AtomicU64::new(0)).unwrap();
|
||||
drop(file);
|
||||
std::fs::remove_file(&first).unwrap();
|
||||
let name = first.file_name().unwrap().to_str().unwrap();
|
||||
for alias in [name.to_owned(), name.to_ascii_lowercase(), format!("{name}. "), format!("{name}::$DATA")] {
|
||||
let (temp, file) = create_stage(&dir.0, OsStr::new(&alias), &AtomicU64::new(0)).unwrap();
|
||||
assert_eq!(temp.extension(), Some(OsStr::new("TM2")), "{alias}");
|
||||
assert!(!first.try_exists().unwrap());
|
||||
drop(file);
|
||||
std::fs::remove_file(temp).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// The native-path fallback preserves both byte content and no-clobber behavior.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn publication_and_retirement_accept_native_windows_paths() {
|
||||
use std::{ffi::OsString, os::windows::ffi::OsStringExt};
|
||||
|
||||
let dir = Dir::new().unwrap();
|
||||
let path = |suffix: &str| {
|
||||
let mut name = OsString::from_wide(&[0xd800]);
|
||||
name.push(suffix);
|
||||
assert!(name.to_str().is_none());
|
||||
dir.0.join(name)
|
||||
};
|
||||
let from = path("-legacy");
|
||||
let to = path("-retained");
|
||||
write_noreplace(&from, b"original").unwrap();
|
||||
let error = write_noreplace(&from, b"other").unwrap_err();
|
||||
assert!(!error.published);
|
||||
assert_eq!(error.error.kind(), io::ErrorKind::AlreadyExists);
|
||||
std::fs::write(&to, b"existing").unwrap();
|
||||
assert_eq!(rename_noreplace(&from, &to).unwrap_err().kind(), io::ErrorKind::AlreadyExists);
|
||||
assert_eq!(std::fs::read(&from).unwrap(), b"original");
|
||||
assert_eq!(std::fs::read(&to).unwrap(), b"existing");
|
||||
std::fs::remove_file(&to).unwrap();
|
||||
rename_noreplace(&from, &to).unwrap();
|
||||
assert!(!from.try_exists().unwrap());
|
||||
assert_eq!(std::fs::read(&to).unwrap(), b"original");
|
||||
assert_eq!(std::fs::read_dir(&dir.0).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
/// An existing destination survives both the fallback and the native primitive unchanged.
|
||||
#[test]
|
||||
fn fallback_is_exclusive_and_moves_complete_bytes() {
|
||||
let dir = Dir::new().unwrap();
|
||||
let (from, to) = (dir.0.join("legacy"), dir.0.join("backup"));
|
||||
std::fs::write(&from, b"original").unwrap();
|
||||
std::fs::write(&to, b"existing").unwrap();
|
||||
let unsupported = |_: &Path, _: &Path| Err(io::Error::from(io::ErrorKind::Unsupported));
|
||||
let failed = move_noreplace(&from, &to, unsupported, |from, to| std::fs::hard_link(from, to), |path| std::fs::remove_file(path)).unwrap_err();
|
||||
assert!(!failed.published);
|
||||
assert_eq!(std::fs::read(&to).unwrap(), b"existing");
|
||||
assert_eq!(std::fs::read(&from).unwrap(), b"original");
|
||||
std::fs::remove_file(&to).unwrap();
|
||||
move_noreplace(&from, &to, unsupported, |from, to| std::fs::hard_link(from, to), |path| std::fs::remove_file(path)).unwrap();
|
||||
assert!(!from.exists());
|
||||
assert_eq!(std::fs::read(&to).unwrap(), b"original");
|
||||
}
|
||||
|
||||
/// A published destination cannot be called unchanged when source cleanup or fsync fails.
|
||||
#[test]
|
||||
fn fallback_unlink_and_directory_flush_failures_report_publication() {
|
||||
let dir = Dir::new().unwrap();
|
||||
let (from, to) = (dir.0.join("legacy"), dir.0.join("backup"));
|
||||
std::fs::write(&from, b"original").unwrap();
|
||||
let error = move_noreplace(
|
||||
&from,
|
||||
&to,
|
||||
|_, _| Err(io::ErrorKind::Unsupported.into()),
|
||||
|from, to| std::fs::hard_link(from, to),
|
||||
|_| Err(io::ErrorKind::PermissionDenied.into()),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(error.published);
|
||||
assert_eq!(std::fs::read(&from).unwrap(), b"original");
|
||||
assert_eq!(std::fs::read(&to).unwrap(), b"original");
|
||||
let error = finish_publication(Err(error), || Ok(())).unwrap_err();
|
||||
assert!(error.published);
|
||||
assert_eq!(error.error.kind(), io::ErrorKind::PermissionDenied);
|
||||
let error = finish_publication(Ok(()), || Err(io::ErrorKind::Other.into())).unwrap_err();
|
||||
assert!(error.published);
|
||||
assert_eq!(std::fs::read(&to).unwrap(), b"original");
|
||||
}
|
||||
|
||||
/// Running out of staging names must not look like a taken destination.
|
||||
#[test]
|
||||
fn staging_exhaustion_is_not_reported_as_an_existing_destination() {
|
||||
let dir = Dir::new().unwrap();
|
||||
let next = AtomicU64::new(0);
|
||||
for _ in 0..32 {
|
||||
drop(create_stage(&dir.0, OsStr::new("actions.atn"), &next).unwrap().1);
|
||||
}
|
||||
let error = create_stage(&dir.0, OsStr::new("actions.atn"), &AtomicU64::new(0)).unwrap_err();
|
||||
assert_ne!(error.kind(), io::ErrorKind::AlreadyExists);
|
||||
}
|
||||
|
||||
/// A staging name that cannot be removed is named in the error, keeping its kind and state.
|
||||
#[test]
|
||||
fn failed_staging_cleanup_names_the_leftover_file() {
|
||||
let temp = Path::new("PC000001.TM1");
|
||||
let failure = || PublishNewError { published: true, error: io::ErrorKind::PermissionDenied.into() };
|
||||
let error = retry_stage_cleanup(failure(), temp, |_| Err(io::ErrorKind::PermissionDenied.into()));
|
||||
assert!(error.published);
|
||||
assert_eq!(error.error.kind(), io::ErrorKind::PermissionDenied);
|
||||
assert!(error.error.to_string().contains("PC000001.TM1"), "{}", error.error);
|
||||
let error = retry_stage_cleanup(failure(), temp, |_| Ok(()));
|
||||
assert!(!error.error.to_string().contains("PC000001.TM1"));
|
||||
let error = retry_stage_cleanup(failure(), temp, |_| Err(io::ErrorKind::NotFound.into()));
|
||||
assert!(!error.error.to_string().contains("PC000001.TM1"));
|
||||
}
|
||||
|
||||
/// Ordinary rename failures must not trigger a second filesystem mutation route.
|
||||
#[test]
|
||||
fn ordinary_rename_errors_do_not_attempt_fallback() {
|
||||
for kind in [io::ErrorKind::AlreadyExists, io::ErrorKind::PermissionDenied, io::ErrorKind::NotFound] {
|
||||
let result = move_noreplace(
|
||||
Path::new("from"),
|
||||
Path::new("to"),
|
||||
|_, _| Err(kind.into()),
|
||||
|_, _| panic!("ordinary failure must not link"),
|
||||
|_| panic!("ordinary failure must not unlink"),
|
||||
);
|
||||
let error = result.unwrap_err();
|
||||
assert!(!error.published);
|
||||
assert_eq!(error.error.kind(), kind);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@
|
||||
//! that large with `ERROR_INVALID_PARAMETER` ("The parameter is incorrect", #375).
|
||||
//! - **A clear out-of-memory error.** The buffer is reserved up front with `try_reserve_exact`,
|
||||
//! and a file larger than the memory available says how much it needed. A file that grows past
|
||||
//! its stat length while being read grows the buffer with `try_reserve` too.
|
||||
//! its stat length while being read grows the buffer with fallible, bounded reservations too.
|
||||
//! - **A total limit.** No read returns more than [`MAX_OPEN_BYTES`], so a file that keeps growing
|
||||
//! while it is read cannot keep an open or a save from finishing.
|
||||
//!
|
||||
@@ -107,7 +107,10 @@ fn read_all_with(reader: &mut impl Read, size_hint: u64, chunk: usize, max: u64)
|
||||
return Err(too_large(max));
|
||||
}
|
||||
let room = usize::try_from(max - buf.len() as u64).unwrap_or(usize::MAX);
|
||||
buf.try_reserve(n.max(chunk).min(room)).map_err(|_| out_of_memory(needed))?;
|
||||
// Keep geometric growth for expanding files, capped at the caller's remaining budget.
|
||||
// try_reserve can double capacity even when the requested increment fits.
|
||||
let growth = n.max(chunk).max(buf.capacity()).min(room);
|
||||
buf.try_reserve_exact(growth).map_err(|_| out_of_memory(needed))?;
|
||||
buf.extend_from_slice(&probe[..n]);
|
||||
}
|
||||
let room = u64::try_from((buf.capacity() - buf.len()).min(chunk)).unwrap_or(u64::MAX);
|
||||
@@ -218,9 +221,12 @@ mod tests {
|
||||
#[test]
|
||||
fn growing_past_the_hint_stays_within_the_limit() {
|
||||
let data = vec![3u8; 4_000];
|
||||
let buf = read_all_with(&mut std::io::Cursor::new(&data), 0, 1 << 20, 5_000).unwrap();
|
||||
assert_eq!(buf, data);
|
||||
assert!(buf.capacity() <= 5_000, "reserved {}", buf.capacity());
|
||||
// A 3,000-byte initial capacity would double past the limit with try_reserve.
|
||||
for hint in [0, 3_000] {
|
||||
let buf = read_all_with(&mut std::io::Cursor::new(&data), hint, 1 << 20, 5_000).unwrap();
|
||||
assert_eq!(buf, data);
|
||||
assert!(buf.capacity() <= 5_000, "hint {hint}, reserved {}", buf.capacity());
|
||||
}
|
||||
let e = read_all_with(&mut std::io::Cursor::new(vec![3u8; 9_000]), 0, 1 << 20, 5_000).unwrap_err();
|
||||
assert_eq!(e.kind(), io::ErrorKind::FileTooLarge);
|
||||
}
|
||||
|
||||
@@ -119,11 +119,25 @@ impl Compressor {
|
||||
}
|
||||
}
|
||||
|
||||
/// Smallest zstd window [`decompress_bounded`] accepts, whatever the object's size.
|
||||
const MAX_ZSTD_WINDOW_FLOOR: u64 = 8 << 20;
|
||||
|
||||
/// Decodes a zstd frame of at most `max` bytes (`LimitExceeded` beyond). With `exact`, the
|
||||
/// decoded length must be exactly that (`Corrupt` otherwise).
|
||||
fn decompress_bounded(data: &[u8], max: usize, exact: Option<usize>, what: &str) -> Result<Vec<u8>> {
|
||||
let zstd = |e: &dyn std::fmt::Display| FormatError::corrupt(format!("{what}: zstd: {e}"));
|
||||
let mut dec = ruzstd::decoding::StreamingDecoder::new(data).map_err(|e| zstd(&e))?;
|
||||
// The decoder allocates its window up front, before any output reaches the length check:
|
||||
// hold it to what this object may decode to (our frames use a 128 KiB window; libzstd's
|
||||
// defaults stay under 8 MiB), not ruzstd's 128 MiB default.
|
||||
let window = u64::try_from(exact.unwrap_or(max)).unwrap_or(u64::MAX).max(MAX_ZSTD_WINDOW_FLOOR);
|
||||
let mut dec = match ruzstd::decoding::StreamingDecoder::new_with_max_window_size(data, window) {
|
||||
Ok(dec) => dec,
|
||||
// A well-formed frame asking for more window than this object may decode to is over its limit.
|
||||
Err(ruzstd::decoding::errors::FrameDecoderError::WindowSizeTooBig { requested, .. }) => {
|
||||
return Err(FormatError::LimitExceeded(format!("{what}: zstd window of {requested} bytes exceeds {window}")));
|
||||
}
|
||||
Err(e) => return Err(zstd(&e)),
|
||||
};
|
||||
let mut out = Vec::with_capacity(exact.unwrap_or(0).min(max).min(64 << 20));
|
||||
// `max` may be `usize::MAX`: one byte past it must not overflow.
|
||||
let limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(1);
|
||||
@@ -879,11 +893,12 @@ fn write_bundle_file(root: &Path, path: &Path, data: &[u8], fs: &dyn crate::atom
|
||||
validate_bundle_file(root, path)?;
|
||||
file.write_all(data)?;
|
||||
file.sync_all()?;
|
||||
drop(file);
|
||||
// Preserve the existing mode where possible, as the generic atomic writer does.
|
||||
// Preserve the existing mode where possible, as the generic atomic writer does: through
|
||||
// the open handle, so a staging entry swapped meanwhile is not what gets the mode.
|
||||
if let Ok(permissions) = std::fs::metadata(path).map(|m| m.permissions()) {
|
||||
let _ = std::fs::set_permissions(&tmp, permissions);
|
||||
let _ = file.set_permissions(permissions);
|
||||
}
|
||||
drop(file);
|
||||
// Recheck the parent and target just before publishing. rename replaces a symlink
|
||||
// itself, never its referent, even if one appears after this check.
|
||||
validate_bundle_file(root, path)?;
|
||||
@@ -1798,3 +1813,14 @@ fn an_incompressible_blob_at_its_limit_still_loads() {
|
||||
let e = spent(9 * data.len() as u64 + 1).blob_bounded(&hash, usize::MAX).unwrap_err();
|
||||
assert!(matches!(e, FormatError::LimitExceeded(ref m) if m.contains(&format!("exceeds {} bytes", data.len() - 1))), "{e}");
|
||||
}
|
||||
|
||||
/// A well-formed zstd frame that asks for a larger window than the object may decode to is over
|
||||
/// its limit, not damaged; one within the window decodes.
|
||||
#[test]
|
||||
fn a_zstd_window_past_the_limit_is_a_limit_not_corruption() {
|
||||
// Magic, a header with a window descriptor only (exponent 15: a 32 MiB window), then one empty last raw block.
|
||||
let frame = |window_descriptor: u8| [0x28, 0xB5, 0x2F, 0xFD, 0x00, window_descriptor, 0x01, 0x00, 0x00];
|
||||
let e = decompress_bounded(&frame(15 << 3), 100, None, "tile").unwrap_err();
|
||||
assert!(matches!(e, FormatError::LimitExceeded(_)), "{e}");
|
||||
assert_eq!(decompress_bounded(&frame(0), 100, None, "tile").unwrap(), Vec::<u8>::new());
|
||||
}
|
||||
Loaded 100 of 197 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user