Merge upstream main and preserve document-scoped canvas menus

This commit is contained in:
Andreas Haraminac committed 2026-11-14 16:06:47 +01:00
commit e0209f4b6e
2149 files changed
+227509 -200229

No files matched your search

+2 -2
View File
@@ -11,12 +11,12 @@ nextest-version = "0.9.150"
#
# GPU tests: each test is its own process here, so the in-process `gpu_lock()` mutexes no longer
# serialize them. Too many concurrent wgpu devices time out (`PollError: ... Wait timed out`), so
# this group caps them at 4.
# this group caps them at 4. scripts/ci-gpu-lavapipe.py reads this group's filters directly.
[test-groups]
gpu = { max-threads = 4 }
[[profile.default.overrides]]
filter = 'package(photocraft-gpu) | (package(photocraft-ui-egui) & (kind(test) | test(/canvas|gpu|mip|type_tool|background_redraw::|floating_group_titles|swap_arrow::tests::rendered_glyph/)))'
filter = 'package(photocraft-gpu) | (package(photocraft-ui-egui) & (kind(test) | test(/canvas|gpu|mip|type_tool|background_redraw::|floating_group_titles|swap_arrow::tests::rendered_glyph/))) | (package(photocraft-automation) & test(/^gpu_backend::/))'
test-group = 'gpu'
# CI (`--profile ci`, .github/workflows/ci.yml). Collect all failures in one integration run
+2
View File
@@ -0,0 +1,2 @@
# The craft-i18n pin: CI and the build read it as one SHA, so it stays LF everywhere (readers trim it too).
craft-i18n.rev text eol=lf
+134 -85
View File
@@ -68,6 +68,12 @@ concurrency:
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
# Git dependencies come from github.com/storytold, and Cargo.lock is complete and up to date.
git-sources:
if: github.event.action != 'labeled' || github.event.label.name == 'full-ci'
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
uses: storytold/craft-common-actions/.github/workflows/git-sources.yml@main
# Whether the Windows legs and the web build run. main, manual runs and PRs labelled `full-ci`
# get both. Other PRs get Windows when they touch code whose behaviour differs by platform: the
# app shell, UI, text and fonts, GPU, pen input, native saves, build scripts or the lockfile.
@@ -82,41 +88,14 @@ 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
persist-credentials: false
- name: Git dependencies come from storytold
run: |
set -euo pipefail
test -f Cargo.lock || { echo "Cargo.lock is missing"; exit 1; }
# Source replacement, patches and path overrides in cargo config never show up
# in Cargo.lock. Parsed rather than grepped: TOML has many spellings of one key.
# Cargo still reads the legacy .cargo/config.
python3 - <<'PY'
import os, sys, tomllib
for path in (".cargo/config", ".cargo/config.toml"):
if not os.path.exists(path):
continue
config = tomllib.load(open(path, "rb"))
replaced = [name for name, source in config.get("source", {}).items()
if isinstance(source, dict) and "replace-with" in source]
if replaced or "patch" in config or "paths" in config:
print(f"{path} replaces, patches or overrides a source")
sys.exit(1)
PY
# Fails when Cargo.lock is out of date with the manifests.
cargo metadata --locked --format-version 1 > /dev/null
python3 - <<'PY'
import sys, tomllib
lock = tomllib.load(open("Cargo.lock", "rb"))
bad = sorted({p["source"] for p in lock.get("package", [])
if p.get("source", "").startswith("git+")
and not p["source"].startswith("git+https://github.com/storytold/")})
if bad:
print("Git dependencies outside github.com/storytold:", *bad, sep="\n")
sys.exit(1)
PY
- id: pick
env:
EVENT: ${{ github.event_name }}
@@ -130,13 +109,14 @@ jobs:
fi
# The browser build (a fat-LTO wasm build) runs only when something it compiles or
# packages changed: the web app and its packaging, crate sources and manifests (the web
# build compiles nearly every crate), the workspace manifests and this workflow.
if git diff --name-only "$BASE" HEAD | grep -Eq '^(apps/photocraft-web(-boot)?/|packaging/web/|packaging/env\.sh$|crates/[^/]+/(src/|Cargo\.toml$|build\.rs$)|Cargo\.(toml|lock)$|rust-toolchain(\.toml)?$|\.github/workflows/ci\.yml$)'; then
# build compiles nearly every crate), the workspace manifests, the craft-i18n pin and this
# workflow.
if git diff --name-only "$BASE" HEAD | grep -Eq '^(apps/photocraft-web(-boot)?/|packaging/web/|packaging/env\.sh$|crates/[^/]+/(src/|Cargo\.toml$|build\.rs$)|Cargo\.(toml|lock)$|craft-i18n\.rev$|rust-toolchain(\.toml)?$|\.github/workflows/ci\.yml$)'; then
echo "web=true" >> "$GITHUB_OUTPUT"
else
echo "web=false" >> "$GITHUB_OUTPUT"
fi
if git diff --name-only "$BASE" HEAD | grep -Eq '^(apps/|crates/(ui-egui|text|gpu|tablet|heif|format)/|Cargo\.lock$|(.*/)?build\.rs$|\.github/workflows/ci\.yml$)'; then
if git diff --name-only "$BASE" HEAD | grep -Eq '^(apps/|crates/(ui-egui|text|gpu|tablet|heif|format)/|Cargo\.lock$|craft-i18n\.rev$|(.*/)?build\.rs$|\.github/workflows/ci\.yml$)'; then
echo "windows=true" >> "$GITHUB_OUTPUT"
else
echo "windows=false" >> "$GITHUB_OUTPUT"
@@ -151,7 +131,7 @@ jobs:
# egui/winit/rfd.
packages: >-
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev
libgtk-3-dev
libgtk-3-dev mesa-vulkan-drivers libvulkan1
# The tests build with the optional craft-fonts input (crates/text/build.rs), so the
# Japanese font tests that skip without it run. Same commit as release.yml.
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
@@ -162,15 +142,15 @@ jobs:
PHOTOCRAFT_NO_PRINT=1
LPDEST=photocraft-no-such-printer
timeout-minutes: 100
# fmt, clippy, layers, scorecard, tests, panic_hunt, doctests and the wasm32 check, with
# fmt, clippy, layers, panel-commands, scorecard, tests, panic_hunt, doctests and the wasm32 check, with
# `--locked --features heif`, then the missing-translations report (xtask/src/main.rs).
command: cargo xtask ci
command: python3 scripts/test-ci-gpu-lavapipe.py && cargo xtask ci && python3 scripts/ci-gpu-lavapipe.py
# Windows tests run as two legs in parallel: the unit tests and the integration tests. As one job
# they took ~28 min on the Windows runner; the legs take ~13 and ~15. Splitting the integration
# tests over a third runner (nextest --partition) saved ~2 min of wall time but cost ~7
# runner-minutes and one more Windows slot per PR. They stay outside the shared gate for sccache,
# which needs its own action step.
# runner-minutes and one more Windows slot per PR. Moving these legs into the shared gate is
# tracked by storytold/craft-common-actions#212.
windows:
needs: platforms
if: needs.platforms.outputs.windows == 'true'
@@ -182,10 +162,17 @@ jobs:
matrix:
part: [unit, integration]
env:
# Released sccache expands Cargo's response files and exceeds Windows' rustc spawn limit
# (#13543). Let Cargo handle long commands until a release includes mozilla/sccache#3026.
# The dependency rust-cache below stays enabled; only compiler caching is disabled.
RUSTC_WRAPPER: ""
# No debuginfo on Windows: writing PDBs for ~200 test binaries cost 2.2 of ~21 build minutes.
# A panic still names its file and line; only backtrace frames lose theirs (Linux keeps
# line-tables-only, so a backtrace with lines is one OS away).
CARGO_PROFILE_DEV_DEBUG: "0"
# The Windows compiler command line carries one -L path per built dependency; keep each
# target path short enough for CreateProcess when the graph is large.
CARGO_TARGET_DIR: 'D:\t'
# The all-language UI tests shape real Japanese, Chinese, Korean and Devanagari labels
# with kittest's strict `MissingGlyphPolicy::Panic`. A hosted Windows image has no
# guaranteed Japanese or Simplified Chinese system font, and egui 0.37 panics on a
@@ -196,6 +183,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
@@ -208,37 +199,25 @@ jobs:
path: craft-fonts
persist-credentials: false
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
# The translations at the commit in craft-i18n.rev, as the gate and release.yml embed them
# (sets CRAFT_I18N_DIR and CRAFT_I18N_REQUIRED=1).
- name: Check out craft-i18n
uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main
- 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
# sccache caches the workspace crates' compiled libraries, which rust-cache leaves out:
# warm, each Windows leg built 4.5 min faster. Like rust-cache, only main writes (PRs read
# 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
with:
version: v0.18.0
- name: Use sccache
env:
MAIN: ${{ github.ref == 'refs/heads/main' }}
run: |
echo "SCCACHE_GHA_ENABLED=true" >> "$GITHUB_ENV"
echo "RUSTC_WRAPPER=sccache" >> "$GITHUB_ENV"
if [ "$MAIN" != true ]; then echo "SCCACHE_GHA_RW_MODE=READ_ONLY" >> "$GITHUB_ENV"; fi
shell: bash
- name: Clippy
if: matrix.part == 'integration'
run: cargo clippy --workspace --all-targets --locked --features heif -- -D warnings
@@ -247,7 +226,7 @@ jobs:
if: matrix.part == 'integration'
run: cargo xtask layers
- uses: taiki-e/install-action@8cca0918f8471c33515202b73f56ab27f2bed283 # v2.87.29
- uses: step-security/taiki-e-install-action@76747d22a7567cc4438546a84f11bdf18e670ab8 # v2.87.32
with:
tool: [email protected]
@@ -284,10 +263,19 @@ 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
# The translations at the commit in craft-i18n.rev, as the gate and release.yml embed them
# (sets CRAFT_I18N_DIR and CRAFT_I18N_REQUIRED=1).
- name: Check out craft-i18n
uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main
- name: Install Linux build dependencies
uses: storytold/craft-common-actions/actions/install-apt-packages@main
with:
@@ -295,21 +283,23 @@ 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@8cca0918f8471c33515202b73f56ab27f2bed283 # v2.87.29
- uses: step-security/taiki-e-install-action@76747d22a7567cc4438546a84f11bdf18e670ab8 # v2.87.32
with:
tool: [email protected]
- name: Test without heif
run: cargo nextest run -p photocraft-heif -p photocraft-codecs -p photocraft-io --locked --profile ci
run: cargo nextest run -p photocraft-io --locked --profile ci
corpus:
if: github.event.action != 'labeled' || github.event.label.name == 'full-ci'
@@ -328,11 +318,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' }}
@@ -358,22 +354,33 @@ 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
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
# The translations at the commit in craft-i18n.rev, as the gate and release.yml embed them
# (sets CRAFT_I18N_DIR and CRAFT_I18N_REQUIRED=1).
- name: Check out craft-i18n
uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main
- 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' }}
cache-on-failure: true
# Checksum-verified, as in release.yml's web build.
- name: Install trunk
run: |
curl --proto '=https' -fsSL "https://github.com/trunk-rs/trunk/releases/download/v${TRUNK_VERSION}/trunk-x86_64-unknown-linux-gnu.tar.gz" \
| tar -xz -C "$HOME/.cargo/bin" trunk
trunk --version
uses: storytold/craft-common-actions/actions/install-trunk@main
with:
trunk-version: ${{ env.TRUNK_VERSION }}
# package.sh runs Trunk's release builds, validates relative URLs, cuts the wasm into
# parts, checks the 24 MiB per-file limit and exercises the packaging step release.yml uses.
- name: Build and verify browser release
@@ -429,11 +436,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
@@ -457,6 +470,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
@@ -466,8 +483,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
@@ -487,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
@@ -496,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: selection-morphology-perf
- name: Compare exact outputs and release timings on 36 MP
@@ -522,11 +547,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
@@ -546,11 +577,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
@@ -570,6 +607,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
@@ -579,8 +620,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
@@ -616,6 +659,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
@@ -630,7 +677,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:
+12 -9
View File
@@ -27,13 +27,16 @@ concurrency:
jobs:
build:
timeout-minutes: 15
name: mdBook build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
- name: Install mdBook
run: cargo install mdbook --version 0.4.52 --locked
- name: Build documentation
run: mdbook build book
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
with:
timeout-minutes: 15
# The book needs mdBook only: no craft-fonts, apt packages, wasm target or nextest.
craft-fonts-ref: ""
targets: ""
free-disk-space: false
# Prebuilt mdBook, the version cargo install built before.
tools: [email protected]
cache-version: v1-docs
command: mdbook build book
+28
View File
@@ -0,0 +1,28 @@
name: House rules
on:
push:
branches: [main]
paths:
- AGENTS.md
- CLAUDE.md
- .github/workflows/house-rules.yml
pull_request:
paths:
- AGENTS.md
- CLAUDE.md
- .github/workflows/house-rules.yml
workflow_dispatch:
permissions:
contents: read
concurrency:
group: house-rules-${{ github.ref }}
cancel-in-progress: true
jobs:
house-rules:
uses: storytold/craft-common-actions/.github/workflows/house-rules.yml@main
with:
rust: true
+12 -2
View File
@@ -5,9 +5,9 @@ name: Packaging lint
on:
push:
branches: [main, release]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", "docs/mcp.md", "docs/control-protocol.md"]
pull_request:
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", "docs/mcp.md", "docs/control-protocol.md"]
workflow_dispatch:
permissions:
@@ -21,12 +21,18 @@ jobs:
lint:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/packaging-lint.yml@main
with:
extra-checks-script: packaging/linux/package-docs-test.sh
verified-appimage-inputs:
timeout-minutes: 10
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
@@ -35,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
+8 -2
View File
@@ -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
+14
View File
@@ -1,6 +1,10 @@
name: Release
on:
# A nightly dry run on main: every release build except macOS, nothing signed or released
# (craft-common-actions release.yml `dry-run`). Finds release-only breakage before release day.
schedule:
- cron: "28 2 * * *"
push:
branches: [release]
workflow_dispatch:
@@ -19,14 +23,23 @@ concurrency:
cancel-in-progress: false
jobs:
# Regenerates contributors/contributors.json for the release commit; every build bundles it.
credits:
permissions:
contents: read
pull-requests: read
uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main
release:
needs: credits
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
with:
dry-run: ${{ github.event_name == 'schedule' }}
app-name: photocraft
app-title: PhotoCraft
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
version: ${{ inputs.version }}
contributors-artifact: ${{ needs.credits.outputs.artifact-name }}
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
@@ -42,3 +55,4 @@ jobs:
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
+61 -6
View File
@@ -1,3 +1,56 @@
<!-- craft-house-rules:start core source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=540e6cea75d12d0710c3dca89658328e81e508ecef102446ca5bb95b7c0b92bb -->
## House rules
These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy.
1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments.
2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish.
3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location.
4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix.
5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true.
6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why.
7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready.
8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception.
9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop.
10. **Keep secrets and personal details out** of the repository, logs and requests.
11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there.
12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it.
13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it.
14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit.
15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that.
<!-- craft-house-rules:end -->
<!-- craft-house-rules:start rust source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=387e0ccb4b49e567f60951d7d6fff7305054c89f43ad812b9993dc7c38528013 -->
## Rust Craft repositories
These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib).
1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix.
2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it.
3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository.
4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build.
5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md).
6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`.
## Licence allowlist
Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules.
- `ISC`
- `MIT`
- `BSD-2-Clause`
- `BSD-3-Clause`
- `Apache-2.0`
- `OFL-1.1`
- `Ubuntu-font-1.0`
- `Bitstream-Vera`
- `CC0-1.0`
- `CC-BY-4.0`
- `CC-BY-SA-4.0`
- `LicenseRef-Public-Domain`
`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so.
<!-- craft-house-rules:end -->
# AGENTS.md: guide for AI agents and contributors
PhotoCraft is an open-source, native, Photoshop-comparable image editor written in **Rust only** (no JavaScript or TypeScript). **No Tauri, Electron or webview shells:** the desktop app is native egui/eframe on wgpu, and the web build is the same Rust compiled to WebAssembly (trunk + wasm-bindgen). Never add Tauri (or any webview/JS UI framework) as a dependency, build step or packaging target. The product name is always written **PhotoCraft** (`{Function}Craft` in PascalCase, like its siblings ArtCraft, ArtCraftX, DesignCraft, VectorCraft, EffectCraft, FilmCraft, LightCraft, PdfCraft) in user-facing text: UI, window titles, About, installers, release names, docs prose. Machine names stay lowercase: crates (`photocraft-*`), binaries, file names, ids (`ai.storyteller.photocraft`). Shared Rust components live in [storytold/craft-libs](https://github.com/storytold/craft-libs) and are pinned by immutable git revision. UI libraries stay at L6. The goal is 1:1 Photoshop parity (same menus, shortcuts, behaviour and file fidelity) with better performance, and every feature drivable by agents. Read this file first, then `docs/`.
@@ -25,7 +78,7 @@ PhotoCraft is an open-source, native, Photoshop-comparable image editor written
```text
crates/
geom cms color raster L0 foundation (geometry, ICC colour management, pixel formats + blend math, COW tiles)
geom color raster L0 foundation (geometry, pixel formats + blend math, COW tiles); ICC colour management is craft-cms (craft-libs)
psd codecs L0 standalone format crates (no workspace deps; publishable)
tablet L0 standalone pen tablet input (macOS AppKit, X11 XInput2, Windows barrel button); the one isolated unsafe crate
doc L1 document model (layers, masks, adjustments, effects, smart objects: pure data)
@@ -43,7 +96,7 @@ apps/
xtask/ cargo xtask layers | wasm | ci | stats | corpus | test-corpus | parity | perf | scorecard
```
**Layering is enforced** by `cargo xtask layers`. A crate may depend only on lower layers. `psd`, `codecs` and `cms` depend on nothing in the workspace. Nothing below `ui-egui` may use egui, eframe, winit or rfd. A new crate must be registered in `xtask/src/layers.rs`.
**Layering is enforced** by `cargo xtask layers`. A crate may depend only on lower layers. `psd` and `codecs` depend on nothing in the workspace. Nothing below `ui-egui` may use egui, eframe, winit or rfd. A new crate must be registered in `xtask/src/layers.rs`.
## 3. Golden rules
@@ -61,16 +114,15 @@ People trust PhotoCraft with their work, and a crash loses it. A malformed file,
- **Enforced by clippy.** `clippy.toml` allows `unwrap`/`expect`/`panic` in tests only. Clean production crate roots carry `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`; every new workspace crate must also include `[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`.
1. **Everything is a command.** New user-visible behaviour = a command in the engine (`crates/engine/src/*_cmds.rs`, registered in `commands.rs`) with id, label, menu path, shortcut, params doc, `enabled` and `run`, plus tests. The UI, CLI, control channel and MCP all dispatch commands by id. Use the **exact id from `crates/ui-egui/src/menu_catalog.rs`** and the menu item goes live automatically. Only pure view/window state (zoom, panels, screen mode) belongs to the shell (`menus.rs` `UI_COMMANDS`).
2. **No format or colour assumptions.** Bit depth (8/16/32f) and colour model (RGB/Gray/CMYK/Lab…) are runtime data. Never introduce a `u8`-only pixel path in public APIs. Never assume sRGB: colour conversions go through `photocraft-cms` (`Transform`, `transform::cached`). Test at several depths.
2. **No format or colour assumptions.** Bit depth (8/16/32f) and colour model (RGB/Gray/CMYK/Lab…) are runtime data. Never introduce a `u8`-only pixel path in public APIs. Never assume sRGB: colour conversions go through `craft-cms` (`Transform`, `transform::cached`). Test at several depths.
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.
9. **Never panic on input** (see *Never crash* above). A command's `run` closure and anything it calls must return `Err`, never panic, for *any* params or document state: validate params, check bounds before indexing or dividing, and reject absurd sizes before allocating. The `panic_hunt` integration test fuzzes every command with adversarial params and must stay green.
10. **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic).
## 4. Picking work
@@ -96,6 +148,7 @@ When parity rises, raise `FLOOR` in `crates/ui-egui/src/parity.rs` (never lower
cargo test -p <crates you touched>
cargo clippy -p <crates> --all-targets -- -D warnings
cargo xtask layers
cargo xtask panel-commands # if you touched ui-egui: click handlers dispatch command ids (rule 1)
cargo xtask wasm # if you touched L0–L6
cargo xtask parity # if you added commands; commit the regenerated docs/parity-checklist.md
cargo test -p photocraft-engine --test panic_hunt -- --ignored # if you added/changed commands: no panic on adversarial input (Rule 9)
@@ -108,6 +161,8 @@ cargo xtask test-corpus # if you touched psd, io, codecs, compose, gpu, text
While iterating, run less and keep the full commands above as the final gate: `cargo test -p <crate> --lib --tests` skips the examples and doctests plain `cargo test` builds every time (ui-egui has 11 examples), and `cargo test -p <crate> --test <file>` runs one integration-test file. `cargo nextest run` runs tests in parallel across binaries; see `docs/development.md` › Faster test loops.
**MCP in tests and agent sessions: `photocraft-cli mcp --headless`.** Plain `photocraft-cli mcp` works in the open PhotoCraft window while the ArtCraft Launcher's agents switch is on, and then may start PhotoCraft on the developer's machine when it is closed. Scripts, tests and agents that want a session without a window pass `--headless` (or use `photocraft-cli serve`); a test that runs the CLI also gives it its own settings, launcher and flags folders (`PHOTOCRAFT_CONFIG_DIR`, `CRAFT_MCP_DIR`, `CRAFT_FLAGS_FILE`, as `crate::command()` in `apps/photocraft-cli/tests/it/main.rs` does). To drive the running app on purpose, use `--control` (`docs/development.md`).
**Test corpora.** Real-file corpora live in `corpus/` (gitignored, never committed), fetched at pinned commits and sha256-verified by `cargo xtask corpus --all`: our Photoshop- and GIMP-authored oracles from https://github.com/storytold/photocraft-corpus plus psd-tools, ag-psd and PngSuite from their upstreams. Pins: `xtask/src/corpus_pins.rs`. The corpus tests are opt-in (cargo feature `corpus`): plain `cargo test` skips them, and with the feature on a missing corpus fails ("run `cargo xtask corpus --all`"). `cargo xtask test-corpus` fetches and runs them all. CI always runs them (the `corpus` job, cached by pin). Never commit corpus files; new oracles go to photocraft-corpus (its `AGENTS.md`), then a pin bump here. Details: `docs/development.md` › Test corpora.
Commands must **never panic** on bad input (Rule 9): every `run` closure and the code it calls returns `Err`, not a panic, for any params or document state. New commands come with a graceful-failure test (empty/out-of-range/wrong-type params → `Err`, not a crash).
@@ -130,7 +185,7 @@ Then append a terse entry to `log/devlog.md` (what landed, numbers, what's still
- `docs/parity-checklist.md`: generated Photoshop menu coverage.
- `docs/scorecard.md`: generated scorecard (sources: `scorecard/*.toml`, `perf/budgets.toml`, `perf/baseline.json`, corpus floors, prefs audit).
- `docs/releasing.md`: cutting a release (`cargo xtask version`, the `release` branch), signing secrets, packaging scripts in `packaging/`.
- `plan/` (local, gitignored): research, parity plan, execution plan, estimates.
- `plan/` is an optional gitignored notebook (research, parity notes, estimates). Do not ask for it and do not stop when it is absent.
- `log/` (local, gitignored): the dev log.
## 8. Keeping the native format complete
+29 -31
View File
@@ -10,35 +10,17 @@ next to them.
| Path | Title | Author | Source | License |
|---|---|---|---|---|
| `crates/codecs/src/codecs/xpm/x11_colors.rs` | X11 `rgb.txt` color-name lookup table (normalized X.Org RGB values) | X.Org Foundation and X11 contributors | <https://cgit.freedesktop.org/xorg/app/rgb/tree/rgb.txt> | MIT (X.Org app/rgb) |
| `crates/ui-egui/src/i18n/el.tsv` | Greek UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `crates/ui-egui/src/i18n/de.tsv` | German UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `crates/ui-egui/src/i18n/es.tsv` | Spanish UI translations | @gorevyoneticisi; AI contributor: OpenAI Codex | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `crates/ui-egui/src/i18n/it.tsv` | Italian UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `crates/ui-egui/src/i18n/ko.tsv` | Korean UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `crates/ui-egui/src/i18n/nl.tsv` | Dutch UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `crates/ui-egui/src/i18n/pl.tsv` | Polish UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `crates/ui-egui/src/i18n/pt-br.tsv` | Brazilian Portuguese UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `crates/ui-egui/src/i18n/uk.tsv` | Ukrainian UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `crates/ui-egui/src/i18n/cs.tsv` | Czech UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `crates/ui-egui/src/i18n/hu.tsv` | Hungarian UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `crates/ui-egui/src/i18n/vi.tsv` | Vietnamese UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `crates/ui-egui/src/i18n/ar.tsv` | Arabic UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `crates/ui-egui/src/i18n/tr.tsv` | Turkish UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `crates/ui-egui/src/i18n/sr.tsv` | Serbian (Latin, Ekavian) UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `crates/ui-egui/src/i18n/ru.tsv` | Russian UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `crates/ui-egui/src/i18n/sv.tsv` | Swedish UI translations | @kler, @davvarn and PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `crates/ui-egui/src/i18n/fi.tsv` | Finnish UI translations | @Janiz-zzz, @metuuu and PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `crates/ui-egui/src/i18n/da.tsv` | Danish UI translations | @pechnikov2026-star and PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `crates/ui-egui/src/i18n/nb.tsv` | Norwegian Bokmål UI translations | @nikolainyegaard, @Bolla76 and PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `epaint_default_fonts::EGUI_ICONS` (build input; deflated into `OUT_DIR/egui_fonts/egui-icons.ttf.deflate`, registered by `crates/ui-egui/src/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) |
| Embedded at build time from storytold/craft-i18n `locales/<code>/common.tsv` and `locales/<code>/photocraft.tsv` (revision in [`craft-i18n.rev`](craft-i18n.rev)) | UI translations (all languages) | craft-i18n and PhotoCraft contributors; per-language credits and provenance in [craft-i18n's ATTRIBUTION.md](https://github.com/storytold/craft-i18n/blob/main/ATTRIBUTION.md) | <https://github.com/storytold/craft-i18n> | MIT OR Apache-2.0; Copyright (c) 2026 ArtCraft Team and the craft-i18n contributors; notice in [NOTICE](NOTICE) |
| `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`, `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` (113 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/*.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` (117 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,zoom-out}.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 |
| `assets/icons/spirit-level.svg` | Straighten tool glyph: a spirit level with its vial and bubble under a dotted arc | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/sampler.svg` | Color Sampler tool glyph: a target reticle marking a sampled pixel | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/font-similar.svg`, `assets/icons/font-variable.svg` | Font menu filter glyphs: two waves (Show Similar Fonts) and a T over a slider (Show Variable Fonts), drawn on the 24 px icon grid | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/convert-point.svg` | Convert Point tool glyph: an angle with a square anchor on its apex, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
@@ -50,12 +32,14 @@ next to them.
| `assets/icons/marquee-row.svg`, `assets/icons/marquee-column.svg` | Single Row and Single Column Marquee tool glyphs: a dashed row (column) between two edge bars, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/clip-below.svg`, `assets/icons/clip-release.svg` | Clipping-mask cursors (⌥ over the line between two layers): a hooked arrow onto the layer below; the same with a small "no" badge to release | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/layer-mask.svg`, `assets/icons/adjustment-layer.svg` | Layers panel footer glyphs: Add a mask (a frame around a solid disc) and New Fill or Adjustment Layer (a circle, one half solid), drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/vertical-align-{top,middle,bottom}.svg` | Type options-bar alignment glyphs for vertical text: three columns hanging from a top line, centred on a middle line, or standing on a bottom line, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/align-edge-*.svg`, `assets/icons/distribute-*.svg` | Move tool options-bar glyphs: Align (six edges/centres) and Distribute (edges, centres, spacing), a guide line or edge lines with bars, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/ellipse-dashed.svg` | Elliptical Marquee tool glyph: a dashed horizontal ellipse, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/frame-placeholder.svg` | Frame tool glyph: an empty placeholder frame, crossed corner to corner | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/gradient.svg` | Gradient tool glyph: a rounded rectangle filled with a left-to-right linear ramp, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/eraser-background.svg`, `assets/icons/eraser-magic.svg` | Background Eraser and Magic Eraser tool glyphs: Lucide `eraser` plus added marks | Lucide Icons and Contributors; marks by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/eraser.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/brush-replace.svg` | Color Replacement tool glyph: Lucide `brush` plus two swap arrows | Lucide Icons and Contributors; arrows by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/brush.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/history-brush.svg` | History Brush tool glyph: Lucide `brush` plus counter-clockwise history rewind arrow | Lucide Icons and Contributors; arrow by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/brush.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/quick-selection.svg` | Quick Selection tool glyph: Lucide `brush`, scaled to 70%, inside a dashed upright rounded "C" selection | Lucide Icons and Contributors; selection by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/brush.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/bandage-sparkle.svg` | Remove tool glyph: Lucide `bandage` moved down, plus a sparkle mark | Lucide Icons and Contributors; mark by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/bandage.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/direct-select.svg` | Direct Selection tool glyph: Lucide `mouse-pointer-2` plus an anchor square | Lucide Icons and Contributors; square by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/mouse-pointer-2.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
@@ -65,7 +49,6 @@ next to them.
| `assets/icons/symmetry-{vertical,horizontal,dual,diagonal}.svg` | Painting symmetry axis glyphs | @shorbank | Original work; supplied SVG line geometry centred on a common square canvas, stroke adjusted to match the painting-symmetry glyph | MIT OR Apache-2.0, [`assets/icons/LICENSE-symmetry-axes.txt`](assets/icons/LICENSE-symmetry-axes.txt) |
| `assets/icons/lasso-magnetic.svg` | Magnetic Lasso tool glyph, adapted from "Magnetic Lasso Tool" (redrawn on the 24 px toolbar grid) | Lil' Seal (Noun Project); adapted by PhotoCraft contributors | <https://thenounproject.com/icon/magnetic-lasso-tool-177513/> | CC BY 3.0, [`assets/icons/LICENSE-noun-magnetic-lasso.txt`](assets/icons/LICENSE-noun-magnetic-lasso.txt) |
| `assets/dict/en_US-scowl-50.txt.gz` | English word list for Check Spelling (SCOWL 2020.12.07, size 50, en_US; 72,403 words) | Kevin Atkinson and the SCOWL contributors | <http://wordlist.aspell.net/> | SCOWL license (permissive, keep the notice), [`assets/dict/LICENSE-SCOWL.txt`](assets/dict/LICENSE-SCOWL.txt), which also has the build recipe |
| `crates/cms/profiles/photocraft-coated-cmyk.icc` | PhotoCraft Coated CMYK (synthetic) ICC profile | PhotoCraft contributors (generated by `photocraft-cms`, `src/synth.rs`) | Original work, see [`crates/cms/README.md`](crates/cms/README.md) | CC0-1.0 |
| `assets/app-icon/` (all files) | PhotoCraft app icon (nine-tailed kitsune) | The project owner (drawn in ArtCraft, vectorised) | Original work, see [`assets/app-icon/README.md`](assets/app-icon/README.md) | MIT OR Apache-2.0, [`assets/app-icon/LICENSE.txt`](assets/app-icon/LICENSE.txt) |
| `packaging/macos/dmg/` (all files) | PhotoCraft DMG window background and layout | @XusBadia, from the PhotoCraft app icon | Original work, see [`packaging/macos/dmg/README.md`](packaging/macos/dmg/README.md) | MIT OR Apache-2.0, like the code |
| `crates/ui-egui/src/theme.rs` (Solarized Dark palette) | Solarized colour scheme used by the Solarized Dark theme | Ethan Schoonover | <https://ethanschoonover.com/solarized/> | MIT, [`LICENSE-solarized.txt`](crates/ui-egui/src/LICENSE-solarized.txt) |
@@ -86,9 +69,10 @@ from it is committed here. Per-file authors, sources and licences:
| Shippori Mincho Regular (FONTDASU) | Japanese serif Type fallback (desktop) | SIL OFL 1.1, shipped as `OFL-shippori-mincho.txt` |
| BIZ UDMincho Regular (Morisawa) | Japanese serif Type fallback (desktop) | SIL OFL 1.1, shipped as `OFL-biz-ud-mincho.txt` |
The other built-in ICC profiles and the generated LUT looks are produced by code at runtime
(`crates/cms/src/builtin.rs`, `crates/cms/src/lutfile.rs`) and dedicated to the public domain
(CC0-1.0); they are not separate files.
The built-in ICC profiles and the generated LUT looks come from `craft-cms`
([storytold/craft-libs](https://github.com/storytold/craft-libs/tree/main/crates/cms)): the PhotoCraft Coated CMYK profile is a file there
(its `ATTRIBUTION.md`), the others are produced by code at runtime (`src/builtin.rs`,
`src/lutfile.rs`). All are dedicated to the public domain (CC0-1.0).
## Documentation and README
@@ -96,11 +80,12 @@ 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/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/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` |
| `docs/images/clone-source/*.png` | Clone source opacity/flow, cross-document and source-edge previews, and offset readouts | PhotoCraft contributors | Original synthetic red shapes rendered offscreen with the `snapshot` example; adjacent capture scripts and README | MIT OR Apache-2.0 |
| `docs/images/multi-channel-editing/{curves,curves-choices,levels,drawing,mask-view-before,mask-view-after}.png` | Selected colour channel editing (synthetic gradient) | @hidoba | Original synthetic gradient rendered with the offscreen `snapshot` example; adjacent JSON scripts | MIT OR Apache-2.0, adjacent `LICENSE-MIT` and `LICENSE-APACHE` |
| `docs/images/multi-channel-editing/great-wave.jpg`, `rgb.png`, `cmyk.png`, `lab.png`, `gallery-channel-preview-{before,after}.png` | *The Great Wave off Kanagawa*, c. 1830–1832, and PhotoCraft channel-selection captures | Katsushika Hokusai (artwork); PhotoCraft contributors (UI) | [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Tsunami_by_hokusai_19th_century.jpg), Metropolitan Museum reproduction; adjacent JSON capture scripts | Public domain artwork (PD-Art), adjacent `LICENSE-PUBLIC-DOMAIN.txt`; UI/scripts MIT OR Apache-2.0 |
@@ -146,7 +131,7 @@ Files copied into `corpus/` by hand (tiff, exr, raw) must be MIT, BSD or CC0.
| Path | Title | Author | Source | License |
|---|---|---|---|---|
| `crates/psd/tests/fixtures/atn/*.atn` | Independently encoded ATN version-16 and version-12 parser fixtures | PhotoCraft contributors (version-12 files: @yoriswind) | Original synthetic test data; wire layout documented in `crates/psd/src/atn.rs`; provenance in the adjacent README | MIT OR Apache-2.0 |
| `crates/engine/tests/fixtures/atn/v12-commands.atn` | Independently encoded ATN version-12 parser fixture (Gaussian Blur, Levels, Select All, Make Layer; 404 bytes, sha256 `451958b686da9aab45e65ae902c86333b7149d72021c21904e3aae8e39eb77cb`), copied from the PSD crate's fixtures, which now live in craft-libs' `craft-psd` | PhotoCraft contributors (@yoriswind) | Original synthetic test data | MIT OR Apache-2.0 |
## Embedded-vector editor source
@@ -156,3 +141,16 @@ are adapted from Skyfuller1303’s MIT OR Apache-2.0 implementation in
`897f20072762fdf0eb688adcdb8d8cda7b38ce66`. Don Omondi’s embedded AI/PDF/EPS
extension and current-main integration build on that source. Clipboard and unrelated
Shape Tools changes from that branch are not included.
## Assets bundled by the PDF reader dependency (craft-pdf)
PhotoCraft imports PDF pages through `craft-pdf`, pinned to the craft-libs revision
`c5a1cbfb5f9049f9270955caffb5bee5997aebf7`. The renderer vendors Hayro and the assets below;
they ship inside the dependency rather than being copied into this repository. PDFium is no
longer used or shipped.
| Crate / file | Author | Source | Licence | Use |
| --- | --- | --- | --- | --- |
| `hayro-interpret 0.7.0 / assets/Foxit*.pfb` (13 standard-14 font files) | Foxit Software Inc. / PDFium Authors | <https://github.com/storytold/craft-libs/tree/c5a1cbfb5f9049f9270955caffb5bee5997aebf7/vendor/hayro-interpret/assets> | BSD-3-Clause | Renders non-embedded standard-14 PDF fonts |
| `hayro-interpret 0.7.0 / assets/CGATS001Compat-v2-micro.icc` | Clinton Ingram (saucecontrol/Compact-ICC-Profiles) | <https://github.com/storytold/craft-libs/tree/c5a1cbfb5f9049f9270955caffb5bee5997aebf7/vendor/hayro-interpret/assets> | CC0-1.0 | Default CMYK colour conversion |
| `hayro-cmap 0.1.0 / assets/cmaps.brotli` | Adobe | <https://github.com/storytold/craft-libs/tree/c5a1cbfb5f9049f9270955caffb5bee5997aebf7/vendor/hayro-cmap/assets> | BSD-3-Clause | Character-code mapping for CJK PDFs |
Generated
+1054 -558
View File
File diff suppressed because it is too large. Load diff
+47 -16
View File
@@ -4,24 +4,30 @@ members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/photocraft", "apps/photocraft-cli", "xtask"]
[workspace.package]
version = "0.20.1"
version = "0.23.1"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
[workspace.dependencies]
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["serde"] }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3", features = ["serde"] }
# Feature flags shared with the launcher and the other Craft apps (craft-libs#1118, #1119).
craft-flags = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
# The ArtCraft Launcher's agents switch and app list, shared with the launcher, the MCP gateway and
# every Craft app (storytold/craft-ai-integrations#195). Pinned to the head of
# storytold/craft-ai-integrations#197 until it merges.
craft-ai-agents = { git = "https://github.com/storytold/craft-ai-integrations", rev = "35e0352666a117407d62230a6c6c2366f3e21a3b" }
# internal
photocraft-geom = { path = "crates/geom" }
photocraft-color = { path = "crates/color" }
photocraft-cms = { path = "crates/cms" }
photocraft-raster = { path = "crates/raster" }
photocraft-doc = { path = "crates/doc" }
photocraft-ops = { path = "crates/ops" }
photocraft-psd = { path = "crates/psd" }
photocraft-codecs = { path = "crates/codecs" }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] }
photocraft-raw = { path = "crates/raw" }
photocraft-affinity = { path = "crates/affinity" }
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
photocraft-compose = { path = "crates/compose" }
photocraft-gpu = { path = "crates/gpu" }
photocraft-paint = { path = "crates/paint" }
@@ -39,12 +45,32 @@ photocraft-tablet = { path = "crates/tablet" }
photocraft-ipp = { path = "crates/ipp" }
# external
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "b8f7d93b00dfb8f172938f3d2d796ae62dcfe123" }
# ICC colour management: the shared crate (replaces crates/cms; craft-libs#779).
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
# HEIC/HEIF: the shared decoder (replaces crates/heif; craft-libs#784).
craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3", features = ["raster", "write-raster"] }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3", features = ["tree-render", "tree-render-system-fonts"] }
craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
# 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 = "e2dc681a3" }
# 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 = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e2dc681a3", features = ["egui"] }
thiserror = "2"
serde = { version = "1", features = ["derive", "rc"] }
serde_json = "1"
@@ -130,11 +156,11 @@ strip = "debuginfo"
opt-level = "s"
# Decoding and rasterizing keep their speed.
[profile.wasm-release.package.photocraft-codecs]
[profile.wasm-release.package.craft-image-codecs]
opt-level = "s"
[profile.wasm-release.package.photocraft-raw]
opt-level = "s"
[profile.wasm-release.package.photocraft-heif]
[profile.wasm-release.package.craft-heif]
opt-level = "s"
[profile.wasm-release.package.photocraft-vector]
opt-level = "s"
@@ -144,11 +170,11 @@ opt-level = "s"
# (runs when a pipeline is created). "z" keeps the wasm well under the size gate.
[profile.wasm-release.package.photocraft-doc]
opt-level = "z"
[profile.wasm-release.package.photocraft-psd]
[profile.wasm-release.package.craft-psd]
opt-level = "z"
[profile.wasm-release.package.photocraft-format]
opt-level = "z"
[profile.wasm-release.package.photocraft-affinity]
[profile.wasm-release.package.craft-affinity]
opt-level = "z"
[profile.wasm-release.package.serde_json]
opt-level = "z"
@@ -177,7 +203,7 @@ opt-level = "z"
opt-level = 3
[profile.wasm-release.package.photocraft-color]
opt-level = 3
[profile.wasm-release.package.photocraft-cms]
[profile.wasm-release.package.craft-cms]
opt-level = "z"
[profile.wasm-release.package.photocraft-compose]
opt-level = "z"
@@ -203,3 +229,8 @@ eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc79968157
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
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 = "e2dc681a3" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
+11 -2
View File
@@ -33,6 +33,16 @@ RUN set -eu; \
trunk --version
WORKDIR /src
# The interface translations at the commit in craft-i18n.rev (crates/ui-egui/build.rs), as CI and
# releases embed them; without them the build would be English only.
COPY craft-i18n.rev ./
RUN set -eu; \
rev="$(tr -d '[:space:]' < craft-i18n.rev)"; \
mkdir -p /opt/craft-i18n; \
curl --proto '=https' -fsSL --retry 3 -A Photocraft-dev "https://codeload.github.com/storytold/craft-i18n/tar.gz/$rev" \
| tar -xz --strip-components=1 -C /opt/craft-i18n; \
test -d /opt/craft-i18n/locales
ENV CRAFT_I18N_DIR=/opt/craft-i18n CRAFT_I18N_REQUIRED=1
COPY . .
WORKDIR /src/apps/photocraft-web
# Docker serving has no static-host per-file size cap. Thin LTO uses less build
@@ -57,8 +67,7 @@ FROM nginx:${NGINX_VERSION} AS runtime
COPY packaging/web/nginx.conf /etc/nginx/nginx.conf
COPY --from=builder /src/dist/web/ /usr/share/nginx/html/
COPY LICENSE-MIT LICENSE-APACHE NOTICE ATTRIBUTION.md /usr/share/nginx/html/
COPY assets/fonts/OFL-*.txt assets/icons/LICENSE-*.txt assets/dict/LICENSE-*.txt \
crates/ui-egui/src/i18n/LICENSE-translations.txt /usr/share/nginx/html/licenses/
COPY assets/fonts/OFL-*.txt assets/icons/LICENSE-*.txt assets/dict/LICENSE-*.txt /usr/share/nginx/html/licenses/
# Bypass the stock entrypoint: this configuration needs no runtime rewriting.
USER nginx
EXPOSE 8080
+52 -3
View File
@@ -17,17 +17,18 @@ JetBrains Mono font (assets/fonts/JetBrainsMono-Regular.ttf) — SIL Open Font L
Lucide icons (assets/icons/*.svg, except slice-knife.svg) — ISC; icons derived from Feather also MIT. See assets/icons/LICENSE-lucide.txt.
SCOWL English word list (assets/dict/en_US-scowl-50.txt.gz) — SCOWL license. See assets/dict/LICENSE-SCOWL.txt.
libfacedetection face detection weights and network (crates/algo/data/libfacedetection.bin, crates/algo/src/faces/cnn.rs) — BSD-3-Clause, Copyright (c) 2015-2019, Shiqi Yu, all rights reserved. See crates/algo/data/LICENSE-libfacedetection.txt.
Interface translations (embedded at build time from storytold/craft-i18n locales/<code>/common.tsv and photocraft.tsv, at the commit in craft-i18n.rev) — MIT OR Apache-2.0, Copyright (c) 2026 ArtCraft Team and the craft-i18n contributors; the license texts are the same as LICENSE-MIT and LICENSE-APACHE. Per-language credits and provenance: https://github.com/storytold/craft-i18n/blob/main/ATTRIBUTION.md
Builds made with craft-fonts (CRAFT_FONTS_DIR; all official releases) also embed the fonts listed in
https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md (today BIZ UDPGothic, Shippori Mincho and
BIZ UDMincho; not the web build), under the SIL Open Font License 1.1. Their licence texts
ship with the package as OFL-<family>.txt.
Linux Wayland window decorations
-------------------------------
Linux and FreeBSD Wayland window decorations
-------------------------------------------
sctk-adwaita 0.10.1 (https://github.com/PolyMeilex/sctk-adwaita,
commit d5f343c45c04d4a026db57f76760819b7325db00) is used by winit on Linux
for vector window controls. Its title-font features are disabled: no Cantarell
and FreeBSD for vector window controls. Its title-font features are disabled: no Cantarell
font is embedded by this dependency and no font file is added to this repo.
sctk-adwaita's MIT licence:
@@ -70,3 +71,51 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Optional PDF reader (craft-pdf)
PhotoCraft imports PDF pages through craft-pdf (https://github.com/storytold/craft-libs,
MIT OR Apache-2.0), pinned to revision c5a1cbfb5f9049f9270955caffb5bee5997aebf7. It vendors
Hayro 0.7.1, hayro-interpret 0.7.0, hayro-syntax 0.7.2, hayro-jbig2 0.3.0 and
hayro-cmap 0.1.0 (https://github.com/LaurenzV/hayro, MIT OR Apache-2.0). The reader bundles
the standard-14 Foxit fonts (BSD-3-Clause), Adobe CMaps (BSD-3-Clause) and a Compact ICC
profile by Clinton Ingram (CC0-1.0); per-file sources and hashes are in craft-libs
ATTRIBUTION.md. No PDF assets are copied into this repository, and PDFium is no longer used or
shipped.
Licence texts for the optional PDF reader
Hayro (MIT):
Copyright (c) The Hayro Authors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Standard-14 Foxit fonts (BSD-3-Clause):
Copyright 2014 PDFium Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Adobe CMaps (BSD-3-Clause):
Copyright 1990-2023 Adobe. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of Adobe nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Compact ICC profile: CC0 1.0 Universal (public domain dedication), by Clinton Ingram (saucecontrol/Compact-ICC-Profiles).
+4 -4
View File
@@ -185,8 +185,8 @@ Every screenshot here is the real app at work on public-domain art, rendered off
<table>
<tr>
<td width="33%" valign="top">
<h4>🧰 68 tools</h4>
Move · Artboard · Rectangular and Elliptical Marquee · Single Row Marquee · Single Column Marquee · Lasso · Polygonal Lasso · Magnetic Lasso · Object Selection · Quick Selection · Magic Wand · Crop · Perspective Crop · Slice · Slice Select · Frame · Eyedropper · Color Sampler · Ruler · Note · Count · Remove · Spot Healing Brush · Healing Brush · Patch · Content-Aware Move · Red Eye · Brush · Pencil · Mixer Brush · Color Replacement · Clone Stamp · Pattern Stamp · History Brush · Art History Brush · Eraser · Background Eraser · Magic Eraser · Gradient · Paint Bucket · Blur · Sharpen · Smudge · Dodge · Burn · Sponge · Pen · Freeform Pen · Curvature Pen · Add Anchor Point · Delete Anchor Point · Convert Point · Horizontal and Vertical Type · Horizontal and Vertical Type Mask · Path Selection · Direct Selection · Rectangle · Ellipse · Triangle · Polygon · Line · Custom Shape · Hand · Rotate View · Zoom
<h4>🧰 69 tools</h4>
Move · Artboard · Rectangular and Elliptical Marquee · Single Row Marquee · Single Column Marquee · Lasso · Polygonal Lasso · Magnetic Lasso · Object Selection · Quick Selection · Magic Wand · Crop · Perspective Crop · Slice · Slice Select · Frame · Eyedropper · Color Sampler · Ruler · Note · Count · Remove · Spot Healing Brush · Healing Brush · Patch · Content-Aware Move · Red Eye · Brush · Pencil · Mixer Brush · Color Replacement · Clone Stamp · Pattern Stamp · History Brush · Art History Brush · Eraser · Background Eraser · Magic Eraser · Gradient · Paint Bucket · Blur · Sharpen · Smudge · Dodge · Burn · Sponge · Pen · Freeform Pen · Curvature Pen · Add Anchor Point · Delete Anchor Point · Convert Point · Horizontal and Vertical Type · Horizontal and Vertical Type Mask · Path Selection · Direct Selection · Rectangle · Ellipse · Triangle · Polygon · Star · Line · Custom Shape · Hand · Rotate View · Zoom
</td>
<td width="33%" valign="top">
<h4>🖌️ A real brush engine</h4>
@@ -206,7 +206,7 @@ Every screenshot here is the real app at work on public-domain art, rendered off
</td>
<td width="33%" valign="top">
<h4>🗂️ Formats</h4>
PSD and PSB, layered TIFF (Photoshop's layer data in the TIFF, read and written in either byte order), <a href="docs/pdn.md">Paint.NET PDN3 (read, with editable layers and all 14 blend modes)</a>, <a href="docs/ora.md">OpenRaster (read and write, with layers, groups and blend modes, for Krita, MyPaint and GIMP)</a>, <a href="docs/xcf.md">GIMP XCF (read, with layers, groups, masks, blend modes, channels and the selection)</a>, <a href="docs/kra.md">Krita .kra (read, with paint layers, groups, blend modes and transparency masks)</a>, SVG (opens as shape layers, places as a vector Smart Object), plus flat PNG, JPEG, TIFF, WebP (lossy and lossless), GIF, BMP, TGA, ICO, QOI, PNM, OpenEXR, Radiance HDR and FITS (astronomy images: 8/16-bit and 32-bit float, gray or RGB, header kept), and the native <code>.pcraft</code> format. Flat formats retain the depths they support: PNG keeps 8/16-bit samples, TIFF keeps 8/16-bit and 32-bit float samples, and OpenEXR keeps half/float samples; JPEG, WebP and the other 8-bit formats reduce higher-depth samples with an export warning. See the <a href="crates/codecs/README.md#capability-matrix-default-build">codec capability matrix</a> for each format. HEIC photos from iPhone and Mac are read-only (included in official builds; optional <code>--features heif</code> for source builds). AVIF is write-only with the optional <code>avif</code> build feature; AVIF decoding and JPEG XL are unavailable. Affinity documents (<code>.af</code>, <code>.afdesign</code>, <code>.afphoto</code>, <code>.afpub</code>) open natively, read only, with artboards, layers, vectors, text, images and masks; effects, adjustments and other unsupported parts are listed in a warning, and Affinity export is unavailable.
PSD and PSB, layered TIFF (Photoshop's layer data in the TIFF, read and written in either byte order), <a href="docs/pdn.md">Paint.NET PDN3 (read, with editable layers and all 14 blend modes)</a>, <a href="docs/ora.md">OpenRaster (read and write, with layers, groups and blend modes, for Krita, MyPaint and GIMP)</a>, <a href="docs/xcf.md">GIMP XCF (read, with layers, groups, masks, blend modes, channels and the selection)</a>, <a href="docs/kra.md">Krita .kra (read, with paint layers, groups, blend modes and transparency masks)</a>, SVG (opens as shape layers, places as a vector Smart Object), plus flat PNG, JPEG, TIFF, WebP (lossy and lossless), GIF, BMP, TGA, ICO, QOI, PNM, OpenEXR, Radiance HDR and FITS (astronomy images: 8/16-bit and 32-bit float, gray or RGB, header kept), and the native <code>.pcraft</code> format. Flat formats retain the depths they support: PNG keeps 8/16-bit samples, TIFF keeps 8/16-bit and 32-bit float samples, and OpenEXR keeps half/float samples; JPEG, WebP and the other 8-bit formats reduce higher-depth samples with an export warning. See the <a href="https://github.com/storytold/craft-libs/tree/main/crates/image-codecs#capability-matrix-default-build">codec capability matrix</a> for each format. HEIC photos from iPhone and Mac are read-only (included in official builds; optional <code>--features heif</code> for source builds). AVIF is write-only with the optional <code>avif</code> build feature; AVIF decoding and JPEG XL are unavailable. Affinity documents (<code>.af</code>, <code>.afdesign</code>, <code>.afphoto</code>, <code>.afpub</code>) open natively, read only, with artboards, layers, vectors, text, images and masks; effects, adjustments and other unsupported parts are listed in a warning, and Affinity export is unavailable.
</td>
<td width="33%" valign="top">
<h4>🪄 The everyday essentials</h4>
@@ -221,7 +221,7 @@ Every screenshot here is the real app at work on public-domain art, rendered off
PhotoCraft's PSD support is a standalone crate written from Adobe's public specification and tested against a corpus of real-world files.
- **Faithful round trips:** opening and re-saving a document renders the same for 307 of the 309 files in the psd-tools test set and 169 of 170 in our mixed ag-psd/psd-tools set (`crates/io/tests/it/corpus.rs`; fetch the psd-tools set with `cargo xtask corpus --psd-tools`), and anything we don't model yet (raw blocks, descriptors, extras) is carried over instead of being dropped. A re-saved file is not byte-identical to its source: PhotoCraft rewrites image resources, layer records and the composite. Only the standalone `photocraft-psd` crate, parsing and writing a file without the document model, reproduces every parseable corpus file byte for byte (`crates/psd/tests/it/corpus.rs`).
- **Faithful round trips:** opening and re-saving a document renders the same for 307 of the 309 files in the psd-tools test set and 169 of 170 in our mixed ag-psd/psd-tools set (`crates/io/tests/it/corpus.rs`; fetch the psd-tools set with `cargo xtask corpus --psd-tools`), and anything we don't model yet (raw blocks, descriptors, extras) is carried over instead of being dropped. A re-saved file is not byte-identical to its source: PhotoCraft rewrites image resources, layer records and the composite. Only the standalone `craft-psd` crate, parsing and writing a file without the document model, reproduces every parseable corpus file byte for byte (`craft-psd/tests/it/corpus.rs`).
- **Pixels that match:** a composite oracle compares our render with Photoshop's own merged image, covering gradient interpolation (Classic, Perceptual and Linear), layer effects, shape strokes, clipping and fill opacity.
- **Large documents:** PSB, 16 and 32-bit files, and CMYK and Lab documents open natively.
+6 -2
View File
@@ -2,7 +2,7 @@
**Stage: alpha** · next: beta, ~30 points (ready for real work ~45% → ~75%, with reliable PSD) and ~1,100–1,800 h away
> **Last reviewed:** 2026-10-17 · **Last updated:** 2026-10-17 · **Change:** minor (Object Finder retains large enclosed foregrounds (#6548); Russian catalog covers every dynamic label; previously minor: oracle floor 145 of 258 and 953 open issues, as in gaps.md and on GitHub; toolbox count 56 of 68, 12 missing) · **Target:** Adobe Photoshop 2026
> **Last reviewed:** 2026-10-17 · **Last updated:** 2026-10-22 · **Change:** minor (Print: Japanese paper sizes — はがき, 往復はがき, JIS B5/B4, A6, L判, 2L判, KG判, 六切, 四切; previously: Object Finder retains large enclosed foregrounds (#6548); Russian catalog covers every dynamic label; previously minor: oracle floor 145 of 258 and 953 open issues, as in gaps.md and on GitHub; toolbox count 56 of 68, 12 missing) · **Target:** Adobe Photoshop 2026
PhotoCraft's one-page summary of how close it is to Adobe Photoshop 2026 (27.11.0, measured from
the installed app on 2026-10-10) at version 0.6.0. Detail: [target-app parity](docs/target-app-parity.md)
@@ -86,7 +86,8 @@ Rows and evidence: [target-app-parity › Feature areas](docs/target-app-parity.
## Languages
Measured with the `cargo xtask i18n-coverage` key universe (1,608 keys). `partial` everywhere
Measured before the craft-i18n cutover with the former `cargo xtask i18n-coverage` key universe
(1,608 keys); `cargo xtask i18n-report` now reports coverage. `partial` everywhere
because engine messages are still English. Detail: [localization-parity](docs/localization-parity.md).
| Language | Code | UI strings | Status |
@@ -122,8 +123,10 @@ Detail and the next releases: [docs/roadmap.md](docs/roadmap.md).
| Date | Entry |
|---|---|
| 2026-11-02 | Layer Style: with Gradient Overlay selected, a drag on the image moves the gradient (its centre as a fraction of the layer's bounds, `params.offset`), as a drag moves a shadow (#10763) |
| 2026-11-02 | Load Actions: Mac Roman step names with é ä ö ü Ä or ° read as Mac Roman instead of windows-1252 or Cyrillic (#10774): windows-1252's rare 0x80–0x9F letters and a lone Cyrillic letter in a Latin word no longer count as common text, the degree sign does, and the file's own Unicode text settles a word-initial rare letter and breaks exact ties toward windows-1252 or Mac Roman |
| 2026-10-21 | Linux can use font-free Adwaita controls when System Title Bar is selected, while the integrated CSD title bar remains the default (as in #4439). Saved preferences are respected; startup and preference-dialog regressions cover both choices (#6266). |
| 2026-10-22 | Print paper sizes: はがき (100 × 148 mm), 往復はがき (148 × 200), JIS B5 (182 × 257), JIS B4 (257 × 364), A6, L判 (89 × 127), 2L判 (127 × 178), KG判 (102 × 152), 六切 (203 × 254) and 四切 (254 × 305) are selectable in the Print dialog and `file.print`, matched by their customary names (`はがき`, `L判`, `JIS B5`…), and the PDF page takes their exact size. Existing papers unchanged. |
| 2026-10-17 | Object Finder classifies background by boundary coverage, retaining large enclosed foregrounds and rejecting surrounding backdrop (#6548); learned segmentation remains open (#2788) |
| 2026-10-10 | Full re-measure against Photoshop 2026 27.11.0 (installed bundle inspected): breadth ~76%, ready ~45%, alpha. Progress docs reorganized (`parity.md` → `parity-checklist.md`, `parity-estimate.md` merged into `target-app-parity.md`). 0.6.0 released. |
| 2026-10-09 | Remove tool, Rotate View, crop rotation; OpenRaster and Paint.NET; 39 Affinity documents in the corpus |
@@ -138,6 +141,7 @@ Detail and the next releases: [docs/roadmap.md](docs/roadmap.md).
| Date | Change | Summary |
|---|---|---|
| 2026-10-22 | minor | Print: Japanese paper sizes (はがき, 往復はがき, JIS B5/B4, A6, L判, 2L判, KG判, 六切, 四切) in the Print dialog, `file.print` and the PDF output |
| 2026-10-17 | minor | Object Finder retains large enclosed foregrounds (#6548) |
| 2026-10-13 | minor | Focus item 1 quoted the oracle floor as 133 of 256; it is 145 of 258 (`crates/io/tests/it/corpus.rs`, gaps.md G1). Open issues 579 → 953 (2026-10-13) |
| 2026-10-15 | minor | Russian catalog covers every dynamic UI label the other catalogs translate |
+19 -2
View File
@@ -7,9 +7,12 @@ license.workspace = true
build = "build.rs"
[features]
# Open HEIC/HEIF photos (the optional photocraft-heif crate). Not default so distributors choose
default = ["gpu"]
# Open HEIC/HEIF photos (the optional craft-heif crate). Not default so distributors choose
# it; official builds (CI, packaging/, release) build with `--features heif`.
heif = ["photocraft-codecs/heif"]
# Optional native GPU rendering backend, enabled by default in native CLI builds.
gpu = ["photocraft-automation/gpu"]
[lints]
workspace = true
@@ -22,10 +25,16 @@ path = "src/lib.rs"
name = "photocraft-cli"
path = "src/main.rs"
[[example]]
name = "gpu_bench"
required-features = ["gpu"]
[dependencies]
photocraft-automation = { path = "../../crates/automation" }
photocraft-doc = { workspace = true }
photocraft-engine = { workspace = true }
photocraft-io = { workspace = true }
photocraft-io = { workspace = true, features = ["pdf-editable"] }
photocraft-raster = { workspace = true }
photocraft-format = { path = "../../crates/format" }
photocraft-codecs = { workspace = true }
clap = { workspace = true }
@@ -34,12 +43,20 @@ thiserror = { workspace = true }
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
[dev-dependencies]
serde = { workspace = true }
tempfile = "3"
# Reading back a saved PSD's merged-image flag (#8064).
craft-psd = { workspace = true }
# A real ICC profile for the --metadata test (#9466).
craft-cms = { workspace = true }
# Synthetic camera raws (#7789).
photocraft-raw = { workspace = true, features = ["testgen"] }
# Shell completions and man pages (examples/man-and-completions.rs, for the packages); not in
# the binary.
clap_complete = { workspace = true }
clap_mangen = { workspace = true }
# The PSD write recipe runner (tests/it/psd_write_oracle.rs).
xtask = { path = "../../xtask" }
[build-dependencies]
# Icon + VERSIONINFO for photocraft-cli.exe; build.rs only uses it when targeting Windows.
+221
View File
@@ -0,0 +1,221 @@
//! Benchmark example measuring headless CPU vs GPU rendering and export performance.
//!
//! Usage:
//! ```sh
//! cargo run --release -p photocraft-cli --example gpu_bench -- [options]
//! ```
use std::path::PathBuf;
use std::time::Instant;
use clap::Parser;
use photocraft_automation::files;
use photocraft_automation::gpu::GpuRenderer;
use photocraft_doc::{BlendMode, Color, ColorMode, Document, Layer, LayerContent, Rect, SampleType, Size, Surface};
use photocraft_io::ExportOptions;
#[derive(Parser, Debug)]
#[command(name = "gpu_bench", about = "Benchmark headless CPU vs GPU rendering and export performance")]
struct BenchArgs {
/// Input image or PSD file (optional; defaults to synthetic mockup)
#[arg(short, long)]
input: Option<PathBuf>,
/// Synthetic document width in pixels (1..=16384)
#[arg(short, long, default_value_t = 2048, value_parser = clap::value_parser!(u32).range(1..=16384))]
width: u32,
/// Synthetic document height in pixels (1..=16384)
#[arg(short = 'H', long, default_value_t = 2048, value_parser = clap::value_parser!(u32).range(1..=16384))]
height: u32,
/// Synthetic layer count (1..=128)
#[arg(short, long, default_value_t = 8, value_parser = clap::value_parser!(u32).range(1..=128))]
layers: u32,
/// Number of warm GPU runs (0..=50)
#[arg(short = 'r', long = "warm-runs", default_value_t = 3, value_parser = clap::value_parser!(u32).range(0..=50))]
warm_runs: u32,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args = BenchArgs::parse();
let layers = args.layers as usize;
let warm_runs = args.warm_runs as usize;
println!("# PhotoCraft CLI Headless Rendering Benchmark");
println!();
const MAX_SYNTHETIC_PIXELS: u64 = 256 * 1024 * 1024;
let doc = if let Some(path) = &args.input {
println!("- **Input Source**: file `{}`", path.display());
let open_res = files::open(path)?;
open_res.document
} else {
let total_pixels = u64::from(args.width) * u64::from(args.height) * u64::from(args.layers);
if total_pixels > MAX_SYNTHETIC_PIXELS {
return Err(format!(
"requested synthetic benchmark volume ({}x{} x {} layers = {} total pixels) exceeds budget of {} pixels (~{} MB); please lower width, height, or layer count",
args.width,
args.height,
args.layers,
total_pixels,
MAX_SYNTHETIC_PIXELS,
(MAX_SYNTHETIC_PIXELS * 4) / (1024 * 1024)
)
.into());
}
println!("- **Input Source**: synthetic mockup ({}x{}, {} layers)", args.width, args.height, args.layers);
sample_doc(args.width, args.height, layers)
};
println!("- **Dimensions**: {}x{}", doc.size.width, doc.size.height);
println!("- **Layer Count**: {}", doc.layers.len());
println!();
let tmp_dir = std::env::temp_dir().join(format!("pc-bench-{}", std::process::id()));
let _ = std::fs::create_dir_all(&tmp_dir);
let cpu_out = tmp_dir.join("cpu_out.png");
let gpu_cold_out = tmp_dir.join("gpu_cold_out.png");
let gpu_warm_out = tmp_dir.join("gpu_warm_out.png");
let opts = ExportOptions::default();
// 1. CPU Run
print!("Benchmarking CPU export... ");
let t0 = Instant::now();
files::save_with_renderer(&doc, &cpu_out, Some("png"), &opts, None, None)?;
let cpu_dur = t0.elapsed();
println!("{:.2} ms", cpu_dur.as_secs_f64() * 1000.0);
// 2. GPU Cold Run
print!("Benchmarking GPU cold export... ");
let mut gpu_renderer = GpuRenderer::lazy();
let t0 = Instant::now();
let gpu_cold_res = files::save_with_renderer(&doc, &gpu_cold_out, Some("png"), &opts, None, Some(&mut gpu_renderer));
let gpu_cold_dur = t0.elapsed();
let (gpu_succeeded, is_fallback) = match gpu_cold_res {
Ok(warnings) => {
let fallback = warnings.iter().any(|w| w.contains("falling back to CPU"));
if fallback {
println!("{:.2} ms (FALLBACK TO CPU: {:?})", gpu_cold_dur.as_secs_f64() * 1000.0, warnings);
(true, true)
} else if gpu_renderer.context().is_none() {
// The export never reached the renderer (e.g. a single-layer input takes the
// native path), so no GPU work ran: report it as CPU work, not a GPU result.
println!("{:.2} ms (renderer not used)", gpu_cold_dur.as_secs_f64() * 1000.0);
(false, true)
} else {
println!("{:.2} ms", gpu_cold_dur.as_secs_f64() * 1000.0);
let adapter = gpu_renderer.adapter_name().unwrap_or("unknown");
let is_soft = if gpu_renderer.is_software() { " (software rasterizer)" } else { " (hardware)" };
println!("- **GPU Adapter**: `{adapter}`{is_soft}");
(true, false)
}
}
Err(e) => {
println!("FAILED ({e})");
let _ = std::fs::remove_dir_all(&tmp_dir);
return Ok(());
}
};
// 3. GPU Warm Runs
let mut warm_durations = Vec::with_capacity(warm_runs);
let mut warm_fallbacks = 0usize;
if gpu_succeeded && !is_fallback && warm_runs > 0 {
for run in 1..=warm_runs {
print!("Benchmarking GPU warm export (run {run}/{warm_runs})... ");
let t0 = Instant::now();
let warm_res = files::save_with_renderer(&doc, &gpu_warm_out, Some("png"), &opts, None, Some(&mut gpu_renderer))?;
let d = t0.elapsed();
if warm_res.iter().any(|w| w.contains("falling back to CPU")) {
warm_fallbacks += 1;
println!("{:.2} ms (FALLBACK TO CPU)", d.as_secs_f64() * 1000.0);
} else {
println!("{:.2} ms", d.as_secs_f64() * 1000.0);
warm_durations.push(d);
}
}
}
println!();
println!("### Summary Results");
println!("| Mode | Duration | Relative to CPU | Note |");
println!("|---|---|---|---|");
println!("| CPU Baseline | {:.2} ms | 1.00x | Reference CPU compositor |", cpu_dur.as_secs_f64() * 1000.0);
if is_fallback {
println!("| GPU Cold | {:.2} ms | N/A | GPU not used (CPU fallback or a CPU-only export path); no GPU speedup |", gpu_cold_dur.as_secs_f64() * 1000.0);
println!("| GPU Warm | N/A | N/A | Not measured (GPU not used) |");
} else {
let is_software = gpu_renderer.is_software();
let adapter_note = if is_software { "Software rasterizer (e.g. lavapipe/llvmpipe)" } else { "Hardware GPU" };
println!(
"| GPU Cold | {:.2} ms | {:.2}x | Cold adapter initialization + pipeline build ({adapter_note}) |",
gpu_cold_dur.as_secs_f64() * 1000.0,
cpu_dur.as_secs_f64() / gpu_cold_dur.as_secs_f64()
);
if !warm_durations.is_empty() {
let avg_warm: f64 = warm_durations.iter().map(|d| d.as_secs_f64()).sum::<f64>() / (warm_durations.len() as f64);
// Runs that fell back to the CPU are excluded from the average: say how many.
let note = match warm_fallback_note(warm_runs, warm_fallbacks) {
Some(fallbacks) => format!("Reused device context and pipeline caches ({adapter_note}); {fallbacks} (excluded from the average)"),
None => format!("Reused device context and pipeline caches ({adapter_note})"),
};
println!("| GPU Warm (avg) | {:.2} ms | {:.2}x | {note} |", avg_warm * 1000.0, cpu_dur.as_secs_f64() / avg_warm);
} else if let Some(note) = warm_fallback_note(warm_runs, warm_fallbacks) {
println!("| GPU Warm | N/A | N/A | {note} |");
} else {
println!("| GPU Warm | N/A | N/A | Not measured (0 warm runs requested) |");
}
}
let _ = std::fs::remove_dir_all(&tmp_dir);
Ok(())
}
/// The warm-run summary note when every measured warm run fell back to the CPU.
fn warm_fallback_note(warm_runs: usize, warm_fallbacks: usize) -> Option<String> {
(warm_fallbacks > 0).then(|| format!("{warm_fallbacks} of {warm_runs} warm runs fell back to CPU"))
}
fn sample_doc(w: u32, h: u32, layer_count: usize) -> Document {
let mut doc = Document::with_background("bench", Size::new(w, h), ColorMode::Rgb, SampleType::U8, Color::WHITE);
let blend_modes = [BlendMode::Normal, BlendMode::Multiply, BlendMode::Screen, BlendMode::Overlay, BlendMode::Darken, BlendMode::Lighten];
for idx in 0..layer_count {
let mut s = Surface::new(doc.pixel_format());
let x0 = (idx as i32 * 20) % (w as i32 / 2).max(1);
let y0 = (idx as i32 * 20) % (h as i32 / 2).max(1);
let rw = (w as i32 - x0).max(1);
let rh = (h as i32 - y0).max(1);
s.fill_rect(Rect::new(x0, y0, x0 + rw, y0 + rh), &[0.3, 0.5, 0.7, 0.8]);
let mut layer = Layer::new(format!("Layer {}", idx + 1), LayerContent::Raster(s));
layer.opacity = 0.85;
layer.blend = blend_modes[idx % blend_modes.len()];
doc.layers.push(layer);
}
doc
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn synthetic_documents_allow_one_pixel_dimensions() {
for (width, height) in [(1, 1), (1, 16), (16, 1)] {
let doc = sample_doc(width, height, 2);
assert_eq!(doc.size, Size::new(width, height));
}
}
#[test]
fn warm_summary_reports_fallbacks_instead_of_zero_runs() {
assert_eq!(warm_fallback_note(3, 3).as_deref(), Some("3 of 3 warm runs fell back to CPU"));
assert_eq!(warm_fallback_note(3, 1).as_deref(), Some("1 of 3 warm runs fell back to CPU"));
assert_eq!(warm_fallback_note(0, 0), None);
}
}
+161 -9
View File
@@ -11,12 +11,13 @@ use std::fmt;
use std::net::{Ipv4Addr, SocketAddr};
use std::path::PathBuf;
pub(crate) use crate::gpu::GpuArgs;
use clap::error::ErrorKind;
use clap::parser::ValueSource;
use clap::{ArgAction, ArgGroup, ArgMatches, Args, CommandFactory, FromArgMatches, Parser, Subcommand};
use photocraft_automation::args::{AutomationArgs, ControlArgs, blank_env_is_unset, conflict, control_port, name_env_vars};
use photocraft_codecs::{JpegFormat, TiffCompression};
use photocraft_io::{DdsCompression, DpxBits, TgaBits};
use photocraft_io::{DdsCompression, DpxBits, TgaBits, XmpEmbed};
use serde_json::Value;
/// photocraft-cli: headless PhotoCraft
@@ -86,6 +87,18 @@ pub(crate) struct ExportArgs {
/// composite/full.png; it may be omitted. Check the manifest's full_composite member.
#[arg(long)]
pub(crate) pcraft_full_composite: bool,
/// A layered PSD/PSB stores Photoshop's white placeholder instead of the merged image
/// (Maximize Compatibility off): a smaller file and a faster save, but readers that show only
/// the merged image see white. Bitmap, Indexed Color and Duotone documents still write the
/// real image
#[arg(long)]
pub(crate) no_maximize_compatibility: bool,
/// The document metadata a flat export embeds: all (the default) keeps the document's XMP
/// packet and free-form text where the format holds them, as Save As does; none leaves them
/// out, as Export As's Metadata: None. Nothing else changes: the ICC profile, EXIF and
/// resolution are written as they are without it. PSD, PSB and .pcraft always keep the XMP
#[arg(long, value_name = "none|all", value_parser = metadata)]
pub(crate) metadata: Option<XmpEmbed>,
}
/// Convert between formats (.pcraft, .psd, .png, .jpg, .tif, .webp, .exr, …)
@@ -106,6 +119,18 @@ pub(crate) struct ConvertArgs {
/// Explicitly approve high-memory PSD/PSB imports within the hard memory budget
#[arg(long)]
pub(crate) approve_high_memory: bool,
/// PDF import resolution in DPI (default 300)
#[arg(long, value_name = "DPI", value_parser = pdf_dpi)]
pub(crate) pdf_dpi: Option<f32>,
/// PDF pages to import, 1-based: "3" or "2-7" (default all)
#[arg(long)]
pub(crate) pdf_pages: Option<String>,
/// Import PDF paths and embedded-font text as editable layers (experimental; unsupported
/// pages fall back to raster, and embedded fonts may change when edited or reopened)
#[arg(long)]
pub(crate) pdf_editable: bool,
#[command(flatten)]
pub(crate) gpu: GpuArgs,
#[command(flatten)]
pub(crate) export: ExportArgs,
}
@@ -120,6 +145,9 @@ pub(crate) struct InfoArgs {
/// Explicitly approve high-memory PSD/PSB imports within the hard memory budget
#[arg(long)]
pub(crate) approve_high_memory: bool,
/// Also list every text run and paragraph run, anti-aliasing and full layer-effect settings
#[arg(long)]
pub(crate) detail: bool,
}
/// Open a file (or start a new document), run engine commands in order, save the result
@@ -152,6 +180,8 @@ pub(crate) struct RunArgs {
#[arg(long)]
pub(crate) approve_high_memory: bool,
#[command(flatten)]
pub(crate) gpu: GpuArgs,
#[command(flatten)]
pub(crate) export: ExportArgs,
/// `--cmd` and `--params` values in command-line order, set by [`parse`].
#[arg(skip)]
@@ -210,6 +240,8 @@ pub(crate) struct BatchArgs {
#[arg(long)]
pub(crate) approve_high_memory: bool,
#[command(flatten)]
pub(crate) gpu: GpuArgs,
#[command(flatten)]
pub(crate) export: ExportArgs,
}
@@ -238,13 +270,24 @@ pub(crate) struct CommandsArgs {
pub(crate) filter: Option<String>,
}
/// Run the MCP server on stdio (headless engine, or bridge to a running `photocraft --control <port>`)
/// Run the MCP server on stdio: in the open PhotoCraft window when the person lets agents use it
/// (ArtCraft Launcher › Settings › AI agents), otherwise headless
///
/// Headless: each automation root grants that direction of file access; an omitted root denies it.
/// Prefer absolute root paths in MCP client configurations. Bridge: set the roots on the desktop
/// app; root flags are refused. The token flags require --bridge (or PHOTOCRAFT_CONTROL_PORT).
/// The open window is found again on every call, with no port or token to configure. Without
/// the person's consent, or with --headless, it runs headless: each automation root grants that
/// direction of file access; an omitted root denies it. Prefer absolute root paths in MCP client
/// configurations. Bridge (--bridge or PHOTOCRAFT_CONTROL_PORT): a running `photocraft --control
/// <port>`; set the roots on the desktop app, root flags are refused, and the token flags require
/// it.
#[derive(Args)]
pub(crate) struct McpArgs {
/// Always work headless, without the open window
#[arg(long, conflicts_with = "when_closed")]
pub(crate) headless: bool,
/// While agents may use PhotoCraft but it is closed: start it, serve a headless session, or
/// fail (default: the app's When PhotoCraft Is Closed setting)
#[arg(long, value_name = "launch|headless|error", value_parser = when_closed)]
pub(crate) when_closed: Option<photocraft_engine::prefs::WhenAppClosed>,
/// Bridge to the PhotoCraft app listening here instead of a headless engine; a bare port means
/// 127.0.0.1:<PORT>
#[arg(long, value_name = "127.0.0.1:PORT", env = "PHOTOCRAFT_CONTROL_PORT", value_parser = bridge)]
@@ -253,6 +296,8 @@ pub(crate) struct McpArgs {
#[arg(skip)]
pub(crate) bridge_from_env: bool,
#[command(flatten)]
pub(crate) gpu: GpuArgs,
#[command(flatten)]
pub(crate) control: ControlArgs,
#[command(flatten)]
pub(crate) automation: AutomationArgs,
@@ -274,6 +319,8 @@ pub(crate) struct ServeArgs {
#[arg(skip)]
pub(crate) port_from_env: bool,
#[command(flatten)]
pub(crate) gpu: GpuArgs,
#[command(flatten)]
pub(crate) control: ControlArgs,
#[command(flatten)]
pub(crate) automation: AutomationArgs,
@@ -292,11 +339,17 @@ enum ValueError {
TiffCompression,
#[error("expected baseline, optimized or progressive")]
JpegFormat,
#[error("expected none or all")]
Metadata,
#[error("expected on or off")]
OnOff,
#[error("expected a positive number")]
PdfDpi,
/// Why a `--bridge` value, or a PHOTOCRAFT_CONTROL_PORT value for `mcp`, is refused.
#[error("expected a port, 0-65535 (--bridge also takes 127.0.0.1:<PORT>)")]
Bridge,
#[error("expected launch, headless or error")]
WhenClosed,
}
/// Why `parse` refuses `mcp` or `serve` options clap accepted: clap prints it as a usage error
@@ -311,16 +364,28 @@ enum ServerOptionError {
/// authority the bridge can't give (#8035).
#[error("configure automation roots on the desktop app; --automation-read-root and --automation-write-root require headless MCP mode")]
BridgeRoots,
/// Invalid value for PHOTOCRAFT_GPU.
#[error("invalid value '{0}' for 'PHOTOCRAFT_GPU': expected '1' or '0'")]
GpuVar(String),
/// Explicit GPU flags require headless MCP mode, not bridge mode.
#[error("configure rendering on the desktop app; --gpu and --no-gpu require headless MCP mode")]
BridgeGpu,
/// A token flag without the bridge or port that reads it would be ignored (#8035).
#[error("{flag} requires {transport}")]
NeedsTransport { flag: &'static str, transport: &'static str },
/// `--headless` never reaches an app.
#[error("--headless works without the app; {0} is for --bridge")]
HeadlessBridge(&'static str),
/// `--when-closed` is about the open app, which a bridge names itself.
#[error("--when-closed is for the open window; --bridge names the app itself")]
BridgeWhenClosed,
}
impl ServerOptionError {
fn into_clap(self, cmd: &mut clap::Command) -> clap::Error {
let kind = match self {
Self::BridgeVar(_) => ErrorKind::ValueValidation,
Self::BridgeRoots => ErrorKind::ArgumentConflict,
Self::BridgeVar(_) | Self::GpuVar(_) => ErrorKind::ValueValidation,
Self::BridgeRoots | Self::BridgeGpu | Self::HeadlessBridge(_) | Self::BridgeWhenClosed => ErrorKind::ArgumentConflict,
Self::NeedsTransport { .. } => ErrorKind::MissingRequiredArgument,
};
cmd.error(kind, self)
@@ -348,6 +413,10 @@ fn tiff_compression(s: &str) -> Result<TiffCompression, ValueError> {
}
}
fn when_closed(s: &str) -> Result<photocraft_engine::prefs::WhenAppClosed, ValueError> {
photocraft_engine::prefs::WhenAppClosed::parse(s).ok_or(ValueError::WhenClosed)
}
fn on_off(s: &str) -> Result<bool, ValueError> {
match s {
"on" => Ok(true),
@@ -356,10 +425,24 @@ fn on_off(s: &str) -> Result<bool, ValueError> {
}
}
/// A PDF import DPI: a finite number greater than zero. The importer's fallback to 300 DPI is
/// for absent preferences, not for a mistyped flag.
fn pdf_dpi(s: &str) -> Result<f32, ValueError> {
s.parse::<f32>().ok().filter(|dpi| dpi.is_finite() && *dpi > 0.0).ok_or(ValueError::PdfDpi)
}
fn jpeg_format(s: &str) -> Result<JpegFormat, ValueError> {
JpegFormat::parse(s).ok_or(ValueError::JpegFormat)
}
fn metadata(s: &str) -> Result<XmpEmbed, ValueError> {
match s {
"none" => Ok(XmpEmbed::None),
"all" => Ok(XmpEmbed::All),
_ => Err(ValueError::Metadata),
}
}
/// Where `mcp --bridge` connects. Shown as the address: `127.0.0.1:<PORT>` for a port.
#[derive(Clone)]
pub(crate) enum Bridge {
@@ -414,6 +497,11 @@ fn steps(m: &ArgMatches) -> Vec<Step> {
/// stray.psd --help`): clap reports the mistake first.
pub(crate) fn parse(args: &[OsString]) -> Result<Cli, clap::Error> {
let mut cmd = Cli::command().mut_subcommands(|sub| sub.mut_args(blank_env_is_unset));
// `mcp --headless` reaches no app: a PHOTOCRAFT_CONTROL_PORT exported for another tool is not
// read, so a value it couldn't use anyway doesn't stop it.
if args.first().is_some_and(|a| a == "mcp") && args.iter().take_while(|a| *a != "--").any(|a| a == "--headless") {
cmd = cmd.mut_subcommand("mcp", |sub| sub.mut_arg("bridge", |arg| arg.env(None::<&str>)));
}
let argv = std::iter::once(OsString::from("photocraft-cli")).chain(args.iter().cloned());
let matches = match cmd.try_get_matches_from_mut(argv) {
Err(e) if args.iter().take_while(|a| *a != "--").any(|a| *a == "--help" || *a == "-h") => {
@@ -425,8 +513,26 @@ pub(crate) fn parse(args: &[OsString]) -> Result<Cli, clap::Error> {
let mut cli = Cli::from_arg_matches(&matches)?;
let from_env = |m: &ArgMatches, id: &str| m.value_source(id) == Some(ValueSource::EnvVariable);
match (&mut cli.command, matches.subcommand()) {
(Command::Run(r), Some((_, m))) => r.steps = steps(m),
(Command::Run(r), Some((_, m))) => {
r.steps = steps(m);
check_gpu_env(&mut cmd, m)?;
}
(Command::Mcp(a), Some((name, m))) => {
if a.headless {
// `--headless` reaches no app. Given on the command line, the bridge's flags
// conflict; exported for another tool, they are left alone.
for (id, flag) in [("bridge", "--bridge"), ("control_token", "--control-token"), ("control_token_file", "--control-token-file")] {
if m.value_source(id) == Some(ValueSource::CommandLine) {
if let Some(sub) = cmd.find_subcommand_mut(name) {
return Err(ServerOptionError::HeadlessBridge(flag).into_clap(sub));
}
return Err(ServerOptionError::HeadlessBridge(flag).into_clap(&mut cmd));
}
}
a.bridge = None;
check_gpu_env(&mut cmd, m)?;
return Ok(cli);
}
a.bridge_from_env = from_env(m, "bridge");
if a.bridge_from_env
&& let Some(Bridge::Addr(v)) = &a.bridge
@@ -445,10 +551,20 @@ pub(crate) fn parse(args: &[OsString]) -> Result<Cli, clap::Error> {
conflict(sub, m, "automation_read_root", "bridge")?;
conflict(sub, m, "automation_write_root", "bridge")?;
}
if a.bridge.is_some() && (a.automation.automation_read_root.is_some() || a.automation.automation_write_root.is_some()) {
if a.bridge.is_some() && (!a.automation.automation_read_root.is_empty() || a.automation.automation_write_root.is_some()) {
return Err(ServerOptionError::BridgeRoots.into_clap(sub));
}
if a.bridge.is_some() && (m.value_source("gpu") == Some(ValueSource::CommandLine) || m.value_source("no_gpu") == Some(ValueSource::CommandLine))
{
return Err(ServerOptionError::BridgeGpu.into_clap(sub));
}
check_server(sub, m, a.bridge.is_some(), "--bridge")?;
if a.bridge.is_some() && a.when_closed.is_some() {
return Err(ServerOptionError::BridgeWhenClosed.into_clap(sub));
}
}
if a.bridge.is_none() {
check_gpu_env(&mut cmd, m)?;
}
}
(Command::Serve(a), Some((name, m))) => {
@@ -460,12 +576,32 @@ pub(crate) fn parse(args: &[OsString]) -> Result<Cli, clap::Error> {
}
check_server(sub, m, a.port.is_some(), "--port")?;
}
check_gpu_env(&mut cmd, m)?;
}
(Command::Convert(_), Some((_, m))) | (Command::Batch(_), Some((_, m))) => {
check_gpu_env(&mut cmd, m)?;
}
_ => {}
}
Ok(cli)
}
fn check_gpu_env(cmd: &mut clap::Command, m: &ArgMatches) -> Result<(), clap::Error> {
if m.value_source("gpu") == Some(ValueSource::CommandLine) || m.value_source("no_gpu") == Some(ValueSource::CommandLine) {
return Ok(());
}
if let Some(v) = std::env::var_os("PHOTOCRAFT_GPU") {
// A non-UTF-8 value is still a value other than empty, "0" or "1": reject it rather
// than silently treating it as unset and running on the CPU.
let v = v.to_string_lossy();
let trimmed = v.trim();
if !trimmed.is_empty() && trimmed != "1" && trimmed != "0" {
return Err(ServerOptionError::GpuVar(trimmed.to_string()).into_clap(cmd));
}
}
Ok(())
}
/// Refuse a token flag without the bridge or port that reads it (as a flag or its variable). A
/// token variable alone may be a stale export, so it isn't refused.
fn check_server(sub: &mut clap::Command, m: &ArgMatches, has_transport: bool, transport: &'static str) -> Result<(), clap::Error> {
@@ -476,3 +612,19 @@ fn check_server(sub: &mut clap::Command, m: &ArgMatches, has_transport: bool, tr
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
/// `--pdf-dpi` only takes a positive finite number: a mistyped value is refused at parse time
/// instead of silently becoming the importer's 300 DPI fallback.
#[test]
fn pdf_dpi_rejects_non_positive_and_non_finite_values() {
assert!(pdf_dpi("300").is_ok());
assert!(pdf_dpi("0.5").is_ok());
for bad in ["0", "-1", "nan", "inf", "-inf", "abc"] {
assert!(pdf_dpi(bad).is_err(), "{bad} should be refused");
}
}
}
+47 -2
View File
@@ -34,7 +34,13 @@ pub(crate) fn commands(a: &CommandsArgs, out: &mut dyn Write) -> Result {
pub(crate) fn serve(a: &ServeArgs, err: &mut dyn Write) -> Result {
use std::sync::{Arc, Mutex};
let h = Arc::new(Mutex::new(Headless::with_workspace(a.automation.workspace()?)));
let mut h = Headless::with_workspace(a.automation.workspace()?);
let policy = crate::gpu::GpuPolicy::from_args(&a.gpu).map_err(crate::CliError::Other)?;
policy.apply_to_headless(&mut h);
for d in h.drain_diagnostics() {
let _ = writeln!(err, "warning: {d}");
}
let h = Arc::new(Mutex::new(h));
match a.port {
Some(port) => {
if a.port_from_env {
@@ -62,8 +68,12 @@ pub(crate) fn serve(a: &ServeArgs, err: &mut dyn Write) -> Result {
}
}
/// `mcp`: with the suite's `AI-MCP` flag, the open window when agents may use it, otherwise
/// headless (`mcp_live`); without the flag headless, as before it; `--headless` always headless;
/// `--bridge` (or PHOTOCRAFT_CONTROL_PORT) a `photocraft --control` app.
pub(crate) fn mcp(a: &McpArgs, err: &mut dyn Write) -> Result {
let server = match &a.bridge {
None if !a.headless && photocraft_automation::agent_link::mcp_flag() => PhotocraftMcp::live(live_config(a)?),
Some(addr) => {
if a.bridge_from_env {
// Name the mode switch, as `serve` does: the way back to headless is to unset it.
@@ -75,8 +85,43 @@ pub(crate) fn mcp(a: &McpArgs, err: &mut dyn Write) -> Result {
let token = security::client_token(a.control.control_token.as_deref(), a.control.control_token_file.as_deref())?;
PhotocraftMcp::bridge(&addr.to_string(), &token)?
}
None => PhotocraftMcp::headless_with_workspace(a.automation.workspace()?),
None => {
let mut h = Headless::with_workspace(a.automation.workspace()?);
let policy = crate::gpu::GpuPolicy::from_args(&a.gpu).map_err(crate::CliError::Other)?;
policy.apply_to_headless(&mut h);
for d in h.drain_diagnostics() {
let _ = writeln!(err, "warning: {d}");
}
PhotocraftMcp::with_headless(h)
}
};
let rt = tokio::runtime::Builder::new_multi_thread().enable_all().build()?;
Ok(rt.block_on(server.serve_stdio())?)
}
/// `mcp`: the app's settings folder, the closed-app override, the app launcher, and the headless
/// session's roots and rendering for when it works without the window.
fn live_config(a: &McpArgs) -> Result<photocraft_automation::live::LiveConfig> {
let other = |m: &str| crate::CliError::Other(m.to_string());
let dir = photocraft_automation::app_dirs::from_env()
.dir
.ok_or_else(|| other("can't find PhotoCraft's settings folder (no home folder; set PHOTOCRAFT_CONFIG_DIR)"))?;
let mut config = photocraft_automation::live::LiveConfig::new(dir);
config.when_closed = a.when_closed;
// As a headless `mcp` always did: folders that can't be opened stop the start, before the
// server answers anything, rather than at the first call that would fall back to them.
a.automation.workspace()?;
config.read_roots.clone_from(&a.automation.automation_read_root);
config.write_root = a.automation.automation_write_root.clone();
config.launch = std::env::current_exe().ok().and_then(|exe| photocraft_automation::live::launcher(&exe));
let policy = crate::gpu::GpuPolicy::from_args(&a.gpu).map_err(crate::CliError::Other)?;
config.prepare_headless = Some(Box::new(move |h| {
policy.apply_to_headless(h);
// stdout carries the protocol; the warnings a headless start has go to stderr.
let mut err = std::io::stderr();
for d in h.drain_diagnostics() {
let _ = writeln!(err, "warning: {d}");
}
}));
Ok(config)
}
+98 -3
View File
@@ -10,7 +10,7 @@ use crate::{
CliError, Result,
actions::load_actions_file,
args::{BatchArgs, DropletArgs},
output::warn_all,
output::{warn_all, warn_dedup},
};
/// Whether `a` and `b` name the same existing folder, however they are spelt (relative, with a
@@ -51,7 +51,8 @@ pub(crate) fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) ->
let (in_dir, out_dir) = (a.in_dir.as_path(), a.out.as_path());
let (actions, mut set, warnings) = load_actions_file(&a.actions, a.action.as_deref())?;
set.iter_mut().for_each(strip_shell_steps);
warn_all(err, &warnings);
let mut seen_warnings = std::collections::HashSet::<String>::new();
warn_dedup(err, &warnings, &mut seen_warnings);
let opts = ExportOptions::from(&a.export);
// Results are saved as `<out>/<stem>.<ext>`, so an `--out` that is the `--in` folder would
// replace the originals (#492).
@@ -109,17 +110,20 @@ pub(crate) fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) ->
}
std::fs::create_dir_all(out_dir)?;
let mut failures = Vec::new();
let policy = crate::gpu::GpuPolicy::from_args(&a.gpu).map_err(CliError::Other)?;
let mut renderer = policy.create_renderer();
for (input, target) in inputs.iter().zip(targets) {
let input = Path::new(&input.path);
// The selected format encodes the bytes, whatever extension `--naming` gives the file.
// Without --format, a file PhotoCraft only opens (.kra, raw, …) is saved as PSD, the
// same format `--naming`'s {ext} plans.
let ext = format.map_or_else(|| photocraft_engine::file_cmds::batch_same_format(&input.to_string_lossy()), str::to_owned);
let mut h = Headless::trusted_local();
h.set_renderer(renderer.take());
let r = (|| -> Result<Vec<String>> {
if let Some(parent) = target.parent() {
std::fs::create_dir_all(parent)?;
}
let mut h = Headless::trusted_local();
// Steps that play another action find it in the set; the session's playback stack
// stops an action that calls itself.
h.session.actions.list = set.clone();
@@ -140,15 +144,30 @@ pub(crate) fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) ->
let r = h.save(None, Some(&target), Some(&ext), &opts)?;
Ok(serde_json::from_value(r["warnings"].clone()).unwrap_or_default())
})();
let diags = h.drain_diagnostics();
// Release the item's GPU caches before the renderer moves on to the next file.
if h.session.active_index().is_some() {
let _ = h.close(None);
}
if let Some(recovered) = h.take_renderer() {
renderer = Some(recovered);
}
match r {
Ok(ws) => {
ok += 1;
let _ = writeln!(out, "ok {} -> {}", input.display(), target.display());
// Each file's own export warnings (e.g. transparency composited over white) are
// reported for that file, even when an earlier file had the same warning.
warn_all(err, &ws);
// A fallback diagnostic can also be in this file's export warnings; report it
// once, through the per-file warnings above, not twice.
let pending: Vec<String> = diags.into_iter().filter(|d| !ws.contains(d)).collect();
warn_dedup(err, &pending, &mut seen_warnings);
}
Err(e) => {
failed += 1;
let _ = writeln!(err, "FAIL {}: {e}", input.display());
warn_dedup(err, &diags, &mut seen_warnings);
failures.push((input.to_string_lossy().into_owned(), e.to_string()));
if a.stop_on_error {
break;
@@ -267,3 +286,79 @@ mod batch_action_set_tests {
let _ = std::fs::remove_dir_all(&dir);
}
}
#[cfg(test)]
mod tests {
use super::*;
use photocraft_doc::{Color, ColorMode, Document, Rect, SampleType, Size};
use photocraft_io::{BandRenderer, IoError, RenderBand, RenderError};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
struct RecordingRenderer {
calls: Arc<AtomicUsize>,
}
impl BandRenderer for RecordingRenderer {
fn render_bands(
&mut self,
doc: &Document,
rect: Rect,
band_rows: i32,
ctl: &photocraft_raster::Interrupt<'_>,
sink: &mut dyn FnMut(RenderBand) -> Result<(), IoError>,
) -> Result<(), RenderError> {
self.calls.fetch_add(1, Ordering::SeqCst);
photocraft_io::CpuRenderer.render_bands(doc, rect, band_rows, ctl, sink)
}
}
#[test]
fn batch_loop_recovers_renderer_after_error_on_first_item() {
let calls = Arc::new(AtomicUsize::new(0));
let mut renderer: Option<Box<dyn BandRenderer>> = Some(Box::new(RecordingRenderer { calls: calls.clone() }));
let tmp = std::env::temp_dir().join(format!("pc-batch-regress-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&tmp);
std::fs::create_dir_all(&tmp).unwrap();
let bad_file = tmp.join("01_bad.png");
std::fs::write(&bad_file, b"not a valid png or document file").unwrap();
let good_file = tmp.join("02_good.pcraft");
let mut good_doc = Document::with_background("test", Size::new(32, 32), ColorMode::Rgb, SampleType::U8, Color::WHITE);
let extra_layer = good_doc.layers[0].clone();
good_doc.layers.push(extra_layer);
photocraft_automation::files::save(&good_doc, &good_file, None, &Default::default(), None).unwrap();
let target_dir = tmp.join("out");
std::fs::create_dir_all(&target_dir).unwrap();
let inputs = [bad_file, good_file];
let opts = ExportOptions::default();
for (idx, input) in inputs.iter().enumerate() {
let mut h = Headless::trusted_local();
h.set_renderer(renderer.take());
let r = (|| -> Result<Vec<String>> {
h.open(input)?;
let target = target_dir.join(format!("{idx}.png"));
let r = h.save(None, Some(&target), Some("png"), &opts)?;
Ok(serde_json::from_value(r["warnings"].clone()).unwrap_or_default())
})();
if let Some(recovered) = h.take_renderer() {
renderer = Some(recovered);
}
if idx == 0 {
assert!(r.is_err(), "first corrupt item must fail");
} else {
assert!(r.is_ok(), "second valid item must succeed: {:?}", r);
}
}
assert!(renderer.is_some(), "renderer must be preserved across batch items");
assert_eq!(calls.load(Ordering::SeqCst), 1, "renderer must have been invoked on the second item");
let _ = std::fs::remove_dir_all(&tmp);
}
}
+68 -9
View File
@@ -10,7 +10,7 @@ use photocraft_io::ExportOptions;
use crate::{
CliError, Result,
args::{ConvertArgs, InfoArgs, RunArgs, Step},
output::{JsonStyle, print_json, warn_all},
output::{JsonStyle, print_json, warn_all, warn_dedup},
};
/// An output that is the input file itself, however it is spelt (relative, with `./`, through a
@@ -26,18 +26,48 @@ fn refuse_overwriting_input(in_place: bool, input: &Path, output: &Path) -> Resu
Ok(())
}
/// `N` or `N-M`, 1-based and inclusive, into a normalized `(first, last)`.
fn parse_pdf_pages(s: &str) -> Result<(u32, u32)> {
let (a, b) = s.split_once('-').unwrap_or((s, s));
let bad = || CliError::Other(format!("invalid --pdf-pages {s:?}; use N or N-M"));
let a = a.trim().parse::<u32>().map_err(|_| bad())?;
let b = b.trim().parse::<u32>().map_err(|_| bad())?;
if a == 0 || b == 0 {
return Err(CliError::Other(format!("--pdf-pages is 1-based; {s:?} starts at 0")));
}
Ok((a.min(b), a.max(b)))
}
pub(crate) fn convert(a: &ConvertArgs, _out: &mut dyn Write, err: &mut dyn Write) -> Result {
let (input, output) = (&a.input, &a.output);
let opts = ExportOptions::from(&a.export);
refuse_overwriting_input(a.in_place, input, output)?;
let import_opts = photocraft_io::ImportOptions { psd_high_memory_approved: a.approve_high_memory, ..Default::default() };
let import_opts = photocraft_io::ImportOptions {
psd_high_memory_approved: a.approve_high_memory,
pdf_dpi: a.pdf_dpi.unwrap_or(300.0),
pdf_pages: a.pdf_pages.as_deref().map(parse_pdf_pages).transpose()?,
pdf_editable: a.pdf_editable,
..Default::default()
};
let mut o = files::open_with_options(input, &import_opts)?;
// Preferences › Raw Defaults › Resolution at its default, as `run` and `info` open a raw.
photocraft_engine::file_cmds::raw_defaults(&photocraft_engine::Session::new(), &o.warnings, &mut o.document);
warn_all(err, &o.warnings);
warn_all(err, &missing_font_warnings(&o.document));
let ws = files::save(&o.document, output, a.export.format.as_deref(), &opts, None)?;
warn_all(err, &ws);
let mut seen_warnings = std::collections::HashSet::<String>::new();
warn_dedup(err, &o.warnings, &mut seen_warnings);
warn_dedup(err, &missing_font_warnings(&o.document), &mut seen_warnings);
let policy = crate::gpu::GpuPolicy::from_args(&a.gpu).map_err(CliError::Other)?;
let mut renderer = policy.create_renderer();
let ws = match renderer.as_mut() {
Some(renderer) => files::save_with_renderer(&o.document, output, a.export.format.as_deref(), &opts, None, Some(&mut **renderer)),
None => files::save(&o.document, output, a.export.format.as_deref(), &opts, None),
};
// A failed GPU export can leave fallback reasons queued: report them before the error
// propagates, or the user would never learn why the GPU was not used.
if let Some(renderer) = renderer.as_mut() {
warn_dedup(err, &renderer.drain_diagnostics(), &mut seen_warnings);
}
let ws = ws?;
warn_dedup(err, &ws, &mut seen_warnings);
Ok(())
}
@@ -45,7 +75,10 @@ pub(crate) fn info(a: &InfoArgs, out: &mut dyn Write) -> Result {
let file = &a.file;
let mut h = Headless::trusted_local();
let opened = h.open_with_approval(file, a.approve_high_memory)?;
let mut doc = h.inspect(None)?;
let mut doc = match (a.detail, h.session.active()) {
(true, Some(st)) => photocraft_engine::inspect::document_detail(st),
_ => h.inspect(None)?,
};
let mut warnings = opened["warnings"].as_array().cloned().unwrap_or_default();
if let Some(st) = h.session.active() {
warnings.extend(missing_font_warnings(&st.doc).into_iter().map(Value::String));
@@ -73,9 +106,14 @@ fn command_list(a: &RunArgs) -> Result<Vec<(String, Value)>> {
Ok(cmds)
}
/// Reported once by `run --gpu` when a step is `file.export.quickExport`.
const QUICK_EXPORT_CPU_NOTE: &str = "file.export.quickExport runs on the CPU compositor; --gpu applies to --out and the export commands that take a renderer";
pub(crate) fn run_cmds(a: &RunArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result {
let opts = ExportOptions::from(&a.export);
let mut h = Headless::trusted_local();
let policy = crate::gpu::GpuPolicy::from_args(&a.gpu).map_err(CliError::Other)?;
policy.apply_to_headless(&mut h);
// Opening, running commands and exporting can all notice the same missing font:
// one `run` invocation reports each warning line at most once.
let mut reported_fonts = std::collections::HashSet::<String>::new();
@@ -100,12 +138,25 @@ pub(crate) fn run_cmds(a: &RunArgs, out: &mut dyn Write, err: &mut dyn Write) ->
continue;
}
let r = h.command_run(&id, params).map_err(|source| CliError::Command { id: id.clone(), source })?;
if let Some(message) = photocraft_engine::actions_cmds::nested_failure(&id, &r) {
// A direct Batch reports per-file errors and continues, as in Scripts, unless it was
// cancelled, ran out of script steps or couldn't write its error log; failed action or
// script calls still stop the command list before export.
let failure = if id == "file.automate.batch" {
photocraft_engine::actions_cmds::batch_stop(&r)
} else {
photocraft_engine::actions_cmds::nested_failure(&id, &r)
};
if let Some(message) = failure {
return Err(CliError::NestedFailure { id, message });
}
let new_warnings: Vec<String> =
h.session.active().map(|st| missing_font_warnings(&st.doc)).unwrap_or_default().into_iter().filter(|w| reported_fonts.insert(w.clone())).collect();
warn_all(err, &new_warnings);
// Quick Export composites and encodes inside the engine, which has no renderer: say so
// once, so `--gpu` never looks as if it applied to it (docs/development.md, GPU).
if policy.enabled && id == "file.export.quickExport" {
warn_dedup(err, &[QUICK_EXPORT_CPU_NOTE.to_string()], &mut reported_fonts);
}
let mut result = json!({"command": id, "result": r});
if !new_warnings.is_empty() {
result["warnings"] = json!(new_warnings);
@@ -117,11 +168,19 @@ pub(crate) fn run_cmds(a: &RunArgs, out: &mut dyn Write, err: &mut dyn Write) ->
h.session.active().map(|st| missing_font_warnings(&st.doc)).unwrap_or_default().into_iter().filter(|w| reported_fonts.insert(w.clone())).collect();
warn_all(err, &remaining);
if let Some(o) = a.out.as_deref() {
let r = h.save(None, Some(o), a.export.format.as_deref(), &opts)?;
let saved = h.save(None, Some(o), a.export.format.as_deref(), &opts);
// Report GPU diagnostics even when the export fails: the fallback reason is queued
// during the failed export and would otherwise be lost on the error path.
let failed_diags: Vec<String> = h.drain_diagnostics().into_iter().filter(|w| reported_fonts.insert(w.clone())).collect();
warn_all(err, &failed_diags);
let r = saved?;
let ws: Vec<String> = serde_json::from_value(r["warnings"].clone()).unwrap_or_default();
let ws: Vec<String> = ws.into_iter().filter(|w| reported_fonts.insert(w.clone())).collect();
warn_all(err, &ws);
}
let diags = h.drain_diagnostics();
let diags: Vec<String> = diags.into_iter().filter(|w| reported_fonts.insert(w.clone())).collect();
warn_all(err, &diags);
Ok(())
}
+2
View File
@@ -38,6 +38,8 @@ pub(crate) enum CliError {
BatchOption(String),
#[error("{0} file(s) failed")]
FilesFailed(usize),
#[error("{0}")]
Other(String),
}
pub(crate) type Result<T = (), E = CliError> = std::result::Result<T, E>;
+112
View File
@@ -0,0 +1,112 @@
//! GPU acceleration policy and options for photocraft-cli.
use photocraft_automation::Headless;
use photocraft_io::BandRenderer;
/// Optional GPU composition for supported flat exports and full-size previews.
#[derive(clap::Args)]
pub(crate) struct GpuArgs {
/// Prefer GPU rendering, falling back to CPU when unavailable or unsupported
#[arg(long, conflicts_with = "no_gpu")]
pub(crate) gpu: bool,
/// Use CPU rendering, overriding PHOTOCRAFT_GPU
#[arg(long, conflicts_with = "gpu")]
pub(crate) no_gpu: bool,
}
/// Resolved GPU rendering policy.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct GpuPolicy {
pub(crate) enabled: bool,
}
impl GpuPolicy {
/// Resolve policy from arguments and environment.
///
/// Precedence:
/// - Explicit `--gpu` enables GPU.
/// - Explicit `--no-gpu` disables GPU.
/// - Neither flag: `PHOTOCRAFT_GPU` env var (1 = enabled, 0 or empty/unset = disabled).
/// Any other nonempty value is rejected.
pub(crate) fn from_args(args: &GpuArgs) -> Result<Self, String> {
if args.gpu {
return Ok(Self { enabled: true });
}
if args.no_gpu {
return Ok(Self { enabled: false });
}
match std::env::var_os("PHOTOCRAFT_GPU") {
Some(val) => {
let val = val.to_string_lossy();
let trimmed = val.trim();
if trimmed.is_empty() || trimmed == "0" {
Ok(Self { enabled: false })
} else if trimmed == "1" {
Ok(Self { enabled: true })
} else {
Err(format!("invalid value '{trimmed}' for 'PHOTOCRAFT_GPU': expected '1' or '0'"))
}
}
None => Ok(Self { enabled: false }),
}
}
/// Apply policy to a headless automation session.
pub(crate) fn apply_to_headless(&self, h: &mut Headless) {
#[cfg(all(feature = "gpu", not(target_arch = "wasm32")))]
if self.enabled {
h.enable_gpu();
}
#[cfg(any(not(feature = "gpu"), target_arch = "wasm32"))]
if self.enabled {
h.set_renderer(Some(Box::new(DisabledGpuRenderer::new())));
}
}
/// Create an optional boxed renderer under this policy.
#[cfg(all(feature = "gpu", not(target_arch = "wasm32")))]
pub(crate) fn create_renderer(&self) -> Option<Box<dyn BandRenderer>> {
if self.enabled { Some(Box::new(photocraft_automation::gpu::GpuRenderer::lazy())) } else { None }
}
#[cfg(any(not(feature = "gpu"), target_arch = "wasm32"))]
pub(crate) fn create_renderer(&self) -> Option<Box<dyn BandRenderer>> {
if self.enabled { Some(Box::new(DisabledGpuRenderer::new())) } else { None }
}
}
/// Renderer stub emitted when GPU is requested in builds compiled without `--features gpu`.
#[cfg(any(not(feature = "gpu"), target_arch = "wasm32"))]
struct DisabledGpuRenderer {
emitted: bool,
}
#[cfg(any(not(feature = "gpu"), target_arch = "wasm32"))]
impl DisabledGpuRenderer {
fn new() -> Self {
Self { emitted: false }
}
}
#[cfg(any(not(feature = "gpu"), target_arch = "wasm32"))]
impl BandRenderer for DisabledGpuRenderer {
fn render_bands(
&mut self,
_doc: &photocraft_doc::Document,
_rect: photocraft_doc::Rect,
_band_rows: i32,
_ctl: &photocraft_raster::Interrupt<'_>,
_sink: &mut dyn FnMut(photocraft_io::RenderBand) -> Result<(), photocraft_io::IoError>,
) -> Result<(), photocraft_io::RenderError> {
Err(photocraft_io::RenderError::Unavailable("GPU support is not compiled in this build (compile with --features gpu)".into()))
}
fn drain_diagnostics(&mut self) -> Vec<String> {
if self.emitted {
Vec::new()
} else {
self.emitted = true;
vec!["GPU acceleration requested but this build was compiled without GPU support (compile with --features gpu); falling back to CPU".into()]
}
}
}
+1
View File
@@ -14,6 +14,7 @@ mod automation;
mod batch;
mod document;
mod error;
mod gpu;
mod output;
pub use actions::{ActionsError, Steps, load_actions, load_actions_file, parse_actions};
+13
View File
@@ -33,6 +33,11 @@ impl From<&ExportArgs> for ExportOptions {
o.encode.dds.compression = c;
}
o.encode.dds.mipmaps = a.dds_mipmaps;
o.psd_maximize_compatibility = !a.no_maximize_compatibility;
// Conversions keep the whole packet unless asked, as Save As does (#733, #9466).
if let Some(m) = a.metadata {
o.xmp = m;
}
o
}
}
@@ -43,6 +48,14 @@ pub(crate) fn warn_all(err: &mut dyn Write, ws: &[String]) {
}
}
pub(crate) fn warn_dedup(err: &mut dyn Write, ws: &[String], seen: &mut std::collections::HashSet<String>) {
for w in ws {
if seen.insert(w.clone()) {
let _ = writeln!(err, "warning: {w}");
}
}
}
/// How [`print_json`] lays the JSON out.
pub(crate) enum JsonStyle {
Pretty,
+406 -6
View File
@@ -8,14 +8,14 @@ use serde_json::{Value, json};
/// The binary, without the variables `mcp` and `serve` fall back to: a test that wants one sets it.
fn bin() -> Command {
let mut cmd = Command::new(crate::binary());
let mut cmd = crate::command();
for var in ENV_VARS {
cmd.env_remove(var);
}
cmd
}
const ENV_VARS: [&str; 3] = ["PHOTOCRAFT_CONTROL_PORT", "PHOTOCRAFT_CONTROL_TOKEN", "PHOTOCRAFT_CONTROL_TOKEN_FILE"];
const ENV_VARS: [&str; 4] = ["PHOTOCRAFT_CONTROL_PORT", "PHOTOCRAFT_CONTROL_TOKEN", "PHOTOCRAFT_CONTROL_TOKEN_FILE", "PHOTOCRAFT_GPU"];
fn tmp(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("pc-cli-{}-{name}", std::process::id()));
@@ -167,9 +167,9 @@ fn server_modes_reject_ignored_or_conflicting_options() {
for flag in ["--control-token", "--control-token-file"] {
server_usage_error(&[sub, flag, "unused"], if sub == "mcp" { "requires --bridge" } else { "requires --port" });
}
server_usage_error(&[sub, "--automation-write-root", ".", "--automation-write-root", "."], "cannot be used multiple times");
for flag in ["--automation-read-root", "--automation-write-root"] {
server_usage_error(&[sub, flag, ".", flag, "."], "cannot be used multiple times");
server_usage_error(&[sub, &format!("{flag}=")], &format!("a value is required for '{flag} "));
server_usage_error(&[sub, &format!("{flag}=")], "root needs a non-empty directory");
server_usage_error(&[sub, flag, "--automation-write-root", "."], &format!("a value is required for '{flag} "));
}
let transport = if sub == "mcp" { "--bridge" } else { "--port" };
@@ -193,7 +193,7 @@ fn server_validation_does_not_consume_stdio_or_create_files() {
let other = d.join("other.token");
let token_flag = format!("--control-token-file={}", token.display());
let other_flag = format!("--control-token-file={}", other.display());
for tail in [&["stray"][..], &["--automation-read-root", ".", "--automation-read-root", "."], &["--port", "0"], &[&other_flag]] {
for tail in [&["stray"][..], &["--automation-write-root", ".", "--automation-write-root", "."], &["--port", "0"], &[&other_flag]] {
let mut child = bin()
.current_dir(&d)
.args(["serve", "--port", "0", &token_flag])
@@ -363,6 +363,73 @@ fn run_stops_after_failed_action_without_exporting() {
std::fs::remove_dir_all(d).unwrap();
}
/// A direct Batch keeps its partial result without preventing later commands or export.
#[test]
fn run_continues_after_batch_file_errors_and_keeps_partial_results() {
let d = tmp("run-partial-batch");
let good = d.join("good.png");
let bad = d.join("bad.png");
let batch_out = d.join("batch");
let caller_out = d.join("caller.pcraft");
write_png(&good, 6, 4, 3);
std::fs::write(&bad, b"not a PNG").unwrap();
let params = json!({"input":[good,bad],"output":batch_out,"format":"pcraft","steps":[
["layer.renameLayer",{"name":"Batch output"}]
]})
.to_string();
let stdout = ok(bin()
.args(["run", "--new", r#"{"width":8,"height":8}"#])
.args(["--cmd", "file.automate.batch", "--params", &params])
.args(["--cmd", "layer.new.layer", "--params", r#"{"name":"After batch"}"#])
.args(["--cmd", "document.inspect", "--out"])
.arg(&caller_out))
.stdout;
let rows: Vec<Value> = stdout.lines().map(|line| serde_json::from_str(line).unwrap()).collect();
assert_eq!(rows.len(), 3);
assert_eq!(rows[0]["command"], "file.automate.batch");
let result = &rows[0]["result"];
let files = result["files"].as_array().unwrap();
assert_eq!(files.len(), 1);
assert_eq!(Path::new(files[0].as_str().unwrap()).canonicalize().unwrap(), batch_out.join("good.pcraft").canonicalize().unwrap());
assert_eq!(result["errors"].as_array().unwrap().len(), 1);
assert_eq!(result["errors"][0]["file"], json!(bad));
assert!(result["errors"][0]["error"].as_str().is_some_and(|message| !message.is_empty()));
assert!(batch_out.join("good.pcraft").is_file());
assert!(!batch_out.join("bad.pcraft").exists());
assert_eq!(rows[2]["command"], "document.inspect");
assert!(rows[2]["result"]["layers"].as_array().unwrap().iter().any(|layer| layer["name"] == "After batch"));
assert!(caller_out.is_file());
let saved: Value = serde_json::from_str(&ok(bin().arg("info").arg(&caller_out)).stdout).unwrap();
assert!(saved["layers"].as_array().unwrap().iter().any(|layer| layer["name"] == "After batch"));
std::fs::remove_dir_all(d).unwrap();
}
/// A direct Batch whose error log can't be written stops the command list before export, also
/// when a file failed as well (per-file errors alone would let it go on).
#[test]
fn run_stops_when_a_direct_batch_cannot_write_its_error_log() {
let d = tmp("run-batch-log-fails");
let bad = d.join("bad.png");
let out = d.join("result.png");
std::fs::write(&bad, b"not a PNG").unwrap();
// The folder itself as the log path: the log write fails.
let params = json!({"input":[bad],"output":d.join("batch"),"format":"png","steps":[],"errorLog":d}).to_string();
let result = bin()
.args(["run", "--new", r#"{"width":8,"height":8}"#])
.args(["--cmd", "file.automate.batch", "--params", &params])
.args(["--cmd", "document.inspect", "--out"])
.arg(&out)
.output()
.unwrap();
let error = String::from_utf8_lossy(&result.stderr);
assert_eq!(result.status.code(), Some(1), "stdout: {}\nstderr: {error}", String::from_utf8_lossy(&result.stdout));
assert!(error.contains("error log"), "{error}");
let rows: Vec<Value> = String::from_utf8_lossy(&result.stdout).lines().map(|line| serde_json::from_str(line).unwrap()).collect();
assert!(rows.iter().all(|row| row["command"] != "document.inspect"), "later commands must not run");
assert!(!out.exists(), "a stopped command list must not export");
std::fs::remove_dir_all(d).unwrap();
}
#[test]
fn run_continues_after_successful_action_and_exports() {
let d = tmp("run-successful-action");
@@ -800,6 +867,24 @@ fn dds_converts_both_ways_with_the_compression_asked_for() {
}
}
/// #8064: `--no-maximize-compatibility` writes a layered PSD/PSB with Photoshop's placeholder
/// instead of the merged image, flagged in resource 1057; without it, the real image.
#[test]
fn no_maximize_compatibility_writes_the_psd_placeholder() {
let d = tmp("maximize-compat");
let a = d.join("a.png");
write_png(&a, 32, 16, 3);
for (args, ext, real) in
[(&[][..], "psd", true), (&["--no-maximize-compatibility"][..], "psd", false), (&["--no-maximize-compatibility"][..], "psb", false)]
{
let out = d.join(format!("a.{ext}"));
ok(bin().arg("run").arg(&a).args(["--cmd", "layer.new.layer"]).arg("--out").arg(&out).args(args));
let psd = craft_psd::PsdFile::from_bytes(&std::fs::read(&out).unwrap()).unwrap();
assert_eq!(psd.has_real_merged_data(), Some(real), "{args:?} {ext}");
}
std::fs::remove_dir_all(d).unwrap();
}
/// `--tga-bits` picks a TGA's bits per pixel (byte 16 of its header); anything but 24 or 32 is a
/// usage error and nothing is written.
#[test]
@@ -895,6 +980,88 @@ fn jpeg_format_chooses_the_scans() {
}
}
/// #9466: `--metadata none` leaves the document's XMP packet and free-form text out of a flat
/// export from `convert`, `run --out` and `batch`, as Export As's Metadata: None does, and changes
/// nothing else (pixels, ICC profile, resolution). The default, and `all`, keep them as before (the
/// text where the format holds it, as PNG does), and a PSD or `.pcraft` keeps the XMP either way.
/// A value it doesn't name is a usage error and nothing is written.
#[test]
fn metadata_none_leaves_out_the_document_xmp() {
const XMP: &str = "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\
<rdf:Description rdf:about=\"\" xmlns:photoshop=\"http://ns.adobe.com/photoshop/1.0/\">\
<photoshop:DocumentAncestors><rdf:Bag><rdf:li>xmp.did:11111111-2222-3333-4444-555555555555</rdf:li></rdf:Bag></photoshop:DocumentAncestors>\
</rdf:Description></rdf:RDF></x:xmpmeta>";
let d = tmp("metadata");
let input = d.join("in");
std::fs::create_dir_all(&input).unwrap();
let a = input.join("a.png");
let data: Vec<u8> = (0..8 * 6 * 4).map(|i| (i as u8).wrapping_mul(7).wrapping_add(3)).collect();
let mut img = photocraft_codecs::Image::from_u8(8, 6, photocraft_codecs::ChannelLayout::Rgba, data).unwrap();
img.meta.xmp = Some(XMP.into());
img.meta.dpi = Some((300.0, 300.0));
img.meta.text = vec![("Comment".into(), "free-form-note".into())];
// Display P3 rather than sRGB, so no export can pass for keeping it by writing its default.
let p3 = craft_cms::Builtin::DisplayP3.profile().to_bytes().to_vec();
img.icc = Some(p3.clone());
std::fs::write(&a, photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap();
let ancestors = |p: &Path| String::from_utf8_lossy(&std::fs::read(p).unwrap()).contains("DocumentAncestors");
let decoded = |p: &Path| photocraft_codecs::decode(&std::fs::read(p).unwrap()).unwrap();
let note = |p: &Path| decoded(p).meta.text.iter().any(|(_, v)| v == "free-form-note");
assert!(ancestors(&a) && note(&a), "the input carries the packet and the text");
let invert = r#"[{"command":"image.adjustments.invert"}]"#;
for ext in ["png", "webp", "jpg", "tif"] {
let mut converted_files = Vec::new();
for flag in [None, Some("all"), Some("none")] {
let extra: Vec<&str> = flag.map(|f| vec!["--metadata", f]).unwrap_or_default();
let name = format!("{ext}-{}", flag.unwrap_or("default"));
let converted = d.join(format!("convert-{name}.{ext}"));
ok(bin().arg("convert").arg(&a).arg(&converted).args(&extra));
let ran = d.join(format!("run-{name}.{ext}"));
ok(bin().arg("run").arg(&a).arg("--out").arg(&ran).args(&extra));
let o = batch_with(&d, &input, &format!("batch-{name}"), invert, &[&["--format", ext][..], &extra[..]].concat());
assert!(o.status.success(), "batch {name}: {}", String::from_utf8_lossy(&o.stderr));
let batched = d.join(format!("batch-{name}")).join(format!("a.{ext}"));
for out in [&converted, &ran, &batched] {
assert_eq!(ancestors(out), flag != Some("none"), "{name}: {}", out.display());
// PNG holds free-form text; JPEG, WebP and TIFF (but for its named tags) don't.
assert_eq!(note(out), ext == "png" && flag != Some("none"), "{name} text: {}", out.display());
}
converted_files.push(converted);
}
// Only the XMP and text go: the pixels, profile and resolution are the default export's.
let (default, none) = (decoded(&converted_files[0]), decoded(&converted_files[2]));
assert_eq!(none.data(), default.data(), "{ext}: pixels");
assert_eq!(default.icc.as_deref(), Some(&p3[..]), "{ext}: the default export keeps the input's Display P3 profile");
assert_eq!(none.icc, default.icc, "{ext}: ICC profile");
assert_eq!(none.meta.dpi, default.meta.dpi, "{ext}: resolution");
assert!(none.meta.dpi.is_some_and(|(x, y)| (x - 300.0).abs() < 0.5 && (y - 300.0).abs() < 0.5), "{ext}: {:?}", none.meta.dpi);
}
// A layered save keeps the document's XMP whatever the option.
for ext in ["psd", "pcraft"] {
let out = d.join(format!("layered.{ext}"));
ok(bin().arg("convert").arg(&a).arg(&out).args(["--metadata", "none"]));
let back = d.join(format!("layered-{ext}.png"));
ok(bin().arg("convert").arg(&out).arg(&back));
assert!(ancestors(&back), "{ext} kept the packet");
}
for bad in ["None", "exif", "0", ""] {
let out = d.join("bad.png");
let (mut convert, mut run) = (bin(), bin());
convert.arg("convert").arg(&a).arg(&out).args(["--metadata", bad]);
run.arg("run").arg(&a).arg("--out").arg(&out).args(["--metadata", bad]);
for cmd in [&mut convert, &mut run] {
let o = cmd.output().unwrap();
let err = String::from_utf8_lossy(&o.stderr);
assert_eq!(o.status.code(), Some(2), "--metadata {bad}: {err}");
assert!(err.contains("--metadata") && err.contains("expected none or all"), "--metadata {bad}: {err}");
assert!(!out.exists(), "--metadata {bad} wrote a file");
}
let o = batch_with(&d, &input, "bad-batch", invert, &["--metadata", bad]);
assert_eq!(o.status.code(), Some(2), "batch --metadata {bad}");
assert!(!d.join("bad-batch").exists(), "batch --metadata {bad} wrote a folder");
}
}
/// #492: an `--out` folder that is the `--in` folder, however it is spelt, is refused before
/// anything is written, unless `--in-place` asks for it.
#[test]
@@ -1275,7 +1442,7 @@ fn batch_plays_a_photoshop_actions_file() {
fn extensionless_version_12_actions_file_is_read_as_atn() {
let d = tmp("atn-v12");
let path = d.join("Legacy Actions");
std::fs::write(&path, include_bytes!("../../../../crates/psd/tests/fixtures/atn/v12-commands.atn")).unwrap();
std::fs::write(&path, include_bytes!("../../../../crates/engine/tests/fixtures/atn/v12-commands.atn")).unwrap();
let (steps, set, warnings) = photocraft_cli::load_actions_file(&path, None).unwrap();
assert_eq!(set.len(), 1);
assert_eq!(steps, vec![("actions.play".to_string(), json!({"action": set[0].name}))]);
@@ -1690,6 +1857,120 @@ fn batch_skips_deselect_with_nothing_selected() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn every_configured_read_root_must_be_a_valid_directory() {
let d = tmp("invalid-read-roots");
let good = d.join("good");
std::fs::create_dir_all(&good).unwrap();
let file = d.join("file");
std::fs::write(&file, b"not a directory").unwrap();
for sub in ["mcp", "serve"] {
for invalid in [d.join("missing"), file.clone()] {
for roots in [[&good, &invalid], [&invalid, &good]] {
let o = bin()
.arg(sub)
.arg("--automation-read-root")
.arg(roots[0])
.arg(format!("--automation-read-root={}", roots[1].display()))
.stdin(Stdio::null())
.output()
.unwrap();
assert_eq!(o.status.code(), Some(1), "{sub}: {}", String::from_utf8_lossy(&o.stderr));
assert!(String::from_utf8_lossy(&o.stderr).contains("automation read root"));
assert!(o.stdout.is_empty(), "invalid roots must fail before the server starts");
}
}
}
}
#[test]
fn serve_reads_roots_in_order_and_supports_absolute_paths_in_each_root() {
let d = tmp("serve-read-roots");
let first = d.join("first");
let second = d.join("second");
std::fs::create_dir_all(&first).unwrap();
std::fs::create_dir_all(&second).unwrap();
write_png(&first.join("shared.png"), 3, 2, 3);
write_png(&second.join("shared.png"), 7, 4, 5);
write_png(&second.join("fallback.png"), 6, 5, 7);
let mut child = bin()
.args(["serve", "--automation-read-root"])
.arg(&first)
.arg(format!("--automation-read-root={}", second.display()))
.arg("--automation-read-root")
.arg(&first)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let mut stdin = child.stdin.take().unwrap();
for (id, path) in [(1, "shared.png".into()), (2, "fallback.png".into()), (3, second.join("shared.png").to_string_lossy().into_owned())] {
writeln!(stdin, "{}", json!({"id": id, "method": "doc.open", "params": {"path": path}})).unwrap();
}
drop(stdin);
let output = child.wait_with_output().unwrap();
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
let replies: Vec<Value> = String::from_utf8(output.stdout).unwrap().lines().map(|line| serde_json::from_str(line).unwrap()).collect();
assert_eq!(replies.len(), 3);
for (reply, (width, height)) in replies.iter().zip([(3, 2), (6, 5), (7, 4)]) {
assert_eq!(reply["ok"], true, "{reply}");
assert_eq!(reply["result"]["width"], width, "{reply}");
assert_eq!(reply["result"]["height"], height, "{reply}");
}
}
#[test]
fn mcp_reads_roots_in_order_with_fallback() {
let d = tmp("mcp-read-roots");
let first = d.join("first");
let second = d.join("second");
std::fs::create_dir_all(&first).unwrap();
std::fs::create_dir_all(&second).unwrap();
write_png(&first.join("shared.png"), 3, 2, 3);
write_png(&second.join("shared.png"), 7, 4, 5);
write_png(&second.join("fallback.png"), 6, 5, 7);
let mut child = bin()
.arg("mcp")
.arg(format!("--automation-read-root={}", first.display()))
.arg("--automation-read-root")
.arg(&second)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
let mut stdin = child.stdin.take().unwrap();
let mut stdout = BufReader::new(child.stdout.take().unwrap());
let mut send = |value: Value| {
writeln!(stdin, "{value}").unwrap();
stdin.flush().unwrap();
};
let mut recv = |id: u64| -> Value {
loop {
let mut line = String::new();
assert!(stdout.read_line(&mut line).unwrap() > 0, "server closed");
let value: Value = serde_json::from_str(&line).unwrap();
if value["id"] == id {
return value;
}
}
};
send(json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{
"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"0"}}}));
assert_eq!(recv(1)["result"]["serverInfo"]["name"], "photocraft");
send(json!({"jsonrpc":"2.0","method":"notifications/initialized"}));
for (id, path, width) in [(2, "shared.png", 3), (3, "fallback.png", 6)] {
send(json!({"jsonrpc":"2.0","id":id,"method":"tools/call","params":{"name":"doc_open","arguments":{"path":path}}}));
let reply = recv(id);
assert_ne!(reply["result"]["isError"], true, "{reply}");
let opened: Value = serde_json::from_str(reply["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
assert_eq!(opened["width"], width, "{reply}");
}
let _ = child.kill();
let _ = child.wait();
}
/// TIFF Options from the command line (#8827): `--tiff-compression`, `--tiff-transparency on|off`
/// and `--tiff-pyramid`; a bad value is a usage error that writes nothing.
#[test]
@@ -1721,3 +2002,122 @@ fn tiff_options_choose_compression_transparency_and_pyramid() {
assert!(!out.exists(), "{flag} {bad} wrote a file");
}
}
#[test]
fn info_detail_adds_text_runs_and_antialiasing() {
fn type_layer(doc: &Value) -> Option<&Value> {
let mut stack: Vec<&Value> = doc["layers"].as_array()?.iter().collect();
while let Some(l) = stack.pop() {
if l["kind"] == "Type" {
return Some(l);
}
stack.extend(l["children"].as_array().into_iter().flatten());
}
None
}
let dir = tmp("info-detail");
let file = dir.join("t.psd");
ok(bin()
.args(["run", "--new", r#"{"width":64,"height":64}"#, "--cmd", "type.create", "--params", r#"{"text":"Hi","x":4,"y":30,"name":"T"}"#, "--out"])
.arg(&file));
let plain: Value = serde_json::from_str(&ok(bin().arg("info").arg(&file).arg("--compact")).stdout).unwrap();
let text = &type_layer(&plain).expect("type layer")["text"];
assert!(text.get("runs").is_none() && text.get("antialias").is_none(), "{text}");
let detail: Value = serde_json::from_str(&ok(bin().arg("info").arg(&file).args(["--compact", "--detail"])).stdout).unwrap();
let text = &type_layer(&detail).expect("type layer")["text"];
assert!(text.get("antialias").is_some(), "{text}");
assert!(text["runs"].as_array().is_some_and(|r| !r.is_empty()), "{text}");
let _ = std::fs::remove_dir_all(&dir);
}
/// Flags that don't go together are usage errors before anything starts. Adding PhotoCraft to an
/// MCP client is the ArtCraft Launcher's job, so there is no `mcp install`, and plain `mcp` does
/// what `--live` did, so there is no `--live` either.
#[test]
fn mcp_rejects_mismatched_flags() {
for (args, needle) in [
(&["mcp", "install"][..], "install"),
(&["mcp", "--live"], "--live"),
(&["mcp", "--client", "json"], "--client"),
(&["mcp", "--headless", "--bridge", "127.0.0.1:1"], "--bridge"),
(&["mcp", "--headless", "--control-token-file", "t"], "--control-token-file"),
(&["mcp", "--headless", "--when-closed", "launch"], "--when-closed"),
(&["mcp", "--when-closed", "sometimes"], "sometimes"),
(&["mcp", "--bridge", "127.0.0.1:1", "--when-closed", "error"], "--when-closed"),
] {
let o = bin().args(args).stdin(Stdio::null()).output().unwrap();
let err = String::from_utf8_lossy(&o.stderr);
assert_eq!(o.status.code(), Some(2), "{args:?}: {err}");
assert!(err.contains(needle), "{args:?}: {err}");
}
}
/// One MCP exchange with `photocraft-cli mcp <args>`: initialize, then each tool call; returns the
/// tool results.
fn mcp_session(args: &[&str], env: &[(&str, &std::ffi::OsStr)], calls: &[(&str, Value)]) -> Vec<Value> {
let mut cmd = bin();
cmd.args(args).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null());
for (k, v) in env {
cmd.env(k, v);
}
let mut child = cmd.spawn().unwrap();
let mut stdin = child.stdin.take().unwrap();
let mut stdout = BufReader::new(child.stdout.take().unwrap());
let mut send = |v: Value| {
writeln!(stdin, "{v}").unwrap();
stdin.flush().unwrap();
};
let mut recv = |id: u64| -> Value {
loop {
let mut line = String::new();
assert!(stdout.read_line(&mut line).unwrap() > 0, "server closed");
let v: Value = serde_json::from_str(&line).unwrap();
if v["id"] == id {
return v;
}
}
};
send(json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{
"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"0"}}}));
recv(1);
send(json!({"jsonrpc":"2.0","method":"notifications/initialized"}));
let mut out = Vec::new();
for (i, (name, arguments)) in calls.iter().enumerate() {
let id = 2 + i as u64;
send(json!({"jsonrpc":"2.0","id":id,"method":"tools/call","params":{"name":name,"arguments":arguments}}));
out.push(recv(id)["result"].clone());
}
drop(stdin);
let _ = child.kill();
let _ = child.wait();
out
}
/// Plain `mcp` without the person's consent works headless, as it always did: commands run, UI
/// tools say they need the open app. `--headless` too, and it doesn't read a PHOTOCRAFT_CONTROL_PORT
/// exported for another tool (here not even a port).
#[test]
fn mcp_without_consent_works_headless() {
let dir = tmp("mcp-plain");
let empty = tmp("mcp-plain-launcher");
// `crate::command()` keeps the machine's launcher and flags out already; this test names its
// own settings and an empty launcher folder as well, to say what it relies on.
let env = [("PHOTOCRAFT_CONFIG_DIR", dir.as_os_str()), ("CRAFT_MCP_DIR", empty.as_os_str())];
let calls = [("command_list", json!({})), ("ui_inspect", json!({}))];
let r = mcp_session(&["mcp", "--when-closed", "error"], &env, &calls);
assert_ne!(r[0]["isError"], true, "headless commands run: {}", r[0]);
assert_eq!(r[1]["isError"], true, "{}", r[1]);
assert!(r[1]["content"][0]["text"].as_str().unwrap().contains("bridge"), "{}", r[1]);
let mut env = env.to_vec();
env.push(("PHOTOCRAFT_CONTROL_PORT", std::ffi::OsStr::new("not-a-port")));
let r = mcp_session(&["mcp", "--headless"], &env, &calls[..1]);
assert_ne!(r[0]["isError"], true, "{}", r[0]);
// Without the `AI-MCP` flag a Control Port saved before the agents switch (which the app
// reads as "agents may connect") still leaves plain `mcp` headless: it neither looks for
// the app nor applies When PhotoCraft Is Closed ("error" would fail this call).
std::fs::write(dir.join("preferences.json"), r#"{"integrations": {"controlPort": 7878}}"#).unwrap();
let r = mcp_session(&["mcp", "--when-closed", "error"], &env[..2], &calls[..1]);
assert_ne!(r[0]["isError"], true, "without the flag plain mcp stays headless: {}", r[0]);
let _ = std::fs::remove_dir_all(&dir);
let _ = std::fs::remove_dir_all(&empty);
}
+335
View File
@@ -0,0 +1,335 @@
//! Tests for photocraft-cli GPU rendering flags, precedence, and fallback behavior.
use std::path::{Path, PathBuf};
use std::process::Command;
use serde_json::Value;
fn bin() -> Command {
let mut cmd = crate::command();
cmd.env_remove("PHOTOCRAFT_CONTROL_PORT");
cmd.env_remove("PHOTOCRAFT_CONTROL_TOKEN");
cmd.env_remove("PHOTOCRAFT_CONTROL_TOKEN_FILE");
cmd.env_remove("PHOTOCRAFT_GPU");
cmd
}
fn tmp(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("pc-cli-gpu-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
fn write_png(path: &Path, w: u32, h: u32) {
let data: Vec<u8> = (0..w * h * 4).map(|i| (i as u8).wrapping_mul(7)).collect();
let img = photocraft_codecs::Image::from_u8(w, h, photocraft_codecs::ChannelLayout::Rgba, data).unwrap();
std::fs::write(path, photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap();
}
#[test]
fn gpu_and_no_gpu_conflict() {
let d = tmp("conflict");
let in_png = d.join("in.png");
let out_png = d.join("out.png");
write_png(&in_png, 16, 16);
let o = bin().args(["convert", "--gpu", "--no-gpu", in_png.to_str().unwrap(), out_png.to_str().unwrap()]).output().unwrap();
assert_eq!(o.status.code(), Some(2));
let stderr = String::from_utf8_lossy(&o.stderr);
assert!(stderr.contains("cannot be used with") || stderr.contains("conflicts with"), "{stderr}");
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn gpu_env_var_validation() {
let d = tmp("env_val");
let in_png = d.join("in.png");
let out_png = d.join("out.png");
write_png(&in_png, 16, 16);
// Invalid non-empty value rejected with usage error naming the variable
for bad in ["2", "true", "yes", "false", "on", "off"] {
let o = bin().env("PHOTOCRAFT_GPU", bad).args(["convert", in_png.to_str().unwrap(), out_png.to_str().unwrap()]).output().unwrap();
assert_eq!(o.status.code(), Some(2), "expected exit 2 for PHOTOCRAFT_GPU={bad}");
let stderr = String::from_utf8_lossy(&o.stderr);
assert!(stderr.contains("PHOTOCRAFT_GPU"), "expected stderr to name variable: {stderr}");
assert!(stderr.contains("expected '1' or '0'"), "expected usage note: {stderr}");
}
// Empty or blank value is accepted as unset (CPU default)
for empty in ["", " "] {
let out_sub = d.join(format!("out_{}.png", empty.trim()));
let o = bin().env("PHOTOCRAFT_GPU", empty).args(["convert", in_png.to_str().unwrap(), out_sub.to_str().unwrap()]).output().unwrap();
assert!(o.status.success(), "expected success for PHOTOCRAFT_GPU={empty:?}");
assert!(out_sub.is_file());
}
let _ = std::fs::remove_dir_all(&d);
}
#[cfg(unix)]
#[test]
fn gpu_env_var_rejects_a_non_utf8_value() {
use std::ffi::OsString;
use std::os::unix::ffi::OsStringExt;
let d = tmp("env_non_utf8");
let in_png = d.join("in.png");
let out_png = d.join("out.png");
write_png(&in_png, 16, 16);
let bad = OsString::from_vec(vec![0xff, 0xfe]);
let o = bin().env("PHOTOCRAFT_GPU", bad).args(["convert", in_png.to_str().unwrap(), out_png.to_str().unwrap()]).output().unwrap();
assert_eq!(o.status.code(), Some(2), "a non-UTF-8 PHOTOCRAFT_GPU must be a usage error");
let stderr = String::from_utf8_lossy(&o.stderr);
assert!(stderr.contains("PHOTOCRAFT_GPU"), "the usage error must name the variable: {stderr}");
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn explicit_flags_override_environment() {
let d = tmp("override");
let in_png = d.join("in.png");
let in_layers = d.join("in.pcraft");
let out1 = d.join("out1.png");
let out2 = d.join("out2.png");
write_png(&in_png, 16, 16);
// A single-layer PNG takes the native export path and never calls the renderer; a
// multi-layer document composites, so it observes whether `--gpu` reached the backend.
let o = bin().args(["run", "--new", r#"{"width":16,"height":16}"#, "--cmd", "layer.new.layer", "--out", in_layers.to_str().unwrap()]).output().unwrap();
assert!(o.status.success(), "stderr: {}", String::from_utf8_lossy(&o.stderr));
// --no-gpu overrides PHOTOCRAFT_GPU=1
let o = bin().env("PHOTOCRAFT_GPU", "1").args(["convert", "--no-gpu", in_png.to_str().unwrap(), out1.to_str().unwrap()]).output().unwrap();
assert!(o.status.success(), "stderr: {}", String::from_utf8_lossy(&o.stderr));
assert!(out1.is_file());
// --gpu overrides PHOTOCRAFT_GPU=0
let o = bin().env("PHOTOCRAFT_GPU", "0").args(["convert", "--gpu", in_layers.to_str().unwrap(), out2.to_str().unwrap()]).output().unwrap();
assert!(o.status.success(), "stderr: {}", String::from_utf8_lossy(&o.stderr));
assert!(out2.is_file());
let stderr = String::from_utf8_lossy(&o.stderr);
// The renderer reports either its adapter, an unavailable adapter, or (in a build without
// GPU support) that GPU rendering was requested; the CPU default emits none of these.
let markers = ["GPU adapter:", "no GPU adapter available", "could not build GPU compositor", "falling back to CPU"];
assert!(markers.iter().any(|marker| stderr.contains(marker)), "explicit --gpu must reach the renderer when the environment disables it: {stderr}");
// Explicit flag overrides even bad environment value
let out3 = d.join("out3.png");
let o = bin().env("PHOTOCRAFT_GPU", "invalid").args(["convert", "--no-gpu", in_png.to_str().unwrap(), out3.to_str().unwrap()]).output().unwrap();
assert!(o.status.success(), "stderr: {}", String::from_utf8_lossy(&o.stderr));
assert!(out3.is_file());
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn mcp_bridge_rejects_explicit_gpu_flags_and_ignores_env() {
// Explicit --gpu with --bridge rejected
let o = bin().args(["mcp", "--bridge", "127.0.0.1:50000", "--gpu"]).output().unwrap();
assert_eq!(o.status.code(), Some(2));
let stderr = String::from_utf8_lossy(&o.stderr);
assert!(stderr.contains("configure rendering on the desktop app"), "{stderr}");
// Explicit --no-gpu with --bridge rejected
let o = bin().args(["mcp", "--bridge", "127.0.0.1:50000", "--no-gpu"]).output().unwrap();
assert_eq!(o.status.code(), Some(2));
let stderr = String::from_utf8_lossy(&o.stderr);
assert!(stderr.contains("configure rendering on the desktop app"), "{stderr}");
// An invalid PHOTOCRAFT_GPU value is ignored in bridge mode: the desktop process controls
// rendering, so the bridge must not validate the variable or reject the request for it.
let o = bin().env("PHOTOCRAFT_GPU", "invalid").args(["mcp", "--bridge", "127.0.0.1:50000"]).stdin(std::process::Stdio::null()).output().unwrap();
let stderr = String::from_utf8_lossy(&o.stderr);
assert!(!stderr.contains("PHOTOCRAFT_GPU"), "bridge mode must ignore the GPU environment: {stderr}");
}
#[test]
fn convert_and_run_honor_gpu_flag_and_preserve_stdout_protocol() {
let d = tmp("protocol");
let out_png = d.join("out.png");
// run --gpu output on stdout is clean JSON
let o =
bin().args(["run", "--gpu", "--new", r#"{"width":32,"height":32}"#, "--cmd", "layer.new.layer", "--out", out_png.to_str().unwrap()]).output().unwrap();
assert!(o.status.success(), "stderr: {}", String::from_utf8_lossy(&o.stderr));
assert!(out_png.is_file());
let stdout = String::from_utf8_lossy(&o.stdout);
for line in stdout.lines() {
let v: Value = serde_json::from_str(line).expect("each stdout line must be valid JSON");
assert!(v.get("command").is_some());
}
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn batch_recovers_renderer_after_failed_item_and_preserves_gpu_policy() {
let d = tmp("batch_regress");
let in_dir = d.join("in");
let out_dir = d.join("out");
std::fs::create_dir_all(&in_dir).unwrap();
std::fs::create_dir_all(&out_dir).unwrap();
// First item is corrupt and fails to open
let corrupt_png = in_dir.join("01_corrupt.png");
std::fs::write(&corrupt_png, b"invalid png bytes").unwrap();
// Second item is valid
let valid_png = in_dir.join("02_valid.png");
write_png(&valid_png, 32, 32);
let actions = d.join("actions.json");
std::fs::write(&actions, serde_json::json!([{"command": "layer.new.layer", "params": {"name": "Batch"}}]).to_string()).unwrap();
let o = bin()
.args(["batch", "--gpu", "--actions"])
.arg(&actions)
.args(["--in", in_dir.to_str().unwrap(), "--out", out_dir.to_str().unwrap()])
.output()
.unwrap();
// Exit code 1 because 1 file failed
assert_eq!(o.status.code(), Some(1));
let stdout = String::from_utf8_lossy(&o.stdout);
let stderr = String::from_utf8_lossy(&o.stderr);
assert!(stdout.contains("1 succeeded, 1 failed"), "stdout: {stdout}");
assert!(stderr.contains("FAIL"), "stderr must report failing item: {stderr}");
let markers = ["GPU adapter:", "no GPU adapter available", "could not build GPU compositor", "falling back to CPU"];
assert!(markers.iter().any(|marker| stderr.contains(marker)), "--gpu must reach the batch renderer: {stderr}");
assert!(out_dir.join("02_valid.png").is_file(), "second item must have been saved successfully");
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn diagnostics_preserve_clean_stdout_and_emit_to_stderr() {
let d = tmp("diag_clean");
let in_png = d.join("in.png");
let out_png = d.join("out.png");
write_png(&in_png, 32, 32);
let o = bin().args(["convert", "--gpu", in_png.to_str().unwrap(), out_png.to_str().unwrap()]).output().unwrap();
assert!(o.status.success(), "stderr: {}", String::from_utf8_lossy(&o.stderr));
assert!(out_png.is_file());
// Convert emits no stdout; diagnostics must go to stderr
assert!(o.stdout.is_empty(), "convert stdout must remain completely empty, got: {:?}", String::from_utf8_lossy(&o.stdout));
let stderr = String::from_utf8_lossy(&o.stderr);
assert!(stderr.contains("falling back to CPU"), "single-layer convert must report its CPU fallback on stderr: {stderr}");
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn serve_gpu_preserves_clean_protocol_stdout_and_drains_diagnostics_to_stderr() {
use std::io::{BufRead, BufReader, Write};
use std::process::Stdio;
let mut child = bin().args(["serve", "--gpu"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
let mut stdin = child.stdin.take().unwrap();
let mut stdout = BufReader::new(child.stdout.take().unwrap());
// 1. Initial valid command
writeln!(stdin, "{}", serde_json::json!({"id": 1, "method": "doc.new", "params": {"width": 16, "height": 16}})).unwrap();
stdin.flush().unwrap();
let mut line1 = String::new();
assert!(stdout.read_line(&mut line1).unwrap() > 0, "server must respond");
let v1: Value = serde_json::from_str(&line1).expect("line 1 on stdout must be valid JSON");
assert_eq!(v1["id"], 1);
assert_eq!(v1["ok"], true, "{v1}");
// 2. A second layer so the render below composites instead of taking the native path.
writeln!(stdin, "{}", serde_json::json!({"id": 2, "method": "engine.execute", "params": {"command": "layer.new.layer", "params": {"name": "Top"}}}))
.unwrap();
stdin.flush().unwrap();
let mut line2 = String::new();
assert!(stdout.read_line(&mut line2).unwrap() > 0, "server must respond to the layer command");
let v2: Value = serde_json::from_str(&line2).expect("line 2 on stdout must be valid JSON");
assert_eq!(v2["id"], 2);
assert_eq!(v2["ok"], true, "{v2}");
// 3. Failure recovery: invalid request receives error reply without crashing server
writeln!(stdin, "{}", serde_json::json!({"id": 3, "method": "invalid.nonexistent.method", "params": {}})).unwrap();
stdin.flush().unwrap();
let mut line3 = String::new();
assert!(stdout.read_line(&mut line3).unwrap() > 0, "server must respond to invalid request");
let v3: Value = serde_json::from_str(&line3).expect("line 3 on stdout must be valid JSON");
assert_eq!(v3["id"], 3);
assert_eq!(v3["ok"], false, "{v3}");
// 4. Subsequent valid command still succeeds (proves session & renderer recovery)
writeln!(stdin, "{}", serde_json::json!({"id": 4, "method": "doc.inspect"})).unwrap();
stdin.flush().unwrap();
let mut line4 = String::new();
assert!(stdout.read_line(&mut line4).unwrap() > 0, "server must respond to the inspect request");
let v4: Value = serde_json::from_str(&line4).expect("line 4 on stdout must be valid JSON");
assert_eq!(v4["id"], 4);
assert_eq!(v4["ok"], true, "{v4}");
// 5. Render the composite: one JSON line on stdout, diagnostics only on stderr.
writeln!(stdin, "{}", serde_json::json!({"id": 5, "method": "doc.render", "params": {"maxSide": 16}})).unwrap();
stdin.flush().unwrap();
let mut line5 = String::new();
assert!(stdout.read_line(&mut line5).unwrap() > 0, "server must answer the render request");
let v5: Value = serde_json::from_str(&line5).expect("line 5 on stdout must be valid JSON");
assert_eq!(v5["id"], 5);
assert_eq!(v5["ok"], true, "{v5}");
assert!(v5["result"]["base64"].as_str().is_some_and(|b| !b.is_empty()), "render must return PNG bytes: {v5}");
// Close stdin and verify graceful exit
drop(stdin);
let output = child.wait_with_output().unwrap();
assert!(output.status.success());
// Every render that reaches the renderer reports its adapter or why it fell back, whichever
// build and adapter this test runs on.
// `doc.render` returns the diagnostics of its own render in the reply's `warnings`; any left
// in the queue go to stderr. Either way they stay off the protocol lines' framing.
let stderr = String::from_utf8_lossy(&output.stderr);
let reported = format!("{stderr}\n{}", v5["result"]["warnings"]);
let markers = ["GPU adapter:", "no GPU adapter available", "could not build GPU compositor", "falling back to CPU", "GPU acceleration requested"];
assert!(markers.iter().any(|m| reported.contains(m)), "render must report its GPU backend or fallback in its reply or on stderr: {reported}");
}
#[test]
fn cpu_default_does_not_emit_gpu_warnings() {
let d = tmp("cpu_default");
let in_png = d.join("in.png");
let out_png = d.join("out.png");
write_png(&in_png, 16, 16);
let o = bin().args(["convert", in_png.to_str().unwrap(), out_png.to_str().unwrap()]).output().unwrap();
assert!(o.status.success(), "stderr: {}", String::from_utf8_lossy(&o.stderr));
assert!(out_png.is_file());
let stderr = String::from_utf8_lossy(&o.stderr);
assert!(!stderr.contains("GPU"), "default CPU convert should not emit GPU warnings, got: {stderr}");
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn run_gpu_quick_export_reports_that_it_runs_on_the_cpu() {
let d = tmp("quick_export");
let out_png = d.join("quick.png");
let params = format!(r#"{{"path":{}}}"#, serde_json::to_string(&out_png.to_string_lossy()).unwrap());
let args = ["run", "--new", r#"{"width":16,"height":16,"background":"white"}"#, "--cmd", "file.export.quickExport", "--params", params.as_str()];
let o = bin().args(args).arg("--gpu").output().unwrap();
assert!(o.status.success(), "stderr: {}", String::from_utf8_lossy(&o.stderr));
assert!(out_png.is_file());
let stderr = String::from_utf8_lossy(&o.stderr);
assert_eq!(stderr.matches("quickExport runs on the CPU compositor").count(), 1, "one CPU note expected: {stderr}");
let o = bin().args(args).output().unwrap();
assert!(o.status.success());
assert!(!String::from_utf8_lossy(&o.stderr).contains("runs on the CPU compositor"), "no note without --gpu");
let _ = std::fs::remove_dir_all(&d);
}
+19
View File
@@ -1,12 +1,31 @@
//! The crate's integration tests, linked into one test binary.
mod cli;
mod gpu;
#[cfg(all(target_os = "linux", target_env = "gnu"))]
mod malloc_tuning;
mod man_and_completions;
mod orientation;
mod psd_write_oracle;
/// Nextest archives relocate binaries; plain Cargo keeps the compile-time path valid.
fn binary() -> std::ffi::OsString {
std::env::var_os("NEXTEST_BIN_EXE_photocraft_cli").unwrap_or_else(|| env!("CARGO_BIN_EXE_photocraft-cli").into())
}
/// The CLI, kept away from this machine's own PhotoCraft settings, ArtCraft Launcher and feature
/// flags: plain `mcp` works in the open app when the launcher's switch lets agents use it, and
/// would otherwise find (or start) the developer's own PhotoCraft. A test that needs a settings
/// folder of its own sets `PHOTOCRAFT_CONFIG_DIR` again; the last value wins.
fn command() -> std::process::Command {
let base = std::env::temp_dir().join(format!("pc-cli-it-isolated-{}", std::process::id()));
let settings = base.join("settings");
let _ = std::fs::create_dir_all(&settings);
let mut cmd = std::process::Command::new(binary());
cmd.env("PHOTOCRAFT_CONFIG_DIR", &settings)
.env("CRAFT_MCP_DIR", base.join("launcher"))
.env("CRAFT_FLAGS_FILE", base.join("flags.toml"))
.env_remove("CRAFT_FLAGS");
cmd
}
@@ -2,13 +2,13 @@
//! and a value the user set.
use std::io::{BufRead, BufReader, Write};
use std::process::{Command, Stdio};
use std::process::Stdio;
use photocraft_engine::malloc_tuning::{TRIM_THRESHOLD, TRIM_THRESHOLD_VAR};
/// The environment of a running `serve` once it answered a request, as `NAME=value` entries.
fn serve_environ(set: Option<&str>) -> Vec<String> {
let mut cmd = Command::new(crate::binary());
let mut cmd = crate::command();
for var in [TRIM_THRESHOLD_VAR, "MALLOC_MMAP_THRESHOLD_", "MALLOC_TOP_PAD_", "MALLOC_MMAP_MAX_", "MALLOC_ARENA_MAX", "GLIBC_TUNABLES"] {
cmd.env_remove(var);
}
+1 -1
View File
@@ -10,7 +10,7 @@ use photocraft_codecs::{ChannelLayout, DecodeOptions, EncodeOptions, Format, Ima
use serde_json::Value;
fn bin() -> Command {
Command::new(crate::binary())
crate::command()
}
fn tmp(name: &str) -> PathBuf {
@@ -0,0 +1,45 @@
//! Exercise the recipe runner with the real CLI and a synthetic editable PSD.
use std::fs;
use std::path::Path;
use std::process::Command;
use serde_json::{Value, json};
#[test]
fn edited_psd_roundtrip_is_checked_and_bad_expectations_fail() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
let base = root.join("base.psd");
let cli = crate::binary();
let made = Command::new(&cli)
.args(["run", "--new", r#"{"width":64,"height":64}"#, "--cmd", "type.create", "--params", r#"{"text":"Oracle","x":4,"y":30,"name":"Oracle"}"#, "--out"])
.arg(&base)
.output()
.unwrap();
assert!(made.status.success(), "{}", String::from_utf8_lossy(&made.stderr));
let hash = xtask::sha256::hex(&fs::read(&base).unwrap());
let mut recipe = json!({"version":1,"corpus_revision":"synthetic","cases":[{
"id":"style", "base":"base.psd", "base_sha256":hash, "target":{"kind":"Type","name":"Oracle"},
"commands":[{"command":"type.antiAlias.crisp","params":{}}],
"checks":[{"op":"changed_to","path":"/text/antialias","value":"Crisp"},{"op":"unchanged","path":"/text/text"}]
}]});
let recipe_path = root.join("recipes.json");
let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
fs::write(&recipe_path, serde_json::to_vec(&recipe).unwrap()).unwrap();
let cli_path = Path::new(&cli).to_str().unwrap();
let corpus = root.to_str().unwrap();
let recipe_name = recipe_path.to_str().unwrap();
let output = root.join("success");
let args = [recipe_name, corpus, cli_path, output.to_str().unwrap()];
xtask::psd_write_oracle::run(&src, &args).unwrap();
let report: Value = serde_json::from_slice(&fs::read(output.join("report.json")).unwrap()).unwrap();
assert_eq!(report["cases"][0]["status"], "pass");
assert_eq!(report["cases"][0]["photoshop"]["opens"], "not_run");
recipe["cases"][0]["checks"][0]["value"] = json!("Sharp");
fs::write(&recipe_path, serde_json::to_vec(&recipe).unwrap()).unwrap();
let bad_output = root.join("failure");
assert!(xtask::psd_write_oracle::run(&src, &[recipe_name, corpus, cli_path, bad_output.to_str().unwrap()]).is_err());
let bad: Value = serde_json::from_slice(&fs::read(bad_output.join("report.json")).unwrap()).unwrap();
assert_eq!(bad["cases"][0]["status"], "fail");
}
+14
View File
@@ -16,6 +16,15 @@
this page, no Rust runs to say so, so the page itself shows what to do after a while. */
#photocraft_stalled { color: #8c8c8c; visibility: hidden; animation: photocraft-stalled 0s 20s forwards; }
@keyframes photocraft-stalled { to { visibility: visible; } }
/* Revealed by the app when the module traps (an allocation it could not satisfy, or a panic):
the page would otherwise sit on the last frame, frozen. Static text, so it shows even if Rust
can no longer build any. */
#photocraft_stopped { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center;
padding: 0 16px; text-align: center; color: #e0e0e0; background: rgba(38, 38, 38, 0.92); font: 14px system-ui, sans-serif; pointer-events: auto; }
#photocraft_stopped[hidden] { display: none; }
#photocraft_stopped p { margin: 0 0 8px; max-width: 460px; line-height: 1.5; }
#photocraft_stopped a { color: #ffffff; }
#photocraft_stopped_detail { color: #b8b8b8; }
</style>
</head>
<body>
@@ -26,5 +35,10 @@
download or come from a different version of this page. <a href="">Reload</a> to try again; the browser
console lists what failed.</p>
</div>
<div id="photocraft_stopped" hidden role="alert">
<p><strong>PhotoCraft stopped.</strong></p>
<p>Changes since the last save in this tab can't be recovered. <a href="">Reload</a> to start again.</p>
<p id="photocraft_stopped_detail"></p>
</div>
</body>
</html>
+4 -3
View File
@@ -7,7 +7,7 @@ license.workspace = true
publish = false
[features]
# Open HEIC/HEIF photos (the optional photocraft-heif crate). Not default so distributors choose
# Open HEIC/HEIF photos (the optional craft-heif crate). Not default so distributors choose
# it; official builds (CI, packaging/, release) build with `--features heif`.
heif = ["photocraft-codecs/heif"]
@@ -24,6 +24,7 @@ photocraft-io = { workspace = true }
photocraft-codecs = { workspace = true }
photocraft-doc = { workspace = true }
photocraft-ui-egui = { workspace = true }
photocraft-raster = { workspace = true }
egui = { workspace = true }
log = { workspace = true }
@@ -34,9 +35,9 @@ rfd = { workspace = true }
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
js-sys = "0.3"
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "DomRect", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Storage", "Event", "EventTarget", "MouseEvent", "PointerEvent", "BeforeUnloadEvent", "AbortController", "AbortSignal", "DomException", "Response", "IdbFactory", "IdbOpenDbRequest", "IdbDatabase", "IdbRequest", "IdbTransaction", "IdbTransactionMode", "IdbObjectStore", "IdbCursor", "IdbCursorWithValue", "RequestInit", "RequestMode", "Navigator"] }
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "DomRect", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Storage", "Event", "EventTarget", "MouseEvent", "PointerEvent", "BeforeUnloadEvent", "AbortController", "AbortSignal", "DomException", "Response", "IdbFactory", "IdbOpenDbRequest", "IdbDatabase", "IdbRequest", "IdbTransaction", "IdbTransactionMode", "IdbObjectStore", "IdbCursor", "IdbCursorWithValue", "RequestInit", "RequestMode", "Navigator", "ErrorEvent", "PromiseRejectionEvent"] }
[dev-dependencies]
serde_json = { workspace = true }
photocraft-paint = { workspace = true }
photocraft-psd = { workspace = true }
craft-psd = { workspace = true }
+14
View File
@@ -16,6 +16,15 @@
this page, no Rust runs to say so, so the page itself shows what to do after a while. */
#photocraft_stalled { color: #8c8c8c; visibility: hidden; animation: photocraft-stalled 0s 20s forwards; }
@keyframes photocraft-stalled { to { visibility: visible; } }
/* Revealed by the app when the module traps (an allocation it could not satisfy, or a panic):
the page would otherwise sit on the last frame, frozen. Static text, so it shows even if Rust
can no longer build any. */
#photocraft_stopped { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center;
padding: 0 16px; text-align: center; color: #e0e0e0; background: rgba(38, 38, 38, 0.92); font: 14px system-ui, sans-serif; pointer-events: auto; }
#photocraft_stopped[hidden] { display: none; }
#photocraft_stopped p { margin: 0 0 8px; max-width: 460px; line-height: 1.5; }
#photocraft_stopped a { color: #ffffff; }
#photocraft_stopped_detail { color: #b8b8b8; }
</style>
</head>
<body>
@@ -26,5 +35,10 @@
download or come from a different version of this page. <a href="">Reload</a> to try again; the browser
console lists what failed.</p>
</div>
<div id="photocraft_stopped" hidden role="alert">
<p><strong>PhotoCraft stopped.</strong></p>
<p>Changes since the last save in this tab can't be recovered. <a href="">Reload</a> to start again.</p>
<p id="photocraft_stopped_detail"></p>
</div>
</body>
</html>
+148
View File
@@ -0,0 +1,148 @@
//! What the page says when the module stops, and the `?free-mb` diagnostic flag (#10024).
//!
//! A failed allocation on `wasm32-unknown-unknown` aborts the module: the page keeps the last
//! frame and nothing says why. `web.rs` listens for the trap in the page and shows the static
//! `#photocraft_stopped` element; the decisions that need no browser live here, so native tests
//! cover them.
use std::sync::{Mutex, PoisonError};
/// The message of the last panic, kept for the trap that follows it (a panic aborts the module).
static LAST_PANIC: Mutex<String> = Mutex::new(String::new());
/// The most characters of a panic message the page shows.
const MAX_PANIC_CHARS: usize = 300;
/// Truncates `message` to [`MAX_PANIC_CHARS`] characters, on a character boundary.
pub fn truncate(message: &str) -> String {
match message.char_indices().nth(MAX_PANIC_CHARS) {
Some((end, _)) => format!("{}\u{2026}", message.get(..end).unwrap_or_default()),
None => message.to_owned(),
}
}
/// Remembers a panic's message (and where it happened) for [`take_panic`].
pub fn record_panic(message: &str) {
*LAST_PANIC.lock().unwrap_or_else(PoisonError::into_inner) = truncate(message);
}
/// The message [`record_panic`] kept, if any.
pub fn take_panic() -> Option<String> {
let mut last = LAST_PANIC.lock().unwrap_or_else(PoisonError::into_inner);
(!last.is_empty()).then(|| std::mem::take(&mut *last))
}
/// `true` when an uncaught error, by its `name` and `message`, is the module trapping or the
/// browser refusing it memory, rather than some other script error or failed request. Browsers
/// word and capitalize these differently (Safari: `Unreachable code should not be executed`), so
/// the message is matched ignoring case.
pub fn is_trap(name: &str, message: &str) -> bool {
let message = message.to_ascii_lowercase();
name == "RuntimeError"
|| ["unreachable", "memory access out of bounds", "maximum call stack", "could not allocate memory", "out of memory"]
.iter()
.any(|m| message.contains(m))
}
/// Trap messages (lowercase, matched ignoring case) that mean an allocation failed:
/// `unreachable` with no panic before it is the allocation-failure abort (the only one that runs
/// no Rust), the others are the browser refusing to grow the memory. `memory access out of
/// bounds` is not among them: it is a bug.
const OUT_OF_MEMORY: [&str; 3] = ["unreachable", "could not allocate memory", "out of memory"];
/// The line under "PhotoCraft stopped": a captured panic means an internal error; a trap with no
/// panic before it is out of memory when its message says so (or says nothing), and otherwise
/// unexpected.
pub fn detail(panic: Option<&str>, trap_message: &str) -> String {
if let Some(p) = panic {
return format!("It hit an internal error: {p}");
}
let lower = trap_message.to_ascii_lowercase();
if lower.is_empty() || OUT_OF_MEMORY.iter().any(|m| lower.contains(m)) {
"It ran out of memory.".to_owned()
} else {
format!("It stopped unexpectedly: {}", truncate(trap_message))
}
}
/// `?free-mb=N` from a URL query (`?cpu&free-mb=300`): pretend only N MiB can be allocated, so
/// the memory gates and the low-memory warning can be seen without gigabytes of images.
pub fn free_mb(query: &str) -> Option<u64> {
query.trim_start_matches('?').split('&').find_map(|pair| pair.strip_prefix("free-mb=")?.parse().ok())
}
/// The bytes `free-mb` asks for, without overflowing.
pub fn free_bytes(mb: u64) -> u64 {
mb.saturating_mul(1 << 20)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_panic_message_is_shown_as_an_internal_error() {
assert_eq!(detail(Some("index out of bounds"), "unreachable"), "It hit an internal error: index out of bounds");
}
#[test]
fn a_trap_with_no_panic_is_an_out_of_memory_abort() {
assert_eq!(detail(None, "unreachable"), "It ran out of memory.");
assert_eq!(detail(None, "RuntimeError: unreachable executed"), "It ran out of memory.");
assert_eq!(detail(None, ""), "It ran out of memory.");
assert_eq!(detail(None, "WebAssembly.Memory(): could not allocate memory"), "It ran out of memory.");
// Safari and Firefox word and capitalize theirs differently.
assert_eq!(detail(None, "Unreachable code should not be executed"), "It ran out of memory.");
assert_eq!(detail(None, "out of memory"), "It ran out of memory.");
}
#[test]
fn another_kind_of_trap_is_not_blamed_on_memory() {
let text = detail(None, "divide by zero");
assert!(text.starts_with("It stopped unexpectedly: divide by zero"), "{text}");
// A bad memory access is a bug, not memory running out.
let text = detail(None, "memory access out of bounds");
assert!(text.starts_with("It stopped unexpectedly: memory access out of bounds"), "{text}");
}
#[test]
fn only_traps_count() {
assert!(is_trap("RuntimeError", "unreachable"));
assert!(is_trap("RuntimeError", ""));
assert!(is_trap("RangeError", "Maximum call stack size exceeded"));
assert!(is_trap("RangeError", "WebAssembly.Memory(): could not allocate memory"));
// Matched ignoring case: Safari's wording, reported without the RuntimeError name.
assert!(is_trap("Error", "Unreachable code should not be executed"));
assert!(is_trap("Error", "Out of memory"));
assert!(!is_trap("TypeError", "Failed to fetch"));
assert!(!is_trap("Error", "ResizeObserver loop completed"));
}
#[test]
fn long_messages_are_cut_on_a_character_boundary() {
let long = "\u{e9}".repeat(1000);
let cut = truncate(&long);
assert_eq!(cut.chars().count(), MAX_PANIC_CHARS + 1);
assert!(cut.ends_with('\u{2026}'));
assert_eq!(truncate("short"), "short");
assert_eq!(truncate(&"x".repeat(MAX_PANIC_CHARS)).chars().count(), MAX_PANIC_CHARS);
}
#[test]
fn the_recorded_panic_is_taken_once() {
record_panic("boom at a.rs:1");
assert_eq!(take_panic().as_deref(), Some("boom at a.rs:1"));
assert_eq!(take_panic(), None);
}
#[test]
fn free_mb_is_read_from_the_query() {
assert_eq!(free_mb(""), None);
assert_eq!(free_mb("?cpu"), None);
assert_eq!(free_mb("?free-mb=300"), Some(300));
assert_eq!(free_mb("?cpu&free-mb=400&webgl"), Some(400));
assert_eq!(free_mb("?free-mb=lots"), None);
assert_eq!(free_bytes(300), 300 << 20);
assert_eq!(free_bytes(u64::MAX), u64::MAX);
}
}
+24 -1
View File
@@ -12,10 +12,15 @@
//! - dropped files are read asynchronously by `web::WebShell` and delivered through `Services::inbox`.
//!
//! URL query flags: `?cpu` forces the CPU canvas path (same as `PHOTOCRAFT_CPU_CANVAS=1`);
//! `?webgl` forces the WebGL2 backend instead of WebGPU.
//! `?webgl` forces the WebGL2 backend instead of WebGPU; `?free-mb=N` pretends only N MiB can be
//! allocated, so the memory gates and the low-memory warning can be seen without gigabytes of
//! images (diagnostics only).
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#[cfg(any(target_arch = "wasm32", test))]
mod diagnostics;
#[cfg(any(target_arch = "wasm32", test))]
mod preset_bridge;
@@ -48,4 +53,22 @@ mod tests {
assert!(html.contains("animation: photocraft-stalled"), "the hint appears after a delay");
assert!(!html.contains("<script"), "trunk injects the generated loader; the page has no script of its own");
}
/// A module that traps (an allocation it could not satisfy, or a panic) leaves the last frame
/// on screen. The page already holds the message, hidden, with a way to reload; Rust only
/// reveals it and fills in the detail line, so it works even when Rust can no longer build text.
#[test]
fn the_page_holds_a_hidden_stopped_message_with_a_reload_link() {
let html = include_str!("../index.html");
let (_, element) = html.split_once("<div id=\"photocraft_stopped\"").expect("a stopped-message element");
let (element, _) = element.split_once("</div>").expect("the element is closed");
assert!(element.trim_start().starts_with("hidden"), "hidden until a trap: {element}");
assert!(element.contains("role=\"alert\""), "{element}");
assert!(element.contains("<a href=\"\">Reload</a>"), "{element}");
assert!(element.contains("can't be recovered"), "says what is lost: {element}");
assert!(element.contains("id=\"photocraft_stopped_detail\""), "a line for the cause: {element}");
assert!(html.contains("#photocraft_stopped[hidden]"), "display: flex must not defeat the hidden attribute");
assert!(html.contains("pointer-events: auto"), "the link works over the canvas");
assert!(!html.contains("<script"), "still no script of its own");
}
}
+2 -2
View File
@@ -181,7 +181,7 @@ impl PresetBackend for Bridge {
#[cfg(test)]
mod tests {
use super::*;
use photocraft_psd::abr::{AbrSample, LegacyBrush, LegacyTip, write_v12};
use craft_psd::abr::{AbrSample, LegacyBrush, LegacyTip, write_v12};
use serde_json::json;
fn import(s: &mut Session) {
@@ -367,7 +367,7 @@ mod tests {
}
#[test]
fn indexed_brush_store_coexists_with_imported_gradient_preferences() {
use photocraft_psd::grd::{GrdColor, GrdGradient, GrdStop, write};
use craft_psd::grd::{GrdColor, GrdGradient, GrdStop, write};
let b = Bridge::default();
let (mut s, _) = session(b.clone());
import(&mut s);
+104 -9
View File
@@ -15,6 +15,7 @@ use photocraft_ui_egui::{FileDialogAnswer, FileDialogRequest, PhotocraftApp, Ser
use wasm_bindgen::JsCast as _;
type Inbox = Arc<Mutex<Vec<(String, Vec<u8>)>>>;
type PlaceInbox = photocraft_ui_egui::PlaceInbox;
/// Everything File › Open reads: PhotoCraft, Photoshop, OpenRaster, Krita and Affinity documents, flat images, and
/// Photoshop brushes (.abr), gradients (.grd), layer styles (.asl) and swatches (.aco, .act, .ase), which go to the preset libraries.
@@ -25,6 +26,8 @@ const OPEN_EXTS: &[&str] = &[
"afdesign", "afphoto", "afpub",
];
const SVG_EXTS: &[&str] = &["svg", "svgz"];
/// Set once the module has trapped: the page is dead, so nothing is left to protect.
static STOPPED: AtomicBool = AtomicBool::new(false);
const CANVAS_ID: &str = "photocraft_canvas";
/// Fonts the host serves next to the page (`photocraft_ui_egui::served_fonts`): craft-fonts' manifest
@@ -57,6 +60,10 @@ pub fn start() {
};
let q = query();
let force_cpu = q.contains("cpu");
// `?free-mb=N`: the memory gates and the low-memory warning see only N MiB (diagnostics).
if let Some(mb) = crate::diagnostics::free_mb(&q) {
photocraft_raster::headroom::simulate_available(Some(crate::diagnostics::free_bytes(mb)));
}
let mut options = eframe::WebOptions::default();
photocraft_ui_egui::gpu_canvas::use_adapter_limits(&mut options.wgpu_options.wgpu_setup);
if q.contains("webgl")
@@ -75,7 +82,13 @@ pub fn start() {
}
};
let pen_target = canvas.clone();
let result = eframe::WebRunner::new()
let runner = eframe::WebRunner::new();
// After the runner's own panic handler, so the message is kept and the runner's handler
// still runs (a panic aborts the module).
keep_panic_message();
// Before the app is built: a trap while building it shows the stopped message too.
listen_for_trap();
let result = runner
.start(
canvas,
options,
@@ -83,7 +96,7 @@ pub fn start() {
PhotocraftApp::install_type_reset_hooks(&cc.egui_ctx);
PhotocraftApp::setup_context(&cc.egui_ctx, ThemeKind::Pro);
let inbox: Inbox = Arc::default();
let place_inbox: Inbox = Arc::default();
let place_inbox: PlaceInbox = Arc::default();
let served: Served = Arc::default();
load_font_manifest(served.clone(), cc.egui_ctx.clone());
let (session, warnings) = crate::preset_bridge::session(presets.clone());
@@ -180,11 +193,15 @@ fn drag_pos_service(canvas: web_sys::HtmlCanvasElement, pos: DragPos) -> photocr
/// Closing or reloading the tab while a document has unsaved changes asks first, as closing the
/// desktop window does: the browser shows its own "Leave site?" prompt (#1380). `unsaved` is
/// refreshed every frame by [`WebShell`].
/// refreshed every frame by [`WebShell`]. Once the module has stopped ([`STOPPED`]) the prompt is
/// skipped: the document can't be saved any more, and Reload is the only way on.
fn guard_unload(unsaved: Arc<AtomicBool>) {
use wasm_bindgen::closure::Closure;
let Some(window) = web_sys::window() else { return };
let cb = Closure::<dyn FnMut(web_sys::BeforeUnloadEvent)>::new(move |e: web_sys::BeforeUnloadEvent| {
if STOPPED.load(Ordering::Relaxed) {
return;
}
if unsaved.load(Ordering::Relaxed) {
e.prevent_default();
// Older browsers show the prompt only when a return value is set.
@@ -196,6 +213,67 @@ fn guard_unload(unsaved: Arc<AtomicBool>) {
}
}
/// Keeps the message of a panic, then calls the handler that was installed before (the web
/// runner's, which logs it). A panic aborts the module, so the trap that follows has no message of
/// its own; this is what lets the stopped page tell an internal error from running out of memory.
fn keep_panic_message() {
let previous = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
crate::diagnostics::record_panic(&info.to_string());
previous(info);
}));
}
/// Shows the page's static `#photocraft_stopped` message when the module traps. The page learns of
/// a trap as an uncaught `WebAssembly.RuntimeError` (the `error` event) or, inside a spawned
/// future, an unhandled rejection. The module may be mid-call and its runner still borrowed, so
/// the handler touches no app state: it sets [`STOPPED`] and the element, nothing more.
fn listen_for_trap() {
use wasm_bindgen::closure::Closure;
let Some(window) = web_sys::window() else { return };
let on_error = Closure::<dyn FnMut(web_sys::ErrorEvent)>::new(move |e: web_sys::ErrorEvent| {
let error = e.error();
let (name, message) = error_parts(&error, &e.message());
if crate::diagnostics::is_trap(&name, &message) {
show_stopped(&message);
}
});
if window.add_event_listener_with_callback("error", on_error.as_ref().unchecked_ref()).is_ok() {
on_error.forget();
}
let on_rejection = Closure::<dyn FnMut(web_sys::PromiseRejectionEvent)>::new(move |e: web_sys::PromiseRejectionEvent| {
let (name, message) = error_parts(&e.reason(), "");
if crate::diagnostics::is_trap(&name, &message) {
show_stopped(&message);
}
});
if window.add_event_listener_with_callback("unhandledrejection", on_rejection.as_ref().unchecked_ref()).is_ok() {
on_rejection.forget();
}
}
/// The name and message of a thrown value; `fallback` is the event's own message when the value
/// is not an `Error`.
fn error_parts(value: &wasm_bindgen::JsValue, fallback: &str) -> (String, String) {
match value.dyn_ref::<js_sys::Error>() {
Some(error) => (String::from(error.name()), String::from(error.message())),
None => (String::new(), value.as_string().unwrap_or_else(|| fallback.to_owned())),
}
}
/// Reveals `#photocraft_stopped` with the cause. Does as little as possible.
fn show_stopped(trap_message: &str) {
STOPPED.store(true, Ordering::Relaxed);
let detail = crate::diagnostics::detail(crate::diagnostics::take_panic().as_deref(), trap_message);
let Some(document) = web_sys::window().and_then(|w| w.document()) else { return };
if let Some(el) = document.get_element_by_id("photocraft_stopped_detail") {
el.set_text_content(Some(&detail));
}
if let Some(el) = document.get_element_by_id("photocraft_stopped") {
let _ = el.remove_attribute("hidden");
}
}
fn query() -> String {
web_sys::window().and_then(|w| w.location().search().ok()).unwrap_or_default()
}
@@ -267,7 +345,7 @@ struct WebShell {
/// Dropped files to open as documents.
inbox: Inbox,
/// Dropped files to place on the active document's canvas.
place_inbox: Inbox,
place_inbox: PlaceInbox,
/// Read by the `beforeunload` listener ([`guard_unload`]).
unsaved: Arc<AtomicBool>,
served: Served,
@@ -354,16 +432,30 @@ impl eframe::App for WebShell {
// Decided now, where the drop landed: on the document's canvas the files are placed
// as layers (as on the desktop), elsewhere opened.
let places = self.app.dropped_on_canvas(ctx, &names);
let files: Vec<_> = dropped.into_iter().zip(names).zip(places).collect();
let target_doc = self.app.session.active().map(|st| st.doc.id);
let files: Vec<_> = dropped.into_iter().zip(names).zip(places).map(|((f, name), place)| (f, name, place, target_doc)).collect();
let (inbox, place_inbox) = (self.inbox.clone(), self.place_inbox.clone());
let ctx = ctx.clone();
// One after another, so they open or place in the order they were dropped.
wasm_bindgen_futures::spawn_local(async move {
for ((f, name), place) in files {
for (f, name, place, target_doc) in files {
match f.bytes_async().await {
Ok(bytes) => {
let queue = if place { &place_inbox } else { &inbox };
queue.lock().unwrap_or_else(PoisonError::into_inner).push((name, bytes));
if place {
if let Some(doc) = target_doc {
let mut queued = place_inbox.lock().unwrap_or_else(PoisonError::into_inner);
let held = queued.iter().fold(0usize, |sum, (_, _, b)| sum.saturating_add(b.len()));
// Reads that finish before the next frame drains the inbox are
// bounded like the app's own drop queue.
if photocraft_ui_egui::file_open::place_inbox_takes(queued.len(), held, bytes.len()) {
queued.push((doc, name, bytes));
} else {
log::warn!("dropped file {name} wasn't placed: too many dropped files are waiting");
}
}
} else {
inbox.lock().unwrap_or_else(PoisonError::into_inner).push((name, bytes));
}
ctx.request_repaint();
}
Err(e) => log::error!("couldn't read dropped file {name}: {e}"),
@@ -407,7 +499,7 @@ impl eframe::App for WebShell {
}
}
fn services(inbox: Inbox, place_inbox: Inbox, cursor_pos: photocraft_ui_egui::CursorPosFn) -> Services {
fn services(inbox: Inbox, place_inbox: PlaceInbox, cursor_pos: photocraft_ui_egui::CursorPosFn) -> Services {
Services {
screen_pick: screen_color_service(),
import: Some(Box::new(|name: &str, bytes: &[u8], opts: &photocraft_io::ImportOptions| {
@@ -465,6 +557,9 @@ fn services(inbox: Inbox, place_inbox: Inbox, cursor_pos: photocraft_ui_egui::Cu
// Preferences live in the browser's localStorage.
load_prefs: Some(Box::new(|| local_storage()?.get_item(PREFS_KEY).ok().flatten())),
save_prefs: Some(Box::new(|text: &str| local_storage().ok_or("no localStorage")?.set_item(PREFS_KEY, text).map_err(|e| format!("{e:?}")))),
load_gpu_memo: None,
save_gpu_memo: None,
shader_compiler: None,
..Default::default()
}
}
+9 -2
View File
@@ -8,7 +8,7 @@ description = "PhotoCraft: an open-source, native image editor"
build = "build.rs"
[features]
# Open HEIC/HEIF photos (the optional photocraft-heif crate). Not default so distributors choose
# Open HEIC/HEIF photos (the optional craft-heif crate). Not default so distributors choose
# it; official builds (CI, packaging/, release) build with `--features heif`.
heif = ["photocraft-codecs/heif"]
@@ -27,6 +27,7 @@ photocraft-io = { workspace = true }
photocraft-format = { workspace = true }
photocraft-automation = { workspace = true }
photocraft-ui-egui = { workspace = true }
craft-flags = { workspace = true }
# Pen tablet pressure/tilt on macOS and X11 (the workspace's one isolated unsafe helper crate).
photocraft-tablet = { workspace = true }
eframe = { workspace = true, features = ["wgpu", "accesskit", "wayland", "x11", "persistence", "clipboard"] }
@@ -83,7 +84,7 @@ plist = { version = "=1.10.3", features = ["enable_unstable_features_that_may_br
# Drop position on X11 (`cursor.rs`): pure-Rust X client, already in Cargo.lock; pinned exactly.
[target.'cfg(target_os = "linux")'.dependencies]
photocraft-cms = { workspace = true }
craft-cms = { workspace = true }
# The print portal's PDF: a private (0600) temporary file, removed when the dialog is done.
tempfile = "3"
x11rb = { version = "=0.13.2", default-features = false, features = ["image", "randr", "xkb"] }
@@ -102,6 +103,12 @@ async-io = "=2.6.0"
# re-export winit's `EventLoopBuilderExtX11`. Already in Cargo.lock (eframe); pinned exactly.
winit = { version = "=0.30.13", default-features = false, features = ["wayland-csd-adwaita-notitle", "x11"] }
# FreeBSD runs the same Wayland and X11 stack, so the System Title Bar preference should get winit's
# font-free Adwaita controls there as well: without them winit draws sctk's plain fallback frame on
# compositors without server-side decorations (GNOME). Already in Cargo.lock (eframe); pinned exactly.
[target.'cfg(target_os = "freebsd")'.dependencies]
winit = { version = "=0.30.13", default-features = false, features = ["wayland-csd-adwaita-notitle"] }
# Safe Win32 wrappers on Windows: the pointer position for file drops (`cursor.rs`,
# GetCursorPos) and the window frame for the custom title bar (`window_frame.rs`, window styles),
# no dependencies of its own. Pinned exactly: review the diff before bumping.
+281
View File
@@ -0,0 +1,281 @@
//! Agents in the open desktop app: while the person lets them in (ArtCraft Launcher › Settings ›
//! AI agents; without the `AI-MCP` flag, a Control Port saved before), the app serves the control
//! protocol by itself (no `--control`) and publishes the connection file `photocraft-cli mcp`
//! finds it by ([`photocraft_automation::agent_link`]). Turning it on or off, or changing the
//! port or folders in Preferences › AI Integrations, applies at once. The token stays in the settings
//! folder across launches (`agent-control.token`, as `--control-token-file` would keep it; delete
//! it for a new one). Agent requests get the policy and the folders chosen there, exactly as with
//! `--control` and the automation roots.
//!
//! Launch flags win: started with `--control`, the app doesn't install this service and the
//! dialog says the launch options manage the connection.
use std::path::{Path, PathBuf};
use std::sync::mpsc::Receiver;
use photocraft_automation::agent_link::{self, Connection};
use photocraft_automation::security;
use photocraft_engine::prefs::Integrations;
use photocraft_ui_egui::{AgentLink, AgentLinkFn, ControlRequest};
use crate::control_server;
/// The connection while it runs; dropping it stops the server and removes the connection file.
struct Running {
server: control_server::Listening,
dir: PathBuf,
/// The `controlPort` preference it was started for (0 = any).
port_pref: u32,
}
impl Drop for Running {
fn drop(&mut self) {
agent_link::remove_connection(&self.dir, std::process::id());
log::info!("agent connection on 127.0.0.1:{} stopped", self.server.port);
}
}
/// Start serving agents on `port` (0 = any free port): the token from the settings folder
/// (created `0600` when missing), then the connection file. Returns the connection and the
/// channel its requests arrive on. A token file that can't be written leaves the connection off
/// (no server, so no token to leak) and says why.
fn start(dir: &Path, port: u16, ctx: &egui::Context, port_pref: u32) -> Result<(Running, Receiver<ControlRequest>), String> {
let token_file = dir.join(agent_link::TOKEN_FILE);
let token = security::server_token(None, Some(&token_file)).map_err(|e| format!("Agents can't connect: the token file could not be written: {e}"))?;
let (requests, server) = control_server::listen(port, token, ctx.clone()).map_err(|e| format!("Couldn't listen on 127.0.0.1:{port}: {e}"))?;
let running = Running { server, dir: dir.to_path_buf(), port_pref };
agent_link::write_connection(dir, &Connection::new(running.server.port, token_file)).map_err(|e| format!("Couldn't publish the agent connection: {e}"))?;
log::info!("agents can connect on 127.0.0.1:{}", running.server.port);
Ok((running, requests))
}
/// The agent connection service (`settings_dir`: where the connection file and token go).
pub fn service(settings_dir: Option<PathBuf>) -> AgentLinkFn {
let mut running: Option<Running> = None;
Box::new(move |integrations: &Integrations, ctx: &egui::Context| apply(&mut running, settings_dir.as_deref(), integrations, ctx))
}
/// Bring the connection in line with `integrations`: start, restart on another port, stop, or only
/// change the folders agents may use.
fn apply(running: &mut Option<Running>, dir: Option<&Path>, integrations: &Integrations, ctx: &egui::Context) -> AgentLink {
let mut out = AgentLink::default();
if !integrations.connect_agents {
out.stopped = running.take().is_some();
return out;
}
// Allow Agent Control off refuses every control server, this one as `--control`.
if !integrations.allow_agent_control {
out.stopped = running.take().is_some();
out.status.error = Some("Agents can't connect: Allow Agent Control is off in the preferences file.".into());
return out;
}
let Some(dir) = dir else {
out.stopped = running.take().is_some();
out.status.error = Some("Agents can't connect: PhotoCraft has no settings folder (no home folder).".into());
return out;
};
if running.as_ref().is_none_or(|r| r.port_pref != integrations.control_port) {
out.stopped = running.take().is_some();
// The preference's range is 0..=65535; anything else picks a free port.
let port = u16::try_from(integrations.control_port).unwrap_or(0);
match start(dir, port, ctx, integrations.control_port) {
Ok((r, requests)) => {
out.requests = Some(requests);
*running = Some(r);
}
Err(e) => {
log::warn!("{e}");
out.status.error = Some(e);
return out;
}
}
}
out.status.port = running.as_ref().map(|r| r.server.port);
// Agent requests always go through the automation policy; without folders they get no file
// access at all (as `--control` without automation roots). A folder that can't be opened, or
// isn't an absolute path, is left out (that direction fails closed) and named, as at launch.
let no_flags = photocraft_automation::args::AutomationArgs { automation_read_root: Vec::new(), automation_write_root: None };
let workspace = match crate::automation_workspace(&no_flags, integrations) {
Ok((workspace, warning)) => {
if let Some(w) = warning {
out.status.error = Some(format!("Agents can connect, but without file access there: {w}"));
}
workspace
}
Err(e) => {
out.status.error = Some(format!("Agents can connect, but without file access: {e}"));
photocraft_automation::AuthorizedWorkspace::default()
}
};
out.automation = crate::services::automation(Some(workspace));
out
}
/// How often [`launcher_watch`] looks at the ArtCraft Launcher's files.
const LAUNCHER_POLL: std::time::Duration = std::time::Duration::from_secs(2);
/// Whether the ArtCraft Launcher turned agents on for every Craft app
/// ([`agent_link::launcher_allows_agents`]), watched on its own thread so the UI can ask every
/// frame without touching the disk. A change wakes the UI, which then starts or stops the
/// connection. Without a thread (one couldn't be started) the answer stays what it was at launch.
pub fn launcher_watch(ctx: &egui::Context) -> Box<dyn Fn() -> bool> {
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
let on = Arc::new(AtomicBool::new(agent_link::launcher_allows_agents()));
let (seen, ctx) = (on.clone(), ctx.clone());
let started = std::thread::Builder::new().name("launcher-agents".into()).spawn(move || {
loop {
std::thread::sleep(LAUNCHER_POLL);
let now = agent_link::launcher_allows_agents();
if seen.swap(now, Ordering::Relaxed) != now {
log::info!("ArtCraft Launcher: agents {}", if now { "on" } else { "off" });
ctx.request_repaint();
}
}
});
if let Err(e) = started {
log::warn!("couldn't watch the ArtCraft Launcher's agents switch: {e}");
}
Box::new(move || on.load(Ordering::Relaxed))
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
fn temp() -> PathBuf {
static N: AtomicUsize = AtomicUsize::new(0);
let d = std::env::temp_dir().join(format!("photocraft-agent-service-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
fn on(port: u32) -> Integrations {
Integrations { connect_agents: true, control_port: port, ..Default::default() }
}
#[test]
fn turning_agents_on_publishes_a_reachable_connection_and_off_removes_it() {
let dir = temp();
let ctx = egui::Context::default();
let mut link = service(Some(dir.clone()));
// Off (the default): nothing listens, nothing is published.
let off = link(&Integrations::default(), &ctx);
assert!(off.requests.is_none() && !off.stopped && off.status.port.is_none());
assert!(off.automation.command.is_none(), "no agent policy without a connection");
assert_eq!(agent_link::read_connection(&dir).unwrap(), None);
let started = link(&on(0), &ctx);
let port = started.status.port.unwrap();
assert!(started.requests.is_some());
assert!(started.automation.command.is_some() && started.automation.authorize.is_some(), "agent requests go through the policy");
assert!(started.automation.read.is_some(), "the workspace answers (and refuses: no folder chosen)");
let c = agent_link::read_connection(&dir).unwrap().unwrap();
assert_eq!((c.port, c.pid), (port, std::process::id()));
assert!(agent_link::probe(port, agent_link::PROBE_TIMEOUT));
let token = security::client_token(None, Some(&c.token_file)).unwrap();
// Folder changes keep the server and its token.
let folders = Integrations { read_root: dir.to_string_lossy().into_owned(), ..on(0) };
let changed = link(&folders, &ctx);
assert!(changed.requests.is_none() && !changed.stopped);
assert_eq!(changed.status.port, Some(port));
assert!(changed.status.error.is_none(), "{:?}", changed.status.error);
assert_eq!(security::client_token(None, Some(&c.token_file)).unwrap(), token);
// A missing folder still connects, without file access, and says why.
let missing = Integrations { write_root: dir.join("nope").to_string_lossy().into_owned(), ..on(0) };
let partial = link(&missing, &ctx);
assert_eq!(partial.status.port, Some(port));
assert!(partial.status.error.as_deref().is_some_and(|e| e.contains("without file access")), "{:?}", partial.status.error);
assert!(partial.automation.command.is_some());
let stopped = link(&Integrations::default(), &ctx);
assert!(stopped.stopped && stopped.status.port.is_none());
assert_eq!(agent_link::read_connection(&dir).unwrap(), None, "the connection file goes with the server");
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
while agent_link::probe(port, agent_link::PROBE_TIMEOUT) {
assert!(std::time::Instant::now() < deadline, "port {port} still open");
std::thread::sleep(std::time::Duration::from_millis(20));
}
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_new_port_restarts_with_the_same_token_and_a_taken_port_is_reported() {
let dir = temp();
let ctx = egui::Context::default();
let mut link = service(Some(dir.clone()));
let first = link(&on(0), &ctx);
let first_port = first.status.port.unwrap();
let token_file = dir.join(agent_link::TOKEN_FILE);
let first_token = std::fs::read_to_string(&token_file).unwrap();
// A taken port: the error names it and nothing is published for it.
let taken = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let taken_port = taken.local_addr().unwrap().port();
let failed = link(&on(u32::from(taken_port)), &ctx);
assert!(failed.stopped && failed.requests.is_none() && failed.status.port.is_none());
assert!(failed.status.error.as_deref().is_some_and(|e| e.contains(&taken_port.to_string())), "{:?}", failed.status.error);
assert_eq!(agent_link::read_connection(&dir).unwrap(), None);
drop(taken);
// Back to any port: the token in the settings folder is kept, so a client holding it
// (a `--bridge` setup reading the token file) needn't be set up again.
let again = link(&on(0), &ctx);
assert!(again.requests.is_some());
assert!(again.status.port.is_some_and(|p| p != 0));
assert_eq!(std::fs::read_to_string(&token_file).unwrap(), first_token);
let _ = first_port;
drop(link);
assert_eq!(agent_link::read_connection(&dir).unwrap(), None, "quitting removes the connection file");
let _ = std::fs::remove_dir_all(&dir);
}
/// A token file that can't be written (here the "settings folder" is a file) leaves the
/// connection off with the reason shown, and its port free.
#[test]
fn a_token_file_that_cannot_be_written_leaves_agents_off() {
let dir = temp();
let settings = dir.join("not-a-folder");
std::fs::write(&settings, b"").unwrap();
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
let mut link = service(Some(settings));
let r = link(&on(u32::from(port)), &egui::Context::default());
assert!(r.requests.is_none() && r.status.port.is_none());
assert!(r.status.error.as_deref().is_some_and(|e| e.contains("token file")), "{:?}", r.status.error);
std::net::TcpListener::bind(("127.0.0.1", port)).expect("the port was let go");
let _ = std::fs::remove_dir_all(&dir);
}
/// A relative folder would depend on the folder the app was started from: left out and named.
#[test]
fn a_relative_folder_is_left_out_with_a_reason() {
let dir = temp();
let mut link = service(Some(dir.clone()));
let r = link(&Integrations { read_root: ".".into(), ..on(0) }, &egui::Context::default());
assert!(r.status.port.is_some());
assert!(r.status.error.as_deref().is_some_and(|e| e.contains("not an absolute path")), "{:?}", r.status.error);
drop(link);
let _ = std::fs::remove_dir_all(&dir);
}
/// Allow Agent Control off (in the file; the dialog doesn't show it) refuses this server too.
#[test]
fn allow_agent_control_off_keeps_agents_out() {
let dir = temp();
let mut link = service(Some(dir.clone()));
let r = link(&Integrations { allow_agent_control: false, ..on(0) }, &egui::Context::default());
assert!(r.requests.is_none() && r.status.port.is_none() && r.automation.command.is_none());
assert!(r.status.error.as_deref().is_some_and(|e| e.contains("Allow Agent Control")), "{:?}", r.status.error);
assert_eq!(agent_link::read_connection(&dir).unwrap(), None);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn no_settings_folder_is_an_error_not_a_panic() {
let mut link = service(None);
let r = link(&on(0), &egui::Context::default());
assert!(r.requests.is_none() && r.status.error.is_some());
}
}
+8 -90
View File
@@ -10,6 +10,9 @@
//! 3. The platform convention: macOS `~/Library/Application Support/Photocraft`, Windows
//! `%APPDATA%\Photocraft`, Linux `$XDG_CONFIG_HOME/photocraft` or `~/.config/photocraft`.
//!
//! The rules live in [`photocraft_automation::app_dirs`], so `photocraft-cli` resolves the same
//! folder; this module resolves it once for the app and logs the outcome.
//!
//! One exception: the platform convention keeps crash-recovery autosaves out of what is synced
//! with the settings: the Windows roaming profile and the Linux config folder ([`recovery_dir`]).
@@ -17,31 +20,11 @@ use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
/// Files beside the executable that switch on portable mode (either one; contents are ignored).
pub const PORTABLE_MARKERS: [&str; 2] = ["portable.txt", "PhotoCraft.portable"];
/// The data folder created beside the executable in portable mode.
pub const PORTABLE_DATA_DIR: &str = "PhotoCraftData";
/// How [`DataDir::dir`] was chosen.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mode {
/// `PHOTOCRAFT_CONFIG_DIR`.
Override,
/// `<exe dir>/PhotoCraftData`.
Portable,
/// The platform's per-user config directory.
Platform,
}
/// The resolved data directory.
#[derive(Clone, Debug)]
pub struct DataDir {
/// `None` only when no platform directory is known either (no `HOME`/`APPDATA`).
pub dir: Option<PathBuf>,
pub mode: Mode,
/// Set when a portable marker was found but its data folder isn't writable.
pub warning: Option<String>,
}
pub use photocraft_automation::app_dirs::{DataDir, Mode, resolve};
// The tests below exercise the shared resolver too; some of them run on Unix only.
#[cfg(test)]
#[allow(unused_imports)]
use photocraft_automation::app_dirs::{PORTABLE_DATA_DIR, PORTABLE_MARKERS, WRITE_PROBE_ATTEMPTS, ensure_writable, platform_dir, portable_marker};
/// The data directory for this process, resolved once (the portable check probes the disk).
pub fn current() -> &'static DataDir {
@@ -453,70 +436,5 @@ fn copy_file(from: &Path, to: &Path) -> std::io::Result<()> {
dst.sync_all()
}
/// Resolve the data directory from the environment (`env`) and the executable's folder.
pub fn resolve(env: impl Fn(&str) -> Option<OsString>, exe_dir: Option<&Path>) -> DataDir {
if let Some(d) = env("PHOTOCRAFT_CONFIG_DIR").filter(|d| !d.is_empty()) {
return DataDir { dir: Some(PathBuf::from(d)), mode: Mode::Override, warning: None };
}
let platform = platform_dir(&env);
let Some((exe_dir, marker)) = exe_dir.and_then(|d| portable_marker(d).map(|m| (d, m))) else {
return DataDir { dir: platform, mode: Mode::Platform, warning: None };
};
let data = exe_dir.join(PORTABLE_DATA_DIR);
match ensure_writable(&data) {
Ok(()) => DataDir { dir: Some(data), mode: Mode::Portable, warning: None },
Err(e) => {
let fallback = platform.as_ref().map_or_else(|| "nowhere (no user folder found)".to_string(), |p| p.display().to_string());
let warning =
format!("portable mode ({} found) but {} isn't writable ({e}); settings are kept in {fallback} instead", marker.display(), data.display());
DataDir { dir: platform, mode: Mode::Platform, warning: Some(warning) }
}
}
}
/// The platform convention, from `env` (so tests can fake `HOME`/`APPDATA`/`XDG_CONFIG_HOME`).
pub fn platform_dir(env: &impl Fn(&str) -> Option<OsString>) -> Option<PathBuf> {
let home = env("HOME").filter(|h| !h.is_empty()).map(PathBuf::from);
if cfg!(target_os = "macos") {
return home.map(|h| h.join("Library/Application Support/Photocraft"));
}
if cfg!(windows) {
return env("APPDATA").filter(|a| !a.is_empty()).map(|a| PathBuf::from(a).join("Photocraft"));
}
env("XDG_CONFIG_HOME").filter(|x| !x.is_empty()).map(PathBuf::from).or_else(|| home.map(|h| h.join(".config"))).map(|c| c.join("photocraft"))
}
/// The first portable marker file in `exe_dir`, if any.
pub fn portable_marker(exe_dir: &Path) -> Option<PathBuf> {
PORTABLE_MARKERS.iter().map(|m| exe_dir.join(m)).find(|p| p.is_file())
}
/// Probe names tried before giving up on a portable data folder.
const WRITE_PROBE_ATTEMPTS: u32 = 64;
/// Create `dir` and prove a file can be written in it (a folder can exist yet be read-only).
///
/// The probe is created exclusively (`create_new`), so an entry already at its name (a link
/// someone else placed there, say) is never opened, written through or removed: the next name
/// is tried instead. Only a probe this call created is removed.
fn ensure_writable(dir: &Path) -> std::io::Result<()> {
std::fs::create_dir_all(dir)?;
let pid = std::process::id();
for attempt in 0..WRITE_PROBE_ATTEMPTS {
let probe = dir.join(format!(".write-test-{pid}-{attempt}"));
match std::fs::OpenOptions::new().write(true).create_new(true).open(&probe) {
Ok(file) => {
drop(file);
// A leftover probe is harmless; don't fail portable mode over it.
let _ = std::fs::remove_file(&probe);
return Ok(());
}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(e) => return Err(e),
}
}
Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "every write-test name is already taken"))
}
#[cfg(test)]
mod tests;
+144 -24
View File
@@ -1,47 +1,93 @@
//! Localhost JSON-lines control server (one request per line, one reply per line).
//! Loopback only. This is the transport the MCP server will wrap.
//!
//! `--control` starts it for the whole run ([`start`]); Preferences › AI Integrations starts and
//! stops it while the app runs ([`listen`], see `agent_link`).
use std::io::{BufReader, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, Sender, channel};
use std::time::{Duration, Instant};
use photocraft_automation::budgets::write_reply;
use photocraft_automation::security::{
AUTH_DEADLINE, AuthDeadlineStream, ConnectionLimiter, LineRead, MAX_CONNECTIONS, MAX_REQUEST_BYTES, authentication_reply, configure_stream,
AUTH_DEADLINE, AuthDeadlineStream, AuthStep, ConnectionLimiter, LineRead, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ServerHandshake, configure_stream,
read_bounded_line, repeat_auth_reply,
};
use photocraft_ui_egui::ControlRequest;
use photocraft_ui_egui::control::REPLY_DEADLINE;
use serde_json::{Value, json};
/// Start serving a listener already bound during startup, before a window is opened.
/// Start serving a listener already bound during startup, before a window is opened. It serves
/// for the whole run.
pub fn start(listener: TcpListener, token: String, ctx: egui::Context) -> Receiver<ControlRequest> {
let (tx, rx) = channel::<ControlRequest>();
let port = listener.local_addr().map_or(0, |a| a.port());
eprintln!("photocraft: control server listening on {}", listening_addr(&listener, port));
std::thread::spawn(move || {
let limiter = ConnectionLimiter::new(MAX_CONNECTIONS);
let token = Arc::new(token);
for mut stream in listener.incoming().flatten() {
let Some(permit) = limiter.try_acquire() else {
let _ = configure_stream(&stream);
let _ = writeln!(stream, "{}", json!({"id": null, "ok": false, "error": "connection limit reached"}));
continue;
};
let tx = tx.clone();
let ctx = ctx.clone();
let token = Arc::clone(&token);
std::thread::spawn(move || {
let _permit = permit;
serve(stream, &token, tx, ctx);
});
}
});
std::thread::spawn(move || accept(listener, token, tx, ctx, None));
rx
}
/// A control server started by [`listen`]. Dropping it stops accepting connections; connections
/// already open end at their next request, once the app drops the request channel.
pub struct Listening {
/// The bound port (the one the system picked for port 0).
pub port: u16,
stop: Arc<AtomicBool>,
accept: Option<std::thread::JoinHandle<()>>,
}
impl Drop for Listening {
fn drop(&mut self) {
self.stop.store(true, Ordering::Release);
// Wake the accept loop so it sees the flag and closes the listener, and wait for that, so
// the port is free when this returns (a restart on the same port binds it again at once).
// Without a wake-up the loop would block in `accept`: then don't wait.
let woke = TcpStream::connect_timeout(&std::net::SocketAddr::from(([127, 0, 0, 1], self.port)), Duration::from_millis(500)).is_ok();
if woke && let Some(accept) = self.accept.take() {
let _ = accept.join();
}
}
}
/// Serve the control protocol on `127.0.0.1:port` (0 = any free port) until the returned
/// [`Listening`] is dropped.
pub fn listen(port: u16, token: String, ctx: egui::Context) -> std::io::Result<(Receiver<ControlRequest>, Listening)> {
let (tx, rx) = channel::<ControlRequest>();
let listener = TcpListener::bind(("127.0.0.1", port))?;
let port = listener.local_addr()?.port();
let stop = Arc::new(AtomicBool::new(false));
let stopped = stop.clone();
let accept = std::thread::Builder::new().name("control server".into()).spawn(move || accept(listener, token, tx, ctx, Some(stopped)))?;
Ok((rx, Listening { port, stop, accept: Some(accept) }))
}
/// Accept connections on `listener` and serve each on its own thread, until `stop` is set (never,
/// without one).
fn accept(listener: TcpListener, token: String, tx: Sender<ControlRequest>, ctx: egui::Context, stop: Option<Arc<AtomicBool>>) {
let limiter = ConnectionLimiter::new(MAX_CONNECTIONS);
let token = Arc::new(token);
for mut stream in listener.incoming().flatten() {
if stop.as_ref().is_some_and(|s| s.load(Ordering::Acquire)) {
break;
}
let Some(permit) = limiter.try_acquire() else {
let _ = configure_stream(&stream);
let _ = writeln!(stream, "{}", json!({"id": null, "ok": false, "error": "connection limit reached"}));
continue;
};
let tx = tx.clone();
let ctx = ctx.clone();
let token = Arc::clone(&token);
std::thread::spawn(move || {
let _permit = permit;
serve(stream, &token, tx, ctx);
});
}
}
/// The address `listener` is bound to: with `--control 0` the OS picks the port, and a client
/// needs that one, not the requested 0 (#6427). Falls back to the requested port if the OS
/// can't report it.
@@ -66,6 +112,7 @@ fn serve_with_auth_deadline(stream: TcpStream, token: &str, tx: Sender<ControlRe
let mut reader = BufReader::new(AuthDeadlineStream::new(read, auth_deadline));
let mut out = stream;
let mut line = String::new();
let mut handshake = ServerHandshake::new();
let mut authenticated = false;
loop {
match read_bounded_line(&mut reader, &mut line) {
@@ -84,12 +131,12 @@ fn serve_with_auth_deadline(stream: TcpStream, token: &str, tx: Sender<ControlRe
Ok(LineRead::Line) => {}
}
if !authenticated {
let (reply, ok) = authentication_reply(&line, token);
authenticated = ok;
if ok && reader.get_mut().authenticated().is_err() {
let (reply, step) = handshake.reply(&line, token);
authenticated = step == AuthStep::Authenticated;
if authenticated && reader.get_mut().authenticated().is_err() {
break;
}
if write_reply(&mut out, &reply).is_err() || out.flush().is_err() || !authenticated {
if write_reply(&mut out, &reply).is_err() || out.flush().is_err() || step == AuthStep::Rejected {
break;
}
continue;
@@ -137,6 +184,34 @@ mod tests {
use std::io::BufRead;
/// #6427: with port 0 the log names the port the OS bound, which a client can connect to.
#[test]
fn a_listening_server_picks_a_port_and_stops_when_dropped() {
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
let (rx, server) = listen(0, TOKEN.into(), egui::Context::default()).unwrap();
let port = server.port;
assert_ne!(port, 0);
let handler = std::thread::spawn(move || {
let req = rx.recv_timeout(Duration::from_secs(5)).unwrap();
assert_eq!(req.method, "test.ping");
req.reply.send(json!({"ok": true, "result": "pong"})).unwrap();
});
let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
let mut reader = BufReader::new(stream.try_clone().unwrap());
let mut line = String::new();
writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).unwrap();
reader.read_line(&mut line).unwrap();
assert_eq!(serde_json::from_str::<Value>(&line).unwrap()["ok"], true);
writeln!(stream, "{}", json!({"id": 2, "method": "test.ping"})).unwrap();
line.clear();
reader.read_line(&mut line).unwrap();
assert_eq!(serde_json::from_str::<Value>(&line).unwrap()["result"], "pong");
handler.join().unwrap();
drop(server);
// The listener is closed when the drop returns: the same port binds again at once.
TcpListener::bind(("127.0.0.1", port)).expect("the port is free after the drop");
}
#[test]
fn port_zero_logs_the_bound_port() {
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
@@ -326,4 +401,49 @@ mod tests {
handler.join().unwrap();
server.join().unwrap();
}
/// NV-6: the desktop server answers challenge authentication, proving it holds the token
/// before the client sends its proof, and dispatches only after that proof.
#[test]
fn challenge_authentication_proves_the_server_then_serves() {
use photocraft_automation::security::{CHALLENGE_METHOD, ProofRole, generate_nonce, handshake_proof, proof_matches};
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let (tx, rx) = channel::<ControlRequest>();
let server = std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
serve(stream, TOKEN, tx, egui::Context::default());
});
let handler = std::thread::spawn(move || {
let req = rx.recv_timeout(Duration::from_secs(5)).unwrap();
assert_eq!(req.method, "test.after", "only the request after the proof is dispatched");
req.reply.send(json!({"ok": true, "result": "served"})).unwrap();
});
let mut stream = TcpStream::connect(addr).unwrap();
stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
let mut reader = BufReader::new(stream.try_clone().unwrap());
let mut line = String::new();
let client_nonce = generate_nonce().unwrap();
writeln!(stream, "{}", json!({"id": 1, "method": CHALLENGE_METHOD, "params": {"clientNonce": client_nonce}})).unwrap();
reader.read_line(&mut line).unwrap();
let challenge: Value = serde_json::from_str(&line).unwrap();
assert!(!line.contains(TOKEN), "{line}");
let server_nonce = challenge["result"]["serverNonce"].as_str().unwrap().to_owned();
let server_proof = challenge["result"]["serverProof"].as_str().unwrap();
assert!(proof_matches(TOKEN, ProofRole::Server, &client_nonce, &server_nonce, server_proof), "{line}");
let proof = handshake_proof(TOKEN, ProofRole::Client, &client_nonce, &server_nonce).unwrap();
writeln!(stream, "{}", json!({"id": 2, "method": "auth", "params": {"proof": proof}})).unwrap();
line.clear();
reader.read_line(&mut line).unwrap();
assert_eq!(serde_json::from_str::<Value>(&line).unwrap()["result"]["authenticated"], true, "{line}");
writeln!(stream, "{}", json!({"id": 3, "method": "test.after"})).unwrap();
line.clear();
reader.read_line(&mut line).unwrap();
assert_eq!(serde_json::from_str::<Value>(&line).unwrap()["result"], "served");
drop(reader);
drop(stream);
handler.join().unwrap();
server.join().unwrap();
}
}
+1 -1
View File
@@ -6,7 +6,7 @@
//! - **macOS**: `NSEvent.mouseLocation`, converted into the content view of our window under it.
//! - **X11**: `QueryPointer` on our window (a second, pure-Rust X connection).
//! - **Windows**: `GetCursorPos`, relative to the window's client area.
//! - **Wayland**: winit 0.30 delivers no file drops there, so there's nothing to place.
//! - **Wayland**: winit delivers file drops, and egui's last pointer position is used as fallback.
//!
//! No `unsafe`: every OS call goes through a safe binding.
//!
+2 -5
View File
@@ -627,17 +627,14 @@ mod native {
/// True for a symlink, or on Windows any reparse point, whose target could be swapped.
/// Expects `symlink_metadata`, which describes the link itself rather than its target.
fn is_redirect(metadata: &Metadata) -> bool {
if metadata.file_type().is_symlink() {
return true;
}
#[cfg(windows)]
{
use std::os::windows::fs::MetadataExt;
metadata.file_attributes() & 0x0000_0400 != 0 // FILE_ATTRIBUTE_REPARSE_POINT
metadata.file_type().is_symlink() || metadata.file_attributes() & 0x0000_0400 != 0 // FILE_ATTRIBUTE_REPARSE_POINT
}
#[cfg(not(windows))]
{
false
metadata.file_type().is_symlink()
}
}
+59 -23
View File
@@ -45,21 +45,28 @@ pub fn base_dirs(var: &dyn Fn(&str) -> Option<String>) -> Vec<PathBuf> {
dirs
}
/// One `[section]` of an `index.theme`, as (key, value) pairs.
fn section<'a>(index: &'a str, name: &str) -> Vec<(&'a str, &'a str)> {
let mut inside = false;
let mut pairs = vec![];
/// Every `[section]` of an `index.theme` as (key, value) pairs, in one pass; the first section
/// of a name wins. (Looking each directory's section up by rescanning the file multiplied its
/// size by the number of directories.)
fn sections(index: &str) -> std::collections::HashMap<&str, Vec<(&str, &str)>> {
let mut all = std::collections::HashMap::new();
let mut current: Option<Vec<(&str, &str)>> = None;
let mut name = "";
for line in index.lines().map(str::trim) {
if let Some(s) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
if inside {
break;
if let Some(done) = current.take() {
all.entry(name).or_insert(done);
}
inside = s == name;
} else if inside && let Some((k, v)) = line.split_once('=') {
name = s;
current = Some(vec![]);
} else if let (Some(pairs), Some((k, v))) = (current.as_mut(), line.split_once('=')) {
pairs.push((k.trim(), v.trim()));
}
}
pairs
if let Some(done) = current {
all.entry(name).or_insert(done);
}
all
}
fn list(value: Option<&str>) -> impl Iterator<Item = &str> {
@@ -156,13 +163,14 @@ impl IconTheme {
// The first index wins; a theme can still be spread over several base directories.
let Some(index) = roots.iter().find_map(|r| read_small(&r.join("index.theme"))) else { continue };
let index = String::from_utf8_lossy(&index);
let head = section(&index, "Icon Theme");
let all = sections(&index);
let head = all.get("Icon Theme").map_or(&[][..], Vec::as_slice);
let get = |k: &str| head.iter().find(|(key, _)| *key == k).map(|(_, v)| *v);
let mut subdirs: Vec<((i64, i64), &str)> = list(get("Directories"))
.chain(list(get("ScaledDirectories")))
.filter(|d| !d.split('/').any(|part| part == ".." || part.is_empty()))
.take(MAX_DIRS)
.map(|d| (distance(&section(&index, d)), d))
.map(|d| (distance(all.get(d).map_or(&[][..], Vec::as_slice)), d))
.collect();
subdirs.sort_by_key(|(key, _)| *key);
// Not checked for existence: a theme lists hundreds, and the search stops at a hit.
@@ -193,7 +201,8 @@ impl IconTheme {
/// unreadable SVG or an absurd size.
pub fn rasterize_mask(svg: &[u8], px: u32) -> Option<Vec<u8>> {
use resvg::{tiny_skia, usvg};
if !(1..=256).contains(&px) {
// usvg inflates gzip (`.svgz`) input without a decoded-size limit, and icons are plain `.svg`.
if !(1..=256).contains(&px) || svg.starts_with(&[0x1f, 0x8b]) {
return None;
}
// Glyphs are paths: no `<image>` is loaded, so an icon can't make us read another file
@@ -202,17 +211,22 @@ pub fn rasterize_mask(svg: &[u8], px: u32) -> Option<Vec<u8>> {
image_href_resolver: usvg::ImageHrefResolver { resolve_data: Box::new(|_, _, _| None), resolve_string: Box::new(|_, _| None) },
..usvg::Options::default()
};
let tree = usvg::Tree::from_data(svg, &opts).ok()?;
let size = tree.size();
let side = size.width().max(size.height());
if !side.is_finite() || side <= 0.0 {
return None;
}
let s = px as f32 / side;
let (dx, dy) = ((px as f32 - size.width() * s) / 2.0, (px as f32 - size.height() * s) / 2.0);
let mut pixmap = tiny_skia::Pixmap::new(px, px)?;
resvg::render(&tree, tiny_skia::Transform::from_scale(s, s).post_translate(dx, dy), &mut pixmap.as_mut());
Some(pixmap.data().as_chunks::<4>().0.iter().map(|[_, _, _, a]| *a).collect())
// usvg and resvg panic on some malformed drawings: such an icon is unreadable, not a crash.
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let tree = usvg::Tree::from_data(svg, &opts).ok()?;
let size = tree.size();
let side = size.width().max(size.height());
if !side.is_finite() || side <= 0.0 {
return None;
}
let s = px as f32 / side;
let (dx, dy) = ((px as f32 - size.width() * s) / 2.0, (px as f32 - size.height() * s) / 2.0);
let mut pixmap = tiny_skia::Pixmap::new(px, px)?;
resvg::render(&tree, tiny_skia::Transform::from_scale(s, s).post_translate(dx, dy), &mut pixmap.as_mut());
Some(pixmap.data().as_chunks::<4>().0.iter().map(|[_, _, _, a]| *a).collect())
}))
.ok()
.flatten()
}
#[cfg(test)]
@@ -282,6 +296,19 @@ mod tests {
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn sections_are_read_once_and_the_first_of_a_name_wins() {
let all = sections("stray=1\n[A]\nSize=16\n[B]\nSize=22\n[A]\nSize=48\n");
assert_eq!(all["A"], vec![("Size", "16")]);
assert_eq!(all["B"], vec![("Size", "22")]);
assert!(!all.contains_key(""));
}
#[test]
fn a_gzip_icon_is_refused() {
assert_eq!(rasterize_mask(&[0x1f, 0x8b, 8, 0, 0, 0, 0, 0], 16), None);
}
#[test]
fn distance_follows_the_spec() {
assert_eq!(distance(&[("Size", "16"), ("Type", "Fixed")]), (0, 1));
@@ -303,6 +330,15 @@ mod tests {
assert!(rasterize_mask(SQUARE.as_bytes(), 100_000).is_none());
}
/// resvg panics rendering an offset past the pixmap's size: the icon is unreadable instead.
#[test]
fn a_mask_the_renderer_panics_on_is_none() {
let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16">
<filter id="f"><feOffset dx="3e9" dy="-3e9"/></filter><rect width="16" height="16" filter="url(#f)"/>
</svg>"##;
assert!(rasterize_mask(svg.as_bytes(), 16).is_none());
}
/// An icon's `<image>` is never loaded: not a device file, not an embedded picture.
#[test]
fn masks_load_no_images() {
+1 -1
View File
@@ -286,7 +286,7 @@ mod tests {
assert_eq!(parsed.control, Some(50494));
assert_eq!(parsed.auth.control_token.as_deref(), Some("abcd"));
assert_eq!(parsed.auth.control_token_file, None);
assert_eq!(parsed.automation.automation_read_root.as_deref(), Some(std::path::Path::new("/r")));
assert_eq!(parsed.automation.automation_read_root, vec![std::path::PathBuf::from("/r")]);
assert_eq!(parsed.automation.automation_write_root.as_deref(), Some(std::path::Path::new("/w")));
assert!(parsed.safe_gpu && parsed.in_window_menus && parsed.new_instance);
assert_eq!(parsed.present_mode, Some(PresentMode::AutoNoVsync));
+15 -2
View File
@@ -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]
+1 -1
View File
@@ -254,7 +254,7 @@ impl Backend for MacMenu {
pub fn install(ctx: &egui::Context, app: &photocraft_ui_egui::PhotocraftApp) -> Option<native_menu::NativeMenu> {
let language = &app.session.prefs().interface.language;
let lang = photocraft_ui_egui::i18n::Lang::from_pref(language);
let bar = native_menu::photocraft_layout(&photocraft_ui_egui::menus::menu_items(app), lang, language).bar;
let bar = native_menu::app_layout(app, &photocraft_ui_egui::menus::menu_items(app), lang, language).bar;
// Never crash for a menu: if AppKit refuses, keep the in-window menus.
let built = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let mut menu = MacMenu::new(ctx);
+265 -55
View File
@@ -29,6 +29,7 @@
#![cfg_attr(all(windows, not(debug_assertions)), windows_subsystem = "windows")]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod agent_link;
mod app_dirs;
mod app_icon;
mod appearance;
@@ -94,51 +95,77 @@ fn custom_titlebar(prefs_file: Option<&std::path::Path>) -> bool {
CUSTOM_TITLEBAR && !prefs.interface.system_title_bar
}
/// Preferences › Integrations, read before the window opens the way [`custom_titlebar`] is:
/// whether agents may drive this launch at all, and the port to listen on when no `--control`
/// was given (0 = only with `--control`). A missing or unreadable file keeps the defaults.
/// Preferences › AI Integrations, read before the window opens the way [`custom_titlebar`] is:
/// whether agents may drive this launch at all, the port to listen on when no `--control`
/// was given (0 = only with `--control`) and the automation folders used when no
/// `--automation-read-root` / `--automation-write-root` was given. A missing or unreadable file
/// keeps the defaults.
///
/// The section is read on its own, and when it doesn't read as a whole each value on its own,
/// as the app's lenient load reads them (#6611): a wrong-typed value elsewhere in the file, or
/// in the other field, must not turn Allow Agent Control back on while the dialog shows it off.
fn integrations(prefs_file: Option<&std::path::Path>) -> photocraft_engine::prefs::Integrations {
use serde_json::Value;
let mut out = photocraft_engine::prefs::Preferences::default().integrations;
let file: Option<Value> = prefs_file.and_then(|p| std::fs::read_to_string(p).ok()).and_then(|t| serde_json::from_str(&t).ok());
let Some(section) = file.as_ref().and_then(|v| v.get("integrations")) else {
return out;
};
if let Ok(whole) = serde_json::from_value(section.clone()) {
return whole;
let file: Option<serde_json::Value> = prefs_file.and_then(|p| std::fs::read_to_string(p).ok()).and_then(|t| serde_json::from_str(&t).ok());
file.as_ref()
.and_then(|v| v.get("integrations"))
.cloned()
.map(photocraft_engine::prefs::read_integrations_section)
.unwrap_or_else(|| photocraft_engine::prefs::Preferences::default().integrations)
}
/// The automation roots: `--automation-read-root` / `--automation-write-root` (or their
/// variables) win; a direction without one takes Preferences › AI Integrations' folder. A flag's
/// root that can't be opened stops the launch (exit status 2) as before. A preference's root that
/// can't be opened, or isn't an absolute path (it would depend on the folder the app was started
/// from), is left out, so that direction fails closed, and the warning says why: a folder moved
/// since it was chosen must not stop the app from starting. Each folder is opened once, so one
/// that goes away during the launch can't turn into an error, and the same folder for reading
/// and writing shares one capability, as it does when given by flags.
fn automation_workspace(
flags: &photocraft_automation::args::AutomationArgs,
prefs: &photocraft_engine::prefs::Integrations,
) -> Result<(photocraft_automation::workspace::AuthorizedWorkspace, Option<String>), photocraft_automation::AutomationError> {
use photocraft_automation::agent_link::folder;
let mut workspace = flags.workspace()?;
let mut warnings = Vec::new();
for read in [true, false] {
let given = if read { !flags.automation_read_root.is_empty() } else { flags.automation_write_root.is_some() };
let Some(root) = folder(if read { &prefs.read_root } else { &prefs.write_root }).filter(|_| !given) else {
continue;
};
let opened = if !root.is_absolute() {
Err(format!("`{}` is not an absolute path", root.display()))
} else if read {
workspace.with_read_root(&root).map_err(|e| e.to_string())
} else {
workspace.with_write_root(&root).map_err(|e| e.to_string())
};
match opened {
Ok(w) => workspace = w,
Err(e) => {
let which = if read { "Automation Read Folder" } else { "Automation Write Folder" };
warnings.push(format!("Preferences › AI Integrations › {which} is not used: {e}"));
}
}
}
if let Some(allow) = section.get("allowAgentControl").and_then(Value::as_bool) {
out.allow_agent_control = allow;
}
if let Some(port) = section.get("controlPort").and_then(Value::as_u64).and_then(|p| u32::try_from(p).ok()) {
out.control_port = port;
}
out
Ok((workspace, (!warnings.is_empty()).then(|| warnings.join("\n"))))
}
/// The control port this launch listens on, and the warning to print when a request was refused.
/// `--control` (or `PHOTOCRAFT_CONTROL_PORT`) wins over the preference; Allow Agent Control off
/// refuses both, and says so rather than ignoring the flag silently. A preferred port outside
/// 1..=65535 is refused the same way.
/// Only `--control` (or `PHOTOCRAFT_CONTROL_PORT`) opens one at launch: Preferences › AI
/// Integrations' connection starts and stops while the app runs (`agent_link`). Allow Agent
/// Control off refuses the flag too, and says so rather than ignoring it silently.
fn control_port_for(cli: Option<u16>, prefs: &photocraft_engine::prefs::Integrations) -> (Option<u16>, Option<String>) {
if !prefs.allow_agent_control {
let warning = cli.map(|p| format!("photocraft: Preferences › Integrations › Allow Agent Control is off: not listening on port {p}\n"));
let warning = cli.map(|p| {
format!(
"photocraft: Preferences › AI Integrations › Allow Agent Control is off: not listening on port {p}
"
)
});
return (None, warning);
}
if let Some(port) = cli {
return (Some(port), None);
}
match prefs.control_port {
0 => (None, None),
p => match u16::try_from(p).ok().filter(|p| *p != 0) {
Some(port) => (Some(port), None),
None => (None, Some(format!("photocraft: Preferences › Integrations › Control Port {p} is not a usable port: not listening\n"))),
},
}
(cli, None)
}
/// The main window: 1440 × 900 (shrunk to fit the monitor, and maximized on the first frame
@@ -153,7 +180,7 @@ fn native_options(custom_titlebar: bool) -> eframe::NativeOptions {
.with_app_id(APP_ID)
.with_title("PhotoCraft")
.with_inner_size([1440.0, 900.0])
.with_min_inner_size([760.0, 480.0])
.with_min_inner_size(photocraft_ui_egui::MIN_WINDOW_SIZE)
.with_drag_and_drop(true)
.with_decorations(!custom_titlebar)
.with_fullsize_content_view(true)
@@ -282,17 +309,54 @@ fn linux_display_session() -> linux_libs::DisplaySession {
session
}
/// The control server's port, token and workspace, when it is on (exits 2 on a bad configuration).
/// The control server: its listener, token and workspace.
type Control = (std::net::TcpListener, String, photocraft_automation::workspace::AuthorizedWorkspace);
/// What [`control_setup`] set up: the control server when it is on, and a notice for the window
/// (a preference's automation folder that wasn't used).
struct ControlSetup {
control: Option<Control>,
warning: Option<ControlNotice>,
}
/// A notice for the window about the control server: a Dock launch has no console.
struct ControlNotice {
title: &'static str,
lines: Vec<String>,
}
/// The `--control` server's port, token and workspace, when it is on (exits 2 on a bad
/// configuration). Preferences › AI Integrations' folders stand in for automation roots no flag
/// names. The server the agents switch starts is `agent_link`'s, not this.
fn control_setup(
cli_port: Option<u16>,
auth: photocraft_automation::args::ControlArgs,
automation: &photocraft_automation::args::AutomationArgs,
) -> Option<(std::net::TcpListener, String, photocraft_automation::workspace::AuthorizedWorkspace)> {
let (port, warning) = control_port_for(cli_port, &integrations(services::prefs_file().as_deref()));
) -> ControlSetup {
control_setup_in(services::config_dir(), &integrations(services::prefs_file().as_deref()), cli_port, auth, automation)
}
/// [`control_setup`] with the settings folder and Preferences › AI Integrations given.
fn control_setup_in(
settings: Option<std::path::PathBuf>,
prefs: &photocraft_engine::prefs::Integrations,
cli_port: Option<u16>,
auth: photocraft_automation::args::ControlArgs,
automation: &photocraft_automation::args::AutomationArgs,
) -> ControlSetup {
use photocraft_automation::agent_link;
let (port, warning) = control_port_for(cli_port, prefs);
if let Some(warning) = &warning {
eprint!("{warning}");
}
let port = port?;
// A file a crashed (or, on macOS, quit) launch left behind names a port nothing serves. Before
// binding, so this launch's own listener doesn't keep it.
if let Some(dir) = &settings {
agent_link::remove_stale_connection(dir);
}
let Some(port) = port else {
return ControlSetup { control: None, warning: None };
};
let listener = match std::net::TcpListener::bind(("127.0.0.1", port)) {
Ok(listener) => listener,
Err(error) => {
@@ -308,21 +372,26 @@ fn control_setup(
std::process::exit(2);
}
};
if let Some(path) = token_file {
if let Some(path) = &token_file {
eprintln!("photocraft: control token file: {}", path.display());
} else if supplied.is_none() {
eprintln!("photocraft: control token: {token}");
} else {
eprintln!("photocraft: using supplied control token");
}
let workspace = match automation.workspace() {
let (workspace, warning) = match automation_workspace(automation, prefs) {
Ok(workspace) => workspace,
Err(error) => {
eprintln!("photocraft: cannot configure automation workspace: {error}");
std::process::exit(2);
}
};
Some((listener, token, workspace))
if let Some(warning) = &warning {
eprintln!("photocraft: {warning}");
log::warn!("{warning}");
}
let warning = warning.map(|w| ControlNotice { title: "Automation folder not used", lines: w.lines().map(str::to_owned).collect() });
ControlSetup { control: Some((listener, token, workspace)), warning }
}
/// Record this start's backend in the GPU startup marker, if the marker is locked.
@@ -398,7 +467,7 @@ fn main() -> eframe::Result {
let _ = (new_instance, &launch_options);
// Bind and authenticate the authorized control listener before display/GPU initialization.
let control = control_setup(control_port, auth, &automation);
let ControlSetup { control, warning: control_warning } = control_setup(control_port, auth, &automation);
#[cfg(target_os = "linux")]
let native_session = linux_libs::session_from_env(|name| std::env::var(name).ok());
@@ -588,6 +657,7 @@ fn main() -> eframe::Result {
&& app.session.prefs().performance.effective_rendering_mode() != photocraft_engine::prefs::RenderingMode::Cpu
{
app.set_wgpu(rs);
app.start_compositor(&cc.egui_ctx);
} else {
// The window still draws with wgpu: record its errors instead of panicking,
// and notice when the device is lost (#3438).
@@ -617,9 +687,24 @@ fn main() -> eframe::Result {
log::warn!("couldn't remember GPU backend {}: {e}", b.name());
}
});
// Agents in the open window, unless the launch flags (`--control`) manage the
// connection. Behind the suite's AI-MCP feature flag, the ArtCraft Launcher's switch
// (Settings › AI agents) is the one consent; without it, as before, a Control Port.
let flags = craft_flags::load();
for problem in &flags.problems {
log::warn!("feature flags: {problem}");
}
app.agent_link.mcp_flag = flags.enabled(&craft_flags::AI_MCP);
if app.agent_link.mcp_flag {
app.services.launcher_agents = Some(agent_link::launcher_watch(&cc.egui_ctx));
}
if let Some((listener, token, _)) = control {
app.agent_link.launch_flags = true;
app.agent_link.port = listener.local_addr().ok().map(|a| a.port());
let rx = control_server::start(listener, token, cc.egui_ctx.clone());
app = app.with_control(rx);
} else {
app.services.agent_link = Some(agent_link::service(services::config_dir()));
}
#[cfg(target_os = "macos")]
{
@@ -669,9 +754,19 @@ fn main() -> eframe::Result {
if let Some(monitor) = tablet::install_windows() {
let _ = tablet_monitor_win.set(monitor);
}
// With Windows Ink disabled for the tablet, WinTab supplies the pen pressure, tilt,
// rotation and eraser end; the vendor driver still moves the cursor.
#[cfg(target_os = "windows")]
if let Some(poll) =
tablet::install_wintab(cc, &app.stylus.feed, app.session.prefs().tools.tablet_input == photocraft_engine::prefs::TabletInput::WinTab)
{
app.services.tablet_poll = Some(poll);
}
#[cfg(target_os = "linux")]
tablet::spawn_x11(&app.stylus.feed, display);
app.services.right_button_down = tablet::right_button_service();
app.services.pen_end = tablet::pen_end_service();
app.services.pen_screen_px = tablet::pen_screen_service();
// Paths on the command line (Linux/Windows file associations, `photocraft a.psd`).
app.open_paths(&files);
if !unreadable_paths.is_empty() {
@@ -684,6 +779,11 @@ fn main() -> eframe::Result {
if let Some(w) = &app_dirs::current().warning {
photocraft_ui_egui::notices::post(&mut app, "Portable mode is off", vec![w.clone()], false, None);
}
// A preference's automation folder that couldn't be opened, or a token file it couldn't
// write: a Dock launch has no console.
if let Some(ControlNotice { title, lines }) = control_warning {
photocraft_ui_egui::notices::post(&mut app, title, lines, false, None);
}
Ok(Box::new(app))
}),
);
@@ -966,16 +1066,17 @@ mod tests {
#[test]
fn integrations_preferences_decide_the_control_port() {
use photocraft_engine::prefs::Integrations;
let off = Integrations { allow_agent_control: false, control_port: 0 };
let on = Integrations { allow_agent_control: true, control_port: 0 };
let preferred = Integrations { allow_agent_control: true, control_port: 7878 };
let off = Integrations { allow_agent_control: false, control_port: 0, ..Default::default() };
let on = Integrations { allow_agent_control: true, control_port: 0, ..Default::default() };
let preferred = Integrations { allow_agent_control: true, control_port: 7878, ..Default::default() };
// Nothing asked for, nothing listening.
assert_eq!(super::control_port_for(None, &on), (None, None));
// --control wins over the preference.
assert_eq!(super::control_port_for(Some(9000), &preferred), (Some(9000), None));
// The preference opens the port when --control is absent.
assert_eq!(super::control_port_for(None, &preferred), (Some(7878), None));
// The preference alone opens nothing at launch: the agent connection starts it while
// the app runs (`agent_link`).
assert_eq!(super::control_port_for(None, &preferred), (None, None));
// Allow Agent Control off refuses both, and says so when --control asked for one
// rather than ignoring the flag.
@@ -983,14 +1084,8 @@ mod tests {
let (port, warning) = super::control_port_for(Some(9000), &off);
assert_eq!(port, None);
assert!(warning.is_some_and(|w| w.contains("Allow Agent Control") && w.contains("9000")), "the refusal names the port");
let off_with_port = Integrations { allow_agent_control: false, control_port: 7878 };
let off_with_port = Integrations { allow_agent_control: false, control_port: 7878, ..Default::default() };
assert_eq!(super::control_port_for(None, &off_with_port), (None, None), "off beats a preferred port");
// A port a hand-edited file could hold, outside 1..=65535, is refused and named.
let huge = Integrations { allow_agent_control: true, control_port: 70_000 };
let (port, warning) = super::control_port_for(None, &huge);
assert_eq!(port, None);
assert!(warning.is_some_and(|w| w.contains("70000")), "the refusal names the value");
}
#[test]
@@ -1030,7 +1125,7 @@ mod tests {
read
};
let r = read(r#"{"interface":{"enableAnimations":"nope"},"integrations":{"allowAgentControl":false,"controlPort":7878}}"#);
let r = read(r#"{"interface":{"showTooltips":"nope"},"integrations":{"allowAgentControl":false,"controlPort":7878}}"#);
assert!(!r.allow_agent_control, "a bad value in another section");
assert_eq!(r.control_port, 7878);
let r = read(r#"{"integrations":{"allowAgentControl":false,"controlPort":"x"}}"#);
@@ -1038,13 +1133,108 @@ mod tests {
assert_eq!(r.control_port, 0, "the bad port alone takes its default");
// A bad Allow Agent Control alone takes its default.
let r = read(r#"{"integrations":{"allowAgentControl":"no","controlPort":7878}}"#);
assert_eq!(r, photocraft_engine::prefs::Integrations { allow_agent_control: true, control_port: 7878 });
// (A saved port from before the agents switch turns it on, in both reads.)
assert_eq!(r, photocraft_engine::prefs::Integrations { allow_agent_control: true, control_port: 7878, connect_agents: true, ..Default::default() });
read(r#"{"integrations":{"allowAgentControl":false,"controlPort":-1}}"#);
read(r#"{"integrations":{"allowAgentControl":false,"controlPort":4294967296}}"#);
read(r#"{"integrations":"off"}"#);
// serde reads a struct from a list too; the app does.
assert!(!read(r#"{"integrations":[false]}"#).allow_agent_control, "a list");
assert_eq!(read(r#"{"integrations":[false,7878]}"#).control_port, 7878);
// The automation folders: a bad one takes its default alone, too.
let r = read(r#"{"integrations":{"allowAgentControl":false,"readRoot":5,"writeRoot":"/w"}}"#);
assert!(!r.allow_agent_control, "a bad folder");
assert_eq!((r.read_root.as_str(), r.write_root.as_str()), ("", "/w"));
let _ = std::fs::remove_dir_all(&dir);
}
fn temp_dir(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("pc-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn flags(read: Option<&std::path::Path>, write: Option<&std::path::Path>) -> photocraft_automation::args::AutomationArgs {
photocraft_automation::args::AutomationArgs {
automation_read_root: read.map(Into::into).into_iter().collect(),
automation_write_root: write.map(Into::into),
}
}
fn roots(read: &std::path::Path, write: &std::path::Path) -> photocraft_engine::prefs::Integrations {
photocraft_engine::prefs::Integrations {
read_root: read.to_string_lossy().into_owned(),
write_root: write.to_string_lossy().into_owned(),
..Default::default()
}
}
/// Preferences › AI Integrations' folders are the automation roots when no flag names one, and
/// a flag wins over its preference, direction by direction.
#[test]
fn automation_folders_come_from_the_preferences_unless_a_flag_names_one() {
let dir = temp_dir("automation-roots");
let (pref, flag) = (dir.join("pref"), dir.join("flag"));
std::fs::create_dir_all(&pref).unwrap();
std::fs::create_dir_all(&flag).unwrap();
// No flags: both directions from the preferences.
let (ws, warning) = super::automation_workspace(&flags(None, None), &roots(&pref, &pref)).unwrap();
assert_eq!(warning, None);
ws.write("a.txt", b"pref").unwrap();
assert_eq!(std::fs::read(pref.join("a.txt")).unwrap(), b"pref");
assert_eq!(ws.read("a.txt").unwrap(), b"pref");
// One folder for both shares one capability, as the flags do: an implicit save is allowed.
assert_eq!(ws.read_with_save_path("a.txt").unwrap().1.as_deref(), Some("a.txt"));
// A write flag wins over the write folder; reads still come from the preference.
let (ws, _) = super::automation_workspace(&flags(None, Some(&flag)), &roots(&pref, &pref)).unwrap();
ws.write("b.txt", b"flag").unwrap();
assert!(flag.join("b.txt").is_file() && !pref.join("b.txt").exists(), "the flag's folder takes the write");
assert_eq!(ws.read("a.txt").unwrap(), b"pref");
assert_eq!(ws.read_with_save_path("a.txt").unwrap().1, None, "read and write folders differ: no implicit save");
// A read folder spelled like the write flag shares the flag's capability.
let (ws, _) = super::automation_workspace(&flags(None, Some(&flag)), &roots(&flag, &pref)).unwrap();
assert_eq!(ws.read_with_save_path("b.txt").unwrap().1.as_deref(), Some("b.txt"));
// Empty preferences grant nothing, as no flags do.
let (ws, warning) = super::automation_workspace(&flags(None, None), &photocraft_engine::prefs::Integrations::default()).unwrap();
assert_eq!(warning, None);
assert!(ws.read("a.txt").is_err() && ws.write("c.txt", b"x").is_err());
let _ = std::fs::remove_dir_all(&dir);
}
/// A preference's folder that can't be opened is left out (that direction fails closed) and
/// named in the warning; the app still starts. A flag's still stops the launch.
#[test]
fn a_missing_preference_folder_is_left_out_and_a_missing_flag_root_is_an_error() {
let dir = temp_dir("automation-roots-missing");
let missing = dir.join("gone");
let (ws, warning) = super::automation_workspace(&flags(None, None), &roots(&dir, &missing)).unwrap();
let warning = warning.expect("the missing write folder is named");
assert!(warning.contains("Automation Write Folder") && !warning.contains("Read Folder"), "{warning}");
std::fs::write(dir.join("in.txt"), b"x").unwrap();
assert_eq!(ws.read("in.txt").unwrap(), b"x", "the read folder still applies");
assert!(ws.write("out.txt", b"x").is_err(), "no write access without its folder");
assert!(super::automation_workspace(&flags(Some(&missing), None), &roots(&dir, &dir)).is_err(), "a flag's root must open");
let _ = std::fs::remove_dir_all(&dir);
}
/// A relative folder preference would depend on the folder the app was started from: left
/// out with a warning, like a missing one.
#[test]
fn a_relative_preference_folder_is_left_out() {
let dir = temp_dir("automation-roots-relative");
let relative = photocraft_engine::prefs::Integrations { read_root: ".".into(), ..roots(&dir, &dir) };
let (ws, warning) = super::automation_workspace(&flags(None, None), &relative).unwrap();
let warning = warning.expect("the relative read folder is named");
assert!(warning.contains("Automation Read Folder") && warning.contains("not an absolute path"), "{warning}");
assert!(ws.read("anything").is_err(), "no read access from a relative folder");
ws.write("out.txt", b"x").unwrap();
assert!(dir.join("out.txt").is_file(), "the absolute write folder still applies");
let _ = std::fs::remove_dir_all(&dir);
}
@@ -1056,4 +1246,24 @@ mod tests {
let class = entry.lines().find_map(|line| line.strip_prefix("StartupWMClass="));
assert_eq!(class, Some(super::APP_ID));
}
/// Both flatpak manifests build with the craft-i18n commit `craft-i18n.rev` pins: CI and
/// releases read the file, and the manifests have to name the commit themselves. The pin may
/// have a trailing newline or CRLF (a Windows checkout), so it is trimmed, as every reader does.
#[test]
fn the_flatpak_manifests_pin_the_craft_i18n_rev() {
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
let rev = std::fs::read_to_string(root.join("craft-i18n.rev")).unwrap();
let rev = rev.trim();
assert!(rev.len() == 40 && rev.bytes().all(|b| b.is_ascii_hexdigit()), "craft-i18n.rev holds one full SHA: {rev:?}");
for manifest in ["ai.storyteller.photocraft.yml", "ai.storyteller.photocraft.bundle.yml"] {
let text = std::fs::read_to_string(root.join("packaging/linux/flatpak").join(manifest)).unwrap();
let source = text.split("url: https://github.com/storytold/craft-i18n").nth(1).unwrap_or_else(|| panic!("{manifest}: a craft-i18n git source"));
let source = source.split("- type:").next().unwrap_or(source);
let commit =
source.lines().find_map(|l| l.trim().strip_prefix("commit:")).unwrap_or_else(|| panic!("{manifest}: the craft-i18n source pins a commit"));
assert_eq!(commit.trim().trim_matches(['\'', '"']), rev, "{manifest}");
assert!(text.contains("CRAFT_I18N_DIR: /run/build/photocraft/craft-i18n"), "{manifest}: the build names the catalogs");
}
}
}
+6 -6
View File
@@ -294,8 +294,8 @@ mod linux {
return None;
}
bytes.truncate(declared);
let profile = photocraft_cms::Profile::parse(&bytes).ok()?;
(profile.color_space == photocraft_cms::ColorSpace::Rgb).then_some(bytes)
let profile = craft_cms::Profile::parse(&bytes).ok()?;
(profile.color_space == craft_cms::ColorSpace::Rgb).then_some(bytes)
}
fn unambiguous_clone_profile(output_names: &[String], profiles: &HashMap<String, Vec<IccProfile>>) -> Option<IccProfile> {
@@ -320,11 +320,11 @@ mod linux {
#[test]
fn checked_icc_bytes_require_a_bounded_parseable_rgb_profile() {
let rgb = photocraft_cms::Builtin::Srgb.profile().to_bytes();
let rgb = craft_cms::Builtin::Srgb.profile().to_bytes();
let bytes = rgb.as_ref().clone();
assert_eq!(checked_icc_bytes(bytes.clone()), Some(bytes));
let cmyk = photocraft_cms::Builtin::CoatedCmyk.profile().to_bytes();
let cmyk = craft_cms::Builtin::CoatedCmyk.profile().to_bytes();
assert!(checked_icc_bytes(cmyk.as_ref().clone()).is_none());
assert!(checked_icc_bytes(vec![0; 132]).is_none());
assert!(checked_icc_bytes(vec![0; MAX_ICC_BYTES + 1]).is_none());
@@ -332,8 +332,8 @@ mod linux {
#[test]
fn cloned_outputs_use_only_one_unambiguous_profile() {
let srgb = photocraft_cms::Builtin::Srgb.profile().to_bytes();
let p3 = photocraft_cms::Builtin::DisplayP3.profile().to_bytes();
let srgb = craft_cms::Builtin::Srgb.profile().to_bytes();
let p3 = craft_cms::Builtin::DisplayP3.profile().to_bytes();
let profile = |name: &str, bytes: std::sync::Arc<Vec<u8>>| IccProfile { name: name.into(), bytes };
let outputs = ["DP-1".to_owned(), "HDMI-1".to_owned()];
+4 -4
View File
@@ -70,11 +70,11 @@ fn icc_profile(bytes: Vec<u8>) -> Option<Vec<u8>> {
if bytes.is_empty() || bytes.len() > MAX_ICC_PROFILE_BYTES {
return None;
}
let profile = match photocraft_cms::Profile::parse(&bytes) {
let profile = match craft_cms::Profile::parse(&bytes) {
Ok(profile) => profile,
Err(_) => return None,
};
(profile.color_space == photocraft_cms::ColorSpace::Rgb).then_some(bytes)
(profile.color_space == craft_cms::ColorSpace::Rgb).then_some(bytes)
}
#[cfg(target_os = "linux")]
fn icc_profile_atom<C: x11rb::connection::RequestConnection>(conn: &C, name: &str) -> Option<u32> {
@@ -434,13 +434,13 @@ mod tests {
#[cfg(target_os = "linux")]
#[test]
fn x11_screen_capture_accepts_only_bounded_rgb_icc_profiles() {
let rgb = photocraft_cms::Builtin::Srgb.profile().to_bytes();
let rgb = craft_cms::Builtin::Srgb.profile().to_bytes();
let bytes = rgb.as_ref().clone();
assert_eq!(icc_profile(bytes.clone()), Some(bytes));
assert!(icc_profile(Vec::new()).is_none());
assert!(icc_profile(vec![0; MAX_ICC_PROFILE_BYTES + 1]).is_none());
let cmyk = photocraft_cms::Builtin::CoatedCmyk.profile().to_bytes();
let cmyk = craft_cms::Builtin::CoatedCmyk.profile().to_bytes();
assert!(icc_profile(cmyk.as_ref().clone()).is_none());
}
#[cfg(target_os = "linux")]
+137 -63
View File
@@ -36,39 +36,40 @@ fn open_filter_extensions(extensions: &[&str]) -> Vec<String> {
}
/// File › Open's file types after All Formats, as Photoshop lists them: one per format, so a folder
/// of mixed files can be narrowed to one kind (#6337). Together they cover every extension of
/// of mixed files can be narrowed to one kind (#6337). The document formats, the rest by name as in
/// [`SAVE_FILTERS`], then the app's own resources. Together they cover every extension of
/// [`OPEN_EXTS`]. An explicit SVG filter also keeps vector artwork discoverable when a native
/// picker defaults to another filter.
const OPEN_FILTERS: &[(&str, &[&str])] = &[
("PhotoCraft", &["pcraft"]),
("Photoshop", &["psd", "psb", "psdt"]),
("PhotoCraft", &["pcraft"]),
("Affinity", &["af", "afdesign", "afphoto", "afpub"]),
("Krita", &["kra", "krz"]),
("Amiga IFF", &["iff", "lbm", "ilbm"]),
("BMP", &["bmp", "dib"]),
("DDS", &["dds"]),
("DICOM", &["dcm", "dicom", "dc3"]),
("DPX and Cineon", &["dpx", "cin"]),
("FITS", &["fits", "fit", "fts"]),
("GIF", &["gif"]),
("GIMP", &["xcf", "xcfgz", "gz"]),
("HEIF", &["heic", "heif", "hif"]),
("ICO", &["ico"]),
("JPEG", &["jpg", "jpeg"]),
("Krita", &["kra", "krz"]),
("OpenEXR", &["exr"]),
("OpenRaster", &["ora"]),
("Paint.NET", &["pdn"]),
("SVG", SVG_EXTS),
("PCX", &["pcx"]),
("PNG", &["png"]),
("JPEG", &["jpg", "jpeg"]),
("HEIF", &["heic", "heif", "hif"]),
("Portable Bitmap", &["pbm", "pgm", "ppm", "pnm", "pam", "pfm"]),
("QOI", &["qoi"]),
("Radiance HDR", &["hdr"]),
("RAW images", &["dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf"]),
("SVG", SVG_EXTS),
("Targa", &["tga"]),
("TIFF", &["tif", "tiff"]),
("WebP", &["webp"]),
("GIF", &["gif"]),
("BMP", &["bmp", "dib"]),
("Targa", &["tga"]),
("ICO", &["ico"]),
("QOI", &["qoi"]),
("PCX", &["pcx"]),
("DDS", &["dds"]),
("XPM", &["xpm"]),
("Portable Bitmap", &["pbm", "pgm", "ppm", "pnm", "pam", "pfm"]),
("OpenEXR", &["exr"]),
("Radiance HDR", &["hdr"]),
("FITS", &["fits", "fit", "fts"]),
("DPX and Cineon", &["dpx", "cin"]),
("Amiga IFF", &["iff", "lbm", "ilbm"]),
("DICOM", &["dcm", "dicom", "dc3"]),
("Camera Raw", &["dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf"]),
("Brushes", &["abr"]),
("Gradients", &["grd"]),
("Styles", &["asl"]),
@@ -82,35 +83,40 @@ fn open_filters() -> Vec<(&'static str, Vec<String>)> {
.collect()
}
/// File › Save As formats: (filter name, extensions). The filter matching the suggested name's
/// extension comes first, so a .pcraft document saves as .pcraft by default and everything else
/// keeps defaulting to PSD.
/// File › Save As formats: (filter name, extensions). PSD, PSB and PhotoCraft's own format, which
/// keep the most of a document, then the rest by name, so a long list stays easy to search. The
/// filter matching the suggested name's extension comes first, so a .pcraft document saves as
/// .pcraft by default and everything else keeps defaulting to PSD. The PSD type takes `.psb` too:
/// Windows adds the selected type's extension to a name whose extension isn't one of the type's,
/// so `art.psb` typed under the PSD type would come back as `art.psb.psd`.
const SAVE_FILTERS: &[(&str, &[&str])] = &[
("PSD Document", &["psd", "psb"]),
("PDF", &["pdf"]),
("PSB Large Document", &["psb"]),
("PhotoCraft", &["pcraft"]),
("OpenRaster", &["ora"]),
("PNG", &["png"]),
("Amiga IFF", &["iff"]),
("BMP", &["bmp", "dib"]),
("Cineon", &["cin"]),
// Game and 3D textures; DDS Options asks for the compression and mipmaps (#1327).
("DDS", &["dds"]),
("DPX", &["dpx"]),
("FITS", &["fits", "fit"]),
("GIF", &["gif"]),
// BMP and GIF are also in Photoshop's Save As list; ICO is PhotoCraft's own (#4357): up to
// 256×256, with alpha.
("ICO", &["ico"]),
("JPEG", &["jpg", "jpeg"]),
("JPEG XL", &["jxl"]),
("WebP", &["webp"]),
("TIFF", &["tif", "tiff"]),
("Targa", &["tga"]),
// Also in Photoshop's Save As list; ICO is PhotoCraft's own (#4357): up to 256×256, with alpha.
("BMP", &["bmp", "dib"]),
("GIF", &["gif"]),
("ICO", &["ico"]),
("OpenEXR", &["exr"]),
// The encoder picks P5, P6, P7 or PFM from the image, not from the name, so only the neutral
// .pnm is offered: a .pbm or .pgm name would hold pixmap data (CodeRabbit on #9775).
("Netpbm", &["pnm"]),
("OpenEXR", &["exr"]),
("OpenRaster", &["ora"]),
("PDF", &["pdf"]),
("PNG", &["png"]),
("Radiance HDR", &["hdr"]),
("FITS", &["fits", "fit"]),
("DPX", &["dpx"]),
// Game and 3D textures; DDS Options asks for the compression and mipmaps (#1327).
("DDS", &["dds"]),
("Cineon", &["cin"]),
("Amiga IFF", &["iff"]),
("Targa", &["tga"]),
("TIFF", &["tif", "tiff"]),
("WebP", &["webp"]),
];
/// Non-document files the shell saves (Swatches panel exports): offered alone, so the dialog
@@ -136,10 +142,14 @@ fn save_filters(suggested: &str) -> Vec<(String, Vec<String>)> {
return vec![(name.to_string(), exts.iter().map(|e| e.to_string()).collect())];
}
let mut v: Vec<(String, Vec<String>)> = SAVE_FILTERS.iter().map(|(name, exts)| (name.to_string(), exts.iter().map(|e| e.to_string()).collect())).collect();
match v.iter().position(|(_, exts)| exts.contains(&ext)) {
// The type the extension is first for (`.psb` starts on PSB, not on PSD's second extension),
// else any type that lists it.
let own = v.iter().position(|(_, exts)| exts.first() == Some(&ext));
match own.or_else(|| v.iter().position(|(_, exts)| exts.contains(&ext))) {
Some(i) => {
let (name, mut exts) = v.remove(i);
// Windows adds the first type's first extension to a bare name: `.psb`, not `.psd`.
// Windows adds the first type's first extension to a bare name: `cat.jpeg` stays
// `.jpeg`, and `sky.fit` stays `.fit`.
exts.retain(|e| *e != ext);
exts.insert(0, ext);
v.insert(0, (name, exts));
@@ -156,13 +166,26 @@ fn save_filters(suggested: &str) -> Vec<(String, Vec<String>)> {
/// dialog opened with (`opened_with`, `Untitled-1.psd` with PNG picked) or none gets the type's
/// extension, as PolyMeilex/rfd#341 does. An extension the user typed that PhotoCraft saves
/// (`art.png` with the PSD type untouched, the way to save a PNG before this) is theirs and stays,
/// and so does one of the type's own (`.psb` for PSD). One PhotoCraft doesn't save (`scan.2024`)
/// is part of the name, and the type's extension is added after it.
/// and so does one of the type's own. One PhotoCraft doesn't save (`scan.2024`)
/// is part of the name, and the type's extension is added after it. The exception: two of the
/// type's own extensions (`art.psb.psd` under the PSD type) lose the last, since KDE's dialog adds
/// it after a typed one; the returned name can't tell that from a typed `art.psb.psd`, which is
/// rare, so that one is saved as `art.psb` too.
#[cfg(any(target_os = "linux", test))]
pub(crate) fn with_chosen_type(path: &Path, opened_with: Option<&str>, chosen: &[String]) -> PathBuf {
let Some(first) = chosen.first() else { return path.to_path_buf() };
let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
let opened_ext = opened_with.and_then(|n| Path::new(n).extension()).and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
// A name that already had one of the type's extensions, with the type's first one added after
// it (KDE's dialog does that: `art.psb` typed under the PSD type came back as `art.psb.psd`).
let inner = path.file_stem().map(Path::new).and_then(|s| s.extension()).and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
if let (Some(ext), Some(inner)) = (&ext, &inner)
&& ext != inner
&& chosen.contains(ext)
&& chosen.contains(inner)
{
return path.with_extension("");
}
match ext {
Some(ext) if chosen.contains(&ext) => path.to_path_buf(),
Some(ext) if opened_ext.as_ref() == Some(&ext) => path.with_extension(first),
@@ -341,6 +364,41 @@ pub fn prefs_file() -> Option<PathBuf> {
config_dir().map(|d| d.join("preferences.json"))
}
fn gpu_memo_file() -> Option<PathBuf> {
config_dir().map(|d| d.join("gpu-compositor.json"))
}
fn load_gpu_memo_text() -> Option<String> {
use std::io::Read;
let file = std::fs::File::open(gpu_memo_file()?).ok()?;
let cap = photocraft_ui_egui::gpu_memo::MAX_GPU_MEMO_BYTES;
let mut bytes = Vec::new();
file.take((cap + 1) as u64).read_to_end(&mut bytes).ok()?;
if bytes.len() > cap {
log::info!("ignoring oversized GPU compositor memo");
return None;
}
String::from_utf8(bytes).ok()
}
fn shader_compiler_identity() -> String {
#[cfg(target_os = "windows")]
{
let exe = std::env::current_exe().ok();
let exe_dir = exe.as_deref().and_then(Path::parent);
match crate::gpu_startup::dx12_compiler(std::env::var("WGPU_DX12_COMPILER").ok().as_deref(), exe_dir) {
eframe::wgpu::Dx12Compiler::Fxc => "fxc".into(),
eframe::wgpu::Dx12Compiler::DynamicDxc { dxc_path } => format!("dxc:{dxc_path}"),
eframe::wgpu::Dx12Compiler::StaticDxc => "static-dxc".into(),
eframe::wgpu::Dx12Compiler::Auto => "auto".into(),
}
}
#[cfg(not(target_os = "windows"))]
{
String::new()
}
}
/// The brush preset store (one file per preset group plus tip bitmaps; see
/// `photocraft_engine::preset_store`).
pub fn presets_dir() -> Option<PathBuf> {
@@ -663,38 +721,45 @@ fn shell_word(s: &str) -> String {
if s.bytes().all(|b| b.is_ascii_alphanumeric() || b"/._-+:,@".contains(&b)) { s.to_string() } else { format!("'{}'", s.replace('\'', r"'\''")) }
}
pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) -> Services {
let clip: Rc<RefCell<Option<arboard::Clipboard>>> = Rc::default();
let clip_unreadable: Rc<Cell<bool>> = Rc::default();
let automation_read = automation.clone().map(|workspace| {
/// What control and MCP requests may read, write and run, through `workspace` (`None`: no
/// automation, as without `--control` or an agent connection).
pub fn automation(workspace: Option<photocraft_automation::AuthorizedWorkspace>) -> photocraft_ui_egui::AutomationServices {
let read = workspace.clone().map(|workspace| {
Box::new(move |path: &str| {
let bytes = workspace.read(path).map_err(|error| error.to_string())?;
let (bytes, save_path) = workspace.read_with_save_path(path).map_err(|error| error.to_string())?;
let name = Path::new(path).file_name().and_then(|name| name.to_str()).unwrap_or(path).to_string();
Ok((name, bytes))
Ok(photocraft_ui_egui::AutomationReadResult { name, bytes, save_path })
}) as photocraft_ui_egui::AutomationReadFn
});
let automation_write = automation.clone().map(|workspace| {
let write = workspace.clone().map(|workspace| {
Box::new(move |path: &str, bytes: &[u8]| workspace.write(path, bytes).map_err(|error| error.to_string())) as photocraft_ui_egui::AutomationWriteFn
});
let automation_open_pcraft = automation.clone().map(|workspace| {
let open_pcraft = workspace.clone().map(|workspace| {
Box::new(move |path: &str| {
let name = Path::new(path).file_name().and_then(|name| name.to_str()).unwrap_or(path).to_string();
let opened = crate::crash_guard::guard("Open", || workspace.open_pcraft(path).map_err(|e| e.to_string()))?;
Ok(opened.map(|doc| (name, doc)))
}) as photocraft_ui_egui::AutomationOpenPcraftFn
});
let automation_save = automation.clone().map(|workspace| {
let save = workspace.clone().map(|workspace| {
std::sync::Arc::new(move |doc: &Document, path: &str, settings: &photocraft_ui_egui::ExportSettings, ctl: &photocraft_ui_egui::jobs_ui::SaveCtl| {
save_through(doc, path, settings, ctl, |p, encoded, _| workspace.write_stream(p, &mut |w| encoded.write_to(w)).map_err(|e| e.to_string()))
}) as photocraft_ui_egui::SaveFileFn
});
let step: fn(&str, &serde_json::Value) -> photocraft_engine::Result<()> = photocraft_automation::workspace::authorize_desktop_engine_step;
let automation_authorize = automation.is_some().then_some(step);
let automation_command = automation.map(|_| {
let step: photocraft_ui_egui::AutomationAuthorizeFn = photocraft_automation::workspace::authorize_desktop_engine_step;
let authorize = workspace.is_some().then_some(step);
let command = workspace.map(|_| {
Box::new(|id: &str, params: &serde_json::Value| {
photocraft_automation::workspace::authorize_desktop_engine_command(id, params).map_err(|error| error.to_string())
}) as photocraft_ui_egui::AutomationCommandFn
});
photocraft_ui_egui::AutomationServices { read, write, open_pcraft, save, command, authorize }
}
pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) -> Services {
let clip: Rc<RefCell<Option<arboard::Clipboard>>> = Rc::default();
let clip_unreadable: Rc<Cell<bool>> = Rc::default();
let automation = self::automation(automation);
Services {
import: Some(Box::new(|name: &str, bytes: &[u8], opts: &photocraft_io::ImportOptions| {
crate::crash_guard::guard("Open", || {
@@ -714,12 +779,12 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->
Some(photocraft_ui_egui::FileStamp { len: meta.len(), modified: meta.modified().ok() })
})),
same_file: Some(Box::new(|a: &str, b: &str| same_entry(Path::new(a), Path::new(b), same_file))),
automation_read,
automation_write,
automation_open_pcraft,
automation_save,
automation_command,
automation_authorize,
automation_read: automation.read,
automation_write: automation.write,
automation_open_pcraft: automation.open_pcraft,
automation_save: automation.save,
automation_command: automation.command,
automation_authorize: automation.authorize,
encode_png: Some(Box::new(|w, h, rgba| {
let img = Image::from_u8(w, h, ChannelLayout::Rgba, rgba.to_vec()).map_err(|e| e.to_string())?;
photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &EncodeOptions::default()).map_err(|e| e.to_string())
@@ -728,6 +793,7 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->
open_url: Some(Box::new(|url: &str| open::that(url).map_err(|e| e.to_string()))),
beep: Some(platform_beep),
check_updates: Some(crate::updates::service()),
last_update: Some(crate::updates::last_update),
clipboard_set_image: Some({
let clip = clip.clone();
guarded_clipboard_set(move |w: u32, h: u32, px: &[u8]| {
@@ -791,6 +857,14 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->
load_prefs: Some(Box::new(|| std::fs::read_to_string(prefs_file()?).ok())),
photoshop_shortcuts: Some(Box::new(|| crate::photoshop_settings::live_keyboard_shortcuts(&|k| std::env::var_os(k)))),
save_prefs: Some(Box::new(|text: &str| write_atomic(&prefs_file().ok_or("no config directory")?, text.as_bytes()))),
load_gpu_memo: Some(Box::new(load_gpu_memo_text)),
save_gpu_memo: Some(Box::new(|text: &str| {
if text.len() > photocraft_ui_egui::gpu_memo::MAX_GPU_MEMO_BYTES {
return Err("GPU compositor memo exceeds 64 KiB".into());
}
write_atomic(&gpu_memo_file().ok_or("no config directory")?, text.as_bytes())
})),
shader_compiler: Some(shader_compiler_identity()),
system_theme: crate::appearance::service(),
append_text: Some(Box::new(|path: &str, text: &str| {
use std::io::Write;
+40 -1
View File
@@ -218,7 +218,9 @@ fn open_filters_keep_literal_extensions_on_windows_and_macos() {
#[test]
fn native_services_provide_update_transport() {
assert!(native(None).check_updates.is_some());
let services = native(None);
assert!(services.check_updates.is_some());
assert!(services.last_update.is_some());
}
#[test]
@@ -967,3 +969,40 @@ fn tiff_options_reach_the_written_file() {
assert_eq!(info.pages.iter().map(|p| (p.width, p.compression)).collect::<Vec<_>>(), [(200, 5), (100, 5), (50, 5)]);
assert!(!photocraft_codecs::decode(&bytes).unwrap().layout().has_alpha());
}
/// PSB is a save type of its own: it shows in the list, and the type gives a typed name its
/// extension. As an extension of the PSD type it was hidden, and KDE's dialog, which adds the
/// type's first extension, turned `art.psb` into `art.psb.psd`.
#[test]
fn psb_is_its_own_save_type() {
let filters = save_filters("Untitled-1.psd");
let (psd, psb) = (&filters[0], &filters[1]);
// The PSD type takes a typed .psb too, so Windows doesn't add .psd after it.
assert_eq!(psd.1, vec!["psd".to_string(), "psb".to_string()], "{psd:?}");
assert_eq!(psb.1, vec!["psb".to_string()], "{psb:?}");
let big = save_filters("big.psb");
assert_eq!((big[0].0.as_str(), big[0].1.clone()), ("PSB Large Document", vec!["psb".to_string()]), "a .psb starts on its own type");
let chosen = |f: &(String, Vec<String>)| with_chosen_type(Path::new("/pics/art"), Some("art.psd"), &f.1);
assert_eq!(chosen(psd), PathBuf::from("/pics/art.psd"));
assert_eq!(chosen(psb), PathBuf::from("/pics/art.psb"));
let opened = Some("Untitled-1");
assert_eq!(with_chosen_type(Path::new("/pics/art.psb"), opened, &psd.1), PathBuf::from("/pics/art.psb"), "a typed .psb stays");
// KDE adds the type's first extension after a typed one of its own: that one is taken back,
// also from an `art.psb.psd` typed in full (the dialog's answer is the same string).
assert_eq!(with_chosen_type(Path::new("/pics/art.psb.psd"), opened, &psd.1), PathBuf::from("/pics/art.psb"), "KDE's art.psb.psd");
// A dot that's part of the name stays (.jpg isn't one of the PSD type's).
assert_eq!(with_chosen_type(Path::new("/pics/scan.jpg.psd"), opened, &psd.1), PathBuf::from("/pics/scan.jpg.psd"));
}
/// The document formats, then the rest by name, so a long list stays easy to search.
#[test]
fn save_types_list_the_document_formats_then_the_rest_by_name() {
let names: Vec<&str> = SAVE_FILTERS.iter().map(|(name, _)| *name).collect();
assert_eq!(names[..3], ["PSD Document", "PSB Large Document", "PhotoCraft"]);
let key = |name: &&str| name.to_ascii_lowercase();
assert!(names[3..].is_sorted_by_key(key), "{:?}", &names[3..]);
let names: Vec<&str> = OPEN_FILTERS.iter().map(|(name, _)| *name).collect();
assert_eq!(names[..2], ["Photoshop", "PhotoCraft"]);
let formats = names.iter().position(|name| *name == "Brushes").expect("the app's own resources");
assert!(names[2..formats].is_sorted_by_key(key), "{:?}", &names[2..formats]);
}
+106 -6
View File
@@ -1,12 +1,14 @@
//! Pen tablet pressure, tilt, rotation and eraser end on macOS and Linux X11 (issue #79), and
//! barrel button on Windows (#5905).
//! barrel button (#5905) and eraser end (#2285) on Windows.
//!
//! winit 0.30 drops tablet data on both macOS and X11, so `photocraft-tablet` reads it beside winit
//! (an AppKit local event monitor; XInput2 raw events on a second X connection) and this module writes
//! each sample into the UI's [`StylusFeed`], where the canvas reads it exactly like the web runner's
//! Pointer Events and automation's simulated pen. On Windows, winit forwards `WM_POINTER` pressure
//! as touch force, but drops `PEN_FLAG_BARREL` (`0x0001`); `photocraft-tablet` recovers the barrel
//! button through a thread-local message hook beside winit.
//! as touch force, but drops `PEN_FLAG_BARREL` (`0x0001`) and the eraser end (`PEN_FLAG_INVERTED`);
//! `photocraft-tablet` recovers them through thread-local message hooks beside winit. With Windows
//! Ink disabled for the tablet, the optional WinTab mode reads pressure, tilt, rotation and the
//! eraser end from a WinTab 1.4 system context instead ([`install_wintab`]).
//!
//! Wayland compositors give a pen only to clients that bind the tablet protocol
//! (`zwp_tablet_v2`), which winit 0.30 doesn't (and binding it on winit's connection needs
@@ -32,11 +34,50 @@ pub fn sink(feed: StylusFeed) -> impl Fn(Option<Sample>) + Send + 'static {
move |s| feed.set(s.map(pen_sample))
}
/// Install the Windows pointer message hook (main thread; keep the result until the event loop
/// returns). On failure this logs why: the pen barrel button is then missed.
/// Install the Windows pointer message hooks (main thread; keep the result until the event loop
/// returns). On failure this logs why: the pen barrel button and eraser end are then missed.
#[cfg(target_os = "windows")]
pub fn install_windows() -> Option<photocraft_tablet::windows::Monitor> {
photocraft_tablet::windows::Monitor::install().map_err(|e| log::warn!("{e}")).ok()
let monitor = photocraft_tablet::windows::Monitor::install().map_err(|e| log::warn!("{e}")).ok()?;
if !monitor.tracks_leave() {
log::warn!("tablet input: the WH_CALLWNDPROC hook did not install, so the pen leaving the window may be missed");
}
Some(monitor)
}
/// Installs the WinTab backend on the real PhotoCraft window and returns its per-frame poll.
///
/// `enabled` is Preferences > Tools > Pen Tablet > Tablet input set to WinTab. With Windows Ink disabled there, the vendor
/// driver still moves the cursor; this backend only supplies pressure/tilt/rotation/eraser
/// through the normal stylus feed. On failure it logs why and leaves Windows Ink untouched.
#[cfg(target_os = "windows")]
pub fn install_wintab(cc: &eframe::CreationContext<'_>, feed: &StylusFeed, enabled: bool) -> Option<photocraft_ui_egui::TabletPollFn> {
if !enabled {
return None;
}
use eframe::wgpu::rwh::{HasWindowHandle, RawWindowHandle};
let hwnd = match cc.window_handle().ok()?.as_raw() {
RawWindowHandle::Win32(handle) => handle.hwnd.get(),
_ => return None,
};
let ctx = cc.egui_ctx.clone();
if let Err(error) = photocraft_tablet::wintab::install(hwnd, Box::new(move || ctx.request_repaint())) {
log::warn!("WinTab backend: {error}");
return None;
}
let sink = sink(feed.clone());
log::info!("WinTab backend active (system context)");
let logged = std::cell::Cell::new(false);
Some(Box::new(move |focused| {
photocraft_tablet::wintab::poll(focused, &|sample| {
if let Some(sample) = sample
&& !logged.replace(true)
{
log::info!("WinTab sample: pressure={:.3} tilt=({:.1},{:.1}) eraser={}", sample.pressure, sample.tilt_x, sample.tilt_y, sample.eraser);
}
sink(sample);
});
}))
}
/// Stylus barrel button down check (Windows). The right mouse button is left to egui, which
@@ -51,6 +92,29 @@ pub fn right_button_service() -> Option<photocraft_ui_egui::RightButtonDownFn> {
None
}
/// Where the pen is on the screen (Windows), for the title bar's pen moves (#7967).
#[cfg(target_os = "windows")]
pub fn pen_screen_service() -> Option<photocraft_ui_egui::PenScreenFn> {
Some(Box::new(|| photocraft_tablet::windows::pen_screen_px().map(|(x, y)| [x, y])))
}
#[cfg(not(target_os = "windows"))]
pub fn pen_screen_service() -> Option<photocraft_ui_egui::PenScreenFn> {
None
}
/// Which end of the pen is in use (Windows): flipping the pen to its eraser end selects the
/// Eraser (#2285). Elsewhere the end arrives with the samples in the stylus feed.
#[cfg(target_os = "windows")]
pub fn pen_end_service() -> Option<photocraft_ui_egui::PenEndFn> {
Some(Box::new(photocraft_tablet::windows::take_pen_end))
}
#[cfg(not(target_os = "windows"))]
pub fn pen_end_service() -> Option<photocraft_ui_egui::PenEndFn> {
None
}
/// Install the AppKit tablet monitor (main thread, once winit created the shared application:
/// from eframe's app creation, not before the event loop). Keep the result until the event loop
/// returns. On failure this logs why: pens then paint like a mouse.
@@ -382,4 +446,40 @@ mod tests {
assert!(photocraft_ui_egui::stylus::Stylus::sync_eraser_tool(&mut app));
assert_eq!(app.ui.tool, Tool::Brush);
}
/// Windows: what the pointer hooks record reaches the Eraser switch through the service the
/// app installs (#2285).
#[cfg(target_os = "windows")]
#[test]
fn windows_eraser_end_switches_to_the_eraser_and_back() {
use photocraft_tablet::windows::{
PEN_FLAG_ERASER, PEN_FLAG_INVERTED, WM_POINTERDOWN, WM_POINTERLEAVE, WM_POINTERUP, WM_POINTERUPDATE, handle_pointer_message,
};
use photocraft_ui_egui::stylus::Stylus;
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
app.services.pen_end = pen_end_service();
app.ui.tool = Tool::Brush;
let hover = |pen_flags: u32| handle_pointer_message(WM_POINTERUPDATE, 1, move |_| Some(pen_flags));
hover(0);
assert!(!Stylus::sync_eraser_tool(&mut app), "the tip changes nothing");
hover(PEN_FLAG_ERASER);
assert!(!Stylus::sync_eraser_tool(&mut app), "an eraser button on the barrel is not the eraser end");
handle_pointer_message(WM_POINTERLEAVE, 1, |_| None);
hover(PEN_FLAG_INVERTED);
assert!(Stylus::sync_eraser_tool(&mut app));
assert_eq!(app.ui.tool, Tool::Eraser);
handle_pointer_message(WM_POINTERLEAVE, 1, |_| None);
assert!(!Stylus::sync_eraser_tool(&mut app), "out of range");
hover(0);
assert!(Stylus::sync_eraser_tool(&mut app));
assert_eq!(app.ui.tool, Tool::Brush, "the tip restores the Brush");
// An eraser-end tap and the pen leaving, all before the next frame: the frame that
// handles the queued click still selects the Eraser.
handle_pointer_message(WM_POINTERDOWN, 1, |_| Some(PEN_FLAG_INVERTED | PEN_FLAG_ERASER));
handle_pointer_message(WM_POINTERUP, 1, |_| None);
handle_pointer_message(WM_POINTERLEAVE, 1, |_| None);
assert!(Stylus::sync_eraser_tool(&mut app));
assert_eq!(app.ui.tool, Tool::Eraser);
assert!(!Stylus::sync_eraser_tool(&mut app), "out of range");
}
}
+13
View File
@@ -20,6 +20,19 @@ pub fn service() -> CheckFn {
})
}
/// What the last self-update came to, once: `craft-update` removes its records as it reads them.
pub fn last_update() -> Option<Result<String, String>> {
use craft_update::self_update::{Outcome, current_version, take_outcome};
let app = &photocraft_ui_egui::UPDATE_APP;
let paths = craft_update::Paths::for_app(app).ok()?;
let version = photocraft_engine::build_info::VERSION;
let running = current_version(app, version).map_or_else(|| version.to_string(), |v| v.to_string());
match take_outcome(&paths, &running)? {
Outcome::Installed(installed) => Some(Ok(installed.to_string())),
Outcome::Failed(reason) => Some(Err(reason)),
}
}
fn check() -> CheckResult {
let http = craft_update::Http::new("PhotoCraft/Update")?;
let found = craft_update::check_for_update(&photocraft_ui_egui::UPDATE_APP, &http, photocraft_engine::build_info::VERSION)?;
@@ -120,3 +120,49 @@ fn automation_roots_come_from_the_environment_too() {
assert!(stderr.contains("cannot configure automation workspace"), "{var}: stderr: {stderr}");
}
}
#[test]
fn invalid_read_root_is_not_hidden_by_another_valid_root() {
let dir = std::env::temp_dir().join(format!("photocraft-control-roots-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let good = dir.to_str().unwrap();
let missing = dir.join("missing");
let file = dir.join("not-a-directory");
std::fs::write(&file, b"not a directory").unwrap();
for invalid in [&missing, &file] {
for roots in [[good, invalid.to_str().unwrap()], [invalid.to_str().unwrap(), good]] {
let Run { status, stderr } = run_photocraft(&[
"--control",
"0",
"--control-token",
VALID_TOKEN,
"--automation-read-root",
roots[0],
&format!("--automation-read-root={}", roots[1]),
]);
assert_eq!(status.code(), Some(2), "every configured read root must be valid: {stderr}");
assert!(stderr.contains("cannot configure automation workspace"), "stderr: {stderr}");
}
}
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn empty_missing_and_repeated_write_root_flags_are_usage_errors() {
for flags in [
vec!["--automation-read-root"],
vec!["--automation-read-root", ""],
vec!["--automation-read-root="],
vec!["--automation-read-root", "--safe-gpu"],
vec!["--automation-write-root"],
vec!["--automation-write-root="],
vec!["--automation-write-root", "work", "--automation-write-root=work"],
vec!["--automation-write-root=", "--automation-write-root=work"],
] {
let args: Vec<&str> = ["--control", "0", "--control-token", VALID_TOKEN].into_iter().chain(flags).collect();
let Run { status, stderr } = run_photocraft(&args);
assert_eq!(status.code(), Some(2), "{args:?}: {stderr}");
assert!(stderr.contains("--automation-"), "stderr: {stderr}");
assert!(!stderr.contains("cannot configure automation workspace"), "parse errors must fail before opening roots: {stderr}");
}
}
+17
View File
@@ -0,0 +1,17 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="m11 10 3 3" />
<path d="M6.5 21A3.5 3.5 0 1 0 3 17.5a2.62 2.62 0 0 1-.708 1.792A1 1 0 0 0 3 21z" />
<path d="M9.969 17.031 21.378 5.624a1 1 0 0 0-3.002-3.002L6.967 14.031" />
<path d="M3 8.5A6.5 6.5 0 0 1 14 3.5" />
<path d="M3.5 4.5 3 8.5l4-.5" />
</svg>

After

Width:  |  Height:  |  Size: 476 B

+14
View File
@@ -0,0 +1,14 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<rect width="18" height="18" x="3" y="3" rx="2" />
<path d="M9 3v18" />
</svg>

After

Width:  |  Height:  |  Size: 284 B

+14
View File
@@ -0,0 +1,14 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M12 17v5" />
<path d="M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z" />
</svg>

After

Width:  |  Height:  |  Size: 450 B

+14
View File
@@ -0,0 +1,14 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />
<path d="M3 3v5h5" />
</svg>

After

Width:  |  Height:  |  Size: 297 B

+16
View File
@@ -0,0 +1,16 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<rect x="3" y="10" width="18" height="7" rx="2" />
<path d="M8 12v3M16 12v3" />
<circle cx="12" cy="13.5" r="1.1" />
<path d="M8.5 8.4q3.5-2.6 7 0" stroke-dasharray="0.6 1.6" />
</svg>

After

Width:  |  Height:  |  Size: 394 B

+7
View File
@@ -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

+17
View File
@@ -0,0 +1,17 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own Type options-bar glyph for vertical text (not from an icon set). -->
<path d="M3 20h18" />
<path d="M17 4v12" />
<path d="M12 10v6" />
<path d="M7 7v9" />
</svg>

After

Width:  |  Height:  |  Size: 395 B

+17
View File
@@ -0,0 +1,17 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own Type options-bar glyph for vertical text (not from an icon set). -->
<path d="M3 12h18" />
<path d="M17 6v12" />
<path d="M12 9v6" />
<path d="M7 7v10" />
</svg>

After

Width:  |  Height:  |  Size: 395 B

+17
View File
@@ -0,0 +1,17 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own Type options-bar glyph for vertical text (not from an icon set). -->
<path d="M3 4h18" />
<path d="M17 8v12" />
<path d="M12 8v6" />
<path d="M7 8v9" />
</svg>

After

Width:  |  Height:  |  Size: 393 B

+15
View File
@@ -0,0 +1,15 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="11" cy="11" r="8" />
<line x1="21" x2="16.65" y1="21" y2="16.65" />
<line x1="8" x2="14" y1="11" y2="11" />
</svg>

After

Width:  |  Height:  |  Size: 334 B

+2 -2
View File
@@ -4,7 +4,7 @@ The layer numbers below describe allowed dependency direction, not runtime privi
| Layer | Crates | Responsibility |
|---|---|---|
| L0 | `geom`, `cms`, `color`, `raster` | Geometry, ICC processing, color/blend math, pixel formats, and copy-on-write tiles |
| L0 | `geom`, `color`, `raster` | Geometry, color/blend math, pixel formats, and copy-on-write tiles (ICC processing is `craft-cms`, from craft-libs) |
| L0 standalone | `psd`, `codecs`, `affinity` | PSD/PSB and flat raster format parsing/encoding; bounded Affinity preview extraction |
| L1 | `doc` | Pure-data documents, layers, masks, effects, adjustments, text, vectors, and smart objects |
| L2 | `ops`, `paint`, `algo`, `text`, `vector` | History operations, painting, imaging algorithms, type, paths, and shapes |
@@ -22,4 +22,4 @@ Workspace applications are:
| PhotoCraft CLI | `apps/photocraft-cli` | Convert, inspect, run, batch, JSON-lines serve, and MCP |
| PhotoCraft web | `apps/photocraft-web` | The UI and engine compiled for WebAssembly |
New crates must be registered in `xtask/src/layers.rs`. Nothing below `ui-egui` may depend on egui, eframe, winit, or rfd. The `psd`, `codecs`, and `cms` crates have additional independence requirements documented in [`AGENTS.md`](https://github.com/storytold/photocraft/blob/main/AGENTS.md).
New crates must be registered in `xtask/src/layers.rs`. Nothing below `ui-egui` may depend on egui, eframe, winit, or rfd. The `psd` and `codecs` crates have additional independence requirements documented in [`AGENTS.md`](https://github.com/storytold/photocraft/blob/main/AGENTS.md).
+1 -1
View File
@@ -7,7 +7,7 @@ PhotoCraft has two compositors with distinct roles:
The interactive canvas uses the GPU path when the planner can represent the document. Unsupported cases fall back to CPU composition. Current documentation identifies Multichannel documents and regions above the GPU texture limit as fallback cases.
Pixel storage in `photocraft-raster` supports runtime sample depth rather than a public 8-bit-only path. Color mode and profiles are document data; color conversion belongs in `photocraft-cms` rather than being treated as implicit sRGB.
Pixel storage in `photocraft-raster` supports runtime sample depth rather than a public 8-bit-only path. Color mode and profiles are document data; color conversion belongs in `craft-cms` rather than being treated as implicit sRGB.
## Verification
+21
View File
@@ -35,6 +35,27 @@ Warnings do not change the saved document's font declarations and do not stop
the operation. To list or replace the missing families intentionally, use
`type.resolveMissingFonts` on the document.
### Document metadata
`convert`, `run --out` and `batch` keep the document's XMP packet in a flat
export whose format holds one (PNG, JPEG, WebP, TIFF, …), and its free-form
text where the format holds that too (PNG text chunks, TIFF's named text tags
such as ImageDescription; JPEG and WebP have no place for it), as Save As
does. `--metadata none` leaves them out, as Export As's Metadata: None does:
a Photoshop file's XMP can list every placed document's id
(`DocumentAncestors`) and the text of every type layer, and can be far larger
than the image. `--metadata all` is the default. The option changes nothing
else: the ICC profile, EXIF and resolution are written as they are without
it, where the format holds them. An Indexed Color document saved as a palette
PNG carries no XMP, text, ICC profile or EXIF with either value, only its
resolution. PSD, PSB and `.pcraft` saves always keep the XMP. It is not a full
metadata scrub.
```sh
photocraft-cli batch --actions resize.json --in masters/ --out web/ \
--format webp --metadata none
```
### Export selected adjustment layers as a .cube LUT
The engine command `file.export.colorLookupTables` creates a 3D LUT from an
+1 -1
View File
@@ -1,6 +1,6 @@
# Control protocol
The desktop control protocol is newline-delimited JSON over a TCP listener bound to `127.0.0.1`. The first frame on every connection must be `auth` with the configured 256-bit bearer token. After authentication, each request carries `id`, `method`, and optional `params`; each reply includes the matching `id` and either a result or error.
The desktop control protocol is newline-delimited JSON over a TCP listener bound to `127.0.0.1`. Every connection must first authenticate with the configured 256-bit token: either by challenge (`auth.challenge`, then `auth` with an HMAC proof; the token never crosses the wire and the server proves it holds the token first), or with the original single `auth` frame carrying the token. After authentication, each request carries `id`, `method`, and optional `params`; each reply includes the matching `id` and either a result or error.
```json
{"id":"auth","method":"auth","params":{"token":"<64-hex>"}}
+17 -5
View File
@@ -1,17 +1,21 @@
# MCP
`photocraft-automation` implements an MCP server over stdio with two backends:
`photocraft-automation` implements an MCP server over stdio with three backends:
- **Headless:** an in-process `Headless` session owns the engine and performs file I/O.
- **Bridge:** `BridgeClient` forwards tools to a desktop application started with `photocraft --control <port>`.
- **The open window:** plain `photocraft-cli mcp` finds the desktop application through the connection file it publishes while the person lets agents use it (ArtCraft Launcher › Settings › AI agents), before every tool call; while the app is closed it starts it, serves a headless session, or reports an error, as chosen in Preferences › AI Integrations. Without that consent, or with `--headless`, it is the headless session above.
The simplest setup needs no terminal: turn on ArtCraft Launcher › Settings › AI agents and click *Add* next to the AI app; that one entry reaches every Craft app. See [`docs/mcp.md`](../../../docs/mcp.md#connecting-the-desktop-app-no-terminal).
For a source checkout, first [install the CLI on PATH and register the server](../../../docs/mcp.md#install-and-register).
The installed binary survives `cargo clean`; a symlink into `target/release` does not.
Start the headless server with:
Start the headless server with (without `--headless`, `mcp` works in the open PhotoCraft window
while the ArtCraft Launcher's agents switch is on):
```sh
photocraft-cli mcp --automation-read-root /work/project --automation-write-root /work/project
photocraft-cli mcp --headless --automation-read-root /work/project --automation-write-root /work/project
```
Bridge to a running desktop application with the same private token file used by the app:
@@ -56,6 +60,12 @@ explicitly granted at launch; omitting a root omits that authority. Bridge mode
loopback control connection with a bearer token before invoking any control method and uses the
roots configured on the desktop process.
The launcher's switch (off by default) opens the same loopback, token-authenticated control
listener as `--control`, with a token the app keeps in its settings folder (`agent-control.token`,
user-only on Unix; delete it for a new one). The folders chosen in Preferences › AI Integrations
are the desktop process's roots, and the roots of a `mcp` headless session only when agents may
use the app and *When PhotoCraft is closed* is set to work without a window.
The current server does not issue scoped sessions or distinguish trusted tools from high-impact tools. Authentication proves possession of the token; it does not restrict an authenticated client to document-only access. Do not expose either transport through an untrusted broker, shell, proxy, or remote service without adding an external policy boundary.
Filesystem capabilities are implemented. General tool and method capabilities remain
@@ -63,6 +73,8 @@ Filesystem capabilities are implemented. General tool and method capabilities re
The five shared core tools are `command_list`, `command_run`, `command_batch`, `doc_inspect`
and `render_preview`. Existing documented tools, including `doc_render_preview`, remain
listed. `photocraft://document` and `photocraft://commands` expose live JSON. Direct headless
Render Video supports progress and cancellation using the granted write root; see
listed. `photocraft://document` and `photocraft://commands` expose live JSON. Long commands
that are waited on report progress and stop when the request is cancelled, headless and in
bridge mode (where they may also outlast the bridge's reply timeout), and direct headless
Render Video does too, using the granted write root; see
[`docs/mcp.md`](../../../docs/mcp.md) for arguments, cleanup and transport behavior.
+31
View File
@@ -11,6 +11,7 @@ Automation requests are untrusted input with potential effects beyond the active
| MCP capability scopes | **Partial:** filesystem read/write capabilities only; general tool scopes are absent |
| Allowed read/write roots | **Implemented:** separate launch-time roots, with absent authority failing closed |
| Symlink-safe capability filesystem | **Implemented:** relative operations use held directory capabilities and reject link escapes |
| Windows UNC write roots | **Implemented:** handle-relative deletes; two ambient operations on the canonical root path (`create_dir`, `rename`), each below ancestors pinned by held handles; see below |
| Request-byte and JSON-depth limits | **Partial:** 1 MiB request-line limit on TCP and headless JSON-lines stdio (MCP stdio input is not byte-capped); no explicit JSON-depth policy |
| Batch-step limit | **Implemented:** 256 steps for headless and MCP batches |
| Reply-size limit | **Implemented:** 8 MiB encoded JSON/MCP result; aggregate batch reply budget |
@@ -41,3 +42,33 @@ Filesystem handles and a defensive command-path policy are implemented; explicit
capabilities, session-memory/command-duration budgets, and audit events remain. Preview and
reply ceilings do not bound all document operations or desktop screenshot capture. Private token handling, process
isolation, and least-privileged execution are still practical containment measures.
## Windows UNC write roots
`cap-std` 4's Windows `rename`, `remove_file` and `create_dir` are not handle-relative: they
append the request to the handle's own path, read back without its `\\?\` prefix, which below a
UNC root (`\\wsl.localhost\...`, any network share) fails with `ERROR_PATH_NOT_FOUND`
(sunfishcode/cap-std#348). Below such a root, judged by the canonical root path's prefix and
never by a request, the automation workspace keeps every rule above and completes these steps
as follows:
- **Deletes** (a stranded temporary file, the frames of a cancelled export) open the file
relative to the held directory handle with `FILE_FLAG_DELETE_ON_CLOSE` and
`FILE_FLAG_OPEN_REPARSE_POINT`, so a link is deleted rather than its target. Nothing is deleted
by path.
- **Directory creation** and the **rename of a finished temporary file into place** are the only
two operations that touch the filesystem by path. Both run on the canonical verbatim root path
(trusted launch configuration) only after every directory component on the way has been
opened through the handle of its parent, verified a plain directory (not a link, not a file),
and kept open. `cap-std` opens directories without `FILE_SHARE_DELETE`. This protects held
ancestors from Windows-side rename or deletion only when the provider enforces share modes
(`ERROR_SHARING_VIOLATION`). It does not protect against direct Linux-side changes in WSL. The
UNC regression test uses an SMB administrative share, not `\\wsl.localhost`.
The rename replaces the entry at the target without following it;
a directory at the target is refused.
Saves below a UNC root are therefore as atomic as everywhere else (temporary file, flush,
rename). No file contents are written or read through an ambient path; directory creation and
rename use ambient paths. Regression tests
run against the loopback administrative share of the test drive and are skipped where none is
available.
+2 -2
View File
@@ -2,10 +2,10 @@
External bytes enter PhotoCraft through four main paths:
- `photocraft-psd` parses and writes PSD and PSB structures.
- `craft-psd` parses and writes PSD and PSB structures.
- `photocraft-codecs` decodes and encodes flat raster formats.
- `photocraft-format` loads and saves the native `.pcraft` bundle.
- `photocraft-affinity` reads native Affinity documents (`.af`, `.afdesign`, `.afphoto`, `.afpub`): layers, artboards, vectors, text, images and masks; it does not write them.
- `craft-affinity` reads native Affinity documents (`.af`, `.afdesign`, `.afphoto`, `.afpub`): layers, artboards, vectors, text, images and masks; it does not write them.
`photocraft-io` maps PSD and flat images into the document model and exports documents back to those formats. It is the integration layer; parsing limits remain the responsibility of the underlying format crates.
+1 -1
View File
@@ -1,6 +1,6 @@
# PSD and PSB
`photocraft-psd` is a standalone clean-room reader and writer based on Adobe's public PSD specification. It supports PSD version 1 and PSB version 2, preserves unknown blocks for round-trip fidelity, and decodes channel data lazily.
`craft-psd` is a standalone clean-room reader and writer based on Adobe's public PSD specification. It supports PSD version 1 and PSB version 2, preserves unknown blocks for round-trip fidelity, and decodes channel data lazily.
The parser accepts all four PSD compression methods handled by the crate and represents format-level structures before `photocraft-io` maps them to `photocraft-doc`. The current public API and fidelity behavior are documented in [`crates/psd/README.md`](https://github.com/storytold/photocraft/blob/main/crates/psd/README.md).
+3 -3
View File
@@ -1,10 +1,10 @@
# Raster formats
`photocraft-codecs` provides format detection, capability declarations, decode limits, metadata handling, and encoding for flat images. The default build declares read/write support for PNG, JPEG, TIFF, WebP, GIF, BMP, TGA, ICO, Netpbm/PFM, QOI, OpenEXR, and Radiance HDR. HEIF/HEIC (iPhone and Mac photos) is read-only, decoded in pure Rust by `heic-rs` through the optional `photocraft-heif` crate. It is a build-time choice behind the `heif` cargo feature (`cargo build -p photocraft --features heif`): official builds include it; without it HEIC files are still recognised and opening one reports that HEIC support isn't included in that build. AVIF encoding is optional; AVIF decoding is not implemented in the current crate. Lossless JPEG XL (.jxl) export uses the pure-Rust `zune-jpegxl` encoder for 8/16-bit gray, RGB and RGBA data; gray+alpha is expanded to RGBA at the same bit depth. JPEG XL import is tracked separately in #2868.
`photocraft-codecs` provides format detection, capability declarations, decode limits, metadata handling, and encoding for flat images. The default build declares read/write support for PNG, JPEG, TIFF, WebP, GIF, BMP, TGA, ICO, Netpbm/PFM, QOI, OpenEXR, and Radiance HDR. HEIF/HEIC (iPhone and Mac photos) is read-only, decoded in pure Rust by `heic-rs` through the optional `craft-heif` (craft-libs) crate. It is a build-time choice behind the `heif` cargo feature (`cargo build -p photocraft --features heif`): official builds include it; without it HEIC files are still recognised and opening one reports that HEIC support isn't included in that build. AVIF encoding is optional; AVIF decoding is not implemented in the current crate. Lossless JPEG XL (.jxl) export uses the pure-Rust `zune-jpegxl` encoder for 8/16-bit gray, RGB and RGBA data; gray+alpha is expanded to RGBA at the same bit depth. JPEG XL import is tracked separately in #2868.
## Layered TIFF
A TIFF saved by Photoshop with its layers carries them in two private tags: 37724 (`ImageSourceData`, the same layer section a PSD has, preceded by the string `Adobe Photoshop Document Data Block`) and 34377 (the PSD image resources). `photocraft-codecs` passes both through as opaque bytes on `Metadata`; `photocraft-io` rebuilds a PSD model from them plus the TIFF's pixels and hands it to the PSD importer, so groups, masks, layer styles, type, shapes, smart objects and adjustment layers open from a TIFF exactly as from a PSD, and are written back the same way. In Intel-order (`II`) files Photoshop stores the whole block structure byte-swapped (reversed keys such as `MIB8` and `ryaL`, little-endian integers and doubles) while pixel samples stay big-endian; `photocraft-psd`'s `tiff` module converts between the two orders field by field, and drops, with a warning, any block whose layout it does not know rather than pass byte-swapped data to other readers. Limits: up to sixteen extra samples (spot colours and alpha channels, plus a Quick Mask) are written in the IFD and round-trip, with Photoshop image resources for the channel name, ink colour and solidity; Lab documents are saved flat, with their extra samples. Save As asks "Including layers will increase file size" (with "Discard Layers and Save a Copy") while *Ask Before Saving Layered TIFF Files* is on in Preferences › File Handling. Scripted and agent saves write a flat TIFF unless they ask for layers: `--tiff-layers` for `photocraft-cli convert`, `run` and `batch`, and `"tiffLayers": true` in the save, batch and export commands and MCP `doc_save`.
A TIFF saved by Photoshop with its layers carries them in two private tags: 37724 (`ImageSourceData`, the same layer section a PSD has, preceded by the string `Adobe Photoshop Document Data Block`) and 34377 (the PSD image resources). `photocraft-codecs` passes both through as opaque bytes on `Metadata`; `photocraft-io` rebuilds a PSD model from them plus the TIFF's pixels and hands it to the PSD importer, so groups, masks, layer styles, type, shapes, smart objects and adjustment layers open from a TIFF exactly as from a PSD, and are written back the same way. In Intel-order (`II`) files Photoshop stores the whole block structure byte-swapped (reversed keys such as `MIB8` and `ryaL`, little-endian integers and doubles) while pixel samples stay big-endian; `craft-psd`'s `tiff` module converts between the two orders field by field, and drops, with a warning, any block whose layout it does not know rather than pass byte-swapped data to other readers. Limits: up to sixteen extra samples (spot colours and alpha channels, plus a Quick Mask) are written in the IFD and round-trip, with Photoshop image resources for the channel name, ink colour and solidity; Lab documents are saved flat, with their extra samples. Save As asks "Including layers will increase file size" (with "Discard Layers and Save a Copy") while *Ask Before Saving Layered TIFF Files* is on in Preferences › File Handling. Scripted and agent saves write a flat TIFF unless they ask for layers: `--tiff-layers` for `photocraft-cli convert`, `run` and `batch`, and `"tiffLayers": true` in the save, batch and export commands and MCP `doc_save`.
## JPEG XL
@@ -31,7 +31,7 @@ Every route that writes a document to a flat format (Save As, the CLI, MCP `doc_
- Formats without transparency (JPEG, Radiance HDR) get the image composited over white, as Export As and Quick Export do; in CMYK, white is no ink.
- Formats that can't embed an ICC profile (GIF, BMP, TGA, QOI, ICO, Netpbm/PFM) get RGB documents in another profile (linear light, Display P3, …) converted to sRGB through the colour engine (perceptual intent), since an untagged file is read as sRGB. OpenEXR and Radiance HDR get linear sRGB instead (linear gray for a grayscale OpenEXR), which is how they are tagged when opened.
- TGA, as Photoshop's Targa: an RGB Targa is 24 or 32 bits per pixel. Save As and Save a Copy ask (Targa Options, starting at 32 with an alpha channel, else 24); Export As has a Resolution choice (Auto, 24 or 32 bits/pixel); scripts pass `tgaBits` (`--tga-bits` on the CLI). At 32 bits the document's alpha channel is the file's alpha when it has exactly one (spot channels don't count; with several, none is used), and the colours are written exactly, never premultiplied or cleared where the alpha is 0, so a game texture's mask and its colours both survive. Without a usable alpha channel the layers' transparency is the alpha (opaque without any). 24 bits write no alpha, compositing transparency over white. Without a choice: 32 with an alpha channel or transparency, else 24. A 32-bit Targa opens as an opaque Background with its alpha as "Alpha 1", so it round-trips. Grayscale Targas are 8-bit.
- JPEG, as Photoshop's JPEG Options: File › Save, Save As and Save a Copy ask for the Quality on Photoshop's 0–12 scale (with its Low, Medium, High and Maximum presets) and a Format Option: Baseline ("Standard"), Baseline Optimized (Huffman tables fitted to the image) or Progressive. The quality starts at the opened JPEG's own quality, else at the Export preference's JPEG quality; left there, an opened JPEG is written at exactly its own quality. Scripts pass `"quality": 0..12` and `"jpegFormat": "baseline" | "optimized" | "progressive"` (on the CLI, `--quality` on the encoder's 1–100 scale and `--jpeg-format`) and aren't asked; recorded actions replay the answer. The scale maps onto the encoder's 1–100 as `round(q / 12 × 99 + 1)`. RGB JPEGs are written 4:2:0, where Baseline Optimized keeps the standard tables for now (Gray and CMYK, written 4:4:4, get fitted ones). Matte, the progressive scan count (Scans 3–5) and the file-size preview aren't offered.
- JPEG, as Photoshop's JPEG Options: File › Save, Save As and Save a Copy ask for the Quality on Photoshop's 0–12 scale (with its Low, Medium, High and Maximum presets) and a Format Option: Baseline ("Standard"), Baseline Optimized (Huffman tables fitted to the image) or Progressive. The quality starts at the opened JPEG's own quality, else at the Export preference's JPEG quality; left there, an opened JPEG is written at exactly its own quality. Scripts pass `"quality": 0..12` and `"jpegFormat": "baseline" | "optimized" | "progressive"` (on the CLI, `--quality` on the encoder's 1–100 scale and `--jpeg-format`) and aren't asked; recorded actions replay the answer. The scale maps onto the encoder's 1–100 as `round(q / 12 × 99 + 1)`. RGB JPEGs are written 4:2:0, where Baseline Optimized keeps the standard tables for now (Gray and CMYK, written 4:4:4, get fitted ones). Below the Format Options the dialog shows how big the file will be ("152.3K", "1.5M"), so the quality can be chosen with the size in view; it is worked out as the options change, in the background in the desktop app and within the frame in the web build, for documents up to 40 megapixels (4 on the web), and reads "—" for larger ones. Matte and the progressive scan count (Scans 3–5) aren't offered.
- DDS, for game and 3D textures: Save As and Save a Copy ask (DDS Options) for the compression (None, uncompressed and lossless; BC1/DXT1, whose alpha is on or off; BC2/DXT3; BC3/DXT5) and whether to generate mipmaps (the full chain down to 1×1, each level a box filter of the one above). Scripts pass `ddsCompression` (`none`, `bc1`, `bc2`, `bc3`) and `ddsMipmaps` (`--dds-compression`, `--dds-mipmaps` on the CLI). Opening one reads its top mip level.
Flat TIFF and JPEG exports of composited CMYK documents convert the RGB composite back through
+8
View File
@@ -29,6 +29,14 @@ Automation is a privilege boundary because requests can cause filesystem access,
Screenshots are decoded under separate dimension, pixel, and allocation ceilings before
downscaling; the 5 MiB PNG limit applies to the returned image.
- MCP normally uses stdio and can optionally bridge to loopback control TCP.
- ArtCraft Launcher › Settings › AI agents (off by default; one switch for every Craft app) opens that loopback
listener without launch flags. Its token is kept in a user-only file in the settings folder
(`agent-control.token`) and stays the same across restarts and port changes: restarting does
not revoke it. To revoke an exposed token, delete that file; the next start creates a new one.
The published `agent-connection.json` holds the port and the token file's path, never the
token. `photocraft-cli mcp` authenticates with the challenge handshake, so the token
itself is never sent: the listener must first prove it holds the token, and a stale file whose
port another program took fails that check before the client reveals anything.
- The bridge and UI request paths use timeouts.
- Engine commands are expected to reject invalid parameters without panicking.
- Remote filesystem methods use separately granted read and write directory capabilities.
+1 -1
View File
@@ -6,7 +6,7 @@ Parser safety is broader than “does not crash.” A parser must also bound mem
### PSD/PSB
`photocraft-psd` enforces maximum document dimensions and channel counts, bounds decoded channel data, limits ActionDescriptor nesting and pattern edges, and uses checked arithmetic for key decoded-size calculations. Tests cover malformed headers, truncation, property-generated inputs, and dedicated fuzz targets.
`craft-psd` enforces maximum document dimensions and channel counts, bounds decoded channel data, limits ActionDescriptor nesting and pattern edges, and uses checked arithmetic for key decoded-size calculations. Tests cover malformed headers, truncation, property-generated inputs, and dedicated fuzz targets.
### Raster codecs
+44
View File
@@ -14,9 +14,15 @@
# To remove your names, delete your entry (or set fields empty) in a PR. The next
# contributors.py run, and the next build, drop them.
[people.chrisringrose]
sync_github_name = true
[people.brianblakely]
sync_github_name = true
[people.mlo0352]
sync_github_name = true
[people.abdul-karim-mia]
real_name = "Abdul karim mia"
sync_github_name = false
@@ -29,6 +35,9 @@ sync_github_name = false
display_name = "Skyfuller"
sync_github_name = true
[people.JohnXu28]
display_name = "JohnXu"
[people.AlanRockefeller]
sync_github_name = true
@@ -201,6 +210,9 @@ sync_github_name = true
real_name = "Guillem Hermida"
sync_github_name = true
[people.fokas-hoa]
display_name = "Tasos Fokas"
[people.fjamesprice]
sync_github_name = true
@@ -267,6 +279,10 @@ sync_github_name = false
[people.drunkeninja42]
real_name = "Kushagra Sharma"
[people.Terra854]
display_name = "Terra854"
sync_github_name = true
[people.hidoba]
real_name = "Vlad Grankovsky"
display_name = "Vlad Grankovsky"
@@ -308,3 +324,31 @@ sync_github_name = true
real_name = "Simone Recchia"
display_name = "Simone Recchia"
sync_github_name = false
[people.davidvhk]
real_name = "David Vanhoucke"
sync_github_name = true
[people.Luis-0508]
sync_github_name = true
[people.ashokram-si]
real_name = "Ashok Ram"
[people.Kaedo17]
sync_github_name = true
[people.rmsff]
real_name = "Serikov Roman"
sync_github_name = false
[people.tomgardenart]
display_name = "Nostella"
sync_github_name = false
[people.se343r]
display_name = "Tsieg"
sync_github_name = true
[people.slafebre]
real_name = "Sven Lafebre"
+1
View File
@@ -0,0 +1 @@
e02939ef009218e81c44e8ec001fbb7603461de4
-22
View File
@@ -1,22 +0,0 @@
[package]
name = "photocraft-affinity"
description = "Bounded reader for native Affinity documents: archive, object stream and document model"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[lints]
workspace = true
[features]
# Synthetic-container builders for tests and fuzz seeds; not an Affinity exporter.
synth = []
[dependencies]
crc32fast = "1.5"
flate2 = { workspace = true }
ruzstd = "0.9.1"
[dev-dependencies]
proptest = { workspace = true }
-157
View File
@@ -1,157 +0,0 @@
# photocraft-affinity
An independent, bounded Rust reader for native Affinity documents: `.af` from Affinity 3 and
`.afdesign`, `.afphoto` and `.afpub` from Affinity 1 and 2 (container versions 8 to 12). It reads
the archive, the tagged object stream in `doc.dat` and the part of the document model listed below,
and hands `photocraft-io` a document in pixels with every transform composed. It does not write
Affinity files.
## What is imported
`photocraft-io` maps the model to an 8-bit RGB document at the Affinity document's resolution:
| Affinity | PhotoCraft |
|---|---|
| Pages, Publisher spreads | one artboard per spread, spreads side by side 64 px apart |
| Artboards (legacy `ABEn`, or current `.af` `phrp`/`aprp` properties, including converted curves), with name, solid background, any transform | artboards (nested ones as groups with a vector mask; rotated/curved boards use their bounding rectangle) |
| Layers (`Scop`), groups (`Grup`), pass-through or isolated | groups (pass-through or Normal) |
| Curves (`PCrv`): cubic subpaths, closed flags, live corners (`CnrD`) | shape layers (multi-subpath curves fill even-odd) |
| Rectangles with corner radii (relative or absolute, locked or per corner) and round or straight corners, ellipses, polygons (smooth too), stars, square stars, pies, triangles, trapezoids, clouds, hearts, cogs, rounded and elliptical callouts, arrows, double stars, tears, crescents, diamonds and circular segments | shape layers |
| Compound shapes (`Comp`, add and subtract) | one even-odd shape |
| A shape or curve with children clips them | group with the outline as vector mask, the shape at its bottom |
| Vector masks (`AdCh` curves and shapes) | vector masks |
| Pixel masks (`MRst`, attached or as a layer in a group) | layer masks |
| Solid fills: RGBA, HSLA, CMYK, grey, Lab (D50) | shape fill (converted to RGB) |
| Linear, elliptical, radial and conical gradients with Affinity's midpoint bias | gradient fills |
| Strokes: weight, scale with object, dash pattern, alignment, caps, joins, miter limit | shape strokes |
| Fill layers (`FRst`) | filled rectangles |
| Artistic and frame text: characters, font family/weight/style, size, tracking, fixed leading, colour, paragraph alignment, first baseline | type layers (rendered with the fonts installed) |
| Placed images (`ImgN`): the original JPEG/PNG embedded in the file | embedded smart objects |
| Pixel layers (`Rstr`): RGBA 8/16-bit and CMYK 8-bit tiles, cropped to their content | pixel layers |
| Embedded documents and symbols (`EmbN`) | the picture Affinity cached of them |
| Opacity, visibility, lock, names, blend modes | the same (Add as Linear Dodge) |
Everything else is reported in the import warnings, one line per kind with a count, never
dropped silently: layer effects, adjustment layers and live filters, brush and pressure strokes,
transparency gradients, fill opacity, bitmap fills, master pages, unrecognized
parametric shapes (imported as their bounding ellipses), corner types other than round or straight, stars with
rounded points, several fills or strokes on one object (one of each is used), strokes behind the
fill, outlined or scaled text, text fields such as page numbers, frames with columns or a curved
outline, grey/Lab/32-bit pixels, CMYK and Lab colour (converted to RGB without the document's
profile), facing pages and the Average, Negation, Reflect, Glow and Erase blend modes (as Normal).
Opened Affinity documents start without a save path: Save asks for a new copy and never writes
back over the Affinity file. When the native document can't be read at all, `photocraft-io` opens
the embedded PNG preview instead, as one pixel layer named “Affinity preview”, with a warning
that names the reason. That preview can't be placed or used by imports that can't show the
warning (smart-object decoding, stacks, batch, displacement maps, variables).
## Embedded preview
`preview(bytes)` reads only the thumbnail record the header's offset 24 points to (the same in
container versions 8 to 12); it never scans for PNG signatures. All integers are little-endian.
| Record offset | Size | Observed value |
|---|---:|---|
| 0 | 8 | `ffffffff` followed by `Thmb` |
| 8 | 4 | Record version 1 |
| 12 | 4 | PNG byte length + 13 |
| 16 | 4 | PNG start offset 29 |
| 20 | 4 | Zero |
| 24 | 4 | PNG byte length |
| 28 | 1 | PNG encoding 1 |
| 29 | declared length | Exactly one PNG |
The PNG is limited to 16 MiB and 4096 pixels a side. IHDR must come first and be unique, IDAT
chunks contiguous, an optional PLTE unique and before IDAT, every chunk CRC must match and IEND must
end the file; compressed metadata (`zTXt`, `iTXt`, `iCCP`), APNG chunks and unknown critical chunks
are rejected. The I/O adapter decodes it with a 128 MiB allocation limit.
## Provenance and clean-room
Affinity has no published file-format specification, so this reader is built only from a public
description of the format and from public files, never from Affinity itself. This is how
PhotoCraft already treats formats that are only partly documented: `photocraft-psd` fills the gaps
in Adobe's specification from the MIT-licensed psd-tools and ag-psd, and `photocraft-raw` recovered
Nikon's compression tables by black-box analysis of CC0 sample files (see their READMEs).
* **No Affinity software.** Affinity was never downloaded, installed, run, scripted, screenshotted or
disassembled for this work, and nothing from an Affinity installation (program code, resources,
presets, fonts, colour profiles) was read. No file was made with Affinity for it: every sample
is a document its author published.
* **A public, permissively licensed description.** The container and object-stream layout was
learned from [VMDevCpp/afread](https://github.com/VMDevCpp/afread) (MIT, at
`04b672334a43e3e37ded6b5ffc57af231d589774`, written for container versions 7–11) and re-described
in our own words before this Rust code was written; no code was translated. No GPL/AGPL code (such
as Inkscape's Affinity extension) was read.
* **Every structure checked against public files.** afread doesn't say how its author learned the
format, so nothing here rests on it alone: each structure the reader relies on is confirmed by
the public documents. Every archive entry carries a CRC-32 that must match, and every field in
the object stream names its own type, so a misread layout fails loudly instead of producing
plausible wrong data.
* **Meaning fitted to Affinity's own pictures.** What shapes, paints, text and pixel data mean was
worked out by comparing our render with the thumbnail every Affinity document embeds (Affinity's
render of itself), on 176 public documents saved by Affinity 1.x, 2.x and 3.0/3.1 on Windows,
macOS and iPad. The collection has since grown to 189 distinct documents, and the reader opens
all of them. Most are published under CC0, MIT, BSD, Apache-2.0 or CC BY (-SA); the others
(no licence stated, or GPL or non-commercial terms) were only opened locally to compare
pictures, never committed or redistributed. The corpus test keeps the comparison for the pinned
files, which are CC0, MIT or Apache-2.0 only.
* **Nothing of Affinity's is in this repository**: no program code, assets or documents. The test
files are fetched at pinned commits and sha256-verified, never committed.
* **Read-only.** Nothing is written in Affinity's format; export waits until someone can check
written files in Affinity itself.
The same reader is shared, as an independent copy, with VectorCraft's `vectorcraft-affinity`.
## Validation
* Unit tests on synthetic containers built by the `synth` feature (stored, zlib and zstd entries,
checksums, budgets, cycles, hostile streams, every truncation) and property tests of random
mutations, here and in `photocraft-io`'s `tests/it/affinity.rs`.
* `cargo xtask corpus --affinity` fetches 21 public CC0/MIT documents, including the four
Affinity 3 `.af` files of [samuel-etver/vector-art](https://github.com/samuel-etver/vector-art)
(CC0), at pinned commits, each checked against `xtask/affinity-corpus.sha256`. `tests/it/real_files.rs`
parses them; `photocraft-io`'s `tests/it/affinity_corpus.rs` imports and flattens each one and
compares it with the thumbnail Affinity saved in it (mean difference 0–4.6 of 255, with a
ceiling per file).
* `fuzz/` has `cargo-fuzz` targets for the whole reader (`preview`), the object stream (`stream`)
and the I/O import (`import_preview`); CI's fuzz job runs `preview` and `import_preview`:
```sh
cd crates/affinity/fuzz
cargo +nightly fuzz run stream -- -max_total_time=600
cargo +nightly fuzz run import_preview --features io -- -max_total_time=600
```
What has not been verified: files from Affinity builds or platforms outside the public set, files
written by other applications, rotated or skewed images against Affinity's render, mask polarity
against a render with and without the mask, and anything listed as a warning above. The `synth`
builders write only what this reader accepts; Affinity has never opened their output, so they are
test fixtures, not an exporter.
## Safety limits
Every size is checked before it is allocated: 256 MiB per archive entry, 1 GiB extracted per import
and 1 GiB of decoded pixels per import by default (`Limits`: extracted bytes and materialized pixels
are separate budgets, since a bitmap's declared size costs memory whatever its tiles hold), a 64 MiB
zstd window, 4096 saved revisions, array lengths no longer than the
bytes left, 16 777 216 decoded values per document stream (fields and array elements together, counted before
anything is allocated: a value takes about 40 bytes in memory however few it took in the file; the largest of
those 189 public documents uses 3.3 million), 384 levels of object nesting, 128 levels of layers, 500 000 layers, four million curve
nodes per curve, 4 levels of spot colours defined through spot colours, 64 megapixels per pixel layer (cropped to its content first) and 1024 gradient
stops; `photocraft-io` adds 300 000 pixels a side per document and 64 megapixels per image on the
canvas. Every archive entry's CRC-32 and size must match. Malformed input returns an `Error`; the
crate has no panics outside tests.
Compound outlines have a separate active-reference cycle check and a depth cap of 64. Across
the document, geometry expansion admits at most 500 000 combined outline calls and operand-slot
visits (including nulls and non-object values), and four million points created or copied into
compounds. Operand slots are charged before filtering, without first collecting an operand list.
A compound that crosses a limit or contains a cycle is omitted
with a warning as a whole; ordinary shared operands remain valid and keep each occurrence's transform.
## Privacy
Affinity documents can hold the folder they were saved in, user names, original image paths and
XMP metadata. This reader never imports those fields.
-5
View File
@@ -1,5 +0,0 @@
target/
corpus/
artifacts/
coverage/
Cargo.lock
-41
View File
@@ -1,41 +0,0 @@
[package]
name = "photocraft-affinity-fuzz"
version = "0.0.0"
publish = false
edition = "2024"
license = "MIT OR Apache-2.0"
[package.metadata]
cargo-fuzz = true
[workspace]
[features]
io = ["dep:photocraft-io"]
[dependencies]
libfuzzer-sys = "0.4"
photocraft-affinity = { path = "..", features = ["synth"] }
photocraft-io = { path = "../../io", optional = true }
[[bin]]
name = "preview"
path = "fuzz_targets/preview.rs"
test = false
doc = false
bench = false
[[bin]]
name = "import_preview"
path = "fuzz_targets/import_preview.rs"
required-features = ["io"]
test = false
doc = false
bench = false
[[bin]]
name = "stream"
path = "fuzz_targets/stream.rs"
test = false
doc = false
bench = false
@@ -1,10 +0,0 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
// The complete import: native document mapping, or the preview fallback.
if photocraft_affinity::is_affinity(data) {
let _ = photocraft_io::import("fuzz.af", data);
}
});
@@ -1,10 +0,0 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
// The whole native reader (archive, object stream, model) and the preview, on arbitrary bytes.
fuzz_target!(|data: &[u8]| {
let _ = photocraft_affinity::container::header(data);
let _ = photocraft_affinity::preview(data);
let _ = photocraft_affinity::read(data, photocraft_affinity::Limits { max_entry: 16 << 20, max_total: 64 << 20, max_pixel_bytes: 64 << 20 });
});
@@ -1,11 +0,0 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
// The doc.dat object stream and the model built from it, wrapped in a stored archive entry so
// mutations reach the tagged grammar instead of the archive's checksum.
fuzz_target!(|stream: &[u8]| {
let _ = photocraft_affinity::stream::parse(stream);
let file = photocraft_affinity::synth::container(&[("doc.dat", stream, photocraft_affinity::synth::Method::Stored)], None);
let _ = photocraft_affinity::read(&file, photocraft_affinity::Limits { max_entry: 16 << 20, max_total: 64 << 20, max_pixel_bytes: 64 << 20 });
});
-111
View File
@@ -1,111 +0,0 @@
//! Typed reads of [`Stream`] objects. Every accessor returns `None` when a field is missing or has
//! another type, so the document mapping treats odd data as absent rather than failing.
use crate::stream::{ObjId, Object, Stream, Tag, Value};
impl Stream {
pub fn object(&self, id: ObjId) -> Option<&Object> {
self.objects.get(id)
}
pub fn field(&self, id: ObjId, tag: &[u8; 4]) -> Option<&Value> {
self.object(id)?.get(Tag::of(tag))
}
pub fn class(&self, id: ObjId) -> Option<Tag> {
self.object(id).map(|o| o.class)
}
pub fn is(&self, id: ObjId, class: &[u8; 4]) -> bool {
self.class(id) == Some(Tag::of(class))
}
/// The raw slot count of an object's array field (including null slots), for charging
/// traversal work before nulls are filtered out. `None` when the field is not an array.
pub fn array_len(&self, id: ObjId, tag: &[u8; 4]) -> Option<usize> {
self.field(id, tag)?.array_len()
}
/// A child object (shared, linked or inline); `None` for null or missing.
pub fn obj(&self, id: ObjId, tag: &[u8; 4]) -> Option<ObjId> {
match self.field(id, tag)? {
Value::Obj(o) => *o,
_ => None,
}
}
/// An array of objects (nulls skipped).
pub fn objs(&self, id: ObjId, tag: &[u8; 4]) -> Vec<ObjId> {
match self.field(id, tag) {
Some(Value::Array(a)) => a.iter().filter_map(|v| if let Value::Obj(Some(o)) = v { Some(*o) } else { None }).collect(),
_ => Vec::new(),
}
}
pub fn f64(&self, id: ObjId, tag: &[u8; 4]) -> Option<f64> {
match self.field(id, tag)? {
Value::Float(f) if f.is_finite() => Some(*f),
_ => None,
}
}
pub fn int(&self, id: ObjId, tag: &[u8; 4]) -> Option<i64> {
match self.field(id, tag)? {
Value::Int(i) => Some(*i),
Value::UInt(u) => i64::try_from(*u).ok(),
_ => None,
}
}
pub fn bool(&self, id: ObjId, tag: &[u8; 4]) -> Option<bool> {
match self.field(id, tag)? {
Value::Bool(b) => Some(*b),
_ => None,
}
}
pub fn str(&self, id: ObjId, tag: &[u8; 4]) -> Option<&str> {
match self.field(id, tag)? {
Value::Str(s) => Some(s),
_ => None,
}
}
pub fn enumeration(&self, id: ObjId, tag: &[u8; 4]) -> Option<(u16, u16)> {
match self.field(id, tag)? {
Value::Enum { id, version } => Some((*id, *version)),
_ => None,
}
}
/// A fixed vector of `N` finite floats (points, rectangles, transforms).
pub fn floats<const N: usize>(&self, id: ObjId, tag: &[u8; 4]) -> Option<[f64; N]> {
match self.field(id, tag)? {
Value::Floats(v) if v.len() == N && v.iter().all(|f| f.is_finite()) => {
let mut a = [0.0; N];
a.copy_from_slice(v);
Some(a)
}
_ => None,
}
}
pub fn bytes(&self, id: ObjId, tag: &[u8; 4]) -> Option<&[u8]> {
match self.field(id, tag)? {
Value::Bytes(b) | Value::Blob(b) => Some(b),
_ => None,
}
}
pub fn entry(&self, id: ObjId, tag: &[u8; 4]) -> Option<&str> {
match self.field(id, tag)? {
Value::Entry(s) => Some(s),
_ => None,
}
}
/// Untagged fields of a positional object, in order.
pub fn positional(&self, id: ObjId) -> impl Iterator<Item = &Value> {
self.object(id).into_iter().flat_map(|o| o.fields.iter().map(|(_, v)| v))
}
}
-405
View File
@@ -1,405 +0,0 @@
//! The Affinity archive: header, the chain of file allocation tables (one per save) and
//! bounded, CRC-checked extraction of named entries such as `doc.dat` and raster tiles.
use std::collections::{HashMap, HashSet};
use std::io::Read;
use crate::Error;
pub const MAGIC: &[u8; 4] = b"\x00\xffKA";
/// Oldest and newest container versions seen in real documents (Affinity 1.x writes 8,
/// Affinity 3 writes 12). Version 7 is described by afread but no sample exists.
pub const VERSIONS: std::ops::RangeInclusive<u16> = 8..=12;
/// `Prsn` (stored byte-reversed): documents. Asset, brush and style libraries share the magic.
const DOCUMENT_KIND: &[u8; 4] = b"nsrP";
/// A save appends one table; real files have one to a few hundred.
const MAX_TABLES: usize = 4096;
/// Distinct ids the allocation tables may name; each costs a map slot even when only deleted.
const MAX_ENTRIES: usize = 1 << 22;
/// Bytes of entry names the allocation tables may name. A name is retained twice (in the entry
/// and as its map key), and tables can point many names at the same bytes.
const MAX_NAME_BYTES: usize = 32 << 20;
/// File and directory records parsed across every allocation table. Each table walks its own
/// records, and tables may start inside one another and share a long suffix, so the per-table
/// counts do not bound the work: a few thousand overlapping tables could reparse one large run
/// of records each. Real files hold a few hundred saves of a few thousand entries.
const MAX_TABLE_RECORDS: usize = 1 << 25;
/// zstd window ceiling: real documents use a few MiB; this stops a header from reserving gigabytes.
const MAX_ZSTD_WINDOW: u64 = 64 << 20;
/// Decompression budget for one import. Every entry declares its size, which is checked against
/// these limits before anything is allocated, and the decoded length must match it exactly.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Limits {
/// Largest single entry (`doc.dat` or one tile).
pub max_entry: usize,
/// Total bytes extracted over the whole import.
pub max_total: usize,
/// Bytes of decoded pixels one import may hold: every layer's RGBA together, plus the
/// temporary planes the layer being read decodes through. The entry limits bound what is
/// extracted, not what the layers materialized out of it cost (#4960).
pub max_pixel_bytes: usize,
}
impl Default for Limits {
fn default() -> Self {
// The gigabyte the other importers allow decoded pixels (`io`'s `MAX_PIXEL_BYTES`).
Self { max_entry: 256 << 20, max_total: 1 << 30, max_pixel_bytes: 1 << 30 }
}
}
/// The container header, all integers little-endian.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Header {
pub version: u16,
/// Seen as 0, 4 or 8 in real files; bits 0 and 1 mark container variants that are rejected.
pub flags: u16,
pub(crate) fat_offset: u64,
pub(crate) thumbnail_offset: u64,
/// Save time in Unix seconds, as written by the application.
pub saved: u32,
}
/// One FAT record, as of the newest table that mentions its id.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Entry {
pub id: u32,
pub name: String,
offset: u64,
size: u64,
compressed: u64,
crc: u32,
compression: u8,
}
impl Entry {
/// Decompressed size declared by the table.
pub fn size(&self) -> u64 {
self.size
}
}
#[derive(Debug)]
pub struct Archive<'a> {
bytes: &'a [u8],
pub header: Header,
/// Head revision of every named, non-deleted entry.
entries: HashMap<String, Entry>,
/// Number of tables (saves) in the chain.
pub revisions: usize,
extracted: usize,
limits: Limits,
}
pub(crate) struct Cursor<'a> {
bytes: &'a [u8],
pub(crate) pos: usize,
}
impl<'a> Cursor<'a> {
pub(crate) fn new(bytes: &'a [u8], pos: usize) -> Self {
Self { bytes, pos }
}
pub(crate) fn remaining(&self) -> usize {
self.bytes.len().saturating_sub(self.pos)
}
pub(crate) fn take(&mut self, n: usize) -> Result<&'a [u8], Error> {
let end = self.pos.checked_add(n).ok_or(Error::Malformed("length overflow"))?;
let s = self.bytes.get(self.pos..end).ok_or(Error::Malformed("truncated data"))?;
self.pos = end;
Ok(s)
}
pub(crate) fn array<const N: usize>(&mut self) -> Result<[u8; N], Error> {
let s = self.take(N)?;
let mut a = [0u8; N];
a.copy_from_slice(s);
Ok(a)
}
pub(crate) fn u8(&mut self) -> Result<u8, Error> {
Ok(self.array::<1>()?[0])
}
pub(crate) fn u16(&mut self) -> Result<u16, Error> {
Ok(u16::from_le_bytes(self.array()?))
}
pub(crate) fn u32(&mut self) -> Result<u32, Error> {
Ok(u32::from_le_bytes(self.array()?))
}
pub(crate) fn u64(&mut self) -> Result<u64, Error> {
Ok(u64::from_le_bytes(self.array()?))
}
}
fn offset(v: u64) -> Result<usize, Error> {
usize::try_from(v).map_err(|_| Error::Malformed("offset beyond addressable memory"))
}
/// True when `bytes` start with the Affinity container signature (documents and libraries).
pub fn is_affinity(bytes: &[u8]) -> bool {
bytes.starts_with(MAGIC)
}
/// Check the signature, version and document kind.
pub fn header(bytes: &[u8]) -> Result<Header, Error> {
if !is_affinity(bytes) {
return Err(Error::Malformed("missing container signature"));
}
let mut c = Cursor::new(bytes, 4);
let version = c.u16()?;
let flags = c.u16()?;
if !VERSIONS.contains(&version) {
return Err(Error::Unsupported("unknown container version"));
}
if flags & 3 != 0 {
return Err(Error::Unsupported("container variant"));
}
if c.take(4)? != DOCUMENT_KIND {
return Err(Error::Unsupported("this Affinity file is a library (assets, brushes or styles), not a document"));
}
if c.take(4)? != b"#Inf" {
return Err(Error::Malformed("missing information header"));
}
let fat_offset = c.u64()?;
let thumbnail_offset = c.u64()?;
c.take(16)?;
let saved = u32::try_from(c.u64()?).unwrap_or(0);
c.take(8)?;
if c.take(4)? != b"Prot" {
return Err(Error::Malformed("missing protocol header"));
}
Ok(Header { version, flags, fat_offset, thumbnail_offset, saved })
}
impl<'a> Archive<'a> {
pub fn open(bytes: &'a [u8], limits: Limits) -> Result<Self, Error> {
let header = header(bytes)?;
// Newest record per id: (table date, table index, record).
let mut latest: HashMap<u32, (u64, usize, Option<Box<Entry>>)> = HashMap::new();
let mut names: HashMap<u32, String> = HashMap::new();
let mut name_bytes = 0usize;
let mut seen = HashSet::new();
let mut next = header.fat_offset;
let mut tables = 0usize;
let mut records_left = MAX_TABLE_RECORDS;
while next != 0 {
if !seen.insert(next) {
return Err(Error::Malformed("allocation tables form a cycle"));
}
tables += 1;
if tables > MAX_TABLES {
return Err(Error::Limit("too many saved revisions"));
}
let mut c = Cursor::new(bytes, offset(next)?);
let tag = c.array::<4>()?;
let level = match &tag {
b"#FAT" => 1,
b"#FT2" => 2,
b"#FT3" => 3,
b"#FT4" => 4,
_ => return Err(Error::Malformed("missing allocation table")),
};
next = c.u64()?;
let date = c.u64()?;
c.take(24)?;
let files = c.u32()?;
c.take(8)?;
let dirs = c.u16()?;
c.take(1)?;
// Charge the declared records before walking them.
let declared = usize::try_from(files).unwrap_or(usize::MAX).saturating_add(usize::from(dirs));
records_left = records_left.checked_sub(declared).ok_or(Error::Limit("too many allocation records"))?;
for _ in 0..files {
let id = c.u32()?;
let flag = c.u8()?;
let mut record = None;
match flag {
0 | 1 => {
let offset = c.u64()?;
let size = c.u64()?;
let compressed = c.u64()?;
let crc = c.u32()?;
let stored = c.u8()?;
if level >= 2 {
c.take(4)?;
}
if level >= 4 {
c.take(4)?;
}
// Old tables number the methods; newer ones store the method byte itself.
let compression = if level <= 2 {
match stored {
1 => 0x01,
2 => 0x41,
3 => 0x81,
4 => 0xC1,
_ => 0,
}
} else {
stored
};
record = Some(Box::new(Entry { id, name: String::new(), offset, size, compressed, crc, compression }));
}
2 => {}
_ => return Err(Error::Malformed("unknown allocation record")),
}
if flag == 0 {
let len = usize::from(c.u16()?);
let raw = c.take(len)?;
// Only the first name per id is kept: charge and copy just that one.
if let std::collections::hash_map::Entry::Vacant(slot) = names.entry(id) {
let name = String::from_utf8_lossy(raw).into_owned();
name_bytes = name_bytes.saturating_add(name.len());
if name_bytes > MAX_NAME_BYTES {
return Err(Error::Limit("archive entry names too large"));
}
slot.insert(name);
}
}
// Equal dates: the first table in the chain (the newest) wins, as in afread.
let replace = latest.get(&id).is_none_or(|(d, _, _)| date > *d);
if replace {
// Deletion records are five bytes each: cap what distinct ids may retain.
if latest.len() >= MAX_ENTRIES && !latest.contains_key(&id) {
return Err(Error::Limit("too many archive entries"));
}
latest.insert(id, (date, tables, record));
}
}
for _ in 0..dirs {
let len = usize::from(c.u16()?);
c.take(10)?;
c.take(len)?;
}
}
let mut entries = HashMap::new();
for (id, (_, _, record)) in latest {
if let (Some(mut e), Some(name)) = (record, names.get(&id)) {
e.name = name.clone();
entries.insert(e.name.clone(), *e);
}
}
Ok(Self { bytes, header, entries, revisions: tables, extracted: 0, limits })
}
pub fn entry(&self, name: &str) -> Option<&Entry> {
self.entries.get(name)
}
pub fn entry_names(&self) -> impl Iterator<Item = &str> {
self.entries.keys().map(String::as_str)
}
/// Bytes extracted so far, counted against [`Limits::max_total`].
pub fn extracted(&self) -> usize {
self.extracted
}
/// Extract an entry by name: decompress, undo the byte predictor and verify the CRC.
pub fn read(&mut self, name: &str) -> Result<Vec<u8>, Error> {
let e = self.entries.get(name).ok_or(Error::Malformed("missing archive entry"))?.clone();
let size = usize::try_from(e.size).map_err(|_| Error::Limit("archive entry too large"))?;
if size > self.limits.max_entry {
return Err(Error::Limit("archive entry too large"));
}
let total = self.extracted.checked_add(size).ok_or(Error::Limit("document too large"))?;
if total > self.limits.max_total {
return Err(Error::Limit("document too large"));
}
// Charge before decoding: a corrupt entry that fails its checksum has already cost the
// decompression, and an importer that recovers must not get it again for free.
self.extracted = total;
let mut c = Cursor::new(self.bytes, offset(e.offset)?);
if c.take(4)? != b"#Fil" {
return Err(Error::Malformed("archive entry has no data block"));
}
let method = e.compression & 3;
let stored_len = if matches!(method, 1 | 2) { e.compressed } else { e.size };
let data = c.take(offset(stored_len)?)?;
let mut out = match method {
1 => inflate(data, size)?,
2 => unzstd(data, size)?,
_ => data.to_vec(),
};
if out.len() != size {
return Err(Error::Malformed("archive entry size mismatch"));
}
unpredict(&mut out, e.compression)?;
if crc32fast::hash(&out) != e.crc {
return Err(Error::Malformed("archive entry checksum mismatch"));
}
Ok(out)
}
}
/// Read at most `size + 1` bytes so a stream that decodes past its declared size is caught
/// without unbounded allocation.
fn read_bounded(mut r: impl Read, size: usize) -> Result<Vec<u8>, Error> {
let mut out = Vec::with_capacity(size.min(64 << 20));
let cap = u64::try_from(size).unwrap_or(u64::MAX).saturating_add(1);
r.by_ref().take(cap).read_to_end(&mut out).map_err(|_| Error::Malformed("corrupt compressed entry"))?;
Ok(out)
}
fn inflate(data: &[u8], size: usize) -> Result<Vec<u8>, Error> {
read_bounded(flate2::bufread::ZlibDecoder::new(data), size)
}
fn unzstd(data: &[u8], size: usize) -> Result<Vec<u8>, Error> {
let mut src = data;
let mut out = Vec::new();
// Entries may hold several concatenated frames.
while !src.is_empty() {
let left = size.checked_sub(out.len()).ok_or(Error::Malformed("archive entry size mismatch"))?;
let decoder = ruzstd::decoding::StreamingDecoder::new_with_max_window_size(&mut src, MAX_ZSTD_WINDOW)
.map_err(|_| Error::Malformed("corrupt compressed entry"))?;
let frame = read_bounded(decoder, left)?;
if frame.is_empty() {
return Err(Error::Malformed("corrupt compressed entry"));
}
out.extend_from_slice(&frame);
if out.len() > size {
return Err(Error::Malformed("archive entry size mismatch"));
}
}
Ok(out)
}
/// Undo the byte predictor selected by the high bits of the compression byte.
fn unpredict(b: &mut [u8], compression: u8) -> Result<(), Error> {
match (compression & 0xC0, compression & 0x20 != 0) {
(0x00, _) => {}
(0x40, _) => byte_delta(b),
(0x80, false) => {
let mut prev = 0u16;
for pair in b.as_chunks_mut::<2>().0.iter_mut() {
let v = u16::from_le_bytes(*pair).wrapping_add(prev);
*pair = v.to_le_bytes();
prev = v;
}
}
(0x80, true) => {
byte_delta(b);
// A 64 KiB tile of 16-bit samples is stored as all high bytes, then all low bytes.
if b.len() == 0x10000 {
let planes = b.to_vec();
let (hi, lo) = planes.split_at(0x8000);
for (i, out) in b.as_chunks_mut::<4>().0.iter_mut().enumerate() {
let (Some(h), Some(l)) = (hi.get(2 * i..2 * i + 2), lo.get(2 * i..2 * i + 2)) else {
return Err(Error::Malformed("tile size"));
};
*out = [l[0], h[0], l[1], h[1]];
}
}
}
_ => return Err(Error::Unsupported("archive entry predictor")),
}
Ok(())
}
fn byte_delta(b: &mut [u8]) {
let mut prev = 0u8;
for v in b {
*v = v.wrapping_add(prev);
prev = *v;
}
}
-310
View File
@@ -1,310 +0,0 @@
//! Outlines of curves (`PCvD` node lists), parametric shapes (`Shpe` objects) and compounds, in
//! node space.
use crate::model::{Affine, Path, Point, Reader, SubPath};
use crate::stream::{ObjId, Tag, Value};
/// Nodes per curve object.
const MAX_NODES: usize = 4_000_000;
const MAX_COMPOUND_DEPTH: usize = 64;
const MAX_OUTLINE_VISITS: usize = 500_000;
const MAX_OUTLINE_POINTS: usize = 4_000_000;
/// Curve records decoded across the document. A shared curve is decoded again for each
/// occurrence, and records that only move handles add no points.
const MAX_OUTLINE_RECORDS: usize = 8_000_000;
/// Geometry is expanded per occurrence, since parametric outlines can depend on their world
/// transform. Bound work across the entire document instead of memoizing by object id alone.
pub(crate) struct Budget {
visits_left: usize,
points_left: usize,
records_left: usize,
}
impl Default for Budget {
fn default() -> Self {
Self { visits_left: MAX_OUTLINE_VISITS, points_left: MAX_OUTLINE_POINTS, records_left: MAX_OUTLINE_RECORDS }
}
}
impl Budget {
/// Charge an outline call or a raw compound operand slot before inspecting it.
fn visit(&mut self) -> Result<(), &'static str> {
self.visits_left = self.visits_left.checked_sub(1).ok_or("compound geometry budget exhausted")?;
Ok(())
}
/// Charge curve records before they are decoded.
fn records(&mut self, n: usize) -> Result<(), &'static str> {
self.records_left = self.records_left.checked_sub(n).ok_or("curve geometry budget exhausted")?;
Ok(())
}
/// Charge both leaf geometry and each copy into a compound before allocating that copy.
fn path(&mut self, path: &Path) -> Result<(), &'static str> {
let points = path.subpaths.iter().fold(0usize, |n, s| n.saturating_add(1).saturating_add(s.segments.len().saturating_mul(3)));
let Some(left) = self.points_left.checked_sub(points) else {
// Do not rebuild an expensive leaf for every subsequent root after exhaustion.
self.visits_left = 0;
return Err("compound geometry budget exhausted");
};
self.points_left = left;
Ok(())
}
}
/// The node-space outline of a curve, shape or compound node, and whether it fills even-odd.
/// Instances (master-page or symbol copies) take the geometry of their master.
pub(crate) fn outline(r: &mut Reader, id: ObjId, class: Tag, world: Affine) -> Option<(Path, bool)> {
match outline_inner(r, id, class, world, &mut Vec::new()) {
Ok(path) => path,
Err(reason) => {
r.warn(reason);
None
}
}
}
fn outline_inner(r: &mut Reader, id: ObjId, class: Tag, world: Affine, active: &mut Vec<ObjId>) -> Result<Option<(Path, bool)>, &'static str> {
r.geometry_budget.visit()?;
if active.contains(&id) {
return Err("cyclic compound shape");
}
// Independent of the layer-tree limit: Comp operands do not pass through Reader::node.
if active.len() >= MAX_COMPOUND_DEPTH {
return Err("compound depth exceeds 64 levels");
}
if class != Tag::of(b"Comp") {
let path = leaf_outline(r, id, class, world);
if let Some((path, _)) = &path {
r.geometry_budget.path(path)?;
}
return Ok(path);
}
active.push(id);
let result = compound(r, id, world, active);
active.pop();
result
}
fn compound(r: &mut Reader, id: ObjId, world: Affine, active: &mut Vec<ObjId>) -> Result<Option<(Path, bool)>, &'static str> {
let s = r.s;
// One path of all operands' contours, filled even-odd, as before. A safety failure rejects
// the whole outline: a partial add/subtract shape could silently change its meaning.
let mut path = Path::default();
// Charge every slot before filtering nulls or malformed values. Stream::objs would scan
// and allocate the whole list first, repeating uncharged work for each shared occurrence.
let children = if let Some(Value::Array(children)) = s.field(id, b"Chld") { children.as_slice() } else { &[] };
for child in children {
r.geometry_budget.visit()?;
let Value::Obj(Some(c)) = child else { continue };
let c = *c;
let local = s.floats::<6>(c, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY);
let Some(class) = s.class(c) else { return Ok(None) };
if s.enumeration(c, b"ComO").is_some_and(|(op, _)| op != 0 && op != 2) {
r.warn("compound shapes that intersect or exclude (imported as add)");
}
if let Some((p, _)) = outline_inner(r, c, class, local.then(world), active)? {
r.geometry_budget.path(&p)?;
path.subpaths.extend(p.transformed(local).subpaths);
}
}
Ok(Some((path, true)))
}
fn leaf_outline(r: &mut Reader, id: ObjId, class: Tag, world: Affine) -> Option<(Path, bool)> {
let s = r.s;
match &class.0.to_be_bytes() {
b"PCrv" | b"TxtC" => {
let crvs = s.obj(id, b"Crvs").or_else(|| s.obj(id, b"MCrM").and_then(|m| s.obj(m, b"Crvs")))?;
let path = curves(r, crvs)?;
let multi = path.subpaths.len() > 1;
Some((path, multi))
}
_ => {
let (shape, box_owner) = match s.obj(id, b"Shpe") {
Some(sh) => (sh, id),
None => {
let master = s.obj(id, b"ShpM")?;
(s.obj(master, b"Shpe")?, master)
}
};
let b = s.floats::<4>(box_owner, b"ShpB")?;
crate::shapes::shape(r, shape, b, world)
}
}
}
/// `PCvD.Data`: positional `[u8, u32 count, then per subpath: bool closed, 18-byte records]`.
/// A record is (f64 x, f64 y, u8 kind, u8 role): role 0 is an anchor, 1 the out-handle of the
/// anchor before it, 2 the in-handle of the anchor after it. A closed subpath repeats its first
/// anchor at the end. `CnrD` live corners are rounded on the stored polyline.
pub(crate) fn curves(r: &mut Reader, crvs: ObjId) -> Option<Path> {
let s = r.s;
let data = s.obj(crvs, b"Data")?;
let mut fields = s.positional(data);
fields.next()?;
let count = match fields.next()? {
Value::UInt(n) => usize::try_from(*n).ok()?,
_ => return None,
};
let corners = match s.obj(crvs, b"CnrD") {
Some(c) => {
let fields: Vec<&Value> = s.positional(c).collect();
// The corner arrays are scanned for every occurrence of a shared curve, so charge
// them like records before they are walked.
if let Some(len) = fields.get(1).and_then(|v| v.array_len())
&& let Err(reason) = r.geometry_budget.records(len)
{
r.warn(reason);
return None;
}
corner_radii(fields)
}
None => None,
};
let mut path = Path::default();
let mut seen = 0usize;
for index in 0..count {
let closed = match fields.next()? {
Value::Bool(b) => *b,
_ => return None,
};
let records = fields.next()?;
let len = records.array_len()?;
seen = seen.checked_add(len)?;
if seen > MAX_NODES {
r.warn("curves with more than four million nodes");
return None;
}
// Charge the subpath itself as well as its records: an empty subpath adds no records
// or points, but a shared curve full of them is still walked for every occurrence.
if let Err(reason) = r.geometry_budget.records(len.saturating_add(1)) {
r.warn(reason);
return None;
}
let anchors = match records {
Value::Array(a) => anchors(a.iter().map(record)),
Value::Records { size: 18, data } => anchors(data.as_chunks::<18>().0.iter().map(record18)),
// Records of another width are no curve nodes.
_ => anchors(std::iter::repeat_n(None, len)),
}?;
let radii = if index == 0 { corners.as_ref() } else { None };
if let Some(sp) = subpath(&anchors, closed, radii) {
path.subpaths.push(sp);
}
}
if corners.is_some() && count > 1 {
r.warn("rounded corners on curves with several subpaths (only the first is rounded)");
}
Some(path)
}
struct Anchor {
p: Point,
inh: Option<Point>,
out: Option<Point>,
/// Index of the anchor's record (live corners refer to records).
record: usize,
}
fn record(v: &Value) -> Option<(Point, u8)> {
let Value::Bytes(b) = v else { return None };
record18(b.as_slice().try_into().ok()?)
}
/// One 18-byte curve node: f64 x, f64 y, u8 kind, u8 role.
fn record18(b: &[u8; 18]) -> Option<(Point, u8)> {
let x = f64::from_le_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]);
let y = f64::from_le_bytes([b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]]);
if !x.is_finite() || !y.is_finite() {
return None;
}
Some((Point { x, y }, b[17]))
}
fn anchors(records: impl ExactSizeIterator<Item = Option<(Point, u8)>>) -> Option<Vec<Anchor>> {
let mut out: Vec<Anchor> = Vec::with_capacity(records.len() / 3 + 1);
let mut pending_in = None;
for (i, v) in records.enumerate() {
let (p, role) = v?;
match role {
0 => {
out.push(Anchor { p, inh: pending_in.take(), out: None, record: i });
}
1 => {
// A leading out-handle without an anchor is edit state only.
if let Some(a) = out.last_mut() {
a.out = Some(p);
}
}
2 => pending_in = Some(p),
_ => return None,
}
}
Some(out)
}
fn subpath(anchors: &[Anchor], closed: bool, radii: Option<&Vec<(usize, f64)>>) -> Option<SubPath> {
let first = anchors.first()?;
if let Some(radii) = radii.filter(|r| !r.is_empty()) {
// Index each record's maximum radius once. Scanning the whole radius list per anchor
// was O(anchors * radii), which a file with large anchor and radius arrays could drive
// into quadratic work. Duplicate record indices keep the maximum, matching the prior
// fold(0.0, f64::max) behavior.
let mut radius_by_record: std::collections::HashMap<usize, f64> = std::collections::HashMap::with_capacity(radii.len());
for &(rec, r) in radii {
let slot = radius_by_record.entry(rec).or_insert(0.0);
*slot = slot.max(r);
}
let corner = |a: &Anchor| radius_by_record.get(&a.record).copied().unwrap_or(0.0);
let polyline = anchors.iter().all(|a| a.inh.is_none_or(|h| h == a.p) && a.out.is_none_or(|h| h == a.p));
if polyline {
let mut pts: Vec<(Point, f64)> = anchors.iter().map(|a| (a.p, corner(a))).collect();
// A closed subpath repeats its first anchor; its radius may be on either copy.
if closed
&& pts.len() > 1
&& pts.first().map(|p| p.0) == pts.last().map(|p| p.0)
&& let Some((_, r)) = pts.pop()
&& let Some(f) = pts.first_mut()
{
f.1 = f.1.max(r);
}
return Some(crate::shapes::fillet(&pts, closed));
}
}
let segments = anchors
.windows(2)
.filter_map(|w| {
let [a, b] = w else { return None };
Some([a.out.unwrap_or(a.p), b.inh.unwrap_or(b.p), b.p])
})
.collect();
Some(SubPath { start: first.p, segments, closed })
}
/// `CnrD`: positional `[u8, i32[] record indices, f64[] radii, u8[] types]`.
fn corner_radii(fields: Vec<&Value>) -> Option<Vec<(usize, f64)>> {
let (Some(Value::Array(idx)), Some(Value::Array(rad))) = (fields.get(1), fields.get(2)) else { return None };
Some(
idx.iter()
.zip(rad)
.filter_map(|(i, r)| match (i, r) {
(Value::Int(i), Value::Float(r)) if r.is_finite() && *r > 0.0 => Some((usize::try_from(*i).ok()?, *r)),
_ => None,
})
.collect(),
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn curve_records_are_charged_across_the_document() {
let mut b = Budget::default();
assert!(b.records(MAX_OUTLINE_RECORDS).is_ok());
assert_eq!(b.records(1), Err("curve geometry budget exhausted"));
}
}
-51
View File
@@ -1,51 +0,0 @@
//! Reader for native Affinity documents (`.af`, and `.afdesign`/`.afphoto`/`.afpub` from
//! Affinity 1 and 2): the archive container, the tagged object stream in `doc.dat`, and the
//! subset of the document model PhotoCraft imports.
//!
//! Layouts follow the MIT-licensed afread reference and were checked against public documents
//! saved by Affinity 1.x to 3.x (container versions 8 to 12); see the crate README for provenance
//! and the exact supported subset. Nothing here writes Affinity files.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
use std::fmt;
mod access;
pub mod container;
mod geometry;
pub mod model;
pub mod paint;
pub mod preview;
mod raster;
mod shapes;
pub mod stream;
#[cfg(any(test, feature = "synth"))]
pub mod synth;
mod text;
pub use container::{Archive, Limits, MAGIC, is_affinity};
pub use model::{Document, read};
pub use preview::{MAX_PREVIEW_BYTES, MAX_PREVIEW_DIMENSION, Preview, preview};
/// Why a file could not be read. Messages are short reasons; callers add advice.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Error {
Malformed(&'static str),
Unsupported(&'static str),
Limit(&'static str),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Malformed(s) => write!(f, "damaged Affinity file: {s}"),
Self::Unsupported(s) => write!(f, "unsupported Affinity file: {s}"),
Self::Limit(s) => write!(f, "Affinity file exceeds a safety limit: {s}"),
}
}
}
impl std::error::Error for Error {}
#[cfg(test)]
mod tests;
-694
View File
@@ -1,694 +0,0 @@
//! The document model PhotoCraft imports: spreads, artboards, layers, groups, curves, shapes,
//! text and images, with transforms composed into document space. Anything else is reported
//! by [`Document::warnings`] instead of being dropped silently.
use std::collections::{BTreeMap, HashSet};
use crate::paint::{self, Paint, Stroke};
use crate::stream::{ObjId, Stream, Tag};
use crate::{Archive, Error, Limits, stream};
/// Affine map `x' = a·x + c·y + e`, `y' = b·x + d·y + f` (kurbo's coefficient order).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Affine(pub [f64; 6]);
impl Affine {
pub const IDENTITY: Self = Self([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
/// Affinity's `Xfrm`, stored row by row: (a, c, e, b, d, f).
pub(crate) fn from_xfrm(m: [f64; 6]) -> Self {
Self([m[0], m[3], m[1], m[4], m[2], m[5]])
}
pub fn then(self, outer: Self) -> Self {
let [a, b, c, d, e, f] = self.0;
let [oa, ob, oc, od, oe, of] = outer.0;
Self([oa * a + oc * b, ob * a + od * b, oa * c + oc * d, ob * c + od * d, oa * e + oc * f + oe, ob * e + od * f + of])
}
pub fn apply(&self, p: Point) -> Point {
let [a, b, c, d, e, f] = self.0;
Point { x: a * p.x + c * p.y + e, y: b * p.x + d * p.y + f }
}
/// Geometric mean of the axis scales: how much a stroke width or font size grows.
pub fn scale(&self) -> f64 {
let [a, b, c, d, ..] = self.0;
(a * d - b * c).abs().sqrt()
}
pub fn is_finite(&self) -> bool {
self.0.iter().all(|v| v.is_finite())
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Point {
pub x: f64,
pub y: f64,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Rect {
pub x0: f64,
pub y0: f64,
pub x1: f64,
pub y1: f64,
}
/// One cubic Bézier subpath, in document pixels.
#[derive(Debug, Clone, PartialEq)]
pub struct SubPath {
pub start: Point,
/// (control 1, control 2, end) per segment.
pub segments: Vec<[Point; 3]>,
pub closed: bool,
}
/// An outline in document pixels.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Path {
pub subpaths: Vec<SubPath>,
}
impl Path {
pub fn transformed(&self, m: Affine) -> Self {
Self {
subpaths: self
.subpaths
.iter()
.map(|s| SubPath { start: m.apply(s.start), segments: s.segments.iter().map(|seg| seg.map(|p| m.apply(p))).collect(), closed: s.closed })
.collect(),
}
}
}
/// Affinity's blend modes, numbered by the `Blnd` enum.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Blend {
#[default]
Normal,
PassThrough,
Darken,
DarkerColor,
Multiply,
ColorBurn,
Lighten,
LighterColor,
Screen,
ColorDodge,
Add,
Overlay,
SoftLight,
HardLight,
VividLight,
PinLight,
LinearLight,
HardMix,
Difference,
Exclusion,
Subtract,
Hue,
Saturation,
Luminosity,
Color,
Average,
Negation,
Reflect,
Glow,
Erase,
}
impl Blend {
/// The enum (id, version) pairs observed in a document whose layers are named after their mode.
fn from_enum(id: u16, version: u16) -> Option<Self> {
use Blend::*;
Some(match (id, version) {
(0, _) => Normal,
(1, 0) => Darken,
(2, 1) => DarkerColor,
(2, 0) => Multiply,
(3, 0) => ColorBurn,
(4, 0) => Lighten,
(6, 1) => LighterColor,
(5, 0) => Screen,
(6, 0) => ColorDodge,
(7, 0) => Add,
(8, 0) => Overlay,
(9, 0) => SoftLight,
(10, 0) => HardLight,
(11, 0) => VividLight,
(12, 0) => PinLight,
(15, 1) => LinearLight,
(13, 0) => HardMix,
(14, 0) => Difference,
(15, 0) => Exclusion,
(16, 0) => Subtract,
(17, 0) => Hue,
(18, 0) => Saturation,
(19, 0) => Luminosity,
(20, 0) => Color,
(21, 0) => Average,
(22, 0) => Negation,
(23, 0) => Reflect,
(24, 0) => Glow,
(25, 0) => Erase,
_ => return None,
})
}
}
/// A run of text with one set of character attributes.
#[derive(Debug, Clone, PartialEq)]
pub struct TextRun {
pub text: String,
/// PostScript name and family of the chosen font.
pub postscript: String,
pub family: String,
/// CSS weight (400 regular, 700 bold).
pub weight: i64,
pub italic: bool,
/// Font size in document pixels, before the node's transform.
pub size: f64,
/// Tracking in em.
pub tracking: f64,
/// Fixed line pitch in document pixels, when the run overrides automatic leading.
pub leading: Option<f64>,
pub fill: Paint,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Align {
Left,
Center,
Right,
Justify,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Text {
pub runs: Vec<TextRun>,
pub align: Align,
/// Artistic text: the first baseline's anchor point in node space (start, centre or end of the
/// line according to `align`). Frame text: the frame box in node space.
pub anchor: Point,
pub frame: Option<Rect>,
/// Node space to document pixels.
pub transform: Affine,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Pixels {
/// Straight-alpha RGBA, 8 bits per channel, row by row.
Rgba8(Vec<u8>),
/// The original file a placed image was made from (PNG, JPEG…), as embedded.
Encoded(Vec<u8>),
}
#[derive(Debug, Clone, PartialEq)]
pub struct Image {
pub width: u32,
pub height: u32,
pub pixels: Pixels,
/// Pixel space (0..w, 0..h) to document pixels.
pub transform: Affine,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Kind {
/// Layer container (`Scop`).
Layer,
Group,
/// Artboard: a rectangle that clips its children; `background` paints behind them.
Artboard {
rect: Rect,
background: Vec<Paint>,
},
/// Curve, parametric shape or compound shape: an outline with its fills and strokes.
/// Children of a shape are clipped by its outline (painted over its fills, under its strokes).
Shape {
path: Path,
fills: Vec<Paint>,
strokes: Vec<Stroke>,
even_odd: bool,
},
Text(Text),
Image(Image),
/// Something this reader does not import; its children are still imported.
Unsupported,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Node {
pub class: Tag,
pub name: String,
pub visible: bool,
pub locked: bool,
pub opacity: f64,
pub blend: Blend,
pub kind: Kind,
/// Vector mask in document pixels: the node shows only inside it (nonzero fill).
pub mask: Option<Path>,
/// Pixel mask: grey levels (white shows the node, black hides it); outside it the node is hidden.
pub pixel_mask: Option<Image>,
/// Bottom to top.
pub children: Vec<Node>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Spread {
/// Spread bounds in document pixels (the canvas, or the union of the artboards).
pub bounds: Rect,
/// Pages of a Publisher-style spread (one, or two facing pages), in document pixels.
pub pages: Vec<Rect>,
/// Transparent background; otherwise the page is white.
pub transparent: bool,
/// Bottom to top.
pub nodes: Vec<Node>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Document {
/// Pixels per inch: all geometry is in document pixels at this resolution.
pub dpi: f64,
pub spreads: Vec<Spread>,
/// Application that last saved the file, as stored (`Affinity 3.0.2`), when present.
pub saved_by: Option<String>,
/// Content that was not imported or was approximated, one line per kind, deduplicated.
pub warnings: Vec<String>,
}
/// Deepest layer nesting followed; deeper content is reported, not imported.
const MAX_TREE_DEPTH: usize = 128;
/// Total layer nodes imported.
const MAX_NODES: usize = 500_000;
/// Total raw `Chld` slots inspected across the whole traversal, including null slots and slots
/// reached through repeated references to a shared group. The node limit only counts produced
/// nodes, so a shared group holding a large null-filled child array could still be rescanned
/// many times; this bounds that work. Generous relative to MAX_NODES for real documents.
const MAX_CHILD_SLOTS: usize = 8_000_000;
/// Bytes of layer names the model may retain across all occurrences.
const MAX_NAME_BYTES: usize = 64 << 20;
/// Page rectangles the model may retain across all spreads (real books have a few hundred).
const MAX_PAGES: usize = 1 << 18;
/// Bytes of font names the text runs may retain across the document.
const MAX_FONT_NAME_BYTES: usize = 16 << 20;
/// Read a document: archive, `doc.dat` and the model.
pub fn read(bytes: &[u8], limits: Limits) -> Result<Document, Error> {
let mut archive = Archive::open(bytes, limits)?;
let doc = archive.read("doc.dat")?;
let s = stream::parse(&doc)?;
// The parsed stream owns copies of everything it needs: do not hold the inflated bytes
// (hundreds of MB for a large vector document) while the model is built.
drop(doc);
Reader::new(&s, &mut archive, limits).document()
}
pub(crate) struct Reader<'s, 'a, 'b> {
pub(crate) s: &'s Stream,
pub(crate) archive: &'b mut Archive<'a>,
pub(crate) dpi: f64,
warnings: BTreeMap<String, usize>,
nodes: usize,
child_slots: usize,
name_bytes: usize,
pages: usize,
font_name_bytes: usize,
active: HashSet<ObjId>,
pub(crate) geometry_budget: crate::geometry::Budget,
/// Decoded pixels still available ([`Limits::max_pixel_bytes`] less what the layers read so
/// far hold).
pixels_left: usize,
}
impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
fn new(s: &'s Stream, archive: &'b mut Archive<'a>, limits: Limits) -> Self {
Self {
s,
archive,
dpi: 72.0,
warnings: BTreeMap::new(),
nodes: 0,
child_slots: 0,
name_bytes: 0,
pages: 0,
font_name_bytes: 0,
active: HashSet::new(),
geometry_budget: crate::geometry::Budget::default(),
pixels_left: limits.max_pixel_bytes,
}
}
/// Admit a layer's decoded pixels before they are allocated (#4960). `rgba` is the layer's
/// output, which stays with the document; `planes` is the working set it decodes through and
/// releases. Every layer read so far is still live while this one decodes, so the peak is all
/// three together.
pub(crate) fn admit_pixels(&mut self, rgba: usize, planes: usize) -> Result<(), Error> {
let peak = rgba.saturating_add(planes);
if peak > self.pixels_left {
return Err(Error::Limit("decoded pixel layers exceed the pixel budget"));
}
self.pixels_left -= rgba;
Ok(())
}
pub(crate) fn warn(&mut self, what: impl Into<String>) {
*self.warnings.entry(what.into()).or_default() += 1;
}
fn document(mut self) -> Result<Document, Error> {
let s = self.s;
let root = s.root;
self.dpi = s.obj(root, b"UVCn").and_then(|u| s.f64(u, b"UPPI")).filter(|d| *d > 0.0 && *d < 100_000.0).unwrap_or(72.0);
let saved_by = s.obj(root, b"NVer").map(|v| {
let product = s.str(v, b"Prod").unwrap_or("Affinity");
match (s.int(v, b"Majr"), s.int(v, b"Minr"), s.int(v, b"Bild")) {
(Some(a), Some(b), Some(c)) => format!("{product} {a}.{b}.{c}"),
_ => product.to_string(),
}
});
let doc = s.obj(root, b"DocR").ok_or(Error::Malformed("document has no root node"))?;
let mut spreads = Vec::new();
for spread in s.objs(doc, b"Chld") {
if !s.is(spread, b"Sprd") {
self.warn("an unknown kind of page");
continue;
}
let pages = self.pages(spread)?;
let default_size = s.floats::<2>(doc, b"DfSz").filter(|[w, h]| *w > 0.0 && *h > 0.0).map(|[w, h]| Rect { x0: 0.0, y0: 0.0, x1: w, y1: h });
let bounds = s.floats::<4>(spread, b"SprB").map(rect).or_else(|| pages.iter().copied().reduce(union)).or(default_size).unwrap_or(Rect {
x0: 0.0,
y0: 0.0,
x1: 0.0,
y1: 0.0,
});
let transparent = s.bool(spread, b"SprT").unwrap_or(false);
let (nodes, mask) = self.children(spread, Affine::IDENTITY, 0)?;
if mask.is_some() {
self.warn("mask layers directly on a page (imported without them)");
}
spreads.push(Spread { bounds, pages, transparent, nodes });
}
if spreads.is_empty() {
return Err(Error::Malformed("document has no pages"));
}
if !s.objs(doc, b"MpCh").is_empty() {
self.warn("master pages (their content is not placed on the pages that use them)");
}
let warnings = self.warnings.into_iter().map(|(w, n)| if n > 1 { format!("{w} ({n}×)") } else { w }).collect();
Ok(Document { dpi: self.dpi, spreads, saved_by, warnings })
}
/// The children of `parent`, and the pixel mask a mask layer among them puts on the parent.
fn children(&mut self, parent: ObjId, world: Affine, depth: usize) -> Result<(Vec<Node>, Option<Image>), Error> {
let s = self.s;
let mut out = Vec::new();
let mut mask = None;
// Charge every raw child slot (null slots included) against a document-wide budget
// before filtering. A shared group with a large null-filled Chld array could otherwise
// be rescanned through each reference without the node limit noticing.
self.charge_slots(s.array_len(parent, b"Chld").unwrap_or(0))?;
for c in s.objs(parent, b"Chld") {
if s.is(c, b"MRst") {
// A mask layer inside a group or layer masks that container.
if s.bool(c, b"Visi") == Some(false) {
continue;
}
let local = s.floats::<6>(c, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY);
match crate::raster::mask(self, c, local.then(world))? {
Some(m) if mask.is_none() => mask = Some(m),
Some(_) => self.warn("several pixel masks on one layer (only the first is used)"),
None => {}
}
continue;
}
if let Some(n) = self.node(c, world, depth + 1)? {
out.push(n);
}
}
Ok((out, mask))
}
/// Counts raw array slots (null ones included) against [`MAX_CHILD_SLOTS`].
pub(crate) fn charge_slots(&mut self, n: usize) -> Result<(), Error> {
self.child_slots = self.child_slots.saturating_add(n);
if self.child_slots > MAX_CHILD_SLOTS {
return Err(Error::Limit("too many child slots in the layer tree"));
}
Ok(())
}
fn node(&mut self, id: ObjId, parent: Affine, depth: usize) -> Result<Option<Node>, Error> {
let s = self.s;
if depth > MAX_TREE_DEPTH {
self.warn("layers nested deeper than 128 levels");
return Ok(None);
}
self.nodes += 1;
if self.nodes > MAX_NODES {
return Err(Error::Limit("too many layers"));
}
// A node that contains itself (a shared object linked back into its own subtree).
if !self.active.insert(id) {
self.warn("a layer that contains itself");
return Ok(None);
}
let local = s.floats::<6>(id, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY);
let world = local.then(parent);
let class = s.class(id).unwrap_or(Tag(0));
// A shared layer's name is copied for every occurrence, so charge the bytes first.
let name = s.str(id, b"Desc").unwrap_or_default();
self.name_bytes = self.name_bytes.saturating_add(name.len());
if self.name_bytes > MAX_NAME_BYTES {
return Err(Error::Limit("layer names too large"));
}
let name = name.to_string();
let visible = s.bool(id, b"Visi").unwrap_or(true);
let locked = s.bool(id, b"Edtb").is_some_and(|e| !e);
let opacity = s.f64(id, b"Opac").map_or(1.0, |o| o.clamp(0.0, 1.0));
let blend = match s.enumeration(id, b"Blnd") {
None if s.bool(id, b"PasT") != Some(false) && is_container(class) => Blend::PassThrough,
None => Blend::Normal,
Some((i, v)) => Blend::from_enum(i, v).unwrap_or_else(|| {
self.warn("an unknown blend mode (imported as Normal)");
Blend::Normal
}),
};
let kind = if !world.is_finite() {
self.warn("a layer with an invalid transform");
Kind::Unsupported
} else {
self.kind(id, class, world, parent)?
};
// A compound's children are its operands, already merged into its outline.
let (children, child_mask) = if class == Tag::of(b"Comp") { (Vec::new(), None) } else { self.children(id, world, depth)? };
let (mask, attached_mask) = self.attached_masks(id, world)?;
let pixel_mask = attached_mask.or(child_mask);
self.active.remove(&id);
self.charge_slots(s.array_len(id, b"FiEf").unwrap_or(0))?;
if s.objs(id, b"FiEf").iter().any(|e| s.bool(*e, b"Enab") != Some(false)) {
self.warn("layer effects (shadows, glows, outlines, bevels…)");
}
Ok(Some(Node { class, name, visible, locked, opacity, blend, kind, mask, pixel_mask, children }))
}
fn kind(&mut self, id: ObjId, class: Tag, world: Affine, parent: Affine) -> Result<Kind, Error> {
let s = self.s;
Ok(match &class.0.to_be_bytes() {
b"Scop" => Kind::Layer,
b"Grup" => Kind::Group,
b"PCrv" | b"ShpN" | b"Comp" | b"SNEN" | b"SNRR" | b"ShRN" => {
// Current .af boards carry artboard properties (aprp) in phrp; older
// documents use ABEn. Converted curve boards keep those properties too.
// Other property classes also use phrp, so the field alone is not a marker.
if s.bool(id, b"ABEn") == Some(true) || s.obj(id, b"phrp").is_some_and(|p| s.is(p, b"aprp")) {
if class != Tag::of(b"ShpN") {
self.warn("a converted artboard outline (imported at its bounding box)");
}
return Ok(self.artboard(id, world));
}
let Some((local, even_odd)) = crate::geometry::outline(self, id, class, world) else {
self.warn(format!("a {} that could not be read", describe(class)));
return Ok(Kind::Unsupported);
};
let (fills, strokes) = paint::node_paint(self, id, world);
Kind::Shape { path: local.transformed(world), fills, strokes, even_odd }
}
b"TxtA" | b"TxtF" | b"TxtC" => match crate::text::read(self, id, world) {
Some(t) => Kind::Text(t),
None => {
self.warn("text whose story could not be read (master-page text, or an unknown layout)");
Kind::Unsupported
}
},
b"ImgN" | b"Rstr" => match crate::raster::node_image(self, id, world)? {
Some(img) => Kind::Image(img),
None => Kind::Unsupported,
},
b"EmbN" => match crate::raster::embedded(self, id, world)? {
Some(img) => {
self.warn("embedded documents and symbols (imported as pictures of them)");
Kind::Image(img)
}
None => {
self.warn("embedded documents and symbols without a cached picture");
Kind::Unsupported
}
},
b"FRst" => {
// A fill layer paints its whole bitmap area; its gradient lives in page space.
let b = s.obj(id, b"Bitm");
let size = |t: &[u8; 4]| b.and_then(|b| s.int(b, t)).map(|v| v as f64).filter(|v| *v > 0.0);
match (size(b"BmpW"), size(b"BmpH")) {
(Some(w), Some(h)) => {
let local = Path { subpaths: vec![crate::shapes::rectangle(0.0, 0.0, w, h)] };
let fills = paint::fills(self, id, parent, b"BFFl");
Kind::Shape { path: local.transformed(world), fills, strokes: Vec::new(), even_odd: false }
}
_ => {
self.warn("fill layers without an area");
Kind::Unsupported
}
}
}
_ => {
self.warn(format!("{} layers", describe(class)));
Kind::Unsupported
}
})
}
/// Vector shapes attached to a node (`AdCh`) mask it: it shows only inside their outlines;
/// an attached mask layer is a pixel mask. Adjustments attached the same way are reported.
fn attached_masks(&mut self, id: ObjId, world: Affine) -> Result<(Option<Path>, Option<Image>), Error> {
let s = self.s;
// Every occurrence of a shared layer scans its whole attachment array, null slots included.
self.charge_slots(s.array_len(id, b"AdCh").unwrap_or(0))?;
let attached = s.objs(id, b"AdCh");
let mut mask: Option<Path> = None;
let mut pixels: Option<Image> = None;
for a in attached {
let class = s.class(a).unwrap_or(Tag(0));
if s.bool(a, b"Visi") == Some(false) {
continue;
}
if class == Tag::of(b"PCrv") || class == Tag::of(b"ShpN") || class == Tag::of(b"Comp") {
let local = s.floats::<6>(a, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY).then(world);
if let Some((p, _)) = crate::geometry::outline(self, a, class, local) {
mask.get_or_insert_with(Path::default).subpaths.extend(p.transformed(local).subpaths);
}
} else if class == Tag::of(b"MRst") {
let local = s.floats::<6>(a, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY).then(world);
match crate::raster::mask(self, a, local)? {
Some(m) if pixels.is_none() => pixels = Some(m),
Some(_) => self.warn("several pixel masks on one layer (only the first is used)"),
None => {}
}
} else {
self.warn(format!("{} layers attached to other layers (imported without them)", describe(class)));
}
}
Ok((mask, pixels))
}
fn artboard(&mut self, id: ObjId, world: Affine) -> Kind {
let s = self.s;
let b = s.floats::<4>(id, b"ShpB").map(rect).unwrap_or(Rect { x0: 0.0, y0: 0.0, x1: 0.0, y1: 0.0 });
let corners = [Point { x: b.x0, y: b.y0 }, Point { x: b.x1, y: b.y0 }, Point { x: b.x1, y: b.y1 }, Point { x: b.x0, y: b.y1 }].map(|p| world.apply(p));
let [a, b2, c, d, ..] = world.0;
if b2.abs() > 1e-9 || c.abs() > 1e-9 || a <= 0.0 || d <= 0.0 {
self.warn("a rotated or flipped artboard (imported at its bounding box)");
}
let xs = corners.map(|p| p.x);
let ys = corners.map(|p| p.y);
let rect = Rect {
x0: xs.iter().copied().fold(f64::INFINITY, f64::min),
y0: ys.iter().copied().fold(f64::INFINITY, f64::min),
x1: xs.iter().copied().fold(f64::NEG_INFINITY, f64::max),
y1: ys.iter().copied().fold(f64::NEG_INFINITY, f64::max),
};
let background = paint::fills(self, id, world, b"BFFl");
Kind::Artboard { rect, background }
}
}
impl Reader<'_, '_, '_> {
/// Page rectangles: `SpMd.PagR[].rctp` (Publisher 2, Affinity 3) or `SprB` split into `PagC`
/// equal pages (Publisher 1 facing spreads). A spread listed several times, or sharing one
/// large page array, is expanded into a new vector each time, so the slots scanned and the
/// rectangles retained are charged across the document.
fn pages(&mut self, spread: ObjId) -> Result<Vec<Rect>, Error> {
let s = self.s;
if let Some(md) = s.obj(spread, b"SpMd") {
self.charge_slots(s.array_len(md, b"PagR").unwrap_or(0))?;
let remaining = MAX_PAGES.saturating_sub(self.pages);
let v: Vec<Rect> = s
.objs(md, b"PagR")
.into_iter()
.filter_map(|p| s.floats::<4>(p, b"rctp").map(rect))
.filter(|r| r.x1 > r.x0 && r.y1 > r.y0)
.take(remaining.saturating_add(1))
.collect();
if !v.is_empty() {
self.charge_pages(v.len())?;
return Ok(v);
}
}
Ok(match (s.floats::<4>(spread, b"SprB").map(rect), s.int(spread, b"PagC")) {
(Some(b), Some(n @ 2..=16)) => {
self.charge_pages(n as usize)?;
let w = (b.x1 - b.x0) / n as f64;
(0..n).map(|i| Rect { x0: b.x0 + w * i as f64, x1: b.x0 + w * (i + 1) as f64, ..b }).collect()
}
_ => Vec::new(),
})
}
/// Counts retained font-name bytes against [`MAX_FONT_NAME_BYTES`]; false once it is spent.
pub(crate) fn charge_font_name(&mut self, n: usize) -> bool {
self.font_name_bytes = self.font_name_bytes.saturating_add(n);
self.font_name_bytes <= MAX_FONT_NAME_BYTES
}
/// Counts retained page rectangles against [`MAX_PAGES`].
fn charge_pages(&mut self, n: usize) -> Result<(), Error> {
self.pages = self.pages.saturating_add(n);
if self.pages > MAX_PAGES {
return Err(Error::Limit("too many pages"));
}
Ok(())
}
}
pub(crate) fn union(a: Rect, b: Rect) -> Rect {
Rect { x0: a.x0.min(b.x0), y0: a.y0.min(b.y0), x1: a.x1.max(b.x1), y1: a.y1.max(b.y1) }
}
fn is_container(class: Tag) -> bool {
class == Tag::of(b"Scop") || class == Tag::of(b"Grup")
}
pub(crate) fn rect(v: [f64; 4]) -> Rect {
Rect { x0: v[0], y0: v[1], x1: v[2], y1: v[3] }
}
/// A readable name for a layer class in warnings.
pub(crate) fn describe(class: Tag) -> &'static str {
match &class.0.to_be_bytes() {
b"PCrv" => "curve",
b"ShpN" | b"SNEN" | b"SNRR" | b"ShRN" => "shape",
b"Comp" => "compound",
b"Rstr" => "pixel",
b"ImgN" => "image",
b"EmbN" => "embedded document",
b"MPIN" => "master page instance",
b"FRst" => "fill",
b"MRst" => "mask",
b"Slic" | b"SlcP" => "slice",
b"3DLA" => "3D",
[_, _, b'R', b'A'] => "adjustment",
_ => "unknown",
}
}
-417
View File
@@ -1,417 +0,0 @@
//! Fills, strokes and colours. Two schemas exist: Affinity 1 (`BFil` fill, `PFil` stroke paint,
//! `LSty` stroke style) and Affinity 2/3 (`BFFl`, `LIFl` and `LILn` lists with a current index).
use crate::model::{Affine, Reader};
use crate::stream::{ObjId, Value};
/// A colour as stored: RGB and grey values are encoded in the document's RGB space (sRGB unless
/// the document embeds another profile), CMYK values go through its CMYK profile. Alpha is straight.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Color {
Rgb {
r: f64,
g: f64,
b: f64,
a: f64,
},
Cmyk {
c: f64,
m: f64,
y: f64,
k: f64,
a: f64,
},
Gray {
v: f64,
a: f64,
},
/// CIE L*a*b* (D50).
Lab {
l: f64,
a: f64,
b: f64,
alpha: f64,
},
}
impl Color {
pub fn alpha(&self) -> f64 {
match self {
Color::Rgb { a, .. } | Color::Cmyk { a, .. } | Color::Gray { a, .. } => *a,
Color::Lab { alpha, .. } => *alpha,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GradientKind {
Linear,
/// Elliptical and radial: distance from the centre in unit space.
Radial,
/// Angle around the centre.
Conical,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Stop {
pub offset: f64,
pub color: Color,
/// Affinity's midpoint bias for the segment from this stop to the next (0.5 = even blend).
pub bias: f64,
}
impl Stop {
/// Where, between this stop (0) and the next (1), the blend reaches half way: the bias curve
/// fitted to Affinity's renders is `t^k` (bias ≥ 0.5) or `1-(1-t)^k`, with `k = 1 + 8·|bias-0.5|`.
pub fn half_point(&self) -> f64 {
let k = 1.0 + 8.0 * (self.bias - 0.5).abs();
let h = 0.5f64.powf(1.0 / k);
if self.bias >= 0.5 { h } else { 1.0 - h }
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Gradient {
pub kind: GradientKind,
pub stops: Vec<Stop>,
/// Unit space to document pixels: linear runs from unit (0,0) to (1,0); radial is the unit
/// circle; conical starts along unit +x and turns towards unit +y.
pub transform: Affine,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub enum Paint {
#[default]
None,
Solid(Color),
Gradient(Gradient),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Cap {
Butt,
Round,
Square,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Join {
Miter,
Round,
Bevel,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Align {
Center,
Inside,
Outside,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Stroke {
pub paint: Paint,
/// Width in document pixels.
pub width: f64,
pub cap: Cap,
pub join: Join,
pub miter_limit: f64,
pub align: Align,
/// Dash and gap lengths in document pixels, and the phase.
pub dash: Option<(Vec<f64>, f64)>,
/// Painted below the fill instead of above it.
pub behind: bool,
}
/// Gradient stops per gradient.
const MAX_STOPS: usize = 1024;
/// Dash and gap lengths per stroke. Affinity's editor offers three dash/gap pairs; a longer
/// pattern would be copied into every shape that shares its style.
const MAX_DASHES: usize = 64;
/// The first `n` components of a float vector or packed `f32` record. Colours and gradient
/// positions use a few leading components; a shared colour with a huge record is decoded for
/// every occurrence, so the rest is neither converted nor copied.
fn floats(v: &Value, n: usize) -> Option<Vec<f64>> {
match v {
Value::Floats(f) => Some(f.iter().take(n).copied().collect()),
Value::Bytes(b) if b.len() % 4 == 0 => Some(f32_samples(b, n)),
_ => None,
}
}
/// Up to `n` little-endian `f32` samples widened to `f64`.
fn f32_samples(b: &[u8], n: usize) -> Vec<f64> {
b.as_chunks::<4>().0.iter().take(n).map(|c| f64::from(f32::from_le_bytes(*c))).collect()
}
/// Spot colours defined through spot colours. A spot colour (`Pant`) is read through its RGB
/// equivalent, else its base colour, which in real files hold plain colours. Colours are shared
/// objects, so one can link to itself, and with both links followed at every level a colour read
/// costs up to 2^(depth+1) lookups.
const MAX_SPOT_DEPTH: usize = 4;
/// A colour object (`RGBA`, `HSLA`, `CMYK`, `GRAY`, `LABA`, `Pant`).
pub(crate) fn color(r: &mut Reader, id: ObjId) -> Option<Color> {
color_at(r, id, 0)
}
/// [`color`] of an object `depth` spot colours down.
fn color_at(r: &mut Reader, id: ObjId, depth: usize) -> Option<Color> {
let s = r.s;
let class = s.class(id)?;
// `n` is how many components the model reads; only those are decoded and checked.
let col = |n: usize| -> Option<Vec<f64>> {
let v = floats(s.field(id, b"_col")?, n)?;
v.iter().all(|f| f.is_finite()).then_some(v)
};
Some(match &class.0.to_be_bytes() {
b"RGBA" => {
let v = col(4)?;
Color::Rgb { r: *v.first()?, g: *v.get(1)?, b: *v.get(2)?, a: v.get(3)?.clamp(0.0, 1.0) }
}
b"HSLA" => {
let v = col(4)?;
let (r2, g, b) = hsl(*v.first()?, *v.get(1)?, *v.get(2)?);
Color::Rgb { r: r2, g, b, a: v.get(3)?.clamp(0.0, 1.0) }
}
b"CMYK" => {
let v = col(5)?;
Color::Cmyk { c: *v.first()?, m: *v.get(1)?, y: *v.get(2)?, k: *v.get(3)?, a: v.get(4)?.clamp(0.0, 1.0) }
}
b"GRAY" => {
let v = col(2)?;
Color::Gray { v: *v.first()?, a: v.get(1)?.clamp(0.0, 1.0) }
}
b"LABA" => {
let b = s.bytes(id, b"_col")?;
let u = |i: usize| -> Option<f64> { Some(f64::from(u16::from_le_bytes([*b.get(2 * i)?, *b.get(2 * i + 1)?])) / 65535.0) };
Color::Lab { l: 100.0 * u(0)?, a: 255.0 * u(1)? - 128.0, b: 255.0 * u(2)? - 128.0, alpha: u(3)? }
}
b"Pant" => {
if depth >= MAX_SPOT_DEPTH {
r.warn("spot colours nested deeper than 4 levels (left empty)");
return None;
}
r.warn("spot colours (imported as their RGB equivalent)");
return s.obj(id, b"srgb").and_then(|c| color_at(r, c, depth + 1)).or_else(|| s.obj(id, b"base").and_then(|c| color_at(r, c, depth + 1)));
}
b"RegC" => Color::Cmyk { c: 1.0, m: 1.0, y: 1.0, k: 1.0, a: 1.0 },
_ => {
r.warn("colours in an unknown model");
return None;
}
})
}
fn hsl(h: f64, s: f64, l: f64) -> (f64, f64, f64) {
let c = (1.0 - (2.0 * l - 1.0).abs()) * s;
let hp = (h.rem_euclid(1.0)) * 6.0;
let x = c * (1.0 - (hp % 2.0 - 1.0).abs());
let (r, g, b) = match hp as u32 {
0 => (c, x, 0.0),
1 => (x, c, 0.0),
2 => (0.0, c, x),
3 => (0.0, x, c),
4 => (x, 0.0, c),
_ => (c, 0.0, x),
};
let m = l - c / 2.0;
(r + m, g + m, b + m)
}
/// A fill descriptor (`FDsc`) or, in Affinity 1 files, a bare `FilS`; `local` maps the node's
/// space to document pixels.
pub(crate) fn descriptor(r: &mut Reader, id: ObjId, local: Affine) -> Option<Paint> {
let s = r.s;
let (fill, unit) = if s.is(id, b"FDsc") {
let unit = s.floats::<6>(id, b"FDeX").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY);
(s.obj(id, b"FDeF")?, unit)
} else {
(id, Affine::IDENTITY)
};
match &s.class(fill)?.0.to_be_bytes() {
b"FilN" => Some(Paint::None),
b"FilS" => Some(Paint::Solid(color(r, s.obj(fill, b"Colr")?)?)),
b"FilG" => {
let kind = match s.enumeration(fill, b"Type").map(|(i, _)| i) {
Some(0) | None => GradientKind::Linear,
Some(1 | 2) => GradientKind::Radial,
Some(3) => GradientKind::Conical,
Some(_) => {
r.warn("gradients of an unknown kind (imported as linear)");
GradientKind::Linear
}
};
let grad = s.obj(fill, b"Grad")?;
// A shared gradient is decoded again for every occurrence: charge the arrays scanned
// and copy only as many positions as there are stops to keep.
if r.charge_slots(s.array_len(grad, b"Cols").unwrap_or(0).saturating_add(s.array_len(grad, b"Posn").unwrap_or(0))).is_err() {
r.warn("gradients beyond the document work budget (left empty)");
return Some(Paint::None);
}
let cols = s.objs(grad, b"Cols");
let posn: Vec<Vec<f64>> = match s.field(grad, b"Posn") {
// A position is (offset, bias): later components are not decoded.
Some(Value::Array(a)) => a.iter().filter_map(|v| floats(v, 2)).take(MAX_STOPS).collect(),
Some(Value::Records { size, data }) if *size % 4 == 0 && *size > 0 => {
data.chunks_exact(usize::from(*size)).map(|b| f32_samples(b, 2)).take(MAX_STOPS).collect()
}
_ => Vec::new(),
};
let mut stops = Vec::new();
for (c, p) in cols.iter().zip(&posn).take(MAX_STOPS) {
let color = color(r, *c)?;
let offset = p.first().copied().filter(|v| v.is_finite()).unwrap_or(0.0).clamp(0.0, 1.0);
let bias = p.get(1).copied().filter(|v| v.is_finite()).unwrap_or(0.5).clamp(0.0, 1.0);
stops.push(Stop { offset, color, bias });
}
if stops.is_empty() {
return Some(Paint::None);
}
Some(Paint::Gradient(Gradient { kind, stops, transform: unit.then(local) }))
}
b"FilB" => {
r.warn("bitmap and pattern fills (left empty)");
Some(Paint::None)
}
_ => {
r.warn("fills of an unknown kind (left empty)");
Some(Paint::None)
}
}
}
/// The active entry of a paint list (the `index`-th object, else the first) and how many
/// objects the list holds. Every raw slot, null ones included, is charged before the list is
/// walked: a shared layer's lists are read again for each occurrence. A list beyond the
/// document's work budget reads as empty.
fn current(r: &mut Reader, id: ObjId, list: &[u8; 4], index: &[u8; 4]) -> (Option<ObjId>, usize) {
let s = r.s;
let Some(Value::Array(items)) = s.field(id, list) else { return (None, 0) };
if r.charge_slots(items.len()).is_err() {
r.warn("fill and stroke lists beyond the document work budget (left empty)");
return (None, 0);
}
let want = s.int(id, index).and_then(|i| usize::try_from(i).ok()).unwrap_or(0);
let (mut first, mut chosen, mut count) = (None, None, 0usize);
for o in items.iter().filter_map(|v| if let Value::Obj(Some(o)) = v { Some(*o) } else { None }) {
first = first.or(Some(o));
if count == want {
chosen = Some(o);
}
count += 1;
}
(chosen.or(first), count)
}
/// The fills of `list` (artboard backgrounds use `BFFl`).
pub(crate) fn fills(r: &mut Reader, id: ObjId, local: Affine, list: &[u8; 4]) -> Vec<crate::paint::Paint> {
fills_counted(r, id, local, list).0
}
/// [`fills`], and how many entries `list` holds.
fn fills_counted(r: &mut Reader, id: ObjId, local: Affine, list: &[u8; 4]) -> (Vec<Paint>, usize) {
let (d, count) = current(r, id, list, b"BFCr");
let d = d.or_else(|| r.s.obj(id, b"BFil"));
(d.and_then(|d| descriptor(r, d, local)).filter(|p| *p != Paint::None).into_iter().collect(), count)
}
/// A node's fill and stroke. `local` maps the node's space to document pixels.
pub(crate) fn node_paint(r: &mut Reader, id: ObjId, local: Affine) -> (Vec<Paint>, Vec<Stroke>) {
let s = r.s;
let (fills, fill_count) = fills_counted(r, id, local, b"BFFl");
let (pen, style, pen_count) = if s.field(id, b"LIFl").is_some() {
let (pen, pens) = current(r, id, b"LIFl", b"LICr");
(pen, current(r, id, b"LILn", b"LICr").0, pens)
} else {
(s.obj(id, b"PFil"), s.obj(id, b"LSty"), 0)
};
if fill_count > 1 || pen_count > 1 {
r.warn("several fills or strokes on one object (only the active one is imported)");
}
if s.f64(id, b"FOpc").is_some_and(|o| o < 0.999) {
r.warn("fill opacity (imported at full fill opacity)");
}
if s.obj(id, b"Trns").is_some() {
r.warn("transparency gradients (imported without them)");
}
let behind = matches!(s.field(id, b"DrwO"), Some(Value::Array(a)) if a.first() == Some(&Value::Enum { id: 1, version: 0 }));
let stroke = match (pen, style) {
(Some(pen), Some(style)) => stroke(r, pen, style, local, behind),
_ => None,
};
(fills, stroke.into_iter().collect())
}
fn stroke(r: &mut Reader, pen: ObjId, ldsc: ObjId, local: Affine, behind: bool) -> Option<Stroke> {
let s = r.s;
let paint = descriptor(r, pen, local)?;
if paint == Paint::None {
return None;
}
let lsty = if s.is(ldsc, b"LDsc") { s.obj(ldsc, b"LDeL")? } else { ldsc };
let weight = s.f64(lsty, b"Wght").filter(|w| *w > 0.0 && *w < 1e7)?;
// "Scale with object": the weight follows the object's transform; otherwise it is absolute.
let scales = s.bool(ldsc, b"LDSc").unwrap_or(true);
let width = if scales { weight * local.scale() } else { weight };
let data = s.bytes(lsty, b"Data").unwrap_or_default();
let miter_limit = data.get(0..8).and_then(|b| b.try_into().ok()).map(f64::from_le_bytes).filter(|m| m.is_finite() && *m >= 1.0).unwrap_or(4.0);
// Cap and join bytes are only partly understood: (0, 0) is butt/miter in every clean sample;
// (2, 2) ends plain lines square and brush lines round; joins import round, which never
// looks wrong.
let (cap, join) = match (data.get(8).copied(), data.get(9).copied(), data.get(10).copied()) {
(Some(0), Some(0), _) => (Cap::Butt, Join::Miter),
(Some(0), Some(_), _) => (Cap::Butt, Join::Round),
(Some(2), Some(2), Some(3)) => (Cap::Round, Join::Round),
(Some(2), Some(2), _) => (Cap::Square, Join::Round),
_ => (Cap::Round, Join::Round),
};
let align = match s.int(ldsc, b"LDSa") {
Some(1) => Align::Inside,
Some(2) => Align::Outside,
_ => Align::Center,
};
let dash = match s.field(lsty, b"Patn") {
// Each occurrence of a shared style keeps its own scaled copy: refuse long patterns
// before scanning or copying them.
Some(Value::Array(a)) if a.len() > MAX_DASHES => {
r.warn("dash patterns longer than 64 entries (imported as solid strokes)");
None
}
// The copies are retained across the document: charge them like other shared slots.
Some(Value::Array(a)) if r.charge_slots(a.len()).is_err() => {
r.warn("dash patterns beyond the document work budget (imported as solid strokes)");
None
}
Some(Value::Array(a)) if data.get(10) == Some(&2) || !a.is_empty() => {
let mut v: Vec<f64> = a.iter().filter_map(|x| if let Value::Float(f) = x { Some(*f) } else { None }).collect();
while v.len() >= 2 && v.iter().rev().take(2).all(|x| *x == 0.0) {
v.truncate(v.len() - 2);
}
let valid = !v.is_empty() && v.iter().all(|x| x.is_finite() && *x >= 0.0) && v.iter().any(|x| *x > 0.0);
valid.then(|| (v.iter().map(|x| x * width).collect(), s.f64(lsty, b"Phse").unwrap_or(0.0) * width))
}
_ => None,
};
if s.obj(lsty, b"Brus").is_some() || s.obj(ldsc, b"LDeP").is_some() {
r.warn("brush and pressure strokes (imported as plain strokes)");
}
Some(Stroke { paint, width, cap, join, miter_limit, align, dash, behind })
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_the_components_a_schema_reads_are_decoded() {
// A 64 KiB record decodes to the four components asked for, not sixteen thousand.
let record = Value::Bytes(1.0f32.to_le_bytes().repeat(16_383));
assert_eq!(floats(&record, 4), Some(vec![1.0; 4]));
assert_eq!(floats(&Value::Floats(vec![0.5; 6]), 2), Some(vec![0.5; 2]));
// Fewer components than asked for are returned as they are, for the caller to refuse.
assert_eq!(floats(&Value::Floats(vec![0.5; 3]), 5), Some(vec![0.5; 3]));
assert_eq!(floats(&Value::Bytes(vec![0; 3]), 4), None);
}
}
-124
View File
@@ -1,124 +0,0 @@
//! The indexed PNG thumbnail Affinity stores next to the archive: Affinity's own render of the
//! document, at most 512 pixels on the long side in real files, never the document itself.
use crate::Error;
use crate::container::header;
pub const MAX_PREVIEW_BYTES: usize = 16 << 20;
pub const MAX_PREVIEW_DIMENSION: u32 = 4096;
/// Borrowed embedded thumbnail, at its own dimensions, never the native document dimensions.
#[derive(Debug)]
pub struct Preview<'a> {
pub png: &'a [u8],
pub width: u32,
pub height: u32,
}
fn bytes_at(bytes: &[u8], offset: usize, length: usize) -> Result<&[u8], Error> {
let end = offset.checked_add(length).ok_or(Error::Malformed("offset overflow"))?;
bytes.get(offset..end).ok_or(Error::Malformed("truncated record"))
}
fn le32(bytes: &[u8], offset: usize) -> Result<u32, Error> {
let b = bytes_at(bytes, offset, 4)?;
Ok(u32::from_le_bytes(b.try_into().map_err(|_| Error::Malformed("integer"))?))
}
fn be32(bytes: &[u8], offset: usize) -> Result<u32, Error> {
let b = bytes_at(bytes, offset, 4)?;
Ok(u32::from_be_bytes(b.try_into().map_err(|_| Error::Malformed("PNG integer"))?))
}
/// Read only the indexed `Thmb` record (identical in container versions 8 to 12), checking every PNG chunk CRC. Compressed
/// pixels must still be validated by the consuming image decoder, with allocation limits.
pub fn preview(bytes: &[u8]) -> Result<Preview<'_>, Error> {
let h = header(bytes)?;
if h.thumbnail_offset == 0 {
return Err(Error::Unsupported("no embedded preview"));
}
let offset = usize::try_from(h.thumbnail_offset).map_err(|_| Error::Malformed("thumbnail offset overflow"))?;
if offset < 72 {
return Err(Error::Malformed("thumbnail overlaps the file header"));
}
let record = bytes.get(offset..).ok_or(Error::Malformed("thumbnail offset outside file"))?;
if bytes_at(record, 0, 8)? != b"\xff\xff\xff\xffThmb" {
return Err(Error::Malformed("missing indexed thumbnail"));
}
if le32(record, 8)? != 1 || bytes_at(record, 28, 1)? != [1] {
return Err(Error::Unsupported("thumbnail record version or encoding"));
}
let size = usize::try_from(le32(record, 24)?).map_err(|_| Error::Limit("encoded size"))?;
if size > MAX_PREVIEW_BYTES {
return Err(Error::Limit("encoded preview exceeds 16 MiB"));
}
if le32(record, 16)? != 29 || le32(record, 20)? != 0 || u64::from(le32(record, 12)?) != size as u64 + 13 {
return Err(Error::Malformed("inconsistent thumbnail record lengths"));
}
let png = bytes_at(record, 29, size)?;
if bytes_at(png, 0, 8)? != b"\x89PNG\r\n\x1a\n" || be32(png, 8)? != 13 || bytes_at(png, 12, 4)? != b"IHDR" {
return Err(Error::Malformed("thumbnail is not a PNG"));
}
let width = be32(png, 16)?;
let height = be32(png, 20)?;
if width == 0 || height == 0 || width > MAX_PREVIEW_DIMENSION || height > MAX_PREVIEW_DIMENSION {
return Err(Error::Limit("preview dimensions must be 1..4096"));
}
// Bound work by bytes, not a file-supplied chunk count, and require exactly one complete PNG.
let mut pos = 8usize;
let (mut palette, mut image_data, mut image_data_ended) = (false, false, false);
loop {
let length = usize::try_from(be32(png, pos)?).map_err(|_| Error::Limit("PNG chunk length"))?;
let chunk_size = length.checked_add(12).ok_or(Error::Malformed("PNG chunk overflow"))?;
let chunk = bytes_at(png, pos, chunk_size)?;
let checksum_input = bytes_at(chunk, 4, chunk_size - 8)?;
if crc32fast::hash(checksum_input) != be32(chunk, chunk_size - 4)? {
return Err(Error::Malformed("PNG chunk checksum"));
}
let kind = bytes_at(chunk, 4, 4)?;
if !kind.iter().all(u8::is_ascii_alphabetic) {
return Err(Error::Malformed("PNG chunk type"));
}
match kind {
b"IHDR" if pos == 8 => {}
b"IHDR" => return Err(Error::Malformed("duplicate PNG header")),
b"PLTE" => {
if palette || image_data {
return Err(Error::Malformed("PNG palette order"));
}
palette = true;
}
b"IDAT" => {
if image_data_ended {
return Err(Error::Malformed("non-contiguous PNG image data"));
}
image_data = true;
}
b"IEND" if !image_data => return Err(Error::Malformed("PNG has no image data")),
b"IEND" => {}
_ if kind.first().is_some_and(u8::is_ascii_uppercase) => {
return Err(Error::Unsupported("unknown critical PNG chunk"));
}
_ => {}
}
if image_data && kind != b"IDAT" {
image_data_ended = true;
}
// Native sample previews are plain, single-frame PNGs. Pixel allocation limits do not
// necessarily bound aggregate compressed metadata; leave these layouts unsupported.
if matches!(kind, b"zTXt" | b"iTXt" | b"iCCP") {
return Err(Error::Unsupported("compressed PNG metadata in the preview"));
}
if matches!(kind, b"acTL" | b"fcTL" | b"fdAT") {
return Err(Error::Unsupported("animated PNG preview"));
}
pos = pos.checked_add(chunk_size).ok_or(Error::Malformed("PNG offset overflow"))?;
if kind == b"IEND" {
if length != 0 || pos != png.len() {
return Err(Error::Malformed("PNG end or trailing data"));
}
break;
}
}
Ok(Preview { png, width, height })
}
-263
View File
@@ -1,263 +0,0 @@
//! Pixel layers (`Rstr`) and placed images (`ImgN`). A placed image keeps its original file
//! (`DyBm.Bckg` → archive entry `c/N`), which is imported as is; other pixels are planar tiles of
//! 256 bytes × 256 rows per channel, each its own archive entry.
use std::collections::HashMap;
use crate::Error;
use crate::model::{Affine, Image, Pixels, Reader};
use crate::stream::{self, ObjId, Tag, Value};
/// Pixels decoded per layer (the content's bounding box, not the canvas).
const MAX_PIXELS: u64 = 64 << 20;
const TILE: usize = 256;
const TILE_BYTES: usize = TILE * TILE;
pub(crate) fn node_image(r: &mut Reader, id: ObjId, world: Affine) -> Result<Option<Image>, Error> {
let s = r.s;
let Some(bitmap) = s.obj(id, b"Bitm") else {
r.warn("pixel layers without pixels");
return Ok(None);
};
if !s.is(bitmap, b"DyBm") {
r.warn("pixel layers stored in an unknown way");
return Ok(None);
}
let width = s.int(bitmap, b"BmpW").and_then(|v| u32::try_from(v).ok()).unwrap_or(0);
let height = s.int(bitmap, b"BmpH").and_then(|v| u32::try_from(v).ok()).unwrap_or(0);
if width == 0 || height == 0 {
return Ok(None);
}
// A placed image: the original file, byte for byte.
let has_tiles = s.field(bitmap, b"Sta1").is_some();
if let Some(name) = s.entry(bitmap, b"Bckg").filter(|n| !n.is_empty())
&& (s.is(id, b"ImgN") || !has_tiles)
{
match original(r, name) {
Ok(bytes) => return Ok(Some(Image { width, height, pixels: Pixels::Encoded(bytes), transform: world })),
Err(Error::Limit(e)) => return Err(Error::Limit(e)),
Err(_) => r.warn("an embedded image file that could not be read (its cached pixels were used)"),
}
}
// The content's bounding box, so a mostly empty canvas-sized layer stays small.
let crop = s
.field(id, b"BitR")
.and_then(|v| if let Value::Ints(i) = v { Some(i.clone()) } else { None })
.filter(|v| v.len() == 4 && v[0] > i64::from(i32::MIN) + 1)
.map(|v| {
(
v[0].clamp(0, i64::from(width)) as u32,
v[1].clamp(0, i64::from(height)) as u32,
v[2].clamp(0, i64::from(width)) as u32,
v[3].clamp(0, i64::from(height)) as u32,
)
})
.unwrap_or((0, 0, width, height));
if s.field(bitmap, b"Bckg").is_some() && has_tiles && !s.is(id, b"ImgN") {
r.warn("edited placed images use their stored pixels");
}
decode(r, bitmap, crop, world)
}
/// A mask layer (`MRst`): one channel of coverage as grey pixels (white shows, black hides).
pub(crate) fn mask(r: &mut Reader, id: ObjId, world: Affine) -> Result<Option<Image>, Error> {
let s = r.s;
let Some(bitmap) = s.obj(id, b"Bitm") else { return Ok(None) };
let width = s.int(bitmap, b"BmpW").and_then(|v| u32::try_from(v).ok()).unwrap_or(0);
let height = s.int(bitmap, b"BmpH").and_then(|v| u32::try_from(v).ok()).unwrap_or(0);
if width == 0 || height == 0 || !matches!(s.enumeration(bitmap, b"Frmt"), Some((6 | 7, _))) {
r.warn("pixel masks in an unknown format (imported without them)");
return Ok(None);
}
decode(r, bitmap, (0, 0, width, height), world)
}
/// An embedded document or symbol instance (`EmbN`), as the picture of it Affinity caches.
pub(crate) fn embedded(r: &mut Reader, id: ObjId, world: Affine) -> Result<Option<Image>, Error> {
let s = r.s;
let Some(cache) = s.obj(id, b"Bitm").and_then(|e| s.obj(e, b"Cach")) else { return Ok(None) };
let Some(bbox) = s.obj(id, b"Bitm").and_then(|e| s.floats::<4>(e, b"ChBB")) else { return Ok(None) };
let width = s.int(cache, b"BmpW").and_then(|v| u32::try_from(v).ok()).unwrap_or(0);
let height = s.int(cache, b"BmpH").and_then(|v| u32::try_from(v).ok()).unwrap_or(0);
if width == 0 || height == 0 {
return Ok(None);
}
let [x0, y0, x1, y1] = bbox;
// The instance's origin is the centre of the embedded content (checked against the
// thumbnails of documents with embedded documents and SVG files).
let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
let place = Affine([(x1 - x0) / f64::from(width), 0.0, 0.0, (y1 - y0) / f64::from(height), x0 - cx, y0 - cy]).then(world);
decode(r, cache, (0, 0, width, height), place)
}
/// Decode the tiles of a bitmap inside `crop` (pixels), placed by `world` (bitmap pixels to document).
fn decode(r: &mut Reader, bitmap: ObjId, crop: (u32, u32, u32, u32), world: Affine) -> Result<Option<Image>, Error> {
let s = r.s;
let (x0, y0, x1, y1) = crop;
if x1 <= x0 || y1 <= y0 {
return Ok(None);
}
let (w, h) = (x1 - x0, y1 - y0);
if u64::from(w) * u64::from(h) > MAX_PIXELS {
r.warn("pixel layers larger than 64 megapixels");
return Ok(None);
}
let format = s.enumeration(bitmap, b"Frmt").map(|(f, _)| f);
let (channels, bps) = match format {
Some(0) => (4, 1),
Some(1) => (4, 2),
Some(6) => (1, 1),
Some(7) => (1, 2),
Some(4) => {
r.warn("CMYK pixel layers (converted to RGB without the document's colour profile)");
(5, 1)
}
_ => {
r.warn("pixel layers in grey, Lab or 32-bit formats");
return Ok(None);
}
};
// A layer is materialized from its declared size, whatever the tiles hold: admit the output
// and the planes it decodes through before either is allocated (#4960).
let pixels = (w as usize).checked_mul(h as usize).ok_or(Error::Limit("pixel layer size"))?;
let scratch = pixels.checked_mul(channels * bps).ok_or(Error::Limit("pixel layer size"))?;
r.admit_pixels(pixels.checked_mul(4).ok_or(Error::Limit("pixel layer size"))?, scratch)?;
let mut planes = Vec::with_capacity(channels);
let mut cache = HashMap::new();
for c in 1..=channels {
planes.push(plane(r, bitmap, c, bps, (x0, y0, w, h), &mut cache)?);
}
let n = (w as usize) * (h as usize);
let mut rgba = vec![0u8; n * 4];
let sample = |p: &Vec<u8>, i: usize| -> f64 {
if bps == 2 {
f64::from(u16::from_le_bytes([p.get(2 * i).copied().unwrap_or(0), p.get(2 * i + 1).copied().unwrap_or(0)])) / 65535.0
} else {
f64::from(p.get(i).copied().unwrap_or(0)) / 255.0
}
};
for (i, px) in rgba.as_chunks_mut::<4>().0.iter_mut().enumerate() {
let v: Vec<f64> = planes.iter().map(|p| sample(p, i)).collect();
let (r2, g, b, a) = if channels == 1 {
(v[0], v[0], v[0], 1.0)
} else if channels == 5 {
let k = 1.0 - v[3];
((1.0 - v[0]) * k, (1.0 - v[1]) * k, (1.0 - v[2]) * k, v[4])
} else {
(v[0], v[1], v[2], v[3])
};
px.copy_from_slice(&[r2, g, b, a].map(|c| (c.clamp(0.0, 1.0) * 255.0).round() as u8));
}
let transform = Affine([1.0, 0.0, 0.0, 1.0, f64::from(x0), f64::from(y0)]).then(world);
Ok(Some(Image { width: w, height: h, pixels: Pixels::Rgba8(rgba), transform }))
}
/// The original image file: entry `c/N` is a stream whose root (`Blck`) holds it as `Data`.
fn original(r: &mut Reader, name: &str) -> Result<Vec<u8>, Error> {
let bytes = r.archive.read(name)?;
let s = stream::parse(&bytes)?;
let root = s.object(s.root).ok_or(Error::Malformed("embedded image"))?;
match root.get(Tag::of(b"Data")) {
Some(Value::Blob(b)) if !b.is_empty() => Ok(b.clone()),
_ => Err(Error::Malformed("embedded image without data")),
}
}
fn tag(prefix: &[u8; 3], c: usize) -> [u8; 4] {
[prefix[0], prefix[1], prefix[2], b'0' + c as u8]
}
/// One channel of level 0, cropped to (x0, y0, w, h) pixels; `bps` bytes per sample.
fn plane(
r: &mut Reader,
bitmap: ObjId,
c: usize,
bps: usize,
(x0, y0, w, h): (u32, u32, u32, u32),
cache: &mut HashMap<String, Vec<u8>>,
) -> Result<Vec<u8>, Error> {
let s = r.s;
let width = s.int(bitmap, b"BmpW").and_then(|v| usize::try_from(v).ok()).unwrap_or(0);
let height = s.int(bitmap, b"BmpH").and_then(|v| usize::try_from(v).ok()).unwrap_or(0);
let tw = s.int(bitmap, &tag(b"TWi", c)).and_then(|v| usize::try_from(v).ok()).unwrap_or_else(|| (width * bps).div_ceil(TILE));
let th = s.int(bitmap, &tag(b"THi", c)).and_then(|v| usize::try_from(v).ok()).unwrap_or_else(|| height.div_ceil(TILE));
// Borrow the file-controlled arrays: collecting the whole state array first costs its full
// length on every occurrence of a shared layer, however small the declared grid is.
let states: &[Value] = match s.field(bitmap, &tag(b"Sta", c)) {
Some(Value::Array(a)) => a,
_ => &[],
};
// Tile references in order. Null slots are skipped, but every slot walked (null or not) is
// charged below, so a shared bitmap's long null prefix is not rescanned for free.
let mut tiles: &[Value] = match s.field(bitmap, &tag(b"Idx", c)) {
Some(Value::Array(a)) => a,
_ => &[],
};
// The scan below runs for every occurrence of a shared bitmap, whatever it produces.
r.charge_slots(states.len().min(tw.saturating_mul(th)))?;
let row = (w as usize) * bps;
let mut out = vec![0u8; row * h as usize];
let (bx0, bx1) = (x0 as usize * bps, (x0 + w) as usize * bps);
let (py0, py1) = (y0 as usize, (y0 + h) as usize);
for (t, state) in states.iter().enumerate().take(tw.saturating_mul(th)) {
let state = &if let Value::UInt(u) = state { u8::try_from(*u).unwrap_or(255) } else { 255 };
let (ty, tx) = (t / tw.max(1), t % tw.max(1));
let fill = match state {
0 | 1 => None,
2 => Some(0xFF),
4 => {
let Some(at) = tiles.iter().position(|v| matches!(v, Value::Obj(Some(_)))) else {
r.charge_slots(tiles.len())?;
return Err(Error::Malformed("missing pixel tile"));
};
r.charge_slots(at + 1)?;
let Some(Value::Obj(Some(blck))) = tiles.get(at) else { return Err(Error::Malformed("missing pixel tile")) };
let blck = *blck;
tiles = tiles.get(at + 1..).unwrap_or_default();
let (ox, oy) = (tx * TILE, ty * TILE);
if ox >= bx1 || ox + TILE <= bx0 || oy >= py1 || oy + TILE <= py0 {
continue;
}
let name = s.entry(blck, b"Data").ok_or(Error::Malformed("pixel tile without data"))?.to_string();
if !cache.contains_key(&name) {
let mut data = r.archive.read(&name)?;
// Older files wrap a tile in a one-field stream: header, then a 64 KiB blob.
if data.len() == TILE_BYTES + 22 && data.starts_with(b"\x00\xffKS") {
data = data.get(21..21 + TILE_BYTES).ok_or(Error::Malformed("pixel tile"))?.to_vec();
}
if data.len() != TILE_BYTES {
return Err(Error::Malformed("pixel tile size"));
}
cache.insert(name.clone(), data);
}
let tile = cache.get(&name).ok_or(Error::Malformed("pixel tile"))?;
copy(&mut out, row, (bx0, py0, bx1, py1), (ox, oy), |x, y| tile.get(y * TILE + x).copied().unwrap_or(0));
continue;
}
3 => {
r.warn("32-bit pixel layers");
None
}
5 => {
r.warn("pixel layers drawn from an embedded image (left empty)");
None
}
_ => return Err(Error::Malformed("unknown pixel tile state")),
};
if let Some(v) = fill {
copy(&mut out, row, (bx0, py0, bx1, py1), (tx * TILE, ty * TILE), |_, _| v);
}
}
Ok(out)
}
/// Copy the overlap of a tile at byte column `ox`, row `oy` into the cropped plane.
fn copy(out: &mut [u8], row: usize, (bx0, py0, bx1, py1): (usize, usize, usize, usize), (ox, oy): (usize, usize), at: impl Fn(usize, usize) -> u8) {
for y in oy.max(py0)..(oy + TILE).min(py1) {
for x in ox.max(bx0)..(ox + TILE).min(bx1) {
if let Some(b) = out.get_mut((y - py0) * row + (x - bx0)) {
*b = at(x - ox, y - oy);
}
}
}
}
-484
View File
@@ -1,484 +0,0 @@
//! Parametric shapes: Affinity stores the shape's parameters and its box, never the outline.
//! Formulas were fitted to Affinity's own renders (the document thumbnails) of public files.
use std::f64::consts::{FRAC_PI_2, PI, TAU};
use crate::model::{Affine, Path, Point, Reader, SubPath};
use crate::stream::{ObjId, Tag, Value};
/// Handle length of a quarter circle of radius 1.
const KAPPA: f64 = 0.552_284_749_830_793_4;
/// Vertices of a polygon or star.
const MAX_SIDES: i64 = 10_000;
/// The last value of a tag: a shape changed from one kind to another keeps a stale first block.
/// Indexed: a shared shape is read again for every occurrence, and rescanning a large field
/// list each time multiplied into work far beyond the file's size.
fn last<'a>(r: &'a Reader, id: ObjId, tag: &[u8; 4]) -> Option<&'a Value> {
r.s.object(id)?.get_last(Tag::of(tag))
}
fn num(r: &Reader, id: ObjId, tag: &[u8; 4]) -> Option<f64> {
match last(r, id, tag)? {
Value::Float(f) if f.is_finite() => Some(*f),
Value::UInt(u) => Some(*u as f64),
Value::Int(i) => Some(*i as f64),
_ => None,
}
}
fn sides(r: &Reader, id: ObjId, tag: &[u8; 4], default: f64) -> usize {
let n = num(r, id, tag).unwrap_or(default).round();
n.clamp(3.0, MAX_SIDES as f64) as usize
}
fn pt(x: f64, y: f64) -> Point {
Point { x, y }
}
fn polygon(pts: impl IntoIterator<Item = Point>) -> Option<SubPath> {
let mut it = pts.into_iter();
let start = it.next()?;
let segments = it.map(|p| [p, p, p]).collect();
Some(SubPath { start, segments, closed: true })
}
/// Outline of `shape` (a `Shpe` object) in the node box `b` = (x0, y0, x1, y1).
pub(crate) fn shape(r: &mut Reader, shape: ObjId, b: [f64; 4], world: Affine) -> Option<(Path, bool)> {
let [x0, y0, x1, y1] = b;
let (w, h) = (x1 - x0, y1 - y0);
let (cx, cy, rx, ry) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0, w / 2.0, h / 2.0);
let on_ellipse = |a: f64, f: f64| pt(cx + f * rx * a.cos(), cy + f * ry * a.sin());
let class = r.s.class(shape)?;
let sub = match &class.0.to_be_bytes() {
b"ShNR" | b"ShRR" => {
// Only the four corners are read: a longer array is not scanned or copied, which
// would otherwise repeat for every occurrence of a shared shape.
let types: Vec<Option<u16>> = match last(r, shape, b"CTyp") {
Some(Value::Array(a)) => a.iter().take(4).map(|t| if let Value::Enum { id, .. } = t { Some(*id) } else { None }).collect(),
_ => Vec::new(),
};
let radii: Vec<f64> = match last(r, shape, b"ShCR") {
Some(Value::Floats(v)) => v.iter().take(4).map(|f| if f.is_finite() && *f > 0.0 { *f } else { 0.0 }).collect(),
_ => Vec::new(),
};
// Corners follow the first one (top left) unless they were unlocked; then each has
// its own radius and type, clockwise from the top left.
let locked = !matches!(last(r, shape, b"Lock"), Some(Value::Bool(false)));
let corners: [(f64, Option<u16>); 4] = std::array::from_fn(|i| {
let i = if locked { 0 } else { i };
(radii.get(i).copied().unwrap_or(0.0), types.get(i).copied().flatten())
});
if types.is_empty() || corners.iter().all(|(f, _)| *f == 0.0) {
polygon([pt(x0, y0), pt(x1, y0), pt(x1, y1), pt(x0, y1)])?
} else {
if corners.iter().any(|(f, t)| *f > 0.0 && !matches!(t, Some(0 | 1 | 4))) {
r.warn("rectangles with concave or other corner types (imported with round corners)");
}
let absolute = r.s.bool(shape, b"AbSz") == Some(true);
let [a, b2, c, d, ..] = world.0;
let (sx, sy) = ((a * a + b2 * b2).sqrt(), (c * c + d * d).sqrt());
cornered_rect(
b,
corners.map(|(f, t)| {
let (crx, cry) = if !absolute {
(f * w.min(h), f * w.min(h))
} else if sx > 0.0 && sy > 0.0 {
// An absolute radius is in document pixels, whatever the node's scale.
(f / sx, f / sy)
} else {
(0.0, 0.0)
};
(crx, cry, t == Some(1))
}),
)
}
}
b"ShpE" => ellipse(cx, cy, rx, ry),
b"ShPy" => {
let n = sides(r, shape, b"Side", 5.0);
let a = |i: usize| -FRAC_PI_2 + TAU * i as f64 / n as f64;
if r.s.object(shape).is_some_and(|_| matches!(last(r, shape, b"Smth"), Some(Value::Bool(true)))) {
// Smoothed: tangent handles of length curv·4/3·tan(π/2n) along the inscribed ellipse.
let k = num(r, shape, b"Curv").unwrap_or(0.0) * 4.0 / 3.0 * (PI / (2.0 * n as f64)).tan();
let v = |i: usize| on_ellipse(a(i), 1.0);
let t = |i: usize| pt(-rx * a(i).sin(), ry * a(i).cos());
let segments = (0..n)
.map(|i| {
let (p, q, tp, tq) = (v(i), v(i + 1), t(i), t(i + 1));
[pt(p.x + k * tp.x, p.y + k * tp.y), pt(q.x - k * tq.x, q.y - k * tq.y), q]
})
.collect();
SubPath { start: v(0), segments, closed: true }
} else {
polygon((0..n).map(|i| on_ellipse(a(i), 1.0)))?
}
}
b"ShSt" => {
let n = sides(r, shape, b"Pnts", 5.0);
let q = num(r, shape, b"IRad").unwrap_or(0.382).clamp(0.0, 1.0);
if [b"CrcI", b"CrcO", b"CrvL", b"CrvR"].iter().any(|t| num(r, shape, t).is_some_and(|v| v.abs() > 1e-9)) {
r.warn("stars with rounded or curved points (imported with sharp points)");
}
polygon((0..2 * n).map(|i| on_ellipse(-FRAC_PI_2 + PI * i as f64 / n as f64, if i % 2 == 0 { 1.0 } else { q })))?
}
b"ShSS" => {
let n = sides(r, shape, b"Side", 5.0);
let ri = num(r, shape, b"COut").unwrap_or(0.5).clamp(0.0, 1.0);
let step = PI / n as f64;
let (l, hw, inner) = (step.cos(), ri * step.sin(), ri * step.cos());
polygon((0..n).flat_map(|k| {
let phi = -FRAC_PI_2 + step + TAU * k as f64 / n as f64;
let (c, s) = (phi.cos(), phi.sin());
[(inner, -hw), (l, -hw), (l, hw), (inner, hw)].map(|(u, v)| pt(cx + rx * (u * c - v * s), cy + ry * (u * s + v * c)))
}))?
}
b"ShPi" => {
let raw_start = num(r, shape, b"AngS").unwrap_or(0.0);
let raw_end = num(r, shape, b"AngE").unwrap_or(TAU);
// Normalize in constant time. Repeatedly adding TAU can hang on finite values
// large enough that floating-point addition no longer changes the endpoint.
let start = raw_start.rem_euclid(TAU);
let delta = raw_end - raw_start;
let sweep = if raw_end >= raw_start {
delta.min(TAU)
} else if delta.is_finite() {
delta.rem_euclid(TAU)
} else {
(raw_end.rem_euclid(TAU) - start).rem_euclid(TAU)
};
let inner = num(r, shape, b"IRad").unwrap_or(0.0).clamp(0.0, 1.0);
pie(cx, cy, rx, ry, start, start + sweep, inner)
}
b"ShpT" => {
let p = num(r, shape, b"Pos ").unwrap_or(0.5);
polygon([pt(x0 + p * w, y0), pt(x1, y1), pt(x0, y1)])?
}
b"ShTz" => {
let (l, rr) = (num(r, shape, b"PosL").unwrap_or(0.25), num(r, shape, b"PosR").unwrap_or(0.75));
polygon([pt(x0 + l * w, y0), pt(x0 + rr * w, y0), pt(x1, y1), pt(x0, y1)])?
}
b"ShCl" => cloud(cx, cy, rx, ry, sides(r, shape, b"Bubl", 12.0)),
b"ShHt" => heart(b),
b"ShCg" => cog(r, shape, cx, cy, rx, ry),
b"ShCR" => callout_rect(r, shape, b, false),
b"ShCE" => callout_ellipse(r, shape, cx, cy, rx, ry),
b"ShDA" => arrow(r, shape, b),
b"ShDS" => double_star(r, shape, cx, cy, rx, ry),
b"ShTr" => tear(r, shape, b),
b"ShCr" => crescent(cx, cy, rx, ry),
b"ShpD" => polygon([pt(cx, y0), pt(x1, cy), pt(cx, y1), pt(x0, cy)])?,
b"ShSg" => segment(r, shape, cx, cy, rx, ry),
_ => {
r.warn("an unrecognized parametric shape (imported as its bounding ellipse)");
ellipse(cx, cy, rx, ry)
}
};
let mut path = Path { subpaths: vec![sub] };
if class == Tag::of(b"ShCg") {
let hole = num(r, shape, b"Hole").unwrap_or(0.3).clamp(0.0, 0.9);
if hole > 0.0 {
path.subpaths.push(ellipse(cx, cy, rx * hole, ry * hole));
}
return Some((path, true));
}
Some((path, false))
}
fn cloud(cx: f64, cy: f64, rx: f64, ry: f64, bubbles: usize) -> SubPath {
let n = bubbles.clamp(3, 128) * 4;
let points: Vec<Point> = (0..n)
.map(|i| {
let a = TAU * i as f64 / n as f64 - FRAC_PI_2;
let lobe = (0.5 - 0.5 * (TAU * i as f64 / 4.0).cos()).powi(2);
let radius = 0.78 + 0.22 * lobe;
pt(cx + rx * radius * a.cos(), cy + ry * radius * a.sin())
})
.collect();
let segments = (0..n)
.map(|i| {
let p0 = points[(i + n - 1) % n];
let p1 = points[i];
let p2 = points[(i + 1) % n];
let p3 = points[(i + 2) % n];
[pt(p1.x + (p2.x - p0.x) / 6.0, p1.y + (p2.y - p0.y) / 6.0), pt(p2.x - (p3.x - p1.x) / 6.0, p2.y - (p3.y - p1.y) / 6.0), p2]
})
.collect();
SubPath { start: points[0], segments, closed: true }
}
fn heart([x0, y0, x1, y1]: [f64; 4]) -> SubPath {
let (w, h) = (x1 - x0, y1 - y0);
let p = |x: f64, y: f64| pt(x0 + x * w, y0 + y * h);
let start = p(0.5, 0.92);
let segments = vec![
[p(0.38, 0.85), p(0.04, 0.67), p(0.04, 0.37)],
[p(0.04, 0.02), p(0.39, 0.00), p(0.5, 0.27)],
[p(0.61, 0.00), p(0.96, 0.02), p(0.96, 0.37)],
[p(0.96, 0.67), p(0.62, 0.85), start],
];
SubPath { start, segments, closed: true }
}
fn cog(r: &Reader, shape: ObjId, cx: f64, cy: f64, rx: f64, ry: f64) -> SubPath {
let teeth = sides(r, shape, b"Teth", 12.0);
let tooth = num(r, shape, b"TtSz").unwrap_or(0.3).clamp(0.05, 0.9);
let notch = num(r, shape, b"NtSz").unwrap_or(0.45).clamp(0.05, 0.95);
let tip = 1.0;
let root = (1.0 - 0.2 * tooth - 0.08 * notch).clamp(0.55, 0.95);
let mut pts = Vec::with_capacity(teeth * 4);
for i in 0..teeth {
let base = TAU * i as f64 / teeth as f64 - FRAC_PI_2;
for (offset, radius) in [(-0.5, root), (-0.32, tip), (0.32, tip), (0.5, root)] {
let a = base + offset * TAU / teeth as f64;
pts.push(pt(cx + rx * radius * a.cos(), cy + ry * radius * a.sin()));
}
}
polygon(pts).unwrap_or_else(|| rectangle_sub(cx - rx, cy - ry, cx + rx, cy + ry))
}
fn callout_rect(r: &Reader, shape: ObjId, [x0, y0, x1, y1]: [f64; 4], _ellipse: bool) -> SubPath {
let (w, h) = (x1 - x0, y1 - y0);
let tail_h = num(r, shape, b"TlHg").unwrap_or(0.2).clamp(0.0, 0.8) * h;
let tail_w = num(r, shape, b"TlWd").unwrap_or(0.1).clamp(0.02, 0.8) * w;
let tip_x = x0 + num(r, shape, b"TlRP").unwrap_or(0.5).clamp(0.0, 1.0) * w;
let base_x = x0 + num(r, shape, b"TlEP").unwrap_or(0.4).clamp(0.0, 1.0) * w;
let a = (base_x - tail_w / 2.0).clamp(x0, x1);
let c = (base_x + tail_w / 2.0).clamp(x0, x1);
let body_bottom = y1 - tail_h;
let radius = (w.min(body_bottom - y0) * 0.12).max(0.0);
// The three contours overlap inside the fill; no internal edge is visible in a filled shape.
// Join the tail to the rounded body in one closed outline to avoid a seam in stroked shapes.
let start = pt(x0 + radius, y0);
let segments = vec![
[pt(x1 - radius, y0), pt(x1 - radius, y0), pt(x1 - radius, y0)],
[pt(x1 - (1.0 - KAPPA) * radius, y0), pt(x1, y0 + (1.0 - KAPPA) * radius), pt(x1, y0 + radius)],
[pt(x1, body_bottom - radius), pt(x1, body_bottom - radius), pt(x1, body_bottom - radius)],
[pt(x1, body_bottom), pt(x1, body_bottom), pt(x1 - radius, body_bottom)],
[pt(c + radius * 0.2, body_bottom), pt(tip_x, y1 - tail_h * 0.15), pt(tip_x, y1)],
[pt(tip_x, y1), pt(tip_x, y1), pt(tip_x, y1)],
[pt(tip_x, y1 - tail_h * 0.15), pt(a - radius * 0.2, body_bottom), pt(a, body_bottom)],
[pt(x0 + radius, body_bottom), pt(x0, body_bottom), pt(x0, body_bottom - radius)],
[pt(x0, y0 + radius), pt(x0, y0 + radius), pt(x0, y0 + radius)],
[pt(x0, y0 + (1.0 - KAPPA) * radius), pt(x0 + (1.0 - KAPPA) * radius, y0), start],
];
SubPath { start, segments, closed: true }
}
fn callout_ellipse(r: &Reader, shape: ObjId, cx: f64, cy: f64, rx: f64, ry: f64) -> SubPath {
let tail_h = num(r, shape, b"TlHg").unwrap_or(0.2).clamp(0.0, 0.8);
let pos = num(r, shape, b"TlEP").unwrap_or(0.25).clamp(0.0, 1.0);
let angle = num(r, shape, b"TlAn").unwrap_or(0.0);
let a0 = pos * TAU - angle;
let a1 = a0 + 0.35;
let start = pt(cx + rx * a1.cos(), cy + ry * a1.sin());
let end = pt(cx + rx * a0.cos(), cy + ry * a0.sin());
let tip = pt(cx + rx * (a0 + 0.18).cos() * 1.08, cy + ry * (a0 + 0.18).sin() * (1.0 + tail_h));
// A single ellipse-like outline with a short triangular tail at its lower edge.
let mut segments = Vec::new();
arc(cx, cy, rx, ry, a1, a0 + TAU, &mut segments);
segments.push([end, end, tip]);
segments.push([tip, tip, start]);
SubPath { start, segments, closed: true }
}
fn arrow(r: &Reader, shape: ObjId, [x0, y0, x1, y1]: [f64; 4]) -> SubPath {
let h = y1 - y0;
let thick = num(r, shape, b"Thck").unwrap_or(0.35).clamp(0.05, 0.9) * h;
let shaft = (y0 + y1 - thick) / 2.0;
let lower = shaft + thick;
let head_start = x1 - h * 0.45;
polygon([pt(x0, shaft), pt(head_start, shaft), pt(head_start, y0), pt(x1, (y0 + y1) / 2.0), pt(head_start, y1), pt(head_start, lower), pt(x0, lower)])
.unwrap_or_else(|| rectangle_sub(x0, shaft, x1, lower))
}
fn double_star(r: &Reader, shape: ObjId, cx: f64, cy: f64, rx: f64, ry: f64) -> SubPath {
let n = sides(r, shape, b"Pnts", 6.0).saturating_mul(2).clamp(8, 64);
let inner = num(r, shape, b"IRad").unwrap_or(0.6).clamp(0.05, 0.95);
let outer = num(r, shape, b"PRad").unwrap_or(0.9).clamp(0.2, 1.0);
polygon((0..2 * n).map(|i| {
let a = -FRAC_PI_2 + PI * i as f64 / n as f64;
let radius = if i % 2 == 0 { outer } else { outer * inner };
pt(cx + rx * radius * a.cos(), cy + ry * radius * a.sin())
}))
.unwrap_or_else(|| rectangle_sub(cx - rx, cy - ry, cx + rx, cy + ry))
}
fn tear(r: &Reader, shape: ObjId, [x0, y0, x1, y1]: [f64; 4]) -> SubPath {
let (w, h) = (x1 - x0, y1 - y0);
let bulge = num(r, shape, b"Ball").unwrap_or(0.25).clamp(0.0, 0.5);
let bend = num(r, shape, b"Bend").unwrap_or(0.0).clamp(-0.5, 0.5);
let top = pt((x0 + x1) / 2.0, y0);
let bottom = pt((x0 + x1) / 2.0 + bend * w * 0.25, y1);
let segments = vec![
[pt(x0 + w * 0.25, y0 + h * 0.42), pt(x0 + w * (0.5 - bulge), y1 - h * 0.03), bottom],
[pt(x1 - w * (0.5 - bulge), y1 - h * 0.03), pt(x1 - w * 0.25, y0 + h * 0.42), top],
];
SubPath { start: top, segments, closed: true }
}
fn crescent(cx: f64, cy: f64, rx: f64, ry: f64) -> SubPath {
let start = pt(cx, cy - ry);
let mut segments = Vec::new();
arc(cx, cy, rx, ry, -FRAC_PI_2, -3.0 * FRAC_PI_2, &mut segments);
// The inner arc returns from the lower tip to the upper tip, leaving a crescent open to the right.
let ix = cx + rx * 0.72;
let irx = rx * 0.86;
let iry = ry * 0.82;
let from = pt(ix, cy + iry);
segments.push([from, from, from]);
let mut inner = Vec::new();
arc(ix, cy, irx, iry, FRAC_PI_2, -FRAC_PI_2, &mut inner);
segments.extend(inner);
SubPath { start, segments, closed: true }
}
fn segment(r: &Reader, shape: ObjId, cx: f64, cy: f64, rx: f64, ry: f64) -> SubPath {
// Keep hostile but finite angles in a small range before constructing arc controls.
let angle = num(r, shape, b"Angl").unwrap_or(0.0).rem_euclid(TAU);
let p0 = num(r, shape, b"Pos0").unwrap_or(0.25).clamp(0.0, 1.0);
let p1 = num(r, shape, b"Pos1").unwrap_or(0.75).clamp(0.0, 1.0);
let a0 = angle + (p0 - 0.5) * TAU;
let mut a1 = angle + (p1 - 0.5) * TAU;
while a1 < a0 {
a1 += TAU;
}
let mut segments = Vec::new();
arc(cx, cy, rx, ry, a0, a1.min(a0 + TAU), &mut segments);
let start = pt(cx + rx * a0.cos(), cy + ry * a0.sin());
let end = pt(cx + rx * a1.cos(), cy + ry * a1.sin());
segments.push([end, end, start]);
SubPath { start, segments, closed: true }
}
fn rectangle_sub(x0: f64, y0: f64, x1: f64, y1: f64) -> SubPath {
rectangle(x0, y0, x1, y1)
}
pub(crate) fn rectangle(x0: f64, y0: f64, x1: f64, y1: f64) -> SubPath {
SubPath { start: pt(x0, y0), segments: [pt(x1, y0), pt(x1, y1), pt(x0, y1)].map(|p| [p, p, p]).to_vec(), closed: true }
}
fn ellipse(cx: f64, cy: f64, rx: f64, ry: f64) -> SubPath {
let (kx, ky) = (KAPPA * rx, KAPPA * ry);
SubPath {
start: pt(cx + rx, cy),
segments: vec![
[pt(cx + rx, cy + ky), pt(cx + kx, cy + ry), pt(cx, cy + ry)],
[pt(cx - kx, cy + ry), pt(cx - rx, cy + ky), pt(cx - rx, cy)],
[pt(cx - rx, cy - ky), pt(cx - kx, cy - ry), pt(cx, cy - ry)],
[pt(cx + kx, cy - ry), pt(cx + rx, cy - ky), pt(cx + rx, cy)],
],
closed: true,
}
}
/// A rectangle whose corners (top left, top right, bottom right, bottom left) are each rounded,
/// or cut straight across, by their (horizontal, vertical) radii. Two radii that don't fit along
/// one side shrink in proportion until they do.
fn cornered_rect([x0, y0, x1, y1]: [f64; 4], corners: [(f64, f64, bool); 4]) -> SubPath {
let fit = |r: f64, pair: f64, side: f64| if pair > side { side * (r / pair) } else { r };
let [tl, tr, br, bl] = corners;
let (w, h) = (x1 - x0, y1 - y0);
let rx = [fit(tl.0, tl.0 + tr.0, w), fit(tr.0, tl.0 + tr.0, w), fit(br.0, bl.0 + br.0, w), fit(bl.0, bl.0 + br.0, w)];
let ry = [fit(tl.1, tl.1 + bl.1, h), fit(tr.1, tr.1 + br.1, h), fit(br.1, tr.1 + br.1, h), fit(bl.1, tl.1 + bl.1, h)];
let (kx, ky) = (rx.map(|r| (1.0 - KAPPA) * r), ry.map(|r| (1.0 - KAPPA) * r));
// (where the corner leaves the previous side, its two handles, where it joins the next side)
let arcs = [
[pt(x1 - rx[1], y0), pt(x1 - kx[1], y0), pt(x1, y0 + ky[1]), pt(x1, y0 + ry[1])],
[pt(x1, y1 - ry[2]), pt(x1, y1 - ky[2]), pt(x1 - kx[2], y1), pt(x1 - rx[2], y1)],
[pt(x0 + rx[3], y1), pt(x0 + kx[3], y1), pt(x0, y1 - ky[3]), pt(x0, y1 - ry[3])],
[pt(x0, y0 + ry[0]), pt(x0, y0 + ky[0]), pt(x0 + kx[0], y0), pt(x0 + rx[0], y0)],
];
let mut segments = Vec::with_capacity(8);
for ([s, c1, c2, e], straight) in arcs.into_iter().zip([tr.2, br.2, bl.2, tl.2]) {
segments.push([s, s, s]);
if s != e {
segments.push(if straight { [e, e, e] } else { [c1, c2, e] });
}
}
SubPath { start: pt(x0 + rx[0], y0), segments, closed: true }
}
/// Elliptical arc from angle `a0` to `a1` (radians, measured y-up as Affinity's pie angles are),
/// as cubic segments of at most a quarter turn.
fn arc(cx: f64, cy: f64, rx: f64, ry: f64, a0: f64, a1: f64, out: &mut Vec<[Point; 3]>) {
let n = ((a1 - a0).abs() / FRAC_PI_2).ceil().clamp(1.0, 8.0) as usize;
let step = (a1 - a0) / n as f64;
let k = 4.0 / 3.0 * (step / 4.0).tan();
let p = |a: f64| pt(cx + rx * a.cos(), cy - ry * a.sin());
let d = |a: f64| pt(-rx * a.sin(), -ry * a.cos());
for i in 0..n {
let (s, e) = (a0 + step * i as f64, a0 + step * (i + 1) as f64);
let (ps, pe, ds, de) = (p(s), p(e), d(s), d(e));
out.push([pt(ps.x + k * ds.x, ps.y + k * ds.y), pt(pe.x - k * de.x, pe.y - k * de.y), pe]);
}
}
fn pie(cx: f64, cy: f64, rx: f64, ry: f64, a0: f64, a1: f64, inner: f64) -> SubPath {
let start = pt(cx + rx * a0.cos(), cy - ry * a0.sin());
let mut segments = Vec::new();
arc(cx, cy, rx, ry, a0, a1, &mut segments);
if inner > 0.0 {
let p = pt(cx + inner * rx * a1.cos(), cy - inner * ry * a1.sin());
segments.push([p, p, p]);
arc(cx, cy, inner * rx, inner * ry, a1, a0, &mut segments);
} else {
let c = pt(cx, cy);
segments.push([c, c, c]);
}
SubPath { start, segments, closed: true }
}
/// A polyline with circular corners of the given radii (Affinity's live corners on curves).
pub(crate) fn fillet(pts: &[(Point, f64)], closed: bool) -> SubPath {
let n = pts.len();
let get = |i: isize| -> Option<Point> {
if closed { pts.get(i.rem_euclid(n as isize) as usize).map(|p| p.0) } else { usize::try_from(i).ok().and_then(|i| pts.get(i)).map(|p| p.0) }
};
let mut corners: Vec<(Point, Point, Point, Point)> = Vec::with_capacity(n);
for (i, (p, radius)) in pts.iter().enumerate() {
let (prev, next) = (get(i as isize - 1), get(i as isize + 1));
let (Some(a), Some(b)) = (prev, next) else {
corners.push((*p, *p, *p, *p));
continue;
};
let (u1, l1) = unit(*p, a);
let (u2, l2) = unit(*p, b);
let cos = (u1.x * u2.x + u1.y * u2.y).clamp(-1.0, 1.0);
let phi = cos.acos();
if *radius <= 0.0 || phi < 1e-6 || (PI - phi) < 1e-6 {
corners.push((*p, *p, *p, *p));
continue;
}
let t = (radius / (phi / 2.0).tan()).min(l1 / 2.0).min(l2 / 2.0);
let r = t * (phi / 2.0).tan();
let k = 4.0 / 3.0 * ((PI - phi) / 4.0).tan() * r;
let s = pt(p.x + u1.x * t, p.y + u1.y * t);
let e = pt(p.x + u2.x * t, p.y + u2.y * t);
corners.push((s, pt(s.x - u1.x * k, s.y - u1.y * k), pt(e.x - u2.x * k, e.y - u2.y * k), e));
}
let Some(first) = corners.first().copied() else { return SubPath { start: pt(0.0, 0.0), segments: vec![], closed } };
let mut segments = Vec::with_capacity(2 * n);
let mut cur = first.0;
let start = cur;
for (i, (s, c1, c2, e)) in corners.iter().enumerate() {
if i > 0 {
segments.push([cur, *s, *s]);
}
if s != e {
segments.push([*c1, *c2, *e]);
}
cur = *e;
}
if closed && cur != start {
segments.push([cur, start, start]);
}
SubPath { start, segments, closed }
}
fn unit(from: Point, to: Point) -> (Point, f64) {
let (dx, dy) = (to.x - from.x, to.y - from.y);
let l = (dx * dx + dy * dy).sqrt();
if l > 0.0 { (pt(dx / l, dy / l), l) } else { (pt(0.0, 0.0), 0.0) }
}
-484
View File
@@ -1,484 +0,0 @@
//! The tagged object stream inside `doc.dat`: a self-describing tree of objects whose fields carry
//! a type code and a four-character tag. Parsing needs no schema; unknown fields are kept, so the
//! document mapping can name what it could not import.
use crate::Error;
use crate::container::Cursor;
/// A four-character tag in its readable order (`Desc`, `Chld`).
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Tag(pub u32);
impl Tag {
pub const fn of(s: &[u8; 4]) -> Self {
Self(u32::from_be_bytes(*s))
}
}
impl std::fmt::Debug for Tag {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", String::from_utf8_lossy(&self.0.to_be_bytes()))
}
}
impl std::fmt::Display for Tag {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Debug::fmt(self, f)
}
}
/// Index of an object in [`Stream::objects`].
pub type ObjId = usize;
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
Int(i64),
UInt(u64),
Float(f64),
Bool(bool),
Enum {
id: u16,
version: u16,
},
Str(String),
/// Fixed-length vectors of i32/f32/f64 (points, rectangles, transforms).
Ints(Vec<i64>),
Floats(Vec<f64>),
/// Fixed-size record (curve nodes, ids) or fixed-size struct (colour components).
Bytes(Vec<u8>),
Blob(Vec<u8>),
/// Name of another archive entry (raster tiles, embedded files).
Entry(String),
Flags(u64),
/// `None` is a null object.
Obj(Option<ObjId>),
Array(Vec<Value>),
/// An array of fixed-size records (`0x2c`, curve nodes) held in one buffer: `size` bytes each.
/// Counts as one value per record against [`MAX_VALUES`], like the array of `Bytes` it replaces.
Records {
size: u16,
data: Vec<u8>,
},
}
impl Value {
/// Slot count of an array field (including null slots); `None` for a scalar.
pub fn array_len(&self) -> Option<usize> {
match self {
Value::Array(a) => Some(a.len()),
Value::Records { size, data } => Some(data.len() / usize::from(*size).max(1)),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
Root,
/// Defined once and referenced by id elsewhere.
Shared,
Inline,
/// Untagged fields identified by position (curve data).
Positional,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Object {
pub class: Tag,
pub kind: Kind,
/// Class chain, most derived first (`ShpN`, `VNod`, `Node`).
pub chain: Vec<Tag>,
/// Fields in stream order; positional fields have tag 0.
pub fields: Vec<(Tag, Value)>,
/// Index for objects with more than [`SCAN`] fields: (tag, index of its first occurrence,
/// index of its last occurrence) sorted by tag, so `get` and `get_last` are a binary search.
/// A shared object can be referenced by many sibling layers, and each reference used to
/// rescan all of its fields; indexing once keeps repeated lookups from multiplying into
/// quadratic work. Smaller objects have no index (and no per-object hash map to build):
/// scanning a handful of fields is cheaper.
index: Vec<(Tag, u32, u32)>,
}
/// Objects with at most this many fields are scanned instead of indexed.
const SCAN: usize = 12;
fn build_index(fields: &[(Tag, Value)]) -> Vec<(Tag, u32, u32)> {
if fields.len() <= SCAN {
return Vec::new();
}
// Positional fields share tag 0 and are not looked up by tag. Sorting by (tag, index) puts
// each tag's occurrences together in stream order: the first and last of each run keep
// first-match semantics for `get` and last-match semantics for `get_last`.
let mut index: Vec<(Tag, u32, u32)> = fields.iter().zip(0u32..).filter(|((t, _), _)| t.0 != 0).map(|((t, _), i)| (*t, i, i)).collect();
index.sort_unstable();
index.dedup_by(|later, kept| {
let same = later.0 == kept.0;
if same {
kept.2 = later.2;
}
same
});
index
}
impl Object {
pub fn new(class: Tag, kind: Kind, chain: Vec<Tag>, fields: Vec<(Tag, Value)>) -> Self {
let index = build_index(&fields);
Object { class, kind, chain, fields, index }
}
pub fn get(&self, tag: Tag) -> Option<&Value> {
if tag.0 == 0 {
return None;
}
if self.fields.len() <= SCAN {
return self.fields.iter().find(|(t, _)| *t == tag).map(|(_, v)| v);
}
let at = self.index.binary_search_by_key(&tag, |e| e.0).ok()?;
self.index.get(at).and_then(|&(_, i, _)| self.fields.get(i as usize)).map(|(_, v)| v)
}
/// The last field with `tag`, for objects that may repeat a tag (a shape changed from one
/// kind to another keeps a stale first block). Indexed like [`Object::get`], so repeated
/// lookups on a large shared object do not rescan its fields.
pub fn get_last(&self, tag: Tag) -> Option<&Value> {
if tag.0 == 0 {
return None;
}
if self.fields.len() <= SCAN {
return self.fields.iter().rev().find(|(t, _)| *t == tag).map(|(_, v)| v);
}
let at = self.index.binary_search_by_key(&tag, |e| e.0).ok()?;
self.index.get(at).and_then(|&(_, _, i)| self.fields.get(i as usize)).map(|(_, v)| v)
}
/// Replaces the fields (the root object is filled in after it is pushed) and rebuilds the
/// tag index so `get` stays correct.
fn set_fields(&mut self, fields: Vec<(Tag, Value)>) {
self.index = build_index(&fields);
self.fields = fields;
}
}
#[derive(Debug)]
pub struct Stream {
pub root: ObjId,
pub objects: Vec<Object>,
}
/// Deepest object nesting accepted; real documents stay well below (each layer level adds three).
pub const MAX_DEPTH: usize = 384;
const MAX_OBJECTS: usize = 8_000_000;
/// Most values (fields and array elements) one stream may decode. A value takes about 40 bytes
/// in memory however few it took in the file (a bool array packs eight in a byte), so the size
/// of the input alone doesn't bound what parsing allocates: a small compressed entry could
/// otherwise ask for tens of gigabytes. Real documents stay far below.
pub const MAX_VALUES: usize = 1 << 24;
struct Parser<'a> {
c: Cursor<'a>,
objects: Vec<Object>,
/// Shared ids, defined at first use and referenced backwards.
shared: std::collections::HashMap<u32, ObjId>,
depth: usize,
/// Values decoded so far, against [`MAX_VALUES`].
values: usize,
}
/// Parse a stream (`00 FF 4B 53` header). Bytes after the root's terminator are ignored.
pub fn parse(bytes: &[u8]) -> Result<Stream, Error> {
let mut c = Cursor::new(bytes, 0);
if c.take(4)? != b"\x00\xffKS" {
return Err(Error::Malformed("document stream signature"));
}
let version = c.u16()?;
if version > 2 {
return Err(Error::Unsupported("document stream version"));
}
let class = Tag(c.u32()?);
c.u16()?;
if version == 2 {
c.u32()?;
}
let mut p = Parser { c, objects: Vec::new(), shared: std::collections::HashMap::new(), depth: 0, values: 0 };
let root = p.push(Object::new(class, Kind::Root, vec![class], Vec::new()))?;
let fields = p.fields(true, class)?;
if let Some(o) = p.objects.get_mut(root) {
o.set_fields(fields);
}
Ok(Stream { root, objects: p.objects })
}
impl Parser<'_> {
fn push(&mut self, o: Object) -> Result<ObjId, Error> {
if self.objects.len() >= MAX_OBJECTS {
return Err(Error::Limit("too many objects"));
}
self.objects.push(o);
Ok(self.objects.len() - 1)
}
/// Counts `n` more values against [`MAX_VALUES`], before anything is allocated for them.
fn spend(&mut self, n: usize) -> Result<(), Error> {
self.values = self.values.checked_add(n).filter(|&v| v <= MAX_VALUES).ok_or(Error::Limit("too many values in the document stream"))?;
Ok(())
}
/// An empty array with room for `n` values, paid for first; an allocation that still fails
/// is an error, not an abort.
fn vec<T>(&mut self, n: usize) -> Result<Vec<T>, Error> {
self.spend(n)?;
let mut v = Vec::new();
v.try_reserve_exact(n).map_err(|_| Error::Limit("not enough memory for the document stream"))?;
Ok(v)
}
/// Element count of an array: each element takes at least `min` bytes, so a count the
/// remaining input cannot hold is rejected before anything is allocated.
fn count(&mut self, min: usize) -> Result<usize, Error> {
let n = usize::try_from(self.c.u32()?).map_err(|_| Error::Malformed("array length"))?;
if n.checked_mul(min.max(1)).is_none_or(|bytes| bytes > self.c.remaining()) {
return Err(Error::Malformed("array longer than its data"));
}
Ok(n)
}
fn fields(&mut self, tagged: bool, class: Tag) -> Result<Vec<(Tag, Value)>, Error> {
self.depth += 1;
if self.depth > MAX_DEPTH {
return Err(Error::Limit("objects nested too deeply"));
}
let mut out = Vec::new();
loop {
let t = self.c.u8()?;
let code = t & 0x7F;
if code == 0 {
break;
}
self.spend(1)?;
let tag = if tagged { Tag(self.c.u32()?) } else { Tag(0) };
let v = if t & 0x80 != 0 { self.array(code, class)? } else { self.scalar(code, tagged, class)? };
out.push((tag, v));
}
self.depth -= 1;
Ok(out)
}
fn string(&mut self) -> Result<String, Error> {
let n = usize::try_from(self.c.u32()?).map_err(|_| Error::Malformed("string length"))?;
Ok(String::from_utf8_lossy(self.c.take(n)?).into_owned())
}
fn floats(&mut self, n: usize, wide: bool) -> Result<Value, Error> {
let mut v = Vec::with_capacity(n);
for _ in 0..n {
v.push(if wide { f64::from_le_bytes(self.c.array()?) } else { f64::from(f32::from_le_bytes(self.c.array()?)) });
}
Ok(Value::Floats(v))
}
fn scalar(&mut self, code: u8, tagged: bool, class: Tag) -> Result<Value, Error> {
let c = &mut self.c;
Ok(match code {
0x01 => Value::UInt(c.u8()?.into()),
0x02 => Value::UInt(c.u16()?.into()),
0x03 | 0x2f | 0x34 => Value::UInt(c.u32()?.into()),
0x04 => Value::UInt(c.u64()?),
0x05 => Value::Int(i8::from_le_bytes(c.array()?).into()),
0x06 => Value::Int(i16::from_le_bytes(c.array()?).into()),
0x07 => Value::Int(i32::from_le_bytes(c.array()?).into()),
0x08 => Value::Int(i64::from_le_bytes(c.array()?)),
0x09 => Value::Float(f32::from_le_bytes(c.array()?).into()),
0x0a => Value::Float(f64::from_le_bytes(c.array()?)),
0x15..=0x19 => {
let n = usize::from(code - 0x13);
let mut v = Vec::with_capacity(n);
for _ in 0..n {
v.push(i32::from_le_bytes(c.array()?).into());
}
Value::Ints(v)
}
0x1f..=0x23 => return self.floats(usize::from(code - 0x1d), false),
0x24..=0x28 => return self.floats(usize::from(code - 0x22), true),
0x29 => Value::Bool(c.u8()? != 0),
0x2a => Value::Enum { id: c.u16()?, version: c.u16()? },
0x2b | 0x2e => Value::Str(self.string()?),
0x2c => {
let n = usize::from(c.u16()?);
Value::Bytes(c.take(n)?.to_vec())
}
0x35..=0x74 => Value::Bytes(c.take(usize::from(code - 0x34))?.to_vec()),
0x2d => {
let n = usize::try_from(c.u32()?).map_err(|_| Error::Malformed("blob length"))?;
Value::Blob(c.take(n)?.to_vec())
}
0x33 => {
c.u32()?;
let n = usize::try_from(c.u32()?).map_err(|_| Error::Malformed("entry name length"))?;
Value::Entry(String::from_utf8_lossy(c.take(n)?).into_owned())
}
0x75 => {
c.u16()?;
let n = usize::from(c.u8()?);
if n > 8 {
return Err(Error::Malformed("flags wider than 64 bits"));
}
let mut b = [0u8; 8];
b.get_mut(..n).ok_or(Error::Malformed("flags"))?.copy_from_slice(c.take(n)?);
Value::Flags(u64::from_le_bytes(b))
}
0x30 => {
let fields = self.fields(false, class)?;
let id = self.push(Object::new(class, Kind::Positional, Vec::new(), fields))?;
Value::Obj(Some(id))
}
0x31 | 0x32 if !tagged => return Err(Error::Malformed("object without a field tag")),
0x31 => self.shared()?,
0x32 => self.inline(None)?,
_ => return Err(Error::Unsupported("unknown field type in document stream")),
})
}
fn array(&mut self, code: u8, class: Tag) -> Result<Value, Error> {
let min = match code {
0x01 | 0x05 | 0x29 => 1,
0x02 | 0x06 => 2,
0x03 | 0x07 | 0x09 | 0x2f | 0x34 => 4,
0x04 | 0x08 | 0x0a => 8,
0x15..=0x19 => 4 * usize::from(code - 0x13),
0x1f..=0x23 => 4 * usize::from(code - 0x1d),
0x24..=0x28 => 8 * usize::from(code - 0x22),
0x35..=0x74 => usize::from(code - 0x34),
_ => 1,
};
match code {
0x29 => {
let n = usize::try_from(self.c.u32()?).map_err(|_| Error::Malformed("array length"))?;
let bits = self.c.take(n.div_ceil(8))?;
let mut v = self.vec(n)?;
v.extend((0..n).map(|i| Value::Bool(bits.get(i / 8).is_some_and(|b| b >> (i % 8) & 1 != 0))));
Ok(Value::Array(v))
}
0x2a => {
let n = self.count(2)?;
let version = self.c.u16()?;
let mut v = self.vec(n)?;
for _ in 0..n {
v.push(Value::Enum { id: self.c.u16()?, version });
}
Ok(Value::Array(v))
}
0x2b | 0x2e => {
self.c.u32()?;
let n = self.count(4)?;
let mut v = self.vec(n)?;
for _ in 0..n {
v.push(Value::Str(self.string()?));
}
Ok(Value::Array(v))
}
0x2c => {
let n = usize::try_from(self.c.u32()?).map_err(|_| Error::Malformed("array length"))?;
let size = usize::from(self.c.u16()?);
// A zero width passes the length check for any count, then costs a Value per record.
if size == 0 || n.checked_mul(size).is_none_or(|b| b > self.c.remaining()) {
return Err(Error::Malformed("array longer than its data"));
}
// Still one value per record against the budget, but a single allocation.
self.spend(n)?;
let bytes = self.c.take(n * size)?;
let mut data = Vec::new();
data.try_reserve_exact(bytes.len()).map_err(|_| Error::Limit("not enough memory for the document stream"))?;
data.extend_from_slice(bytes);
Ok(Value::Records { size: size as u16, data })
}
0x32 => {
let n = self.count(1)?;
let class = Tag(self.c.u32()?);
self.c.u16()?;
let mut v = self.vec(n)?;
for _ in 0..n {
v.push(self.inline(Some(class))?);
}
Ok(Value::Array(v))
}
0x2d | 0x33 | 0x75 => Err(Error::Malformed("array of an unarrayable type")),
_ => {
let n = self.count(min)?;
let mut v = self.vec(n)?;
for _ in 0..n {
v.push(self.scalar(code, true, class)?);
}
Ok(Value::Array(v))
}
}
}
/// Inline object; `class` is given once for a whole array of them.
fn inline(&mut self, class: Option<Tag>) -> Result<Value, Error> {
match self.c.u8()? {
0 => return Ok(Value::Obj(None)),
1 => {}
_ => return Err(Error::Malformed("object marker")),
}
let class = match class {
Some(c) => c,
None => {
let c = Tag(self.c.u32()?);
self.c.u16()?;
c
}
};
let fields = self.fields(true, class)?;
let id = self.push(Object::new(class, Kind::Inline, vec![class], fields))?;
Ok(Value::Obj(Some(id)))
}
fn shared(&mut self) -> Result<Value, Error> {
let flag = self.c.u8()?;
if flag == 0 {
return Ok(Value::Obj(None));
}
let key = self.c.u32()?;
match flag {
2 => return self.shared.get(&key).map(|id| Value::Obj(Some(*id))).ok_or(Error::Malformed("reference to an undefined object")),
1 => {}
_ => return Err(Error::Malformed("object marker")),
}
if self.shared.contains_key(&key) {
return Err(Error::Malformed("object defined twice"));
}
// Register before the fields: an object's own fields may refer back to it.
let id = self.push(Object::new(Tag(0), Kind::Shared, Vec::new(), Vec::new()))?;
self.shared.insert(key, id);
let mut chain = Vec::new();
let mut fields = Vec::new();
loop {
match self.c.u8()? {
0 => {
let tag = Tag(self.c.u32()?);
self.c.u16()?;
chain.push(tag);
fields.extend(self.fields(true, tag)?);
}
1 => {
chain.push(Tag(self.c.u32()?));
break;
}
2 => break,
_ => return Err(Error::Malformed("object class chain")),
}
if chain.len() > 64 {
return Err(Error::Limit("object class chain too long"));
}
}
let class = chain.first().copied().unwrap_or(Tag(0));
fields.extend(self.fields(true, class)?);
if let Some(o) = self.objects.get_mut(id) {
*o = Object::new(class, Kind::Shared, chain, fields);
}
Ok(Value::Obj(Some(id)))
}
}
-259
View File
@@ -1,259 +0,0 @@
//! Synthetic containers for tests and fuzz seeds (cargo feature `synth`).
//!
//! These builders write the layout the reader accepts, so tests can describe documents in a few
//! lines. They are **not** an Affinity exporter: nothing written here has been opened in Affinity.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use crate::stream::Tag;
/// A field value to encode.
#[derive(Debug, Clone)]
pub enum F {
U8(u8),
U32(u32),
I32(i32),
F32(f32),
F64(f64),
Bool(bool),
Enum(u16, u16),
Str(String),
/// f64 vector of 2..6 values (points, rectangles, transforms).
F64s(Vec<f64>),
/// Fixed-size struct (colour components), 1..64 bytes.
Struct(Vec<u8>),
/// Array of fixed-size records, all `size` bytes.
Records(u16, Vec<Vec<u8>>),
U8s(Vec<u8>),
Entry(String),
/// Shared object: `Def` defines id with class chain and fields, `Ref` links back.
Def(u32, Vec<Tag>, Vec<(Tag, F)>),
Ref(u32),
Null,
/// Inline object.
Obj(Tag, Vec<(Tag, F)>),
/// Positional (untagged) object.
Pos(Vec<F>),
/// Array of shared objects / links.
Shared(Vec<F>),
/// Array of inline objects of one class.
Objs(Tag, Vec<Vec<(Tag, F)>>),
/// Raw bytes appended verbatim (malformed-input tests).
Raw(Vec<u8>),
}
pub fn tag(s: &[u8; 4]) -> Tag {
Tag::of(s)
}
fn put_tag(out: &mut Vec<u8>, t: Tag) {
out.extend(t.0.to_le_bytes());
}
fn code(f: &F) -> u8 {
match f {
F::U8(_) => 0x01,
F::U32(_) => 0x03,
F::I32(_) => 0x07,
F::F32(_) => 0x09,
F::F64(_) => 0x0a,
F::Bool(_) => 0x29,
F::Enum(..) => 0x2a,
F::Str(_) => 0x2b,
F::F64s(v) => 0x22 + v.len() as u8,
F::Struct(b) => 0x34 + b.len() as u8,
F::Records(..) => 0x80 | 0x2c,
F::U8s(_) => 0x80 | 0x01,
F::Entry(_) => 0x33,
F::Def(..) | F::Ref(_) => 0x31,
F::Null => 0x31,
F::Obj(..) => 0x32,
F::Pos(_) => 0x30,
F::Shared(_) => 0x80 | 0x31,
F::Objs(..) => 0x80 | 0x32,
F::Raw(_) => 0,
}
}
fn payload(out: &mut Vec<u8>, f: &F) {
match f {
F::U8(v) => out.push(*v),
F::U32(v) => out.extend(v.to_le_bytes()),
F::I32(v) => out.extend(v.to_le_bytes()),
F::F32(v) => out.extend(v.to_le_bytes()),
F::F64(v) => out.extend(v.to_le_bytes()),
F::Bool(v) => out.push(u8::from(*v)),
F::Enum(id, ver) => {
out.extend(id.to_le_bytes());
out.extend(ver.to_le_bytes());
}
F::Str(s) => {
out.extend((s.len() as u32).to_le_bytes());
out.extend(s.as_bytes());
}
F::F64s(v) => v.iter().for_each(|x| out.extend(x.to_le_bytes())),
F::Struct(b) => out.extend(b),
F::Records(size, recs) => {
out.extend((recs.len() as u32).to_le_bytes());
out.extend(size.to_le_bytes());
recs.iter().for_each(|r| out.extend(r));
}
F::U8s(v) => {
out.extend((v.len() as u32).to_le_bytes());
out.extend(v);
}
F::Entry(name) => {
put_tag(out, tag(b"Data"));
out.extend((name.len() as u32).to_le_bytes());
out.extend(name.as_bytes());
}
F::Def(id, chain, fields) => {
out.push(1);
out.extend(id.to_le_bytes());
// Class chain: each level but the last carries no fields here; the last ends the chain.
let (last, rest) = chain.split_last().expect("class chain");
for t in rest {
out.push(0);
put_tag(out, *t);
out.extend(0u16.to_le_bytes());
out.push(0);
}
out.push(1);
put_tag(out, *last);
fields_into(out, fields, true);
}
F::Ref(id) => {
out.push(2);
out.extend(id.to_le_bytes());
}
F::Null => out.push(0),
F::Obj(class, fields) => {
out.push(1);
put_tag(out, *class);
out.extend(0u16.to_le_bytes());
fields_into(out, fields, true);
}
F::Pos(items) => {
for f in items {
out.push(code(f));
payload(out, f);
}
out.push(0);
}
F::Shared(items) => {
out.extend((items.len() as u32).to_le_bytes());
items.iter().for_each(|f| payload(out, f));
}
F::Objs(class, items) => {
out.extend((items.len() as u32).to_le_bytes());
put_tag(out, *class);
out.extend(0u16.to_le_bytes());
for fields in items {
out.push(1);
fields_into(out, fields, true);
}
}
F::Raw(b) => out.extend(b),
}
}
fn fields_into(out: &mut Vec<u8>, fields: &[(Tag, F)], tagged: bool) {
for (t, f) in fields {
if let F::Raw(b) = f {
out.extend(b);
continue;
}
out.push(code(f));
if tagged {
put_tag(out, *t);
}
payload(out, f);
}
out.push(0);
}
/// A `doc.dat` stream with root class `Pers`.
pub fn stream(root: &[(Tag, F)]) -> Vec<u8> {
let mut out = b"\x00\xffKS".to_vec();
out.extend(2u16.to_le_bytes());
put_tag(&mut out, tag(b"Pers"));
out.extend(0u16.to_le_bytes());
out.extend(30u32.to_le_bytes());
fields_into(&mut out, root, true);
out
}
/// How an entry is stored.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Method {
Stored,
Zlib,
Zstd,
}
/// A version-12 container with one `#FT4` table holding `entries`, then an optional thumbnail record.
pub fn container(entries: &[(&str, &[u8], Method)], thumbnail_png: Option<&[u8]>) -> Vec<u8> {
let mut out = vec![0u8; 72];
out[..4].copy_from_slice(crate::container::MAGIC);
out[4..6].copy_from_slice(&12u16.to_le_bytes());
out[6..8].copy_from_slice(&4u16.to_le_bytes());
out[8..12].copy_from_slice(b"nsrP");
out[12..16].copy_from_slice(b"#Inf");
out[64..68].copy_from_slice(b"Prot");
let mut records = Vec::new();
for (i, (name, data, method)) in entries.iter().enumerate() {
let packed = match method {
Method::Stored => data.to_vec(),
Method::Zlib => {
use std::io::Write;
let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast());
e.write_all(data).unwrap();
e.finish().unwrap()
}
Method::Zstd => ruzstd::encoding::compress_to_vec(*data, ruzstd::encoding::CompressionLevel::Fastest),
};
let offset = out.len() as u64;
out.extend(b"#Fil");
out.extend(&packed);
let mut r = Vec::new();
r.extend((i as u32 + 1).to_le_bytes());
r.push(0);
r.extend(offset.to_le_bytes());
r.extend((data.len() as u64).to_le_bytes());
r.extend((packed.len() as u64).to_le_bytes());
r.extend(crc32fast::hash(data).to_le_bytes());
r.push(match method {
Method::Stored => 0,
Method::Zlib => 1,
Method::Zstd => 2,
});
r.extend(0u32.to_le_bytes());
r.extend(0u32.to_le_bytes());
r.extend((name.len() as u16).to_le_bytes());
r.extend(name.as_bytes());
records.push(r);
}
let fat = out.len() as u64;
out.extend(b"#FT4");
out.extend(0u64.to_le_bytes());
out.extend(1_700_000_000u64.to_le_bytes());
out.extend([0u8; 24]);
out.extend((records.len() as u32).to_le_bytes());
out.extend([0u8; 8]);
out.extend(0u16.to_le_bytes());
out.push(0);
records.iter().for_each(|r| out.extend(r));
let thumb = out.len() as u64;
out[16..24].copy_from_slice(&fat.to_le_bytes());
if let Some(png) = thumbnail_png {
out[24..32].copy_from_slice(&thumb.to_le_bytes());
out.extend(b"\xff\xff\xff\xffThmb");
out.extend(1u32.to_le_bytes());
out.extend((png.len() as u32 + 13).to_le_bytes());
out.extend(29u32.to_le_bytes());
out.extend(0u32.to_le_bytes());
out.extend((png.len() as u32).to_le_bytes());
out.push(1);
out.extend(png);
}
out
}
-860
View File
@@ -1,860 +0,0 @@
//! Unit tests on synthetic inputs; `tests/it/real_files.rs` covers public Affinity documents.
mod preview {
use crate::container::header;
use crate::*;
use proptest::prelude::*;
fn fixture() -> Vec<u8> {
let mut png = b"\x89PNG\r\n\x1a\n".to_vec();
png.extend(13u32.to_be_bytes());
png.extend(b"IHDR");
png.extend(2u32.to_be_bytes());
png.extend(1u32.to_be_bytes());
png.extend([8, 6, 0, 0, 0]);
png.extend(crc32fast::hash(&png[12..]).to_be_bytes());
png.extend([0; 4]);
png.extend(b"IDAT");
png.extend(crc32fast::hash(b"IDAT").to_be_bytes());
png.extend([0; 4]);
png.extend(b"IEND");
png.extend(crc32fast::hash(b"IEND").to_be_bytes());
let mut b = vec![0; 72];
b[..4].copy_from_slice(MAGIC);
b[4..6].copy_from_slice(&12u16.to_le_bytes());
b[8..12].copy_from_slice(b"nsrP");
b[12..16].copy_from_slice(b"#Inf");
b[24..32].copy_from_slice(&72u64.to_le_bytes());
b[64..68].copy_from_slice(b"Prot");
b.extend(b"\xff\xff\xff\xffThmb");
b.extend(1u32.to_le_bytes());
b.extend((png.len() as u32 + 13).to_le_bytes());
b.extend(29u32.to_le_bytes());
b.extend(0u32.to_le_bytes());
b.extend((png.len() as u32).to_le_bytes());
b.push(1);
b.extend(png);
b
}
#[test]
fn indexed_preview_and_header() {
let b = fixture();
assert_eq!(header(&b).unwrap().version, 12);
let p = preview(&b).unwrap();
assert_eq!((p.width, p.height), (2, 1));
assert_eq!(p.png, &b[101..]);
}
#[test]
fn every_truncation_is_rejected() {
let b = fixture();
for end in 0..b.len() {
assert!(preview(&b[..end]).is_err(), "{end}");
}
}
#[test]
fn rejects_assets_versions_offsets_lengths_and_bombs() {
let b = fixture();
for (offset, value) in [
(4, 13u64.to_le_bytes().to_vec()),
(8, b"urBR".to_vec()),
(24, u64::MAX.to_le_bytes().to_vec()),
(24, 1u64.to_le_bytes().to_vec()),
(24, 0u64.to_le_bytes().to_vec()),
(84, u32::MAX.to_le_bytes().to_vec()),
(88, 30u32.to_le_bytes().to_vec()),
(96, u32::MAX.to_le_bytes().to_vec()),
(117, 5000u32.to_be_bytes().to_vec()),
] {
let mut broken = b.clone();
broken[offset..offset + value.len()].copy_from_slice(&value);
assert!(preview(&broken).is_err(), "offset {offset}");
}
// Versions 8 to 11 store the same record (checked on public Affinity 1 and 2 files).
for version in 8..12 {
let mut legacy = b.clone();
legacy[4..6].copy_from_slice(&(version as u16).to_le_bytes());
assert!(preview(&legacy).is_ok());
}
// Flags 4 and 8 occur in real files; the low two bits mark other container variants.
for (flags, ok) in [(4u16, true), (8, true), (1, false), (2, false)] {
let mut variant = b.clone();
variant[6..8].copy_from_slice(&flags.to_le_bytes());
assert_eq!(preview(&variant).is_ok(), ok, "flags {flags}");
}
let mut old = b.clone();
old[4..6].copy_from_slice(&7u16.to_le_bytes());
assert!(matches!(preview(&old), Err(Error::Unsupported(_))));
}
#[test]
fn an_unindexed_png_or_resource_is_never_used() {
let mut b = fixture();
b[24..32].copy_from_slice(&0u64.to_le_bytes());
assert!(preview(&b).is_err());
b[24..32].copy_from_slice(&72u64.to_le_bytes());
b[76..80].copy_from_slice(b"Meta");
assert!(preview(&b).is_err());
}
#[test]
fn every_chunk_checksum_including_the_end_is_checked() {
let b = fixture();
for at in [130, b.len() - 1] {
let mut damaged = b.clone();
damaged[at] ^= 1;
assert_eq!(preview(&damaged).unwrap_err(), Error::Malformed("PNG chunk checksum"));
}
let mut ancillary = vec![0; 4];
ancillary.extend(b"tEXt");
ancillary.extend(crc32fast::hash(b"tEXt").to_be_bytes());
let mut with_ancillary = b.clone();
let at = b.len() - 12;
with_ancillary.splice(at..at, ancillary);
let png_length = (with_ancillary.len() - 101) as u32;
with_ancillary[84..88].copy_from_slice(&(png_length + 13).to_le_bytes());
with_ancillary[96..100].copy_from_slice(&png_length.to_le_bytes());
assert!(preview(&with_ancillary).is_ok());
with_ancillary[at + 8] ^= 1;
assert_eq!(preview(&with_ancillary).unwrap_err(), Error::Malformed("PNG chunk checksum"));
}
#[test]
fn compressed_metadata_and_animation_are_not_preview_support() {
for kind in [b"zTXt", b"iTXt", b"iCCP", b"acTL", b"fcTL", b"fdAT"] {
let mut extra = vec![0; 4];
extra.extend(kind);
extra.extend(crc32fast::hash(kind).to_be_bytes());
let mut b = fixture();
let at = b.len() - 12;
b.splice(at..at, extra);
let length = (b.len() - 101) as u32;
b[84..88].copy_from_slice(&(length + 13).to_le_bytes());
b[96..100].copy_from_slice(&length.to_le_bytes());
assert!(matches!(preview(&b), Err(Error::Unsupported(_))));
}
}
#[test]
fn critical_chunks_follow_a_single_complete_png_layout() {
fn with_chunks(kinds: &[&[u8; 4]]) -> Vec<u8> {
let original = fixture();
let mut b = original[..134].to_vec(); // File, record and complete first IHDR.
for kind in kinds {
b.extend([0; 4]);
b.extend(*kind);
b.extend(crc32fast::hash(*kind).to_be_bytes());
}
let length = (b.len() - 101) as u32;
b[84..88].copy_from_slice(&(length + 13).to_le_bytes());
b[96..100].copy_from_slice(&length.to_le_bytes());
b
}
assert!(preview(&with_chunks(&[b"IDAT", b"IDAT", b"IEND"])).is_ok());
// PNG readers must not reject an otherwise valid unknown ancillary chunk just
// because its reserved (third-letter) bit is set; future versions can define it.
assert!(preview(&with_chunks(&[b"abct", b"IDAT", b"IEND"])).is_ok());
for kinds in [
vec![b"IEND"],
vec![b"IDAT", b"IHDR", b"IEND"],
vec![b"PLTE", b"PLTE", b"IDAT", b"IEND"],
vec![b"IDAT", b"PLTE", b"IEND"],
vec![b"IDAT", b"tEXt", b"IDAT", b"IEND"],
vec![b"ABCD", b"IDAT", b"IEND"],
vec![b"IDAT", b"IEND", b"tEXt"],
] {
assert!(preview(&with_chunks(&kinds)).is_err(), "{kinds:?}");
}
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(256))]
#[test]
fn arbitrary_input_never_panics(b in prop::collection::vec(any::<u8>(), 0..2048)) {
let _ = header(&b);
let _ = preview(&b);
}
#[test]
fn mutations_never_panic(edits in prop::collection::vec((0usize..200, any::<u8>()), 0..32)) {
let mut b = fixture();
for (i, value) in edits { if let Some(v) = b.get_mut(i) { *v = value; } }
let _ = preview(&b);
}
}
}
mod archive {
use crate::Error;
use crate::container::{Archive, Limits};
use crate::stream::{self, Kind, Tag, Value};
use crate::synth::{self, F, Method, tag};
use proptest::prelude::*;
fn doc() -> Vec<u8> {
synth::stream(&[
(tag(b"Desc"), F::Str("Document".into())),
(tag(b"Visi"), F::Bool(true)),
(tag(b"Xfrm"), F::F64s(vec![1.0, 0.0, 5.0, 0.0, 1.0, -2.0])),
(tag(b"Colr"), F::Def(7, vec![tag(b"RGBA")], vec![(tag(b"_col"), F::Struct([0u8; 16].to_vec()))])),
(tag(b"Same"), F::Ref(7)),
(tag(b"Null"), F::Null),
(tag(b"Kids"), F::Shared(vec![F::Def(8, vec![tag(b"Grup"), tag(b"Node")], vec![(tag(b"Desc"), F::Str("g".into()))]), F::Ref(8)])),
(tag(b"Crvs"), F::Obj(tag(b"PCvD"), vec![(tag(b"Data"), F::Pos(vec![F::U8(0), F::U32(1), F::Bool(true), F::Records(18, vec![vec![0; 18]; 4])]))])),
(tag(b"Enum"), F::Enum(2, 1)),
(tag(b"Tile"), F::Entry("d/3".into())),
(tag(b"Stat"), F::U8s(vec![4, 0, 2])),
])
}
#[test]
fn every_method_round_trips_with_checksums() {
let d = doc();
for method in [Method::Stored, Method::Zlib, Method::Zstd] {
let file = synth::container(&[("doc.dat", &d, method), ("d/3", b"tile", method)], None);
let mut a = Archive::open(&file, Limits::default()).unwrap();
assert_eq!(a.header.version, 12);
assert_eq!(a.read("doc.dat").unwrap(), d);
assert_eq!(a.read("d/3").unwrap(), b"tile");
assert_eq!(a.extracted(), d.len() + 4);
assert!(a.read("missing").is_err());
}
}
#[test]
fn the_stream_parses_into_shared_objects_and_links() {
let s = stream::parse(&doc()).unwrap();
let root = &s.objects[s.root];
assert_eq!(root.class, Tag::of(b"Pers"));
assert_eq!(root.get(Tag::of(b"Desc")), Some(&Value::Str("Document".into())));
assert_eq!(root.get(Tag::of(b"Xfrm")), Some(&Value::Floats(vec![1.0, 0.0, 5.0, 0.0, 1.0, -2.0])));
let (Some(Value::Obj(Some(a))), Some(Value::Obj(Some(b)))) = (root.get(Tag::of(b"Colr")), root.get(Tag::of(b"Same"))) else { panic!() };
assert_eq!(a, b);
assert_eq!(s.objects[*a].class, Tag::of(b"RGBA"));
assert_eq!(s.objects[*a].kind, Kind::Shared);
let Some(Value::Array(kids)) = root.get(Tag::of(b"Kids")) else { panic!() };
assert_eq!(kids[0], kids[1]);
let Value::Obj(Some(g)) = kids[0] else { panic!() };
assert_eq!(s.objects[g].chain, vec![Tag::of(b"Grup"), Tag::of(b"Node")]);
assert_eq!(root.get(Tag::of(b"Enum")), Some(&Value::Enum { id: 2, version: 1 }));
assert_eq!(root.get(Tag::of(b"Tile")), Some(&Value::Entry("d/3".into())));
assert_eq!(root.get(Tag::of(b"Null")), Some(&Value::Obj(None)));
}
#[test]
fn checksums_sizes_and_budgets_are_enforced() {
let d = doc();
let file = synth::container(&[("doc.dat", &d, Method::Zstd)], None);
// Flip a byte inside the compressed payload, past the "#Fil" tag at offset 72.
let mut broken = file.clone();
broken[90] ^= 0x55;
let mut a = Archive::open(&broken, Limits::default()).unwrap();
assert!(a.read("doc.dat").is_err());
let mut a = Archive::open(&file, Limits { max_entry: d.len() - 1, max_total: usize::MAX, ..Limits::default() }).unwrap();
assert!(matches!(a.read("doc.dat"), Err(Error::Limit(_))));
let mut a = Archive::open(&file, Limits { max_entry: usize::MAX, max_total: d.len() + 1, ..Limits::default() }).unwrap();
a.read("doc.dat").unwrap();
assert!(matches!(a.read("doc.dat"), Err(Error::Limit(_))));
}
#[test]
fn a_failed_read_still_spends_the_extraction_allowance() {
let d = doc();
let file = synth::container(&[("doc.dat", &d, Method::Zstd)], None);
let mut broken = file.clone();
broken[90] ^= 0x55;
// Room for exactly one read: the failed attempt must use it up, so a caller that
// recovers from the checksum error cannot make the same entry decode again.
let mut a = Archive::open(&broken, Limits { max_entry: usize::MAX, max_total: d.len(), ..Limits::default() }).unwrap();
assert!(a.read("doc.dat").is_err());
assert_eq!(a.extracted(), d.len());
assert!(matches!(a.read("doc.dat"), Err(Error::Limit(_))));
}
#[test]
fn a_declared_size_smaller_than_the_data_is_rejected_not_truncated() {
let big = vec![7u8; 1 << 20];
let mut file = synth::container(&[("doc.dat", &big, Method::Zlib)], None);
// Rewrite the declared size in the table to 1 KiB: decoding must stop and fail.
let fat = u64::from_le_bytes(file[16..24].try_into().unwrap()) as usize;
let size_at = fat + 59 + 5 + 8;
file[size_at..size_at + 8].copy_from_slice(&1024u64.to_le_bytes());
let mut a = Archive::open(&file, Limits::default()).unwrap();
assert_eq!(a.read("doc.dat").unwrap_err(), Error::Malformed("archive entry size mismatch"));
}
#[test]
fn libraries_and_cyclic_tables_are_rejected() {
let d = doc();
let mut file = synth::container(&[("doc.dat", &d, Method::Stored)], None);
let mut library = file.clone();
library[8..12].copy_from_slice(b"rAsA");
assert!(matches!(Archive::open(&library, Limits::default()), Err(Error::Unsupported(_))));
let fat = u64::from_le_bytes(file[16..24].try_into().unwrap());
let at = fat as usize + 4;
file[at..at + 8].copy_from_slice(&fat.to_le_bytes());
assert_eq!(Archive::open(&file, Limits::default()).unwrap_err(), Error::Malformed("allocation tables form a cycle"));
}
#[test]
fn allocation_records_are_charged_before_they_are_walked() {
let d = doc();
let mut file = synth::container(&[("doc.dat", &d, Method::Stored)], None);
let fat = u64::from_le_bytes(file[16..24].try_into().unwrap()) as usize;
// The table's file count sits after its tag, next, date and 24 reserved bytes.
let files = fat + 4 + 8 + 8 + 24;
file[files..files + 4].copy_from_slice(&u32::MAX.to_le_bytes());
assert_eq!(Archive::open(&file, Limits::default()).unwrap_err(), Error::Limit("too many allocation records"));
// A count within the budget still reaches the records (and here fails on missing data).
file[files..files + 4].copy_from_slice(&1_000_000u32.to_le_bytes());
assert!(matches!(Archive::open(&file, Limits::default()), Err(Error::Malformed(_))));
}
#[test]
fn allocation_records_are_charged_across_every_table() {
let d = doc();
let mut file = synth::container(&[("doc.dat", &d, Method::Stored), ("other.dat", &d, Method::Stored)], None);
let fat = u64::from_le_bytes(file[16..24].try_into().unwrap()) as usize;
// Chain a copy of the (valid, two-record) table after it; the copy is the last table.
let second = file.len();
let table = file[fat..].to_vec();
file.extend(&table);
file[fat + 4..fat + 12].copy_from_slice(&(second as u64).to_le_bytes());
let files = second + 4 + 8 + 8 + 24;
// Each count alone is within the archive budget of 2^25; together they exceed it by one.
file[files..files + 4].copy_from_slice(&((1u32 << 25) - 1).to_le_bytes());
assert_eq!(Archive::open(&file, Limits::default()).unwrap_err(), Error::Limit("too many allocation records"));
// Exactly the budget is allowed: the second table is walked (and fails on missing data).
file[files..files + 4].copy_from_slice(&((1u32 << 25) - 2).to_le_bytes());
assert!(matches!(Archive::open(&file, Limits::default()), Err(Error::Malformed(_))));
// Directory records count too: one more (after the file count and 8 bytes) is over.
file[files + 12..files + 14].copy_from_slice(&1u16.to_le_bytes());
assert_eq!(Archive::open(&file, Limits::default()).unwrap_err(), Error::Limit("too many allocation records"));
}
#[test]
fn hostile_streams_fail_cleanly() {
let deep = (0..2000).fold(Vec::new(), |inner, _| vec![(tag(b"Chld"), F::Obj(tag(b"Grup"), inner))]);
assert_eq!(stream::parse(&synth::stream(&deep)).unwrap_err(), Error::Limit("objects nested too deeply"));
// An array claiming four billion elements in a few bytes.
let huge = synth::stream(&[(tag(b"Big_"), F::Raw(vec![0x81, b'_', b'g', b'i', b'B', 0xff, 0xff, 0xff, 0xff, 0]))]);
assert_eq!(stream::parse(&huge).unwrap_err(), Error::Malformed("array longer than its data"));
let forward = synth::stream(&[(tag(b"Link"), F::Ref(99))]);
assert!(stream::parse(&forward).is_err());
let twice = synth::stream(&[(tag(b"A___"), F::Def(1, vec![tag(b"RGBA")], vec![])), (tag(b"B___"), F::Def(1, vec![tag(b"RGBA")], vec![]))]);
assert!(stream::parse(&twice).is_err());
let unknown = synth::stream(&[(tag(b"X___"), F::Raw(vec![0x0b, 1, 2, 3, 4]))]);
assert!(matches!(stream::parse(&unknown), Err(Error::Unsupported(_))));
let d = doc();
for end in 0..d.len() {
assert!(stream::parse(&d[..end]).is_err(), "{end}");
}
}
#[test]
fn fixed_records_of_zero_width_are_rejected_before_any_value_is_made() {
// Four million records of no bytes each pass a length check that multiplies by the width.
let mut f = vec![0x80 | 0x2c];
f.extend(tag(b"Big_").0.to_le_bytes());
f.extend(4_000_000u32.to_le_bytes());
f.extend(0u16.to_le_bytes());
let d = synth::stream(&[(tag(b"Big_"), F::Raw(f))]);
assert_eq!(stream::parse(&d).unwrap_err(), Error::Malformed("array longer than its data"));
}
#[test]
fn a_small_compressed_entry_cannot_make_the_stream_allocate_gigabytes() {
// Each decoded value takes about 40 bytes, and a bool array packs eight in a byte: 16 MiB
// of zero bits, a few KiB once compressed, would ask for 2^27 values (about 4 GiB). An
// array of one-byte values just past the budget fails the same way, before allocating.
let field = |code: u8, n: u32, data: usize| {
let mut f = vec![0x80 | code];
f.extend(tag(b"Big_").0.to_le_bytes());
f.extend(n.to_le_bytes());
f.resize(f.len() + data, 0);
F::Raw(f)
};
let bools = 1u32 << 27;
let bytes = u32::try_from(stream::MAX_VALUES).unwrap() + 1;
for f in [field(0x29, bools, (bools / 8) as usize), field(0x01, bytes, bytes as usize)] {
let d = synth::stream(&[(tag(b"Big_"), f)]);
let file = synth::container(&[("doc.dat", &d, Method::Zstd)], None);
assert!(file.len() < d.len() / 100, "{} of {}", file.len(), d.len());
let entry = Archive::open(&file, Limits::default()).unwrap().read("doc.dat").unwrap();
assert_eq!(stream::parse(&entry).unwrap_err(), Error::Limit("too many values in the document stream"));
}
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(512))]
#[test]
fn mutated_containers_and_streams_never_panic(edits in prop::collection::vec((0usize..4096, any::<u8>()), 1..24)) {
let d = doc();
for method in [Method::Stored, Method::Zlib, Method::Zstd] {
let mut file = synth::container(&[("doc.dat", &d, method)], None);
for (i, v) in &edits {
let n = file.len();
file[i % n] = *v;
}
if let Ok(bytes) = Archive::open(&file, Limits::default()).and_then(|mut a| a.read("doc.dat")) {
let _ = stream::parse(&bytes);
}
}
let mut s = d.clone();
for (i, v) in &edits {
let n = s.len();
s[i % n] = *v;
}
let _ = stream::parse(&s);
}
}
}
mod shapes {
use crate::container::Limits;
use crate::model::{Document, Kind, Path, Point, SubPath};
use crate::stream::Tag;
use crate::synth::{self, F, Method, tag};
fn shape(id: u32, class: &[u8; 4], parameters: Vec<(Tag, F)>) -> F {
F::Def(
id,
vec![tag(b"ShpN")],
vec![(tag(b"ShpB"), F::F64s(vec![0.0, 0.0, 10.0, 20.0])), (tag(b"Shpe"), F::Def(id + 10_000, vec![tag(class)], parameters))],
)
}
/// Reads a document whose one page holds the object `top` from `definitions`, on a thread of
/// its own, and fails the test when reading takes more than 20 s.
fn read(definitions: Vec<F>, top: u32) -> Document {
let data = synth::stream(&[
(tag(b"Defs"), F::Shared(definitions)),
(
tag(b"DocR"),
F::Def(
1,
vec![tag(b"DocN")],
vec![(
tag(b"Chld"),
F::Shared(vec![F::Def(
2,
vec![tag(b"Sprd")],
vec![(tag(b"SprB"), F::F64s(vec![0.0, 0.0, 400.0, 300.0])), (tag(b"Chld"), F::Shared(vec![F::Ref(top)]))],
)]),
)],
),
),
]);
let bytes = synth::container(&[("doc.dat", &data, Method::Zlib)], None);
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || tx.send(crate::model::read(&bytes, Limits::default())).ok());
rx.recv_timeout(std::time::Duration::from_secs(20)).unwrap_or_else(|_| panic!("reading the document did not finish")).unwrap()
}
#[test]
fn empty_subpaths_of_a_shared_curve_are_charged_for_every_occurrence() {
// One curve of 100k empty subpaths, placed 100 times: no records and no points, but
// ten million subpaths walked unless each one is charged.
let mut data = vec![F::U8(0), F::U32(100_000)];
for _ in 0..100_000 {
data.extend([F::Bool(false), F::Records(18, Vec::new())]);
}
let curve = F::Def(5, vec![tag(b"PCrv")], vec![(tag(b"Crvs"), F::Obj(tag(b"PCvD"), vec![(tag(b"Data"), F::Pos(data))]))]);
let group = F::Def(6, vec![tag(b"Grup")], vec![(tag(b"Chld"), F::Shared((0..100).map(|_| F::Ref(5)).collect()))]);
let d = read(vec![curve, group], 6);
assert!(d.warnings.iter().any(|w| w.contains("curve geometry budget exhausted")), "{:?}", d.warnings);
}
fn path(document: &Document) -> &Path {
match &document.spreads[0].nodes[0].kind {
Kind::Shape { path, .. } => path,
other => panic!("expected shape, got {other:?}"),
}
}
#[test]
fn artistic_text_reads_its_characters_runs_and_anchor() {
let glyphs = F::Obj(tag(b"Glyp"), vec![(tag(b"Utf8"), F::Str("Hi".into()))]);
let run = F::Obj(tag(b"Item"), vec![]);
let attributes = F::Obj(tag(b"GAtt"), vec![(tag(b"Runs"), F::Objs(tag(b"Runs"), vec![vec![(tag(b"Indx"), F::I32(2)), (tag(b"Item"), run)]]))]);
let block = vec![(tag(b"Glyp"), glyphs), (tag(b"GAtt"), attributes)];
let text = F::Def(
100,
vec![tag(b"TxtA")],
vec![
(tag(b"TxtH"), F::Obj(tag(b"ArFr"), vec![(tag(b"FrmB"), F::F64s(vec![0.0, 0.0, 100.0, 50.0]))])),
(tag(b"StSt"), F::Obj(tag(b"StSt"), vec![(tag(b"Blok"), F::Objs(tag(b"Blok"), vec![block]))])),
],
);
let document = read(vec![text], 100);
let Kind::Text(t) = &document.spreads[0].nodes[0].kind else { panic!("expected text") };
assert_eq!(t.runs.len(), 1);
assert_eq!(t.runs[0].text, "Hi");
assert_eq!(t.align, crate::model::Align::Left);
assert_eq!(t.anchor, Point { x: 0.0, y: 0.0 });
assert!(t.frame.is_none());
}
#[test]
fn pie_angles_with_huge_finite_values_do_not_loop_or_emit_nonfinite_points() {
let document = read(vec![shape(100, b"ShPi", vec![(tag(b"AngS"), F::F64(1.0e308)), (tag(b"AngE"), F::F64(-1.0e308))])], 100);
for subpath in &path(&document).subpaths {
assert!(subpath.start.x.is_finite() && subpath.start.y.is_finite());
assert!(subpath.segments.len() <= 20);
assert!(subpath.segments.iter().flatten().all(|point| point.x.is_finite() && point.y.is_finite()));
}
}
#[test]
fn wrapped_pie_angles_keep_the_same_geometry_as_the_positive_span() {
let make = |end| read(vec![shape(100, b"ShPi", vec![(tag(b"AngS"), F::F64(0.0)), (tag(b"AngE"), F::F64(end))])], 100);
assert_eq!(path(&make(-std::f64::consts::FRAC_PI_2)), path(&make(3.0 * std::f64::consts::FRAC_PI_2)));
}
/// A 10×20 rectangle (`ShNR`) with the given parameters, read back as its outline.
fn rectangle(parameters: Vec<(Tag, F)>) -> (SubPath, Vec<String>) {
let node =
F::Def(3, vec![tag(b"ShpN")], vec![(tag(b"ShpB"), F::F64s(vec![0.0, 0.0, 10.0, 20.0])), (tag(b"Shpe"), F::Def(4, vec![tag(b"ShNR")], parameters))]);
let spread = F::Def(2, vec![tag(b"Sprd")], vec![(tag(b"SprB"), F::F64s(vec![0.0, 0.0, 400.0, 300.0])), (tag(b"Chld"), F::Shared(vec![node]))]);
let data = synth::stream(&[(tag(b"DocR"), F::Def(1, vec![tag(b"DocN")], vec![(tag(b"Chld"), F::Shared(vec![spread]))]))]);
let doc = crate::read(&synth::container(&[("doc.dat", &data, Method::Zlib)], None), Limits::default()).unwrap();
let Kind::Shape { path, .. } = &doc.spreads[0].nodes[0].kind else { panic!("expected a shape") };
(path.subpaths[0].clone(), doc.warnings)
}
/// `CTyp`: an array of corner-type enums (top left, top right, bottom right, bottom left).
fn corner_types(ids: [u16; 4]) -> F {
let mut raw = vec![0xaa];
raw.extend(tag(b"CTyp").0.to_le_bytes());
raw.extend(4u32.to_le_bytes());
raw.extend(0u16.to_le_bytes());
raw.extend(ids.iter().flat_map(|id| id.to_le_bytes()));
F::Raw(raw)
}
#[test]
fn unlocked_rectangle_corners_keep_their_own_radius_and_type() {
let p = |x: f64, y: f64| Point { x, y };
// Relative radii scale by 10. Round 5, round 1, straight 3, none.
let corners = |lock: Option<bool>| {
let mut fields = vec![(tag(b"ShCR"), F::F64s(vec![0.5, 0.1, 0.3, 0.0])), (tag(b"CTyp"), corner_types([0, 0, 1, 4]))];
fields.extend(lock.map(|l| (tag(b"Lock"), F::Bool(l))));
rectangle(fields)
};
let (sub, warnings) = corners(Some(false));
assert!(warnings.is_empty(), "{warnings:?}");
assert_eq!(sub.start, p(5.0, 0.0));
let ends: Vec<Point> = sub.segments.iter().map(|s| s[2]).collect();
assert_eq!(ends, [p(9.0, 0.0), p(10.0, 1.0), p(10.0, 17.0), p(7.0, 20.0), p(0.0, 20.0), p(0.0, 5.0), p(5.0, 0.0)]);
assert_eq!(sub.segments[3], [p(7.0, 20.0); 3], "the straight corner is a line");
assert_ne!(sub.segments[1][0], p(9.0, 0.0), "the round corner is a curve");
// Locked (the default): every corner follows the top left one.
let (sub, _) = corners(None);
assert_eq!(sub.segments.len(), 8);
assert_eq!(sub.segments[3][2], p(5.0, 20.0));
}
}
/// Aggregate materialized-pixel admission (#4960). The entry limits bound what the archive
/// extracts; these cover what the decoded layers and their working planes cost, which is declared
/// by each bitmap's `BmpW`/`BmpH` and needs no tile data at all.
mod pixels {
use crate::Error;
use crate::container::Limits;
use crate::model::{Document, Kind};
use crate::synth::{self, F, Method, tag};
/// A `Rstr` pixel layer whose bitmap declares `w`×`h` pixels and holds no tiles.
fn layer(id: u32, w: i32, h: i32) -> F {
F::Def(
id,
vec![tag(b"Rstr")],
vec![
(tag(b"Desc"), F::Str(format!("Layer {id}"))),
(tag(b"Bitm"), F::Def(id + 1, vec![tag(b"DyBm")], vec![(tag(b"BmpW"), F::I32(w)), (tag(b"BmpH"), F::I32(h)), (tag(b"Frmt"), F::Enum(0, 0))])),
],
)
}
/// A document whose one page holds a pixel layer per `sizes` entry.
fn document(sizes: &[(i32, i32)]) -> Vec<u8> {
let children: Vec<F> = sizes.iter().enumerate().map(|(i, &(w, h))| layer(10 + 2 * i as u32, w, h)).collect();
let data = synth::stream(&[(
tag(b"DocR"),
F::Def(
1,
vec![tag(b"DocN")],
vec![(
tag(b"Chld"),
F::Shared(vec![F::Def(
2,
vec![tag(b"Sprd")],
vec![(tag(b"SprB"), F::F64s(vec![0.0, 0.0, 256.0, 256.0])), (tag(b"Chld"), F::Shared(children))],
)]),
)],
),
)]);
synth::container(&[("doc.dat", &data, Method::Zlib)], None)
}
fn imported_layers(d: &Document) -> usize {
d.spreads[0].nodes.iter().filter(|n| matches!(n.kind, Kind::Image(_))).count()
}
/// A 64×64 layer costs 16 KiB of RGBA and 16 KiB of planes, so 40 KiB admits one and not two.
const ONE_LAYER: usize = 40 << 10;
#[test]
fn a_pixel_layer_within_the_budget_imports() {
let limits = Limits { max_pixel_bytes: ONE_LAYER, ..Limits::default() };
let d = crate::model::read(&document(&[(64, 64)]), limits).unwrap();
assert_eq!(imported_layers(&d), 1, "{:?}", d.warnings);
}
#[test]
fn layers_past_the_pixel_budget_are_rejected_before_they_are_allocated() {
let limits = Limits { max_pixel_bytes: ONE_LAYER, ..Limits::default() };
// The document is a few hundred bytes: the sizes are in the headers, not the entries.
let bytes = document(&[(64, 64), (64, 64)]);
assert!(bytes.len() < 4096, "the fixture is {} bytes", bytes.len());
assert!(matches!(crate::model::read(&bytes, limits), Err(Error::Limit(_))), "the second layer materialized");
// Two layers fit once the budget covers their pixels together.
let room = Limits { max_pixel_bytes: ONE_LAYER + (32 << 10), ..Limits::default() };
assert_eq!(imported_layers(&crate::model::read(&bytes, room).unwrap()), 2);
}
#[test]
fn a_declared_size_larger_than_the_budget_is_rejected_on_its_own() {
// 2048×2048 is 16 MiB of RGBA and 16 MiB of planes, past a 1 MiB budget.
let limits = Limits { max_pixel_bytes: 1 << 20, ..Limits::default() };
assert!(
matches!(crate::model::read(&document(&[(2048, 2048)]), limits), Err(Error::Limit(_))),
"16 MiB of declared pixels materialized under a 1 MiB budget"
);
}
}
/// Spot colours that link to themselves or to each other. Each document is read on a 1 MiB
/// stack, the smallest main-thread stack PhotoCraft runs on (Windows), first in a child process
/// that must finish within 20 s. A stack overflow aborts the process it happens in, so unbounded
/// recursion fails the one test that caused it instead of taking the other tests in the binary
/// down with it.
mod spot_colours {
use std::io::{Read, Write};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use crate::container::Limits;
use crate::model::{Document, Kind};
use crate::paint::{Color, Paint};
use crate::stream::Tag;
use crate::synth::{self, F, Method, tag};
/// A one-page document whose page holds `top`, read in a child process first and then here.
fn read(top: Vec<F>) -> Document {
let spread = F::Def(2, vec![tag(b"Sprd")], vec![(tag(b"SprB"), F::F64s(vec![0.0, 0.0, 400.0, 300.0])), (tag(b"Chld"), F::Shared(top))]);
let data = synth::stream(&[(tag(b"DocR"), F::Def(1, vec![tag(b"DocN")], vec![(tag(b"Chld"), F::Shared(vec![spread]))]))]);
let bytes = synth::container(&[("doc.dat", &data, Method::Zlib)], None);
let test = std::thread::current().name().unwrap_or("reader").to_owned();
read_in_child(&bytes, &test);
read_on_small_stack(bytes, &test).unwrap()
}
/// Reads on a 1 MiB thread named after the test, so a stack overflow message names the test.
fn read_on_small_stack(bytes: Vec<u8>, test: &str) -> Result<Document, crate::Error> {
let reader = std::thread::Builder::new().name(test.to_owned()).stack_size(1 << 20).spawn(move || crate::read(&bytes, Limits::default())).unwrap();
reader.join().unwrap_or_else(|panic| std::panic::resume_unwind(panic))
}
/// Set in the child process to the name of the test it reads for.
const CHILD: &str = "PHOTOCRAFT_AFFINITY_READ_CHILD";
/// Runs `read_child` in a new process of this test binary on `bytes` and fails the test if
/// that process crashes, panics or takes over 20 s, or never read the document.
fn read_in_child(bytes: &[u8], test: &str) {
let mut child = Command::new(std::env::current_exe().unwrap())
.args(["tests::spot_colours::read_child", "--exact", "--ignored", "--nocapture", "--test-threads=1"])
.env(CHILD, test)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let drain = |mut pipe: Box<dyn Read + Send>| {
std::thread::spawn(move || {
let mut text = String::new();
let _ = pipe.read_to_string(&mut text);
text
})
};
let stdout = drain(Box::new(child.stdout.take().unwrap()));
let stderr = drain(Box::new(child.stderr.take().unwrap()));
// Fed from a thread, so a child that never reads cannot block the deadline below; a child
// that dies first breaks the pipe and is reported by its exit status.
let (mut stdin, input) = (child.stdin.take().unwrap(), bytes.to_vec());
let feed = std::thread::spawn(move || {
let _ = stdin.write_all(&input);
});
let deadline = Instant::now() + Duration::from_secs(20);
let status = loop {
if let Some(status) = child.try_wait().unwrap() {
break Some(status);
}
if Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
break None;
}
std::thread::sleep(Duration::from_millis(10));
};
feed.join().unwrap();
let output = format!("{}{}", stdout.join().unwrap(), stderr.join().unwrap());
match status {
None => panic!("reading the document did not finish within 20 s:\n{output}"),
Some(status) if !status.success() => panic!("reading the document failed in a child process ({status}):\n{output}"),
// A filter that matched no test would also exit successfully, having read nothing.
Some(_) => assert!(output.contains(&format!("read {} bytes", bytes.len())), "the child process did not read the document:\n{output}"),
}
}
/// Not a test of its own: `read_in_child` runs it in a child process to read the document on
/// its stdin. Without the variable, as when run with `--ignored`, it does nothing.
#[test]
#[ignore = "run by read_in_child in a child process"]
fn read_child() {
let Some(test) = std::env::var_os(CHILD) else { return };
let mut bytes = Vec::new();
std::io::stdin().read_to_end(&mut bytes).unwrap();
let len = bytes.len();
let _ = read_on_small_stack(bytes, &test.to_string_lossy());
println!("read {len} bytes");
}
/// An ellipse filled with `colour`.
fn filled(id: u32, colour: F) -> F {
F::Def(
id,
vec![tag(b"ShpN")],
vec![
(tag(b"ShpB"), F::F64s(vec![0.0, 0.0, 1.0, 1.0])),
(tag(b"Shpe"), F::Def(id + 1_000_000, vec![tag(b"ShpE")], vec![])),
(tag(b"BFFl"), F::Shared(vec![F::Def(id + 2_000_000, vec![tag(b"FilS")], vec![(tag(b"Colr"), colour)])])),
],
)
}
fn spot(id: u32, fields: Vec<(Tag, F)>) -> F {
F::Def(id, vec![tag(b"Pant")], fields)
}
fn fills(doc: &Document) -> &[Paint] {
match &doc.spreads[0].nodes[0].kind {
Kind::Shape { fills, .. } => fills,
other => panic!("expected a shape, got {other:?}"),
}
}
fn warned(doc: &Document, what: &str) -> bool {
doc.warnings.iter().any(|w| w.contains(what))
}
#[test]
fn a_spot_colour_that_is_its_own_rgb_equivalent_is_refused() {
let doc = read(vec![filled(10, spot(20, vec![(tag(b"srgb"), F::Ref(20))]))]);
assert!(fills(&doc).is_empty(), "{:?}", fills(&doc));
assert!(warned(&doc, "spot colours nested deeper than 4 levels"), "{:?}", doc.warnings);
}
#[test]
fn spot_colours_that_are_each_others_base_and_rgb_equivalent_are_refused() {
let doc = read(vec![filled(10, spot(20, vec![(tag(b"base"), spot(21, vec![(tag(b"srgb"), F::Ref(20))]))]))]);
assert!(fills(&doc).is_empty(), "{:?}", fills(&doc));
assert!(warned(&doc, "spot colours nested deeper than 4 levels"), "{:?}", doc.warnings);
}
#[test]
fn spot_colours_of_spot_colours_do_not_take_exponential_time() {
// Each level's RGB equivalent and base are the next level, and the last is in an unknown
// model, so both are followed everywhere: 2^41 colour reads before the fix.
fn level(id: u32, left: u32) -> F {
if left == 0 {
return F::Def(id, vec![tag(b"XXXX")], vec![]);
}
spot(id, vec![(tag(b"srgb"), level(id + 1, left - 1)), (tag(b"base"), F::Ref(id + 1))])
}
let doc = read(vec![filled(10, level(100, 40))]);
assert!(fills(&doc).is_empty(), "{:?}", fills(&doc));
}
/// `spots` spot colours, each defined through the next, around an opaque RGB colour.
fn spots(id: u32, spots: u32) -> F {
if spots == 0 {
let rgba: Vec<u8> = [1.0f32, 0.5, 0.25, 1.0].iter().flat_map(|c| c.to_le_bytes()).collect();
return F::Def(id, vec![tag(b"RGBA")], vec![(tag(b"_col"), F::Struct(rgba))]);
}
spot(id, vec![(tag(b"srgb"), self::spots(id + 1, spots - 1))])
}
#[test]
fn spot_colours_nest_four_levels_and_no_deeper() {
let doc = read(vec![filled(10, spots(100, 4))]);
assert_eq!(fills(&doc), [Paint::Solid(Color::Rgb { r: 1.0, g: 0.5, b: 0.25, a: 1.0 })]);
let doc = read(vec![filled(10, spots(100, 5))]);
assert!(fills(&doc).is_empty(), "{:?}", fills(&doc));
assert!(warned(&doc, "spot colours nested deeper than 4 levels"), "{:?}", doc.warnings);
}
}
/// Object lookup and record arrays against the structures they replaced.
mod stream_storage {
use crate::stream::{self, Kind, Object, Tag, Value};
use crate::synth::{self, F, tag};
/// The per-object map `Object::get` used before: first occurrence of each real tag.
fn reference(fields: &[(Tag, Value)], t: Tag) -> Option<&Value> {
let mut index = std::collections::HashMap::new();
for (i, (ft, _)) in fields.iter().enumerate() {
if ft.0 != 0 {
index.entry(*ft).or_insert(i);
}
}
index.get(&t).map(|&i| &fields[i].1)
}
#[test]
fn lookup_keeps_first_match_for_every_object_size() {
for n in 0..60u32 {
// Tags repeat (n % 7 distinct tags) and every fifth field is positional (tag 0).
let fields: Vec<(Tag, Value)> = (0..n).map(|i| (if i % 5 == 0 { Tag(0) } else { Tag(100 + i % 7) }, Value::UInt(u64::from(i)))).collect();
let object = Object::new(Tag(1), Kind::Inline, vec![Tag(1)], fields.clone());
for t in 0..120 {
assert_eq!(object.get(Tag(t)), reference(&fields, Tag(t)), "{n} fields, tag {t}");
}
}
}
#[test]
fn last_lookup_keeps_last_match_for_every_object_size() {
for n in 0..60u32 {
let fields: Vec<(Tag, Value)> = (0..n).map(|i| (if i % 5 == 0 { Tag(0) } else { Tag(100 + i % 7) }, Value::UInt(u64::from(i)))).collect();
let object = Object::new(Tag(1), Kind::Inline, vec![Tag(1)], fields.clone());
for t in 0..120 {
let expected = if t == 0 { None } else { fields.iter().rev().find(|(k, _)| *k == Tag(t)).map(|(_, v)| v) };
assert_eq!(object.get_last(Tag(t)), expected, "{n} fields, tag {t}");
}
}
}
#[test]
fn a_fixed_size_array_is_one_buffer_and_one_value_per_record() {
let records: Vec<u8> = (0..18 * 5).map(|i| i as u8).collect();
let bytes = synth::stream(&[(tag(b"Nods"), F::Records(18, records.chunks(18).map(<[u8]>::to_vec).collect()))]);
let s = stream::parse(&bytes).unwrap();
let root = s.object(s.root).unwrap();
assert_eq!(root.get(Tag::of(b"Nods")), Some(&Value::Records { size: 18, data: records }));
assert_eq!(root.get(Tag::of(b"Nods")).and_then(Value::array_len), Some(5));
}
}
-179
View File
@@ -1,179 +0,0 @@
//! Artistic and frame text: the story's characters with their font, size, colour, tracking and
//! leading, the paragraph alignment and the first baseline. Layout (line breaks in frames, kerning,
//! OpenType features) is left to the importing application.
use crate::model::{Affine, Align, Point, Reader, Text, TextRun, rect};
use crate::paint::{self, Paint};
use crate::stream::{ObjId, Stream, Value};
/// Characters read per text node (stories are split into blocks; this caps hostile ones).
const MAX_CHARS: usize = 1 << 20;
pub(crate) fn read(r: &mut Reader, id: ObjId, world: Affine) -> Option<Text> {
let s = r.s;
let story = s.obj(id, b"StSt")?;
let frame = s.obj(id, b"TxtH")?;
let artistic = s.is(frame, b"ArFr");
let bounds = s.floats::<4>(frame, b"FrmB").map(rect)?;
let mut runs = Vec::new();
let mut align = None;
let mut total = 0usize;
let mut placeholders = false;
for block in s.objs(story, b"Blok") {
let glyphs = s.obj(block, b"Glyp")?;
let chars = block_chars(s, glyphs, total, &mut placeholders);
total = total.checked_add(chars.len())?;
if total > MAX_CHARS {
r.warn("text longer than a million characters (truncated)");
break;
}
let mut start = 0usize;
for run in s.obj(block, b"GAtt").map(|g| s.objs(g, b"Runs")).unwrap_or_default() {
let end = usize::try_from(s.int(run, b"Indx")?).ok()?.min(chars.len());
if end <= start {
continue;
}
let text: String = chars.get(start..end)?.iter().filter(|c| **c != '\0' && **c != '\u{FFFC}').collect();
start = end;
let Some(attrs) = s.obj(run, b"Item") else { continue };
if !text.is_empty() {
runs.push(run_attrs(r, attrs, text, world));
}
}
if align.is_none() {
align = s.obj(block, b"PAtt").and_then(|p| s.objs(p, b"Runs").first().copied()).and_then(|run| s.obj(run, b"Item")).map(|p| paragraph_align(r, p));
}
}
if placeholders {
r.warn("text fields such as page numbers (left out of the text)");
}
let align = align.unwrap_or(Align::Left);
let first_baseline = bounds.y0 + s.f64(frame, b"ArtV").unwrap_or(0.0);
let anchor_x = match align {
Align::Center => (bounds.x0 + bounds.x1) / 2.0,
Align::Right => bounds.x1,
_ => bounds.x0,
};
if !artistic {
if s.objs(frame, b"ColW").len() > 1 || s.array_len(frame, b"ColW").is_some_and(|n| n > 1) {
r.warn("text frames with several columns (imported as one column)");
}
if s.class(id) == Some(crate::stream::Tag::of(b"TxtC")) {
r.warn("text frames with a curved outline (imported as rectangular frames)");
}
}
Some(Text { runs, align, anchor: Point { x: anchor_x, y: first_baseline }, frame: if artistic { None } else { Some(bounds) }, transform: world })
}
/// The characters of one text block. A block without a UTF-8 string is a list of segments: each
/// inline object (page number, anchor) takes one `U+FFFC` before its segment's text. Stops once
/// `total` plus these characters would pass the cap.
fn block_chars(s: &Stream, glyphs: ObjId, total: usize, placeholders: &mut bool) -> Vec<char> {
// One past the allowance is enough to trip the check in `read`; both arms stop there.
let room = MAX_CHARS.saturating_sub(total).saturating_add(1);
match s.str(glyphs, b"Utf8") {
Some(t) => t.chars().take(room).collect(),
None => {
// Inline objects (page numbers, anchors) each take one index before the segment text.
let mut v = Vec::new();
// Shared segments repeated by reference must not expand beyond the allowance first.
for seg in s.objs(glyphs, b"Mixd") {
if v.len() >= room {
break;
}
let inline = s.objs(seg, b"Glys").len();
v.extend(std::iter::repeat_n('\u{FFFC}', inline.min(room - v.len())));
*placeholders |= inline > 0;
v.extend(s.str(seg, b"Utf8").unwrap_or_default().chars().take(room.saturating_sub(v.len())));
}
v
}
}
}
fn slot<T: Copy>(v: Option<&Value>, i: usize, f: impl Fn(&Value) -> Option<T>) -> Option<T> {
match v? {
Value::Array(a) => a.get(i).and_then(f),
_ => None,
}
}
fn float(v: &Value) -> Option<f64> {
match v {
Value::Float(f) if f.is_finite() => Some(*f),
_ => None,
}
}
fn int(v: &Value) -> Option<i64> {
match v {
Value::Int(i) => Some(*i),
Value::UInt(u) => i64::try_from(*u).ok(),
_ => None,
}
}
/// Longest font name kept; real PostScript and family names are far shorter.
const MAX_FONT_NAME: usize = 256;
/// A font name for one run. Runs repeat the same shared string, so its copies are charged
/// against a document-wide byte budget; an overlong name or an exhausted budget leaves it empty.
fn font_name(r: &mut Reader, font: Option<ObjId>, tag: &[u8; 4]) -> String {
let name = font.and_then(|f| r.s.str(f, tag)).unwrap_or_default();
if name.len() > MAX_FONT_NAME {
r.warn("font names longer than 256 bytes (left empty)");
return String::new();
}
if !r.charge_font_name(name.len()) {
r.warn("font names beyond the document metadata budget (left empty)");
return String::new();
}
name.to_string()
}
fn run_attrs(r: &mut Reader, attrs: ObjId, text: String, world: Affine) -> TextRun {
let s = r.s;
let doubles = s.field(attrs, b"Doub");
let ints = s.field(attrs, b"Ints");
let size = slot(doubles, 0, float).filter(|v| *v > 0.0 && *v < 1e6).unwrap_or(12.0 * r.dpi / 72.0);
let tracking = slot(doubles, 4, float).unwrap_or(0.0);
let leading = (slot(ints, 4, int) == Some(1)).then(|| slot(doubles, 13, float)).flatten().filter(|v| *v > 0.0);
let objects = match s.field(attrs, b"Objs") {
Some(Value::Array(a)) => a.iter().map(|v| if let Value::Obj(o) = v { *o } else { None }).collect(),
_ => Vec::new(),
};
let fill = objects.first().copied().flatten().and_then(|f| paint::descriptor(r, f, world)).unwrap_or(Paint::None);
if objects.get(1).copied().flatten().and_then(|f| paint::descriptor(r, f, world)).is_some_and(|p| p != Paint::None) {
r.warn("outlined (stroked) text");
}
if slot(doubles, 10, float).is_some_and(|h| (h - 1.0).abs() > 1e-3) {
r.warn("horizontally scaled text");
}
let font = s.obj(attrs, b"DFnt");
let postscript = font_name(r, font, b"Post");
let family = font_name(r, font, b"Famy");
TextRun {
text,
postscript,
family,
weight: font.and_then(|f| s.int(f, b"Wegt")).unwrap_or(400),
italic: font.and_then(|f| s.bool(f, b"Ital")).unwrap_or(false),
size,
tracking,
leading,
fill,
}
}
fn paragraph_align(r: &mut Reader, p: ObjId) -> Align {
match slot(r.s.field(p, b"Ints"), 0, int) {
Some(1) => Align::Center,
Some(2) => Align::Right,
Some(3) => Align::Justify,
Some(0) | None => Align::Left,
Some(_) => {
r.warn("an unknown paragraph alignment (imported as left)");
Align::Left
}
}
}
Loaded 100 of 2149 files, more files were not shown because too many files have changed in this diff. Show more