Merge main into fix/13940-comps-to-files-names

This commit is contained in:
RickiNano committed 2026-11-23 18:22:36 +01:00
commit 08b333edaf
987 files changed
+19792 -17670

No files matched your search

+2522 -2183
View File
File diff suppressed because it is too large. Load diff
+36 -6
View File
@@ -21,11 +21,24 @@ nextest-version = "0.9.150"
# parallelism.
[test-groups]
gpu = { max-threads = 4 }
# mcp_wait builds a 6000x6000 document and a radius-1000 Gaussian Blur so the
# waited command runs long enough to cancel. On the artcraft k8s gate pods that
# often fails with "not enough working memory" when it shares the shard with
# the rest of the suite; hosted ubuntu-24.04 stays green. A bridged jobs.list
# poll can also miss its 300ms test timeout under that load (run 45136461883).
# Run these alone: the group caps them at one, and threads-required keeps the
# rest of the shard off the machine while they run.
heavy-filter = { max-threads = 1 }
[[profile.default.overrides]]
filter = 'package(photocraft-gpu) | test(/(^|::|_)gpu_tests::/)'
test-group = 'gpu'
[[profile.default.overrides]]
filter = 'package(photocraft-automation) & test(/^mcp_wait::/)'
test-group = 'heavy-filter'
threads-required = "num-test-threads"
# CI (`--profile ci`, .github/workflows/ci.yml). Collect all failures in one integration run
# instead of exposing one regression per rebuild. A hanging test still terminates, and every
# failure is repeated at the end of the log. The default profile's GPU override still applies.
@@ -43,6 +56,23 @@ archive.include = [
{ path = "gate-shards.json", relative-to = "target", depth = 0, on-missing = "ignore" },
]
# panic_hunt drives every command with adversarial parameters and exists to find hangs, so a hang
# must cost seconds, not the profile's 10 minutes. Hosted ubuntu-24.04 is about 18 s and Windows
# about 26 s. On artcraft-k8s-main it is typically 31-33 s, and under memory pressure it has
# timed out at 45 s after nearly finishing the registry (run 45127595159). The first slow
# warning still comes at 15 s; a run past 90 s is terminated.
[[profile.ci.overrides]]
filter = 'binary(panic_hunt)'
slow-timeout = { period = "15s", terminate-after = 6 }
# Content-Aware Move solves on rayon across every core. On the Windows runner the GPU tests draw
# on the CPU-backed adapter, so two of these beside a GPU test starve it until its device poll
# times out. Each runs alone there.
[[profile.ci.overrides]]
platform = 'cfg(target_os = "windows")'
filter = '(package(photocraft-engine-core) | package(photocraft-engine)) & test(/content_aware_move/)'
threads-required = "num-test-threads"
# Keep phase timings for the remaining expensive Windows GPU regressions visible. This does
# not relax their timeout, isolate failures differently or remove any test cases.
# Page eviction and budget borrowing redraw multi-effect documents. On the Windows
@@ -82,23 +112,23 @@ priority = 100
# 60 to 200 s
filter = '''
(package(photocraft-gpu) & test(=camera_raw::clarity_texture_and_dehaze_with_shadows_highlights_and_per_pixel_stages)) |
(package(photocraft-engine) & test(=cmd::retouch_cmds::content_aware_move::tests::a_coarse_preview_keeps_a_faint_sparse_selection)) |
(package(photocraft-engine-core) & test(=cmd::retouch_cmds::content_aware_move::tests::a_coarse_preview_keeps_a_faint_sparse_selection)) |
(package(photocraft-engine) & test(=crop_content_aware_layers::unmeasured_active_targets_and_delete_off_keep_the_legacy_target)) |
(package(photocraft-engine) & test(=cmd::retouch_cmds::content_aware_move::color_tests::a_flat_patch_matches_the_new_surroundings_at_color_ten)) |
(package(photocraft-engine-core) & test(=cmd::retouch_cmds::content_aware_move::color_tests::a_flat_patch_matches_the_new_surroundings_at_color_ten)) |
(package(photocraft-ui-egui) & test(=tools::type_tool::canvas_tests::every_paragraph_box_handle_resizes_the_box_with_snapping_on)) |
(package(photocraft-ui-egui) & test(=gpu_tests::checker_canvas::pixel_grid_is_solid_and_visible_gpu_2x)) |
(package(photocraft-engine) & test(=cmd::retouch_cmds::tests::content_aware_move_coarse_preview_handles_transform_extend_and_limits)) |
(package(photocraft-engine-core) & test(=cmd::retouch_cmds::tests::content_aware_move_coarse_preview_handles_transform_extend_and_limits)) |
(package(photocraft-ui-egui) & test(=gpu_tests::checker_canvas::pixel_grid_is_solid_and_visible_cpu_2x)) |
(package(photocraft-ui-egui) & test(=gpu_tests::drag_preview_canvas::marquee_previews_show_while_dragging_on_white_and_black_at_1x_and_2x)) |
(package(photocraft-gpu) & test(=camera_raw::shadows_and_highlights_with_per_pixel_stages)) |
(package(photocraft-engine) & test(=cmd::retouch_cmds::content_aware_move::color_tests::a_brightness_change_shifts_the_middle_only_past_color_five)) |
(package(photocraft-engine) & test(=cmd::retouch_cmds::tests::content_aware_move_previews_large_selections_coarse_then_exact_at_all_depths)) |
(package(photocraft-engine-core) & test(=cmd::retouch_cmds::content_aware_move::color_tests::a_brightness_change_shifts_the_middle_only_past_color_five)) |
(package(photocraft-engine-core) & test(=cmd::retouch_cmds::tests::content_aware_move_previews_large_selections_coarse_then_exact_at_all_depths)) |
(package(photocraft-ui-egui) & test(=gpu_tests::live_stroke_canvas::live_tool_camera_navigation_is_visible_in_the_input_frame)) |
(package(photocraft-ui-egui) & test(=gpu_tests::live_stroke_canvas::the_canvas_shows_the_committed_stroke_part_0)) |
(package(photocraft-ui-egui) & test(=gpu_tests::full_res_preview::adjustment_layer_drag_previews_at_full_resolution_when_low_res_is_off)) |
(package(photocraft-ui-egui) & test(=input::hold_keys::tests::cmd_gives_the_move_tool_only_where_the_tool_does_not_take_cmd)) |
(package(photocraft-ui-egui) & test(=guide_cursor_tests::command_over_a_guide_takes_it_where_command_is_the_move_tool)) |
(package(photocraft-gpu) & test(=parity::documents_larger_than_the_texture_limit)) |
(package(photocraft-engine) & test(=cmd::retouch_cmds::content_aware_move::tests::a_preview_within_the_full_resolution_budget_is_the_plain_solve_bit_for_bit))
(package(photocraft-engine-core) & test(=cmd::retouch_cmds::content_aware_move::tests::a_preview_within_the_full_resolution_budget_is_the_plain_solve_bit_for_bit))
'''
priority = 50
+126 -65
View File
@@ -2,7 +2,7 @@ name: CI
# Quality gates for every push to main and every pull request. The Linux and Windows tests run
# through the suite's shared gate workflow in craft-common-actions (`cargo xtask ci`, split over the
# gate's jobs); the test variant and the corpus, web and fuzz jobs are PhotoCraft's own. Every night
# gate's jobs); the test variant, web and fuzz jobs are PhotoCraft's own. Every night
# the Linux gate alone runs a cold build: the safety net for the workspace crates it keeps between
# runs (`cache-workspace-crates`), and a fresh start for that cache entry.
on:
@@ -16,7 +16,7 @@ on:
workflow_dispatch:
inputs:
full_sweep:
description: "Run every testkit sweep case (runtime comparison and integration validation)"
description: "Run every testkit sweep case and every corpus file, as the nightly run does (runtime comparison and integration validation)"
type: boolean
default: false
color_range:
@@ -58,7 +58,9 @@ permissions:
env:
CARGO_TERM_COLOR: always
RUST_BACKTRACE: 1
PHOTOCRAFT_FULL_SWEEP: ${{ inputs.full_sweep && '1' || '0' }}
# Every case of the long test sweeps and every corpus file (photocraft-testkit `full_sweep`): the
# nightly run and manual runs with `full_sweep`. Other runs take a sweep part and the corpus samples.
PHOTOCRAFT_FULL_SWEEP: ${{ (inputs.full_sweep || github.event_name == 'schedule') && '1' || '0' }}
# No test or fuzz run may print a page: the engine refuses to spool, and if something ever
# bypasses that, lp fails loudly on a printer that does not exist.
PHOTOCRAFT_NO_PRINT: "1"
@@ -87,6 +89,8 @@ jobs:
# Pull requests run them only when they change the GPU crate, a workspace crate it builds on, any
# package manifest, or a file outside the workspace packages other than documentation
# (scripts/ci-windows-gpu-tests.py, #15247); the Linux gate runs them on every pull request, and main runs them on Windows too.
# `linux_skip`: the packages the Linux gate leaves out of its test build because nothing a pull request changes
# reaches them (same rule, every package but photocraft-gpu); empty on main, the nightly run and `full-ci`.
# `windows_skip`: the platform-neutral packages whose Windows tests a pull request skips because nothing it
# changes reaches them (same script); empty on main and `full-ci`.
platforms:
@@ -98,6 +102,7 @@ jobs:
windows: ${{ steps.pick.outputs.windows }}
windows_gpu: ${{ steps.pick.outputs.windows_gpu }}
windows_skip: ${{ steps.pick.outputs.windows_skip }}
linux_skip: ${{ steps.pick.outputs.linux_skip }}
web: ${{ steps.pick.outputs.web }}
steps:
- name: Harden runner
@@ -119,6 +124,7 @@ jobs:
echo "windows=true"
echo "windows_gpu=true"
echo "windows_skip="
echo "linux_skip="
echo "web=true"
} >> "$GITHUB_OUTPUT"
exit 0
@@ -142,6 +148,11 @@ jobs:
if [ "$gpu" = false ]; then
echo "::notice::photocraft-gpu's tests are skipped on Windows: this pull request changes nothing they are built from (the Linux gate still runs them)."
fi
linux_skip=$(python3 scripts/ci-windows-gpu-tests.py --skip-linux "$BASE")
echo "linux_skip=$linux_skip" >> "$GITHUB_OUTPUT"
if [ -n "$linux_skip" ]; then
echo "::notice::Tests of packages the pull request does not reach are skipped on Linux (main runs them all): $linux_skip"
fi
skip=$(python3 scripts/ci-windows-gpu-tests.py --skip-neutral "$BASE")
echo "windows_skip=$skip" >> "$GITHUB_OUTPUT"
if [ -n "$skip" ]; then
@@ -163,7 +174,10 @@ jobs:
# the newest one. The lint legs keep no cache (`lint-cache: false`): a cold lint leg costs
# minutes, and their entries (~1 GB per OS) would not fit the 10 GB cache budget.
gate:
if: github.event.action != 'labeled' || github.event.label.name == 'full-ci'
# `platforms` is skipped on the nightly run, which tests everything. When it fails, its outputs
# are empty (`linux_skip` included), so the gate still runs and tests everything.
needs: platforms
if: ${{ !cancelled() && (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/gate.yml@main
with:
@@ -178,16 +192,20 @@ jobs:
# 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: cc9269cd8d8258785dac603fba3122e5d2556795
# Every .rs file is reached by a mod, #[path] or include!; a new unreached file fails the lint leg.
unreached-rs-mode: strict
# CI test binaries carry no debuginfo and no symbols (CARGO_PROFILE_TEST_STRIP below): a
# test build drops from ~19 to ~6.5 GB. A panic still names its file and line; only
# backtrace frames lose names and lines. Local builds keep Cargo.toml's line tables.
dev-debug: "0"
cache-version: v2
env: |
PHOTOCRAFT_FULL_SWEEP=${{ inputs.full_sweep && '1' || '0' }}
PHOTOCRAFT_FULL_SWEEP=${{ (inputs.full_sweep || github.event_name == 'schedule') && '1' || '0' }}
PHOTOCRAFT_NO_PRINT=1
LPDEST=photocraft-no-such-printer
CARGO_PROFILE_TEST_STRIP=symbols
PHOTOCRAFT_CI_EXCLUDE=${{ needs.platforms.outputs.linux_skip }}
PHOTOCRAFT_CORPUS_TESTS=1
timeout-minutes: 100
cache-workspace-crates: true
lint-cache: false
@@ -195,7 +213,7 @@ jobs:
# fmt, egui-fork, clippy, layers, panel-commands, scorecard, the wasm32 check and the
# missing-translations report (`cargo xtask ci lint`, xtask/src/main.rs), and the CI scripts'
# own tests.
lint-command: python3 scripts/test-ci-gpu-lavapipe.py && python3 scripts/test-ci-windows-gpu-tests.py && python3 scripts/test-ci-test-times.py && cargo xtask ci lint
lint-command: python3 scripts/test-ci-gpu-lavapipe.py && python3 scripts/test-ci-windows-gpu-tests.py && python3 scripts/test-ci-test-times.py && python3 scripts/test-ci-toolchain-bump.py && python3 scripts/test-ci-clear-rolling-cache.py && cargo xtask ci lint
archive-command: cargo xtask-gate archive --gpu-shard
after-archive-command: cargo xtask-gate doctest
test-shards: 4
@@ -238,7 +256,7 @@ jobs:
# identical-code folding and PDBs; the link arguments in build.rs (/DELAYLOAD, delayimp.lib)
# are lld-link options too.
env: |
PHOTOCRAFT_FULL_SWEEP=${{ inputs.full_sweep && '1' || '0' }}
PHOTOCRAFT_FULL_SWEEP=${{ (inputs.full_sweep || github.event_name == 'schedule') && '1' || '0' }}
PHOTOCRAFT_NO_PRINT=1
LPDEST=photocraft-no-such-printer
CARGO_TARGET_DIR=D:\t
@@ -257,7 +275,7 @@ jobs:
# budget and GitHub never evicts an entry a run still needs (an evicted Windows entry makes the
# Windows build cold, about 60 instead of 21 minutes). It runs beside the run's jobs and prunes
# each time a job that saves an entry finishes: the gate's build jobs (the Linux rolling entry,
# about 4 GB, and the Windows dependency entry), web and corpus. A skipped job is listed under its
# about 4 GB, and the Windows dependency entry) and web. A skipped job is listed under its
# own name (a skipped reusable-workflow call under the caller job's), so a run that skips one
# still ends. No `needs`: the gate is one reusable call, and waiting for it would leave the
# replaced entry in place until every shard has run. A failed prune warns instead of failing the
@@ -282,12 +300,35 @@ jobs:
with:
watch: true
watch-minutes: 110
content-keys: corpus
saving-jobs: |
^gate( / build \(.*\))?$
^windows( / build \(.*\))?$
^web build and wasm size gate$
^corpus tests$
# The nightly cold run never restores the rolling crates entry, so the old entry is only overlap
# while the cold run saves its own: two entries of about 4 GB, which with the others go over the
# 10 GB cache limit and get the Windows, web and corpus entries evicted. This deletes the old
# entries when the build job starts saving (scripts/ci-clear-rolling-cache.py).
cold-cache-clear:
name: cold cache clear
if: github.event_name == 'schedule'
runs-on: ubuntu-24.04
timeout-minutes: 110
continue-on-error: true
permissions:
actions: write
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
- name: Delete the old rolling entries before the save
env:
GH_TOKEN: ${{ github.token }}
run: python3 scripts/ci-clear-rolling-cache.py
# The same codecs without the optional decoder: HEIC must stay a clear "not in this build" error
# for distributors who leave it out. Runs beside the gate and restores the gate's newest rolling
@@ -327,9 +368,13 @@ jobs:
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev
libgtk-3-dev
- id: rust
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: stable
toolchain: ${{ steps.rust.outputs.toolchain }}
targets: ${{ steps.rust.outputs.targets }}
components: ${{ steps.rust.outputs.components }}
# The gate's own key (the shared action computes it), restore only. The toolchain action
# exports CARGO_HOME, which the gate's legs do not have; align-environment leaves it out of
@@ -347,50 +392,6 @@ jobs:
- name: Test without heif
run: cargo nextest run -p photocraft-io --locked --profile ci
corpus:
if: github.event_name != 'schedule' && (github.event.action != 'labeled' || github.event.label.name == 'full-ci')
timeout-minutes: 30
# Real-file corpus tests (cargo feature `corpus`), on every PR and on main. The corpora are
# pinned in xtask/src/corpus_pins.rs and sha256-verified (xtask/*.sha256) after both a cache
# restore and a download; a missing corpus fails the tests. The cache key changes only when a
# pin or manifest does, so normally this restores in seconds (fork PRs read the base cache).
name: corpus tests
runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-main' || 'ubuntu-latest' }}
env:
# test-corpus builds with --release, but here without the release profile's thin LTO and
# single codegen unit: they ran LTO over the dependency graph for each of the ~95 corpus test
# binaries, so building took 23.5 of the job's 37 minutes while the tests ran for 1.5.
# Turning them off builds 2.7x faster; the code under test is the same.
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: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: stable
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with:
prefix-key: v1-rust
key: corpus
save-if: ${{ github.ref == 'refs/heads/main' }}
cache-on-failure: true
- name: Restore test corpora
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: corpus/
key: corpus-${{ hashFiles('xtask/src/corpus_pins.rs', 'xtask/*.sha256') }}
- name: Fetch and verify corpora
run: cargo xtask corpus --all
- name: Corpus tests
run: cargo xtask test-corpus
web:
timeout-minutes: 60
name: web build and wasm size gate
@@ -415,10 +416,13 @@ jobs:
- name: Check out craft-i18n
uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main
- id: rust
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: stable
targets: wasm32-unknown-unknown
toolchain: ${{ steps.rust.outputs.toolchain }}
targets: ${{ steps.rust.outputs.targets }}
components: ${{ steps.rust.outputs.components }}
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with:
prefix-key: v1-rust
@@ -463,6 +467,9 @@ jobs:
# Placeholder: manual trigger only until a nightly schedule is enabled.
if: github.event_name == 'workflow_dispatch' && inputs.fuzz
runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-main' || 'ubuntu-latest' }}
env:
# cargo-fuzz needs nightly; the checkout's rust-toolchain.toml would pick the pinned release.
RUSTUP_TOOLCHAIN: nightly
strategy:
fail-fast: false
matrix:
@@ -534,13 +541,17 @@ jobs:
packages: >-
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev
libgtk-3-dev
- id: rust
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: stable
toolchain: ${{ steps.rust.outputs.toolchain }}
targets: ${{ steps.rust.outputs.targets }}
components: ${{ steps.rust.outputs.components }}
- name: Compare exact outputs and release timings on 24 MP
run: |
set -o pipefail
cargo test --release -p photocraft-engine --lib color_range_release_comparison -- --ignored --nocapture | tee color-range-perf.txt
cargo test --release -p photocraft-engine-core --lib color_range_release_comparison -- --ignored --nocapture | tee color-range-perf.txt
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
if: always()
with:
@@ -567,9 +578,13 @@ jobs:
packages: >-
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev
libgtk-3-dev
- id: rust
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: stable
toolchain: ${{ steps.rust.outputs.toolchain }}
targets: ${{ steps.rust.outputs.targets }}
components: ${{ steps.rust.outputs.components }}
- name: Compare exact outputs and release timings on 36 MP
run: |
set -o pipefail
@@ -577,7 +592,7 @@ jobs:
- name: Compare cropped command reads and writeback on 36 MP
run: |
set -o pipefail
cargo test --release -p photocraft-engine --lib sparse_modify_release_comparison -- --ignored --nocapture | tee -a selection-morphology-perf.txt
cargo test --release -p photocraft-engine-core --lib sparse_modify_release_comparison -- --ignored --nocapture | tee -a selection-morphology-perf.txt
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
if: always()
with:
@@ -599,9 +614,13 @@ jobs:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- id: rust
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: stable
toolchain: ${{ steps.rust.outputs.toolchain }}
targets: ${{ steps.rust.outputs.targets }}
components: ${{ steps.rust.outputs.components }}
# perf-nightly.yml's entry (same key and runner); only that job saves it.
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with:
@@ -632,9 +651,13 @@ jobs:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- id: rust
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: stable
toolchain: ${{ steps.rust.outputs.toolchain }}
targets: ${{ steps.rust.outputs.targets }}
components: ${{ steps.rust.outputs.components }}
- name: Compare exact outputs and release timings on 36 MP
run: |
set -o pipefail
@@ -665,9 +688,13 @@ jobs:
persist-credentials: false
ref: ${{ inputs.brush_tip_base }}
path: before
- id: rust
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: stable
toolchain: ${{ steps.rust.outputs.toolchain }}
targets: ${{ steps.rust.outputs.targets }}
components: ${{ steps.rust.outputs.components }}
- name: Build the same benchmark against both versions
run: |
cp after/crates/paint/examples/big_dab_bench.rs before/crates/paint/examples/big_dab_bench.rs
@@ -716,9 +743,13 @@ 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"
- id: rust
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: stable
toolchain: ${{ steps.rust.outputs.toolchain }}
targets: ${{ steps.rust.outputs.targets }}
components: ${{ steps.rust.outputs.components }}
- name: Install Linux build dependencies
uses: storytold/craft-common-actions/actions/install-apt-packages@main
with:
@@ -751,3 +782,33 @@ jobs:
with:
name: dry-mixer-performance
path: dry-mixer-perf.txt
# After the nightly cold run passes, a warning (annotation and job summary) says when a newer stable
# Rust release than rust-toolchain.toml's exists. It needs no permission and changes nothing: a bump
# is a pull request that changes the file's `channel` by hand.
toolchain-check:
name: toolchain check
needs: gate
if: github.event_name == 'schedule' && needs.gate.result == 'success'
runs-on: ubuntu-24.04
timeout-minutes: 10
continue-on-error: true
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
- name: Compare the pinned release with stable
run: |
set -euo pipefail
version=$(python3 scripts/ci-toolchain-bump.py)
if [ -z "$version" ]; then
echo "rust-toolchain.toml is current"
exit 0
fi
msg="Rust $version is the newest stable release; rust-toolchain.toml pins an older one. Change its channel in a pull request to move."
echo "::warning title=Newer Rust release::$msg"
echo "$msg" >> "$GITHUB_STEP_SUMMARY"
+5 -1
View File
@@ -51,9 +51,13 @@ jobs:
with:
persist-credentials: false
- id: rust
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: stable
toolchain: ${{ steps.rust.outputs.toolchain }}
targets: ${{ steps.rust.outputs.targets }}
components: ${{ steps.rust.outputs.components }}
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with:
+1
View File
@@ -56,3 +56,4 @@ jobs:
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
+2
View File
@@ -23,4 +23,6 @@ jobs:
fonts-ref: cc9269cd8d8258785dac603fba3122e5d2556795
# The coverage build's ~1.3 GB cache would not fit the repository's 10 GB cache budget.
build-cache: false
python-coverage-source: packaging
python-coverage-script: packaging/nightly-tests.py
secrets: inherit
+5
View File
@@ -11,3 +11,8 @@ target/
/craft-fonts
*.log
__pycache__/
# Checked out inside the workspace by the shared nightly workflows (craft-common-actions).
/.nightly-tools
/.nightly-input
/craft-i18n
+1 -1
View File
@@ -88,7 +88,7 @@ Conventions and paths:
- `unsafe` is allowed only in `crates/tablet/src/macos.rs` and `windows.rs`; the workspace sets `unsafe_code = "forbid"`. The example plug-in in `examples/plugins/` is outside the workspace and uses `unsafe` for the WebAssembly host calls. Every new crate sets `[lints] workspace = true`.
- Attribution file: `ATTRIBUTION.md`. Fonts come from storytold/craft-fonts through `CRAFT_FONTS_DIR` (`docs/development.md` > Fonts).
- Test corpora: storytold/photocraft-corpus, fetched into `corpus/` by `cargo xtask corpus --all` at the pins in `xtask/src/corpus_pins.rs`.
- Test corpora: storytold/photocraft-corpus, fetched into `corpus/` by `cargo xtask corpus --all` at the pins in `xtask/src/corpus_pins.rs`. `cargo xtask test-corpus` runs each directory's fixed sample; `PHOTOCRAFT_FULL_SWEEP=1` runs every file (CI: samples on pull requests and main, every file nightly).
- Feature names are recorded in `docs/feature-names.md`.
- Contributor credits: `docs/contributors.md`.
- Dev log: `log/devlog.md` (local, gitignored). `plan/` is an optional local notebook.
+6
View File
@@ -22,6 +22,8 @@ next to them.
| `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/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 |
| `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) |
| `assets/app-icon/photocraft-nightly.png`, `photocraft-nightly-1024.png`, `photocraft-nightly.ico`, `photocraft-nightly.icns` | PhotoCraft nightly deep-background derivatives | @skylartaylor | Original project-owned256 and padded1024 masters at the revision and hashes in [`nightly-provenance.json`](assets/app-icon/nightly-provenance.json); code-generated background-contribution change only, preserving foreground/alpha; no badge or crescent | MIT OR Apache-2.0, [`assets/app-icon/LICENSE.txt`](assets/app-icon/LICENSE.txt) |
| `packaging/nightly-archive-tests.py` (runtime-generated temporary files) | Synthetic flat-archive inventory and exclusive-output fixtures; regular-file payloads, not real image/executable validity | @skylartaylor | Original test-generated strings/files and symlinks from the committed script; no external media or user documents | MIT OR Apache-2.0 |
| `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) |
| `crates/ui-egui/src/theme.rs` (Breeze Light and Breeze Dark themes) | The Breeze Light and Breeze Dark themes are original colour values on PhotoCraft's Studio layout, chosen to look close to KDE Plasma's Breeze (cool blue-greys, blue accent, 5 px frame radius) so the app blends into a Plasma desktop. None of Breeze's colour values, files or code are copied; the values are a few levels away from its schemes and tuned for text contrast | PhotoCraft contributors | Inspired by the look of KDE Breeze, <https://invent.kde.org/plasma/breeze> (its colour schemes are LGPL-2.0-or-later) | Original work |
@@ -132,3 +134,7 @@ longer used or shipped.
| Dependency | Authors | Source | License and notices |
|---|---|---|---|
| `jpeg-encoder` 0.6.1, through `craft-image-codecs` | Upstream jpeg-encoder, IJG and SIMD authors named in the notices | [Published crate](https://crates.io/crates/jpeg-encoder/0.6.1) | `(MIT OR Apache-2.0) AND IJG`; complete notices in [NOTICE](NOTICE), source texts and checksums in [licenses/jpeg-encoder-0.6.1](licenses/jpeg-encoder-0.6.1) |
Mac Nightly metadata tests (`packaging/macos/nightly_plist_tests.py`) generate plist dictionaries and owned sentinel bytes from this repository's app-owned Info.plist template. They use no native binaries, signing credentials, external products or archives; @skylartaylor.
Windows nightly signing-policy tests generate dummy environment values, signature-status objects and owned sentinel bytes. They never contain signing material or invoke a compiler, signing tool or network; @skylartaylor.
Generated
+180 -117
View File
@@ -1365,12 +1365,12 @@ dependencies = [
[[package]]
name = "craft"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-automation",
"craft-behavior",
"craft-browse",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"craft-color-ui",
"craft-control",
"craft-dialogs",
@@ -1406,7 +1406,7 @@ dependencies = [
[[package]]
name = "craft-affinity"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"crc32fast",
"flate2",
@@ -1427,7 +1427,7 @@ dependencies = [
[[package]]
name = "craft-atomic"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"rustix 1.1.5",
]
@@ -1435,7 +1435,7 @@ dependencies = [
[[package]]
name = "craft-automation"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"base64 0.22.1",
"craft-behavior",
@@ -1460,7 +1460,7 @@ dependencies = [
[[package]]
name = "craft-behavior"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"accesskit",
"bitflags 2.13.2",
@@ -1478,7 +1478,7 @@ dependencies = [
[[package]]
name = "craft-browse"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-docpath",
@@ -1496,7 +1496,7 @@ dependencies = [
[[package]]
name = "craft-cloud-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"egui",
]
@@ -1504,7 +1504,7 @@ dependencies = [
[[package]]
name = "craft-cms"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c42c34bfa127b095fb0a8d5ccaba0c168c254062#c42c34bfa127b095fb0a8d5ccaba0c168c254062"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"md-5",
"rayon",
@@ -1513,7 +1513,7 @@ dependencies = [
[[package]]
name = "craft-cms"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=b2d2a1e948c43d95aa769d4f0a06fe6b869edc39#b2d2a1e948c43d95aa769d4f0a06fe6b869edc39"
dependencies = [
"md-5",
"rayon",
@@ -1522,12 +1522,12 @@ dependencies = [
[[package]]
name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
[[package]]
name = "craft-color"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c42c34bfa127b095fb0a8d5ccaba0c168c254062#c42c34bfa127b095fb0a8d5ccaba0c168c254062"
source = "git+https://github.com/storytold/craft-libs?rev=b2d2a1e948c43d95aa769d4f0a06fe6b869edc39#b2d2a1e948c43d95aa769d4f0a06fe6b869edc39"
dependencies = [
"serde",
]
@@ -1535,9 +1535,9 @@ dependencies = [
[[package]]
name = "craft-color-transform"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c42c34bfa127b095fb0a8d5ccaba0c168c254062#c42c34bfa127b095fb0a8d5ccaba0c168c254062"
source = "git+https://github.com/storytold/craft-libs?rev=b2d2a1e948c43d95aa769d4f0a06fe6b869edc39#b2d2a1e948c43d95aa769d4f0a06fe6b869edc39"
dependencies = [
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c42c34bfa127b095fb0a8d5ccaba0c168c254062)",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b2d2a1e948c43d95aa769d4f0a06fe6b869edc39)",
"craft-color",
"serde",
]
@@ -1545,10 +1545,10 @@ dependencies = [
[[package]]
name = "craft-color-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"craft-host",
"craft-i18n",
"craft-keymap",
@@ -1565,7 +1565,7 @@ dependencies = [
[[package]]
name = "craft-control"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-ai-agents",
"craft-atomic",
@@ -1580,9 +1580,9 @@ dependencies = [
[[package]]
name = "craft-crs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"craft-xml",
"thiserror 2.0.21",
]
@@ -1590,7 +1590,15 @@ dependencies = [
[[package]]
name = "craft-crw"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-crw"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=b2d2a1e948c43d95aa769d4f0a06fe6b869edc39#b2d2a1e948c43d95aa769d4f0a06fe6b869edc39"
dependencies = [
"thiserror 2.0.21",
]
@@ -1598,7 +1606,7 @@ dependencies = [
[[package]]
name = "craft-dds"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"rayon",
]
@@ -1606,21 +1614,25 @@ dependencies = [
[[package]]
name = "craft-develop"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c42c34bfa127b095fb0a8d5ccaba0c168c254062#c42c34bfa127b095fb0a8d5ccaba0c168c254062"
source = "git+https://github.com/storytold/craft-libs?rev=b2d2a1e948c43d95aa769d4f0a06fe6b869edc39#b2d2a1e948c43d95aa769d4f0a06fe6b869edc39"
dependencies = [
"craft-color",
"craft-color-transform",
"craft-develop-model",
"craft-geom",
"craft-raw 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b2d2a1e948c43d95aa769d4f0a06fe6b869edc39)",
"rayon",
"serde",
"serde_json",
]
[[package]]
name = "craft-develop-model"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c42c34bfa127b095fb0a8d5ccaba0c168c254062#c42c34bfa127b095fb0a8d5ccaba0c168c254062"
source = "git+https://github.com/storytold/craft-libs?rev=b2d2a1e948c43d95aa769d4f0a06fe6b869edc39#b2d2a1e948c43d95aa769d4f0a06fe6b869edc39"
dependencies = [
"craft-geom",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c42c34bfa127b095fb0a8d5ccaba0c168c254062)",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b2d2a1e948c43d95aa769d4f0a06fe6b869edc39)",
"miniz_oxide 0.9.1",
"serde",
"serde_json",
@@ -1629,7 +1641,7 @@ dependencies = [
[[package]]
name = "craft-dialogs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"block2 0.6.2",
"craft-atomic",
@@ -1654,7 +1666,7 @@ dependencies = [
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"serde",
]
@@ -1662,7 +1674,7 @@ dependencies = [
[[package]]
name = "craft-draw"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-color-ui",
@@ -1681,12 +1693,12 @@ dependencies = [
[[package]]
name = "craft-eps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
[[package]]
name = "craft-file-formats"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-eps",
"craft-idml",
@@ -1694,7 +1706,7 @@ dependencies = [
"craft-kra",
"craft-ora",
"craft-pcraft-bundle",
"craft-raw",
"craft-raw 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"craft-svg",
"craft-zip",
"serde",
@@ -1704,7 +1716,7 @@ dependencies = [
[[package]]
name = "craft-flags"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-atomic",
"dirs",
@@ -1714,7 +1726,7 @@ dependencies = [
[[package]]
name = "craft-font-catalog"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"fontique",
"harfrust 0.13.3",
@@ -1729,11 +1741,12 @@ dependencies = [
[[package]]
name = "craft-font-manager"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-font-catalog",
"craft-font-store",
"craft-fonts-build",
"craft-host",
"craft-i18n",
"craft-theme",
@@ -1748,7 +1761,7 @@ dependencies = [
[[package]]
name = "craft-font-store"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"cap-primitives",
"craft-atomic",
@@ -1769,12 +1782,12 @@ dependencies = [
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
[[package]]
name = "craft-geom"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c42c34bfa127b095fb0a8d5ccaba0c168c254062#c42c34bfa127b095fb0a8d5ccaba0c168c254062"
source = "git+https://github.com/storytold/craft-libs?rev=b2d2a1e948c43d95aa769d4f0a06fe6b869edc39#b2d2a1e948c43d95aa769d4f0a06fe6b869edc39"
dependencies = [
"serde",
]
@@ -1782,7 +1795,7 @@ dependencies = [
[[package]]
name = "craft-heif"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"heic-rs",
"rayon",
@@ -1791,7 +1804,7 @@ dependencies = [
[[package]]
name = "craft-host"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"bitflags 2.13.2",
"craft-i18n",
@@ -1804,7 +1817,7 @@ dependencies = [
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"chrono",
"fixed_decimal",
@@ -1832,7 +1845,7 @@ dependencies = [
[[package]]
name = "craft-idml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-xml",
"craft-zip",
@@ -1842,13 +1855,13 @@ dependencies = [
[[package]]
name = "craft-image-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-dds",
"craft-heif",
"craft-jpeg",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"crc32fast",
"exr",
"flate2",
@@ -1870,7 +1883,7 @@ dependencies = [
[[package]]
name = "craft-imaging"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-color-ui",
@@ -1888,12 +1901,12 @@ dependencies = [
[[package]]
name = "craft-ipp"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
[[package]]
name = "craft-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"thiserror 2.0.21",
]
@@ -1901,7 +1914,7 @@ dependencies = [
[[package]]
name = "craft-keymap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-host",
"craft-i18n",
@@ -1916,7 +1929,7 @@ dependencies = [
[[package]]
name = "craft-kra"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-xml",
"craft-zip",
@@ -1926,7 +1939,7 @@ dependencies = [
[[package]]
name = "craft-layers"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-i18n",
@@ -1940,7 +1953,7 @@ dependencies = [
[[package]]
name = "craft-menu"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-host",
@@ -1958,11 +1971,11 @@ dependencies = [
[[package]]
name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c42c34bfa127b095fb0a8d5ccaba0c168c254062#c42c34bfa127b095fb0a8d5ccaba0c168c254062"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"brotli-decompressor 6.3.2",
"chrono",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c42c34bfa127b095fb0a8d5ccaba0c168c254062)",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"quick-xml 0.41.0",
"serde",
]
@@ -1970,11 +1983,11 @@ dependencies = [
[[package]]
name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=b2d2a1e948c43d95aa769d4f0a06fe6b869edc39#b2d2a1e948c43d95aa769d4f0a06fe6b869edc39"
dependencies = [
"brotli-decompressor 6.3.2",
"chrono",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b2d2a1e948c43d95aa769d4f0a06fe6b869edc39)",
"quick-xml 0.41.0",
"serde",
]
@@ -1982,7 +1995,7 @@ dependencies = [
[[package]]
name = "craft-ora"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-xml",
"craft-zip",
@@ -1992,7 +2005,7 @@ dependencies = [
[[package]]
name = "craft-pages"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-keymap",
@@ -2007,7 +2020,7 @@ dependencies = [
[[package]]
name = "craft-pcraft-bundle"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"blake3",
"craft-atomic",
@@ -2020,7 +2033,7 @@ dependencies = [
[[package]]
name = "craft-pcraft-format"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"flate2",
"serde",
@@ -2031,7 +2044,7 @@ dependencies = [
[[package]]
name = "craft-pdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"bytemuck",
"flate2",
@@ -2046,7 +2059,7 @@ dependencies = [
[[package]]
name = "craft-pdn"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"flate2",
"thiserror 2.0.21",
@@ -2055,7 +2068,7 @@ dependencies = [
[[package]]
name = "craft-platform"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"async-channel",
"async-io",
@@ -2085,7 +2098,7 @@ dependencies = [
[[package]]
name = "craft-plist"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"thiserror 2.0.21",
]
@@ -2093,7 +2106,7 @@ dependencies = [
[[package]]
name = "craft-print"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2116,7 +2129,7 @@ dependencies = [
[[package]]
name = "craft-psd"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"encoding_rs",
"flate2",
@@ -2127,7 +2140,7 @@ dependencies = [
[[package]]
name = "craft-quit"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"dispatch2",
"egui",
@@ -2138,12 +2151,30 @@ dependencies = [
[[package]]
name = "craft-raw"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"chrono",
"craft-crw",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)",
"craft-crw 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"jxl-oxide",
"miniz_oxide 0.9.1",
"rayon",
"serde",
"thiserror 2.0.21",
"zune-core",
"zune-jpeg",
]
[[package]]
name = "craft-raw"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=b2d2a1e948c43d95aa769d4f0a06fe6b869edc39#b2d2a1e948c43d95aa769d4f0a06fe6b869edc39"
dependencies = [
"chrono",
"craft-crw 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b2d2a1e948c43d95aa769d4f0a06fe6b869edc39)",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b2d2a1e948c43d95aa769d4f0a06fe6b869edc39)",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b2d2a1e948c43d95aa769d4f0a06fe6b869edc39)",
"jxl-oxide",
"miniz_oxide 0.9.1",
"rayon",
@@ -2156,7 +2187,7 @@ dependencies = [
[[package]]
name = "craft-review"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2174,7 +2205,7 @@ dependencies = [
[[package]]
name = "craft-settings"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-atomic",
"craft-host",
@@ -2191,7 +2222,7 @@ dependencies = [
[[package]]
name = "craft-svg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-image-codecs",
"craft-xml",
@@ -2212,7 +2243,7 @@ dependencies = [
[[package]]
name = "craft-table"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-keymap",
@@ -2224,7 +2255,7 @@ dependencies = [
[[package]]
name = "craft-text"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-font-manager",
@@ -2247,7 +2278,7 @@ dependencies = [
[[package]]
name = "craft-theme"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"bitflags 2.13.2",
"craft-tracked",
@@ -2262,7 +2293,7 @@ dependencies = [
[[package]]
name = "craft-theme-editor"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-theme",
@@ -2273,7 +2304,7 @@ dependencies = [
[[package]]
name = "craft-theme-store"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-atomic",
"craft-behavior",
@@ -2288,16 +2319,17 @@ dependencies = [
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c42c34bfa127b095fb0a8d5ccaba0c168c254062#c42c34bfa127b095fb0a8d5ccaba0c168c254062"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"serde",
"thiserror 2.0.21",
"tiff",
]
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=b2d2a1e948c43d95aa769d4f0a06fe6b869edc39#b2d2a1e948c43d95aa769d4f0a06fe6b869edc39"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -2306,7 +2338,7 @@ dependencies = [
[[package]]
name = "craft-time"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -2315,7 +2347,7 @@ dependencies = [
[[package]]
name = "craft-timeline"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-keymap",
@@ -2330,7 +2362,7 @@ dependencies = [
[[package]]
name = "craft-tracked"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"serde",
]
@@ -2338,7 +2370,7 @@ dependencies = [
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-cloud-ui",
"craft-ui-canvas",
@@ -2352,7 +2384,7 @@ dependencies = [
[[package]]
name = "craft-ui-canvas"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-i18n",
@@ -2368,7 +2400,7 @@ dependencies = [
[[package]]
name = "craft-ui-contract"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"accesskit",
"craft-behavior",
@@ -2408,7 +2440,7 @@ dependencies = [
[[package]]
name = "craft-ui-macros"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"proc-macro-crate",
"proc-macro2",
@@ -2419,7 +2451,7 @@ dependencies = [
[[package]]
name = "craft-ui-panels"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2437,7 +2469,7 @@ dependencies = [
[[package]]
name = "craft-ui-patterns"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2458,7 +2490,7 @@ dependencies = [
[[package]]
name = "craft-ui-shell"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2470,6 +2502,7 @@ dependencies = [
"craft-ui-panels",
"craft-window",
"egui",
"raw-window-handle",
"serde",
"web-time",
]
@@ -2477,7 +2510,7 @@ dependencies = [
[[package]]
name = "craft-ui-widgets"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2494,7 +2527,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"chrono",
"craft-host",
@@ -2523,7 +2556,7 @@ dependencies = [
[[package]]
name = "craft-win32"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"winsafe",
]
@@ -2531,7 +2564,7 @@ dependencies = [
[[package]]
name = "craft-window"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-atomic",
"craft-behavior",
@@ -2561,7 +2594,7 @@ dependencies = [
[[package]]
name = "craft-xcf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"flate2",
"thiserror 2.0.21",
@@ -2570,7 +2603,7 @@ dependencies = [
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"quick-xml 0.41.0",
"serde",
@@ -2580,7 +2613,7 @@ dependencies = [
[[package]]
name = "craft-zip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"flate2",
"thiserror 2.0.21",
@@ -4043,7 +4076,7 @@ dependencies = [
[[package]]
name = "hayro"
version = "0.7.1"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"bytemuck",
"hayro-interpret",
@@ -4073,7 +4106,7 @@ dependencies = [
[[package]]
name = "hayro-interpret"
version = "0.7.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"bitflags 2.13.2",
"hayro-cmap",
@@ -4091,7 +4124,7 @@ dependencies = [
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"fearless_simd",
"hayro-ccitt",
@@ -4115,7 +4148,7 @@ checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"flate2",
"hayro-ccitt",
@@ -5199,7 +5232,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
[[package]]
name = "linesweeper"
version = "0.5.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"arrayvec",
"kurbo 0.13.1",
@@ -6415,7 +6448,7 @@ dependencies = [
"clap",
"core-graphics2",
"craft",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"craft-image-codecs",
"craft-svg",
"craft-update",
@@ -6465,7 +6498,7 @@ dependencies = [
"craft",
"craft-develop",
"craft-develop-model",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"criterion",
"photocraft-color",
"photocraft-geom",
@@ -6517,7 +6550,7 @@ dependencies = [
"clap_complete",
"clap_mangen",
"craft",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"craft-image-codecs",
"craft-psd",
"photocraft-automation",
@@ -6540,7 +6573,7 @@ dependencies = [
name = "photocraft-color"
version = "0.23.1"
dependencies = [
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"craft-tracked",
"craft-ui-macros",
"serde",
@@ -6550,7 +6583,7 @@ dependencies = [
name = "photocraft-compose"
version = "0.23.1"
dependencies = [
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"criterion",
"photocraft-color",
"photocraft-doc",
@@ -6578,13 +6611,42 @@ dependencies = [
[[package]]
name = "photocraft-engine"
version = "0.23.1"
dependencies = [
"blake3",
"craft-affinity",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"craft-develop-model",
"craft-image-codecs",
"craft-psd",
"exr",
"photocraft-algo",
"photocraft-color",
"photocraft-compose",
"photocraft-doc",
"photocraft-engine-core",
"photocraft-format",
"photocraft-geom",
"photocraft-io",
"photocraft-paint",
"photocraft-raster",
"photocraft-testkit",
"photocraft-text",
"photocraft-vector",
"rayon",
"serde_json",
"tempfile",
]
[[package]]
name = "photocraft-engine-core"
version = "0.23.1"
dependencies = [
"base64 0.22.1",
"blake3",
"chrono",
"craft",
"craft-affinity",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"craft-develop-model",
"craft-file-formats",
"craft-image-codecs",
@@ -6665,7 +6727,7 @@ name = "photocraft-gpu"
version = "0.23.1"
dependencies = [
"bytemuck",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"half",
"log",
"photocraft-algo",
@@ -6688,7 +6750,7 @@ dependencies = [
"blake3",
"craft",
"craft-affinity",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"craft-crs",
"craft-docpath",
"craft-file-formats",
@@ -6699,7 +6761,7 @@ dependencies = [
"craft-pdn",
"craft-psd",
"craft-svg",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"craft-xcf",
"craft-xml",
"crc32fast",
@@ -6757,7 +6819,7 @@ name = "photocraft-paint"
version = "0.23.1"
dependencies = [
"base64 0.23.1",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"craft-tracked",
"craft-ui-macros",
"photocraft-color",
@@ -6807,8 +6869,9 @@ dependencies = [
name = "photocraft-raw"
version = "0.23.1"
dependencies = [
"craft-develop",
"craft-image-codecs",
"craft-raw",
"craft-raw 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"flate2",
"image",
"photocraft-raw",
@@ -9603,7 +9666,7 @@ dependencies = [
[[package]]
name = "vello_common"
version = "0.0.8"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"bytemuck",
"fearless_simd",
@@ -9651,7 +9714,7 @@ dependencies = [
[[package]]
name = "vello_cpu"
version = "0.0.8"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"bytemuck",
"glifo 0.1.1",
@@ -11287,14 +11350,14 @@ source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d9
[[patch.unused]]
name = "hayro-cmap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
[[patch.unused]]
name = "hayro-postscript"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
[[patch.unused]]
name = "krilla"
version = "0.8.2"
source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
+46 -43
View File
@@ -12,21 +12,21 @@ rust-version = "1.95"
[workspace.dependencies]
# The craft framework through its facade (`craft::ui::…`). The egui `[patch]` below must match
# `craft::egui_fork::REV` (checked by `cargo xtask ci`).
craft = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53", default-features = false }
craft-tracked = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
craft-ui-macros = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362", default-features = false }
craft-tracked = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-ui-macros = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
# internal
photocraft-geom = { path = "crates/geom" }
photocraft-color = { path = "crates/color" }
photocraft-raster = { path = "crates/raster" }
photocraft-doc = { path = "crates/doc" }
photocraft-ops = { path = "crates/ops" }
craft-plist = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] }
craft-plist = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] }
photocraft-raw = { path = "crates/raw" }
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
photocraft-compose = { path = "crates/compose" }
photocraft-gpu = { path = "crates/gpu" }
photocraft-paint = { path = "crates/paint" }
@@ -38,6 +38,7 @@ photocraft-format = { path = "crates/format" }
photocraft-automation = { path = "crates/automation" }
photocraft-plugins = { path = "crates/plugins" }
photocraft-engine = { path = "crates/engine" }
photocraft-engine-core = { path = "crates/engine-core" }
photocraft-ui-egui = { path = "crates/ui-egui" }
photocraft-testkit = { path = "crates/testkit" }
photocraft-tablet = { path = "crates/tablet" }
@@ -45,36 +46,36 @@ photocraft-ipp = { path = "crates/ipp" }
# external
# ICC colour management: the shared crate (replaces crates/cms; craft-libs#779).
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
# HEIC/HEIF: the shared decoder (replaces crates/heif; craft-libs#784).
craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53", features = ["raster", "write-raster"] }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362", features = ["raster", "write-raster"] }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
# Keep the shared embedded-image validation API until the framework revision includes it.
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53", features = ["tree-render", "tree-render-system-fonts"] }
craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362", features = ["tree-render", "tree-render-system-fonts"] }
craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
# Camera-field EXIF reader/writer, shared prerequisite craft-libs#1563.
craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
craft-develop = { git = "https://github.com/storytold/craft-libs", rev = "c42c34bfa127b095fb0a8d5ccaba0c168c254062" }
craft-develop-model = { git = "https://github.com/storytold/craft-libs", rev = "c42c34bfa127b095fb0a8d5ccaba0c168c254062" }
craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-develop = { git = "https://github.com/storytold/craft-libs", rev = "b2d2a1e948c43d95aa769d4f0a06fe6b869edc39" }
craft-develop-model = { git = "https://github.com/storytold/craft-libs", rev = "b2d2a1e948c43d95aa769d4f0a06fe6b869edc39" }
# Interface translations: lookup, fallback, CLDR plurals and language names over the craft-i18n
# catalogs that `crates/ui-egui/build.rs` embeds from `CRAFT_I18N_DIR` (storytold/craft-i18n, at
# the commit in `craft-i18n.rev`). Already in the tree through craft.
craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
# 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 = "e953d47a378776dea207899b10baf969fc8cbe53", features = ["ui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362", features = ["ui"] }
thiserror = "2"
serde = { version = "1", features = ["derive", "rc"] }
serde_json = "1"
@@ -120,7 +121,7 @@ todo = "warn"
# Every cl command selects these packages: each brings features the others lack, so a command that drops one
# builds a second copy of egui, photocraft-io or craft-affinity and of everything above them.
selection = [
"photocraft-ui-egui", "photocraft-engine", "photocraft", "photocraft-algo", "photocraft-automation",
"photocraft-ui-egui", "photocraft-engine", "photocraft-engine-core", "photocraft", "photocraft-algo", "photocraft-automation",
"photocraft-text", "photocraft-tablet", "photocraft-cli", "photocraft-paint", "photocraft-io", "photocraft-gpu",
]
# Crates whose new builds cl names after a command, besides the framework's.
@@ -149,7 +150,7 @@ craft-imaging = ["default", "screen-testing", "ui"]
[workspace.metadata.cl.default_seconds]
"photocraft-ui-egui/photocraft_ui_egui" = 389.0
"photocraft-ui-egui/it" = 221.0
"photocraft-engine/photocraft_engine" = 97.0
"photocraft-engine-core/photocraft_engine_core" = 97.0
# Dependencies carry no debug info: their frames in a backtrace lose file:line, and the target dir
# and link times shrink. The test profile inherits both settings.
@@ -179,6 +180,8 @@ opt-level = 0
# the dev profile's 1.
[profile.test.package.photocraft-engine]
opt-level = 0
[profile.test.package.photocraft-engine-core]
opt-level = 0
# Only the exhaustive rounding proof needs maximum optimization; algo stays at its usual level.
[profile.test.package.photocraft-oil-round-proof]
@@ -339,16 +342,16 @@ opt-level = 3
# Keep the complete egui family and native event bridge on reviewed fork commits.
[patch.crates-io]
krilla = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
vello_common = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
vello_cpu = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
vello_common = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
vello_cpu = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
emath = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
+1 -1
View File
@@ -49,7 +49,7 @@ WORKDIR /src/apps/photocraft-web
# memory than the release zip's fat LTO; retain the profile's other optimizations.
ARG CARGO_PROFILE_WASM_RELEASE_LTO=thin
ARG CARGO_BUILD_JOBS=1
# Optional build provenance shown in About and `--version` (crates/engine/src/build_info.rs).
# Optional build provenance shown in About and `--version` (crates/engine-core/src/build_info.rs).
# .git is not in the build context, so pass it in, e.g.
# --build-arg PHOTOCRAFT_BUILD_SHA=$(git rev-parse HEAD) --build-arg PHOTOCRAFT_BUILD_DATE=$(date -u +%F)
# Left empty, the build reports itself as a dev build.
+2 -1
View File
@@ -1,3 +1,4 @@
use photocraft_engine::actions_cmds::ActionsExt;
use std::io::Write;
use std::path::{Path, PathBuf};
@@ -132,7 +133,7 @@ pub(crate) fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) ->
}
// 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 = ActionList::from_file(ActionsFile::new(set.clone(), Vec::new()));
h.session.actions_mut().list = ActionList::from_file(ActionsFile::new(set.clone(), Vec::new()));
h.open_with_approval(input, a.approve_high_memory)?;
for (id, p) in &actions {
if photocraft_engine::actions_cmds::shell_view_command(id)
+21
View File
@@ -40,6 +40,16 @@ where
T: Into<OsString>,
{
let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
// nightly-v1 is a desktop-only contract. Never let GUI profile arguments fall through
// to stable CLI/MCP directory and credential discovery.
if args.iter().take_while(|arg| arg.as_os_str() != std::ffi::OsStr::new("--")).any(|arg| {
let text = arg.to_string_lossy();
text == "--launch-profile" || text == "--profile-root" || text.starts_with("--launch-profile=") || text.starts_with("--profile-root=")
}) {
let _ = writeln!(err, "nightly-v1 is supported only by the PhotoCraft desktop launcher protocol");
return 2;
}
// Help and `--version` (`help`, `-h`, `<subcommand> --help`, `-V`) come back as errors too,
// for `out`, exit 0: the subcommand never runs.
let cli = match parse(&args) {
@@ -84,3 +94,14 @@ pub(crate) mod test_support {
Invoke { code, stdout: String::from_utf8(stdout).unwrap(), stderr: String::from_utf8(stderr).unwrap() }
}
}
#[cfg(test)]
mod nightly_protocol_tests {
#[test]
fn gui_profile_protocol_is_refused_before_any_cli_command() {
let result = super::test_support::invoke(&["--launch-profile", "nightly-v1", "--profile-root", "a-private-root", "--", "file.psd"]);
assert_eq!(result.code, 2);
assert!(result.stdout.is_empty());
assert!(result.stderr.contains("desktop launcher protocol"));
}
}
+1
View File
@@ -1427,6 +1427,7 @@ fn a_non_unicode_path_is_taken_and_non_unicode_text_is_a_usage_error() {
#[test]
fn batch_plays_a_photoshop_actions_file() {
use photocraft_engine::actions_cmds::{Action, ActionStep};
photocraft_engine::install().unwrap();
let d = tmp("atn");
let input = d.join("in");
std::fs::create_dir_all(&input).unwrap();
+7 -3
View File
@@ -1,5 +1,9 @@
//! Synchronous engine boundary for asynchronous browser storage. No browser handles cross the
//! engine's `Send` boundary. Byte buffers are shared with the single in-flight transaction.
use photocraft_engine::actions_cmds::ActionsExt;
use photocraft_engine::prefs::SavedPrefsExt;
use photocraft_engine::preset_store::PresetStoreExt;
use photocraft_engine::presets::PresetsExt;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::{Arc, Mutex, MutexGuard};
@@ -534,7 +538,7 @@ mod tests {
bridge.load_action_keys(2, keys.clone());
let (session, warnings) = session(bridge.clone());
assert!(!warnings.is_empty());
assert!(session.actions.list.actions().is_empty());
assert!(session.actions().list.actions().is_empty());
assert!(session.tools.presets.iter().any(|preset| preset.name == "Browser seam brush"));
assert_eq!(bridge.committed_action_keys(), None);
assert_eq!(bridge.read(ACTIONS_FILE, 1024).unwrap(), malformed);
@@ -750,7 +754,7 @@ mod tests {
let (mut loaded, _) = session(b);
loaded.load_prefs_json(&prefs).unwrap();
assert_eq!(loaded.tools.presets, s.tools.presets);
assert_eq!(loaded.presets.gradients, s.presets.gradients);
assert!(loaded.presets.gradients.iter().any(|g| g.name == "Browser gradients"));
assert_eq!(loaded.presets().gradients, s.presets().gradients);
assert!(loaded.presets().gradients.iter().any(|g| g.name == "Browser gradients"));
}
}
+6 -5
View File
@@ -1,5 +1,6 @@
//! The browser shell: web `Services`, drag-and-drop, and the eframe web runner.
use photocraft_engine::actions_cmds::ActionsExt;
use std::cell::Cell;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
@@ -100,11 +101,11 @@ pub fn start() {
let served: Served = Arc::default();
load_font_manifest(served.clone(), cc.egui_ctx.clone());
let (session, warnings) = crate::preset_bridge::session(presets.clone());
let actions_revision = session.actions.list.revision();
let actions_revision = session.actions().list.revision();
preset_warnings.extend(warnings);
let drag = listen_drag(&pen_target);
let mut services = services(inbox.clone(), place_inbox.clone(), drag_pos_service(pen_target.clone(), drag));
let mut initial = Some(load_initial_preferences(&presets, database.is_some() && !session.actions.list.actions().is_empty()));
let mut initial = Some(load_initial_preferences(&presets, database.is_some() && !session.actions().list.actions().is_empty()));
services.load_prefs = Some(Box::new(move || initial.take().unwrap_or_else(stored_preferences)));
let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), session, services);
if !preset_warnings.is_empty() {
@@ -381,11 +382,11 @@ struct WebShell {
impl WebShell {
fn save_presets(&mut self, ctx: &egui::Context) {
let session = &self.app.session;
if self.actions_revision != session.actions.list.revision() {
if self.actions_revision != session.actions().list.revision() {
// The engine can reject an oversized definition before calling the backend.
// Never stage that edit's keys with the last successfully queued definitions.
self.presets.verify_action_definitions(&session.actions);
self.actions_revision = session.actions.list.revision();
self.presets.verify_action_definitions(session.actions());
self.actions_revision = session.actions().list.revision();
}
let prefs_revision = session.prefs.rev();
if self.prefs_revision != Some(prefs_revision) {
+1 -1
View File
@@ -111,7 +111,7 @@ winit = { version = "=0.30.13", default-features = false, features = ["wayland-c
[target.'cfg(target_os = "windows")'.dependencies]
# Safe Windows screen-capture bindings; Linux uses the pure-Rust X11 client/portal.
xcap = "=0.9.8"
winsafe = { version = "=0.0.29", default-features = false, features = ["user"] }
winsafe = { version = "=0.0.29", default-features = false, features = ["user", "shell"] }
[build-dependencies]
+39 -3
View File
@@ -4,11 +4,43 @@
//! cross-compile from macOS or Linux still links, unless `PHOTOCRAFT_REQUIRE_WINRES=1` (set by the
//! release workflow) turns it into an error.
#[path = "src/build_channel.rs"]
mod build_channel;
/// Embeds the Windows resources and delay-loads the print-only system DLLs (#5884, #8272).
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-env-changed=PHOTOCRAFT_BUILD_CHANNEL");
println!("cargo:rustc-check-cfg=cfg(photocraft_nightly_v1)");
let nightly = match std::env::var("PHOTOCRAFT_BUILD_CHANNEL").as_deref() {
Ok("nightly-v1") => {
println!("cargo:rustc-cfg=photocraft_nightly_v1");
true
}
// An empty value (an unset CI input) means the default stable build.
Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false,
_ => {
eprintln!("unsupported PHOTOCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)");
std::process::exit(1);
}
};
println!("cargo:rerun-if-changed=../../assets/app-icon/photocraft.ico");
println!("cargo:rerun-if-changed=../../assets/app-icon/photocraft-nightly.ico");
println!("cargo:rerun-if-env-changed=PHOTOCRAFT_REQUIRE_WINRES");
println!("cargo:rerun-if-env-changed=PHOTOCRAFT_VERSION");
let built_version = if nightly {
match std::env::var("PHOTOCRAFT_VERSION") {
Ok(version) if build_channel::is_nightly_version(&version) => version,
_ => {
eprintln!("nightly-v1 requires an explicit PHOTOCRAFT_VERSION feed identity");
std::process::exit(1);
}
}
} else {
std::env::var("CARGO_PKG_VERSION").unwrap_or_default()
};
println!("cargo:rustc-env=PHOTOCRAFT_BUILT_VERSION={built_version}");
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
}
@@ -23,13 +55,17 @@ fn main() {
println!("cargo:rustc-link-arg-bins=delayimp.lib");
}
let mut res = winresource::WindowsResource::new();
res.set_icon("../../assets/app-icon/photocraft.ico")
.set("ProductName", "PhotoCraft")
.set("FileDescription", "PhotoCraft image editor")
res.set_icon(build_channel::windows_icon_path(nightly))
.set("ProductName", if nightly { "PhotoCraft Nightly" } else { "PhotoCraft" })
.set("FileDescription", if nightly { "PhotoCraft Nightly image editor" } else { "PhotoCraft image editor" })
.set("CompanyName", "Learning Machines LLC")
.set("LegalCopyright", "Copyright (c) the PhotoCraft authors. MIT OR Apache-2.0.")
.set("OriginalFilename", "photocraft.exe")
.set("InternalName", "photocraft");
if nightly {
// Launcher verifies the PE ProductVersion against the exact feed identity, not FileVersion.
res.set("ProductVersion", &built_version);
}
if let Err(e) = res.compile() {
if std::env::var_os("PHOTOCRAFT_REQUIRE_WINRES").is_some() {
panic!("embedding Windows resources failed: {e}");
+4 -1
View File
@@ -31,7 +31,10 @@ pub fn current() -> &'static DataDir {
static DIR: OnceLock<DataDir> = OnceLock::new();
DIR.get_or_init(|| {
let exe = std::env::current_exe().ok();
let d = resolve(|k| std::env::var_os(k), exe.as_deref().and_then(Path::parent));
let d = match crate::launch_profile::current().root() {
Some(root) => DataDir { dir: Some(root.to_path_buf()), mode: Mode::Override, warning: None },
None => resolve(|k| std::env::var_os(k), exe.as_deref().and_then(Path::parent)),
};
if let Some(w) = &d.warning {
log::warn!("{w}");
eprintln!("photocraft: {w}");
+52 -6
View File
@@ -1,6 +1,6 @@
//! The app icon, everywhere Windows, macOS and Linux show one (#248).
//!
//! - **Executable:** `build.rs` embeds `assets/app-icon/photocraft.ico` (16–256 px) as icon
//! - **Executable:** `build.rs` selects the stable or nightly-only `.ico` (16–256 px) as icon
//! resource 1, which Explorer, Alt+Tab and an unpinned taskbar button fall back to.
//! - **Window:** [`window_icon`] sets the title-bar and taskbar icon at runtime (`WM_SETICON` on
//! Windows, `_NET_WM_ICON` on X11, the Dock when running unbundled on macOS).
@@ -9,15 +9,16 @@
//! shortcut's icon under its `<Icon Id>`, so that id must carry the target's `.exe` extension
//! (ICE50); an extensionless id showed a blank page on the taskbar. The tests below check it.
//!
//! The process keeps Windows' implicit AppUserModelID (derived from the executable path), which
//! is what makes that matching work for both the MSI shortcut and the portable exe. An explicit
//! ID would need a Win32 call (`unsafe`, which the workspace forbids) and would then also have to
//! be stamped on the shortcut, or the taskbar would stop matching the two.
//! Stable keeps Windows' implicit AppUserModelID (derived from the executable path), which
//! is what makes that matching work for both the MSI shortcut and the portable exe. Changing
//! stable's ID would also require changing its matching shortcut policy. Nightly is separate:
//! its app bootstrap uses the existing safe Windows bindings to set its persistent channel
//! identity before any native window.
/// Window, taskbar and (when running unbundled) Dock icon. macOS gets the padded 1024 px render
/// on Apple's icon grid; elsewhere the 256 px hicolor render of the full tile.
pub fn window_icon() -> egui::IconData {
match eframe::icon_data::from_png_bytes(PNG) {
match eframe::icon_data::from_png_bytes(icon_png(crate::build_flavor::COMPILED, cfg!(target_os = "macos"))) {
Ok(icon) => icon,
Err(e) => {
log::warn!("app icon: {e}");
@@ -26,6 +27,16 @@ pub fn window_icon() -> egui::IconData {
}
}
fn icon_png(flavor: crate::build_flavor::BuildFlavor, macos: bool) -> &'static [u8] {
if flavor != crate::build_flavor::BuildFlavor::NightlyV1 {
PNG
} else if macos {
include_bytes!("../../../assets/app-icon/photocraft-nightly-1024.png")
} else {
include_bytes!("../../../assets/app-icon/photocraft-nightly.png")
}
}
/// Whether the window gets [`window_icon`] at runtime: everywhere except inside a macOS app
/// bundle. There the Dock shows the bundle's `PhotoCraft.icns` (`CFBundleIconFile`), which macOS
/// renders in its own style (Liquid Glass and its tinted and dark variants); a runtime PNG
@@ -60,6 +71,41 @@ const PNG: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nightly_uses_each_platforms_distinct_nonblank_native_size_icon() {
use crate::build_flavor::BuildFlavor;
assert_eq!(icon_png(BuildFlavor::Stable, true), PNG);
assert_eq!(icon_png(BuildFlavor::Stable, false), PNG);
for (macos, expected_size) in [(false, 256), (true, 1024)] {
let nightly = icon_png(BuildFlavor::NightlyV1, macos);
assert_ne!(nightly, PNG);
let icon = eframe::icon_data::from_png_bytes(nightly).unwrap();
assert_eq!((icon.width, icon.height), (expected_size, expected_size));
assert!(icon.rgba.chunks(4).any(|pixel| pixel[3] > 0));
}
}
#[test]
fn nightly_executable_icon_retains_all_six_shell_sizes() {
let ico = include_bytes!("../../../assets/app-icon/photocraft-nightly.ico");
assert_ne!(ico.as_slice(), ICO);
assert_eq!((u16_at(ico, 0), u16_at(ico, 2)), (0, 1));
let mut sizes = Vec::new();
for i in 0..u16_at(ico, 4) {
let entry = 6 + 16 * i;
let width = if ico[entry] == 0 { 256 } else { usize::from(ico[entry]) };
let height = if ico[entry + 1] == 0 { 256 } else { usize::from(ico[entry + 1]) };
assert_eq!(width, height);
let image = &ico[u32_at(ico, entry + 12)..][..u32_at(ico, entry + 8)];
assert!(image.starts_with(b"\x89PNG\r\n\x1a\n"));
let decoded = eframe::icon_data::from_png_bytes(image).unwrap();
assert_eq!((decoded.width as usize, decoded.height as usize), (width, height));
sizes.push(width);
}
for expected in [16, 24, 32, 48, 64, 256] {
assert!(sizes.contains(&expected), "missing nightly icon size {expected}");
}
}
const ICO: &[u8] = include_bytes!("../../../assets/app-icon/photocraft.ico");
const WXS: &str = include_str!("../../../packaging/windows/photocraft.wxs");
+53
View File
@@ -0,0 +1,53 @@
//! The build-time nightly identity shared by the build script and its pure regression tests.
pub fn is_nightly_version(version: &str) -> bool {
let Some((base, suffix)) = version.split_once("-nightly.") else { return false };
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
let base: Vec<_> = base.split('.').collect();
let parts: Vec<_> = suffix.split('.').collect();
base.len() == 3
&& base.iter().all(|s| digits(s))
&& parts.len() == 4
&& parts[0].len() == 8
&& digits(parts[0])
&& digits(parts[1])
&& digits(parts[2])
&& parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
}
pub fn windows_icon_path(nightly: bool) -> &'static str {
if nightly { "../../assets/app-icon/photocraft-nightly.ico" } else { "../../assets/app-icon/photocraft.ico" }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() {
assert_eq!(windows_icon_path(false), "../../assets/app-icon/photocraft.ico");
assert_eq!(windows_icon_path(true), "../../assets/app-icon/photocraft-nightly.ico");
}
#[test]
fn explicit_feed_identity_is_required_for_a_nightly_build() {
assert!(is_nightly_version("0.23.1-nightly.20261120.17.1.gabcdef012345"));
for invalid in [
"",
"0.23.1",
"0.23.1-nightly",
"0.23.1-nightly.20261120",
"0.23.1-nightly.20261120.17.1.gABCDEF012345",
"0.23.1-nightly.20261120.17.1.gabcdef012345\n",
] {
assert!(!is_nightly_version(invalid), "{invalid:?}");
}
}
#[test]
fn version_cannot_inject_a_path_or_an_extra_build_directive() {
for invalid in [
"../0.23.1-nightly.20261120.1.1.gabcdef012345",
"0.23.1-nightly.20261120.1.1.gabcdef012345/other",
"0.23.1-nightly.20261120.1.1.gabcdef012345\ncargo:rustc-cfg=other",
] {
assert!(!is_nightly_version(invalid));
}
}
}
+70
View File
@@ -0,0 +1,70 @@
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
use crate::launch_profile::Profile;
use std::ffi::OsString;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuildFlavor {
Stable,
NightlyV1,
}
pub const COMPILED: BuildFlavor = if cfg!(photocraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
match (flavor, profile.is_nightly()) {
(BuildFlavor::NightlyV1, false) => Err("Open PhotoCraft Nightly from ArtCraft Launcher".into()),
(BuildFlavor::Stable, true) => Err("This is a stable PhotoCraft build; nightly-v1 requires the nightly build".into()),
_ => Ok(()),
}
}
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
desktop_session && flavor == BuildFlavor::NightlyV1
}
pub fn version_query(args: &[OsString]) -> bool {
matches!(args, [arg] if arg == "--version" || arg == "-V")
}
pub fn version(flavor: BuildFlavor, stable: &str) -> String {
match flavor {
BuildFlavor::Stable => stable.to_owned(),
BuildFlavor::NightlyV1 => format!("{stable} (nightly-v1)"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
assert!(!needs_native_error(BuildFlavor::NightlyV1, false));
assert!(!needs_native_error(BuildFlavor::Stable, true));
assert!(!needs_native_error(BuildFlavor::Stable, false));
}
#[test]
fn nightly_build_without_a_profile_is_refused_before_startup() {
let started = std::cell::Cell::new(false);
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
assert!(!started.get());
}
#[test]
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
}
#[test]
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
assert_eq!(version(BuildFlavor::Stable, "0.23.1"), "0.23.1");
assert_eq!(version(BuildFlavor::NightlyV1, "0.23.1"), "0.23.1 (nightly-v1)");
assert!(version_query(&["--version".into()]));
assert!(version_query(&["-V".into()]));
assert!(!version_query(&["--".into(), "--version".into()]));
assert!(!version_query(&[]));
}
}
+27 -2
View File
@@ -13,10 +13,15 @@
//! [`service`] builds the pointer-position service for the app's window, `None` where it can't
//! be read.
pub use platform::service;
pub use platform::{primary_down_service, service};
#[cfg(target_os = "macos")]
mod platform {
/// Not read here: the title-bar move of a floating document window reaches the app as a press and a release.
pub fn primary_down_service() -> Option<photocraft_ui_egui::PrimaryDownFn> {
None
}
use objc2::MainThreadMarker;
use objc2_app_kit::{NSApplication, NSEvent, NSWindow};
use photocraft_ui_egui::CursorPosFn;
@@ -45,6 +50,11 @@ mod platform {
#[cfg(target_os = "linux")]
mod platform {
/// Not read here: the title-bar move of a floating document window reaches the app as a press and a release.
pub fn primary_down_service() -> Option<photocraft_ui_egui::PrimaryDownFn> {
None
}
use eframe::wgpu::rwh::{HasWindowHandle, RawWindowHandle};
use photocraft_ui_egui::CursorPosFn;
use x11rb::protocol::xproto::ConnectionExt;
@@ -81,7 +91,17 @@ mod platform {
#[cfg(target_os = "windows")]
mod platform {
use photocraft_ui_egui::CursorPosFn;
use photocraft_ui_egui::{CursorPosFn, PrimaryDownFn};
/// The physical left button (`GetAsyncKeyState`): a floating document window's title-bar move runs in the OS, which
/// tells the app nothing when it ends (#16415).
pub fn primary_down_service() -> Option<PrimaryDownFn> {
// `GetAsyncKeyState` reads the physical button: with the buttons swapped, the primary one is the right.
Some(Box::new(|| {
let swapped = winsafe::GetSystemMetrics(winsafe::co::SM::SWAPBUTTON) != 0;
winsafe::GetAsyncKeyState(if swapped { winsafe::co::VK::RBUTTON } else { winsafe::co::VK::LBUTTON })
}))
}
pub fn service(_cc: &eframe::CreationContext<'_>) -> Option<CursorPosFn> {
Some(Box::new(|ctx: &egui::Context| {
@@ -104,6 +124,11 @@ fn client_points(screen_px: egui::Pos2, inner_min: egui::Pos2, ppp: f32) -> egui
#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
mod platform {
/// Not read here: the title-bar move of a floating document window reaches the app as a press and a release.
pub fn primary_down_service() -> Option<photocraft_ui_egui::PrimaryDownFn> {
None
}
use photocraft_ui_egui::CursorPosFn;
pub fn service(_cc: &eframe::CreationContext<'_>) -> Option<CursorPosFn> {
+38
View File
@@ -152,6 +152,13 @@ pub(crate) fn command() -> Command {
.mut_args(blank_env_is_unset)
}
/// Nightly has no control server. Its unused inherited port must not prevent a window from
/// opening; Stable retains its existing environment/usage-error behavior.
pub(crate) fn command_for_profile(nightly: bool) -> Command {
let command = command();
if nightly { command.mut_arg("control", |arg| arg.env(None::<&str>)) } else { command }
}
/// Parse the launch arguments (without the binary name) with `cmd`, from [`command`]. Old macOS
/// passes a process serial number (`-psn_…`) when launched from Finder: it is dropped first, unless
/// it comes after `--`. A bad value from a variable is a usage error naming the variable.
@@ -216,6 +223,37 @@ mod tests {
e.to_string()
}
#[test]
fn nightly_ignores_only_the_unused_control_port_environment() {
const CHILD: &str = "PHOTOCRAFT_TEST_CONTROL_PORT_CHILD";
if let Ok(profile) = std::env::var(CHILD) {
let nightly = profile == "nightly";
let result = parse(command_for_profile(nightly), Vec::<OsString>::new());
if nightly {
assert!(result.is_ok(), "unused invalid control-port environment must not block Nightly");
assert!(result.unwrap().control.is_none());
assert!(parse(command_for_profile(true), ["--control", "70000"].map(OsString::from)).is_err(), "explicit invalid values remain invalid");
} else {
assert_eq!(result.err().unwrap().exit_code(), 2, "Stable preserves its invalid-environment error");
}
return;
}
for profile in ["stable", "nightly"] {
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "launch_args::tests::nightly_ignores_only_the_unused_control_port_environment", "--nocapture"])
.env(CHILD, profile)
.env("PHOTOCRAFT_CONTROL_PORT", "not-a-port")
.env_remove("PHOTOCRAFT_CONTROL_TOKEN")
.env_remove("PHOTOCRAFT_CONTROL_TOKEN_FILE")
.env_remove("PHOTOCRAFT_AUTOMATION_READ_ROOT")
.env_remove("PHOTOCRAFT_AUTOMATION_WRITE_ROOT")
.env_remove("PHOTOCRAFT_IN_WINDOW_MENUS")
.output()
.unwrap();
assert!(output.status.success(), "{profile}: {}", String::from_utf8_lossy(&output.stdout));
}
}
#[test]
fn control_port_rejects_unparseable_values_naming_them() {
// Out of range, negative and empty values fail, naming the value (#701); a following
+208
View File
@@ -0,0 +1,208 @@
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state.
//! Stable launches retain their original arguments and directory policy. No environment mutation.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::sync::OnceLock;
pub const VERSION: &str = "nightly-v1";
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Profile {
Stable,
NightlyV1(PathBuf),
}
impl Profile {
pub fn is_nightly(&self) -> bool {
matches!(self, Self::NightlyV1(_))
}
pub fn root(&self) -> Option<&Path> {
match self {
Self::Stable => None,
Self::NightlyV1(root) => Some(root),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Launch {
pub profile: Profile,
pub args: Vec<OsString>,
}
static PROFILE: OnceLock<Profile> = OnceLock::new();
pub fn current() -> &'static Profile {
PROFILE.get().unwrap_or(&Profile::Stable)
}
pub fn install(profile: Profile) -> Result<(), String> {
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
}
/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is
/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here.
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
let mut selector = None;
let mut root = None;
let mut other = Vec::new();
let mut files = Vec::new();
let mut iter = args.iter();
let mut delimiter = false;
while let Some(arg) = iter.next() {
if arg == "--" {
delimiter = true;
files.extend(iter.cloned());
break;
}
if arg == "--launch-profile" || arg == "--profile-root" {
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
if slot.is_some() {
return Err("the profile selector and root must each occur exactly once".into());
}
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
if value.to_string_lossy().starts_with("--") {
return Err("the profile selector/root needs a value".into());
}
*slot = Some(value.clone());
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
} else {
other.push(arg.clone());
}
}
match (selector, root) {
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
(Some(version), Some(root)) if version == VERSION => {
if !delimiter || !other.is_empty() {
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
}
let root = PathBuf::from(root);
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
}
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
}
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
}
}
/// The existing renderer retry is signalled by its process-local failure marker. Ordinary
/// Launcher calls still use the strict selector/root protocol; this is not authentication.
pub fn parse_startup(args: Vec<OsString>, compatibility_retry: bool) -> Result<Launch, String> {
if !compatibility_retry || args.first().is_none_or(|arg| arg != "--safe-gpu") {
return parse(args);
}
let mut launch = parse(args[1..].to_vec())?;
if launch.profile.is_nightly() {
launch.args.insert(0, OsString::from("--safe-gpu"));
Ok(launch)
} else {
// Stable's argument order and parser remain unchanged.
parse(args)
}
}
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
/// root validator, so its old portable/config resolution stays unchanged.
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
if let Profile::NightlyV1(root) = &launch.profile {
launch.profile = Profile::NightlyV1(validate(root)?);
}
Ok(launch)
}
/// Resolve the selected private root before the caller's first startup effect.
pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
let stable_agent = craft::control::agents::default_folder(crate::AGENT_APP_NAME);
crate::profile_root::validate(root, env, exe, stable_agent.as_deref(), photocraft_automation::app_dirs::ensure_writable)
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
fn args(values: &[&str]) -> Vec<OsString> {
values.iter().map(OsString::from).collect()
}
fn absolute() -> &'static str {
if cfg!(windows) { r"C:\NightlyData\profiles\photocraft" } else { "/nightly-data/profiles/photocraft" }
}
fn nightly() -> Vec<OsString> {
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
}
#[test]
fn internal_cpu_retry_preserves_the_nightly_root_and_literal_files() {
let mut argv = args(&["--safe-gpu"]);
argv.extend(nightly());
argv.extend(args(&["document with spaces.psd", "--safe-gpu", "--profile-root"]));
let launch = parse_startup(argv.clone(), true).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.args, args(&["--safe-gpu", "--", "document with spaces.psd", "--safe-gpu", "--profile-root"]));
assert!(parse_startup(argv, false).is_err(), "an ordinary invocation must not gain extra protocol flags");
}
#[test]
fn retry_cannot_bypass_invalid_profiles_or_change_stable_arguments() {
let stable = args(&["--safe-gpu", "--new-instance", "stable.psd"]);
assert_eq!(parse_startup(stable.clone(), true).unwrap(), Launch { profile: Profile::Stable, args: stable });
let mut duplicate = args(&["--safe-gpu", "--safe-gpu"]);
duplicate.extend(nightly());
assert!(parse_startup(duplicate, true).is_err());
assert!(parse_startup(args(&["--safe-gpu", "--launch-profile", VERSION, "--profile-root", "relative", "--"]), true).is_err());
}
#[test]
fn stable_arguments_and_directory_policy_are_unchanged() {
for argv in [args(&[]), args(&["--new-instance", "a.psd"]), args(&["--", "--launch-profile", "file.psd"])] {
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
}
}
#[test]
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
let mut argv = nightly();
argv.extend(args(&["--profile-root", "image with spaces.psd"]));
let launch = parse(argv).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.args, args(&["--", "--profile-root", "image with spaces.psd"]));
}
#[test]
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
for argv in [
args(&["--launch-profile", VERSION]),
args(&["--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
] {
assert!(parse(argv).is_err());
}
}
#[test]
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
let reached = Cell::new(false);
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
assert!(result.is_err());
assert!(!reached.get());
}
#[test]
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
let checked = PathBuf::from(absolute()).join("checked");
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
assert_eq!(launch.profile.root(), Some(checked.as_path()));
assert!(launch.profile.is_nightly());
}
}
+228 -34
View File
@@ -33,13 +33,19 @@ mod app_dirs;
mod app_icon;
#[cfg(target_os = "macos")]
mod apple_events;
#[cfg(test)]
mod build_channel;
mod build_flavor;
mod caps_lock;
mod crash_guard;
mod cursor;
mod gpu_startup;
mod launch_args;
mod launch_profile;
#[cfg(target_os = "macos")]
mod mac_window;
mod process_identity;
mod profile_root;
// Pure logic is tested on every platform; only Linux runs the check.
#[cfg(not(target_arch = "wasm32"))]
mod external_svg;
@@ -47,6 +53,7 @@ mod external_svg;
mod linux_libs;
mod logging;
mod monitor_profile;
mod nightly_session;
mod photoshop_settings;
mod presentation;
// The print portal needs the session bus (zbus, Linux only); its pure helpers are tested everywhere.
@@ -63,11 +70,13 @@ mod ui_state;
mod window_frame;
use photocraft_engine::Session;
#[cfg(target_os = "linux")]
use photocraft_engine::print_cmds::PrintExt;
use photocraft_ui_egui::PhotocraftApp;
use photocraft_ui_egui::Prefix;
use photocraft_ui_egui::window_policy::{self, Backend, Frame, TitleBarPref};
use photocraft_ui_egui::os_window::APP_ID;
use photocraft_ui_egui::os_window;
/// The smallest the main window may be, in points.
const MIN_WINDOW_SIZE: [f32; 2] = [760.0, 480.0];
@@ -81,8 +90,9 @@ fn title_bar_pref(prefs: &photocraft_engine::prefs::Preferences) -> TitleBarPref
/// The automation roots: `--automation-read-root` / `--automation-write-root` (or their
/// variables) win; a direction without one takes Preferences › AI Integrations' folder, and with
/// that empty too the default agent folder `Documents/ArtCraft/Agents/PhotoCraft`, created when
/// first used (`AgentSettings::folders`). A flag's
/// that empty too the channel's default agent folder: stable uses
/// `Documents/ArtCraft/Agents/PhotoCraft`; Nightly uses its private profile's `AgentFiles`.
/// It is created only when first used (`AgentSettings::folders_with`). 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
@@ -93,7 +103,20 @@ fn automation_workspace(
flags: &photocraft_automation::args::AutomationArgs,
prefs: &craft::automation::agents::AgentSettings,
) -> Result<(photocraft_automation::workspace::AuthorizedWorkspace, Option<String>), photocraft_automation::AutomationError> {
automation_workspace_in(flags, prefs, craft::control::agents::default_folder(AGENT_APP_NAME).as_deref())
automation_workspace_for_profile(flags, prefs, launch_profile::current(), || craft::control::agents::default_folder(AGENT_APP_NAME))
}
fn automation_workspace_for_profile(
flags: &photocraft_automation::args::AutomationArgs,
prefs: &craft::automation::agents::AgentSettings,
profile: &launch_profile::Profile,
stable_default: impl FnOnce() -> Option<std::path::PathBuf>,
) -> Result<(photocraft_automation::workspace::AuthorizedWorkspace, Option<String>), photocraft_automation::AutomationError> {
let default = match profile.root() {
Some(root) => Some(profile_root::agent_directory(root).map_err(photocraft_automation::AutomationError::BadRequest)?),
None => stable_default(),
};
automation_workspace_in(flags, prefs, default.as_deref())
}
/// The app's name in its default agent folder, `Documents/ArtCraft/Agents/PhotoCraft`.
@@ -155,14 +178,18 @@ fn control_port_for(cli: Option<u16>, prefs: &photocraft_engine::prefs::Integrat
}
/// The main window: 1440 × 900 (shrunk to fit the monitor, and maximized on the first frame
/// when it still doesn't fit, `work_area::fit_window`), centred on the main monitor. Without
/// when it still doesn't fit, `embed::before_ui`), centred on the main monitor. Without
/// `centered`, Windows cascades each new window from the top-left corner, so it opened at a
/// different offset every launch (#419). A later launch restores the saved position instead
/// (`main` turns `centered` off, #4826). Wayland compositors place windows themselves.
fn native_options(frame: &Frame) -> eframe::NativeOptions {
let viewport = egui::ViewportBuilder::default().with_icon(app_icon::viewport_icon(std::env::current_exe().ok().as_deref()));
let viewport =
viewport.with_app_id(APP_ID).with_title("PhotoCraft").with_inner_size([1440.0, 900.0]).with_min_inner_size(MIN_WINDOW_SIZE).with_drag_and_drop(true);
let viewport = viewport
.with_app_id(os_window::app_id())
.with_title(os_window::name_for(os_window::identity()))
.with_inner_size([1440.0, 900.0])
.with_min_inner_size(MIN_WINDOW_SIZE)
.with_drag_and_drop(true);
eframe::NativeOptions {
viewport: window_policy::apply(viewport, frame),
centered: true,
@@ -225,18 +252,19 @@ fn claim_single_instance(
mut launch_options: Vec<launch_args::PerProcess>,
) -> std::ops::ControlFlow<(), Option<single_instance::Primary>> {
use std::ops::ControlFlow::{Break, Continue};
let new_instance_env = std::env::var("PHOTOCRAFT_NEW_INSTANCE").ok();
let nightly = launch_profile::current().is_nightly();
let new_instance_env = if nightly { None } else { std::env::var("PHOTOCRAFT_NEW_INSTANCE").ok() };
// A variable documented as the equivalent of a per-launch flag counts as that flag: a
// launch that sets only `PHOTOCRAFT_PRESENT_MODE` (say) has per-process options too, so it
// keeps its own process instead of handing its files over and being ignored.
launch_options.extend_from_slice(&single_instance::env_launch_options());
let context = single_instance::LaunchContext {
per_user_settings: app_dirs::current().mode == app_dirs::Mode::Platform,
new_instance_flag: new_instance,
per_user_settings: launch_profile::current().is_nightly() || app_dirs::current().mode == app_dirs::Mode::Platform,
new_instance_flag: new_instance && !nightly,
new_instance_env: new_instance_env.as_deref(),
control,
control: control && !nightly,
unreadable_paths,
launch_options: &launch_options,
launch_options: if nightly { &[] } else { &launch_options },
};
match (single_instance::skip_reason(&context), services::config_dir()) {
(Some(reason), _) => {
@@ -388,7 +416,64 @@ fn write_start_marker(sentinel: &gpu_startup::SharedSentinel, plan: &gpu_startup
}
}
fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> {
process_identity::initialize(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, os_window::id_for(os_window::LaunchIdentity::NightlyV1))
}
fn report_launch_profile_error(error: &str) {
eprintln!("PhotoCraft launch profile: {error}");
let desktop_session = cfg!(windows)
|| cfg!(target_os = "macos")
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) {
if let Err(error) = initialize_nightly_process_identity() {
eprintln!("PhotoCraft launch profile: {error}");
return;
}
#[cfg(any(windows, target_os = "linux", target_os = "macos"))]
let _ = rfd::MessageDialog::new()
.set_title("PhotoCraft Nightly")
.set_description(error)
.set_level(rfd::MessageLevel::Error)
.set_buttons(rfd::MessageButtons::Ok)
.show();
}
}
/// Select the immutable launch profile before any startup service or side effect.
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
// The trusted Launcher protocol is decided before logger/crash/update/font/prefs access.
let argv: Vec<_> = std::env::args_os().skip(1).collect();
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) {
use std::io::Write as _;
let _ = writeln!(std::io::stdout(), "PhotoCraft {}", build_flavor::version(build_flavor::COMPILED, env!("PHOTOCRAFT_BUILT_VERSION")));
return None;
}
let early = launch_profile::parse_startup(argv, std::env::var_os("PHOTOCRAFT_GPU_STARTUP_FAILURE").is_some())
.and_then(|launch| {
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
Ok(launch)
})
.and_then(|launch| {
launch_profile::prepare(launch, |root| launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref()))
})
.unwrap_or_else(|error| {
report_launch_profile_error(&error);
std::process::exit(2)
});
let identity = if early.profile.is_nightly() { os_window::LaunchIdentity::NightlyV1 } else { os_window::LaunchIdentity::Stable };
if let Err(error) = launch_profile::install(early.profile).and_then(|()| os_window::select_identity(identity)) {
report_launch_profile_error(&error);
std::process::exit(2);
}
Some(early.args)
}
fn main() -> eframe::Result {
let Some(arguments) = prepare_launch() else { return Ok(()) };
// Before anything starts a thread: may re-execute this process with glibc tuned to return
// the memory of closed documents (#8743).
photocraft_engine::malloc_tuning::apply();
@@ -396,7 +481,9 @@ fn main() -> eframe::Result {
let logger = logging::install();
crash_guard::install_hook();
#[cfg(not(target_arch = "wasm32"))]
if let Some(done) = craft_update::self_update::finish(&photocraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
if !launch_profile::current().is_nightly()
&& let Some(done) = craft_update::self_update::finish(&photocraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>())
{
if let Err(e) = done {
eprintln!("PhotoCraft update helper failed: {e}");
std::process::exit(1);
@@ -407,10 +494,10 @@ fn main() -> eframe::Result {
// The system font scan can take seconds (minutes on some Macs): run it off the UI thread.
photocraft_ui_egui::type_tool::warm_fonts();
// `--help` and `--version` print to standard output and exit 0. A usage error (an unknown
// option, a missing or bad value, a bad PHOTOCRAFT_CONTROL_PORT: issues #701, #6429, #6431)
// option, a missing or bad value, a bad PHOTOCRAFT_CONTROL_PORT for Stable: issues #701, #6429, #6431)
// names the argument on standard error and exits 2, so a launcher sees the failure. Neither
// panics when the stream is closed or a pipe (`photocraft --help | head -1`).
let launch = launch_args::parse(launch_args::command(), std::env::args_os().skip(1)).unwrap_or_else(|e| e.exit());
let launch = launch_args::parse(launch_args::command_for_profile(launch_profile::current().is_nightly()), arguments).unwrap_or_else(|e| e.exit());
let launch_args::FileNames { openable: files, unreadable: unreadable_paths } = launch.file_names();
let launch_args::LaunchArgs {
files: _,
@@ -451,7 +538,12 @@ fn main() -> eframe::Result {
let _ = (new_instance, &launch_options);
// Bind and authenticate the authorized control listener before display/GPU initialization.
let ControlSetup { control, warning: control_warning } = control_setup(&prefs.integrations, control_port, auth, &automation);
let ControlSetup { control, warning: control_warning } = if launch_profile::current().is_nightly() {
// No inherited stable token file/Launcher agent switch is consulted by this first protocol.
ControlSetup { control: None, warning: None }
} else {
control_setup(&prefs.integrations, control_port, auth, &automation)
};
#[cfg(target_os = "linux")]
let native_session = linux_libs::session_from_env(|name| std::env::var(name).ok());
@@ -549,8 +641,25 @@ fn main() -> eframe::Result {
let app_created = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let created_in_callback = app_created.clone();
let started_sentinel = sentinel.clone();
// After primary IPC claim, before entering the window loop. Stable and secondaries do not
// own a Nightly record. No document names, paths or diagnostic payload is collected.
let (nightly_session, session_health_warning) = match nightly_session::Session::begin_with_health(
launch_profile::current().root(),
photocraft_engine::build_info::VERSION,
photocraft_engine::build_info::git_sha(),
) {
Ok(state) => state,
Err(error) => {
log::warn!("Nightly session health is unavailable: {error}");
(None, true)
}
};
let previous_nightly_unclean = nightly_session.as_ref().is_some_and(nightly_session::Session::previous_unclean);
// Set once a window has posted the interruption notice; until then the record must survive.
let unclean_notice_shown = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let notice_shown_in_callback = unclean_notice_shown.clone();
let result = eframe::run_native(
"PhotoCraft",
os_window::name_for(os_window::identity()),
options,
Box::new(move |cc| {
created_in_callback.store(true, std::sync::atomic::Ordering::Relaxed);
@@ -575,7 +684,7 @@ fn main() -> eframe::Result {
#[cfg(target_os = "linux")]
let session = {
let mut session = Session::new();
session.print_spooler = print_portal::spooler();
*session.print_spooler_mut() = print_portal::spooler();
session
};
#[cfg(not(target_os = "linux"))]
@@ -681,21 +790,24 @@ fn main() -> eframe::Result {
// switch (Settings › AI agents) is the one consent; without it, as before, a Control
// Port saved in the preferences. The launch flags (`--control`) manage the connection
// for the whole run instead.
app.services.agent_switch = Some(craft::automation::agents::AgentSwitch::watch(photocraft_automation::agent_link::LAUNCHER_APP_ID, {
let ctx = cc.egui_ctx.clone();
move || ctx.request_repaint()
}));
let link = if let Some((listener, token, _)) = control {
let host = craft::ui::runtime::windows::WindowHost::of(&cc.egui_ctx);
let (requests, server) = craft::automation::server::serve(listener, token, host)?;
eprintln!("photocraft: control server listening on {}", server.addr);
app = app.with_control(requests);
craft::automation::agents::AgentLink::from_launch(server)
} else {
app.services.agent_automation = Some(Box::new(services::agent_automation));
craft::automation::agents::AgentLink::new(services::config_dir(), photocraft_engine::build_info::long_version())
};
app.services.agent_link = Some(link);
if !launch_profile::current().is_nightly() {
app.services.agent_switch = Some(craft::automation::agents::AgentSwitch::watch(photocraft_automation::agent_link::LAUNCHER_APP_ID, {
let ctx = cc.egui_ctx.clone();
move || ctx.request_repaint()
}));
let link = if let Some((listener, token, _)) = control {
let host = craft::ui::runtime::windows::WindowHost::of(&cc.egui_ctx);
let (requests, server) = craft::automation::server::serve(listener, token, host)?;
eprintln!("photocraft: control server listening on {}", server.addr);
app = app.with_control(requests);
craft::automation::agents::AgentLink::from_launch(server)
} else {
app.services.agent_automation = Some(Box::new(services::agent_automation));
craft::automation::agents::AgentLink::new(services::config_dir(), photocraft_engine::build_info::long_version())
};
app.services.agent_link = Some(link);
}
#[cfg(target_os = "macos")]
{
app.services.os_events = Some(apple_events.connect(&cc.egui_ctx));
@@ -713,6 +825,8 @@ fn main() -> eframe::Result {
}
// Where file drags and drops are (winit 0.30 doesn't say).
app.services.cursor_pos = cursor::service(cc);
// The physical primary button: it ends a floating document window's OS move by its title bar (#16415).
app.services.primary_down = cursor::primary_down_service();
// The custom title bar's undecorated window must stay borderless, or its caption and
// border offset the content and the pointer on some Windows systems (#2246).
app.services.window_frame = window_frame::service(cc, integrated_frame);
@@ -750,6 +864,26 @@ fn main() -> eframe::Result {
let lines = unreadable_paths.iter().map(|p| i18n::fmt(line, &[("path", p.as_str())])).collect();
photocraft_ui_egui::notices::post(&mut app, i18n::t("Could not open"), lines, craft::theme::variant::Tone::Bad, None);
}
if previous_nightly_unclean || session_health_warning {
use photocraft_ui_egui::i18n;
let message = if previous_nightly_unclean {
i18n::t(
"The previous PhotoCraft Nightly session did not finish normally. You can report a problem from About. No diagnostics have been sent.",
)
} else {
i18n::t(
"PhotoCraft Nightly could not record session health in its private profile. You can still edit, but abnormal-exit detection is unavailable.",
)
};
photocraft_ui_egui::notices::post(
&mut app,
i18n::t("PhotoCraft Nightly"),
vec![message.to_owned()],
craft::theme::variant::Tone::Neutral,
None,
);
notice_shown_in_callback.store(previous_nightly_unclean, std::sync::atomic::Ordering::Relaxed);
}
// Portable marker found but its data folder isn't writable (#228): say where settings went.
if let Some(w) = &app_dirs::current().warning {
photocraft_ui_egui::notices::post(&mut app, "Portable mode is off", vec![w.clone()], craft::theme::variant::Tone::Neutral, None);
@@ -762,6 +896,15 @@ fn main() -> eframe::Result {
Ok(app)
}),
);
// This is a controlled return, even for a handled startup error or CPU relaunch. Release
// health ownership BEFORE primary IPC, so a successor never observes a stale busy owner.
// A renderer failure before the window (and so before the CPU retry) has not shown an
// earlier interruption: keep that record so the retry, or the next start, still reports it.
if let Some(watch) = nightly_session
&& let Err(error) = watch.finish(unclean_notice_shown.load(std::sync::atomic::Ordering::Relaxed))
{
log::warn!("Nightly session state was left intact: {error}");
}
// The window is gone: refuse further files and free the lock, so a launch that is waiting (or
// the CPU-compatibility relaunch below) becomes the primary instead of handing its files to a
// process that is exiting.
@@ -838,6 +981,8 @@ pub(crate) fn no_child_spawns() -> std::sync::RwLockWriteGuard<'static, ()> {
#[cfg(test)]
mod tests {
use photocraft_engine::prefs::SavedPrefsExt;
/// Schema-probe `ui.ron` shapes *reconstructed* from the documented 0.14/0.15/0.37 layouts,
/// not recorded machine saves: 0.14 and 0.15 both store the flat window entry, which the
/// first 0.37 launch rewrites; a 0.37 file is left alone. Keeping all three probes makes a
@@ -1094,6 +1239,55 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn nightly_agent_workspace_uses_its_private_profile_not_stable_documents() {
let dir = temp_dir("nightly-agent-roots");
let private = dir.join("nightly profile");
let stable = dir.join("redirected Documents/ArtCraft/Agents/PhotoCraft");
std::fs::create_dir_all(&private).unwrap();
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("existing-document"), b"stable document bytes").unwrap();
let profile = super::launch_profile::Profile::NightlyV1(private.clone());
let (ws, warning) = super::automation_workspace_for_profile(&flags(None, None), &craft::automation::agents::AgentSettings::default(), &profile, || {
panic!("Nightly must never consult the stable agent-folder fallback")
})
.unwrap();
assert_eq!(warning, None);
let canonical_private = std::fs::canonicalize(&private).unwrap();
assert!(ws.read_folders().iter().all(|p| p.starts_with(&canonical_private)));
assert!(ws.write_folder().unwrap().starts_with(&canonical_private));
ws.write("nightly-document", b"nightly document bytes").unwrap();
assert_eq!(ws.read("nightly-document").unwrap(), b"nightly document bytes");
assert_eq!(std::fs::read(stable.join("existing-document")).unwrap(), b"stable document bytes");
assert_eq!(std::fs::read_dir(&stable).unwrap().count(), 1);
drop(ws);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn stable_agent_workspace_preserves_the_resolved_default_folder() {
let dir = temp_dir("stable-agent-roots");
let stable = dir.join("redirected Documents/ArtCraft/Agents/PhotoCraft");
let (ws, warning) = super::automation_workspace_for_profile(
&flags(None, None),
&craft::automation::agents::AgentSettings::default(),
&super::launch_profile::Profile::Stable,
|| Some(stable.clone()),
)
.unwrap();
assert_eq!(warning, None);
// These accessors preserve the configured spelling, not Windows' canonical
// verbatim prefix or expanded short names. The held capability still opens it.
assert_eq!(ws.read_folders(), vec![stable.clone()]);
assert_eq!(ws.write_folder(), Some(stable.clone()));
ws.write("stable-document", b"stable document bytes").unwrap();
assert_eq!(std::fs::read(stable.join("stable-document")).unwrap(), b"stable document bytes");
assert_eq!(ws.read("stable-document").unwrap(), b"stable document bytes");
assert_eq!(ws.read_with_save_path("stable-document").unwrap().1.as_deref(), Some("stable-document"));
drop(ws);
std::fs::remove_dir_all(dir).unwrap();
}
/// Empty preferences fall back to the default agent folder, created when first used, for
/// both directions (one shared capability); a flag or the person's own folder still wins.
#[test]
@@ -1173,7 +1367,7 @@ mod tests {
fn the_desktop_entry_names_the_window_class() {
let entry = include_str!("../../../packaging/linux/ai.storyteller.photocraft.desktop");
let class = entry.lines().find_map(|line| line.strip_prefix("StartupWMClass="));
assert_eq!(class, Some(super::APP_ID));
assert_eq!(class, Some(super::os_window::APP_ID));
}
/// Both flatpak manifests build with the craft-i18n commit `craft-i18n.rev` pins: CI and
+219
View File
@@ -0,0 +1,219 @@
//! App-private Nightly session health, not telemetry or a Launcher protocol.
//! A live owner holds a separate persistent lease; secondary launches never rewrite its record.
//! Dropping the guard does not clear the marker. Only the app's controlled return path does.
use std::fs::{File, OpenOptions};
use std::io::{self, Read};
use std::path::{Path, PathBuf};
const RECORD: &str = "nightly-session.json";
const LEASE: &str = "nightly-session.lock";
const MAX_METADATA_BYTES: usize = 256;
pub struct Session {
_lease: File,
path: PathBuf,
own_record: Vec<u8>,
previous_unclean: bool,
}
fn regular_or_missing(path: &Path) -> io::Result<bool> {
match std::fs::symlink_metadata(path) {
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error),
}
}
impl Session {
/// The warning belongs to this window: a busy secondary has no health-record coverage,
/// while Stable and a lease-owning Nightly window preserve their existing result.
pub fn begin_with_health(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<(Option<Self>, bool)> {
let watch = Self::begin(root, version, commit)?;
let unavailable = root.is_some() && watch.is_none();
Ok((watch, unavailable))
}
/// `None` is stable or another owner of this profile. Neither case touches the record.
/// The supplied root must already be the validated private Nightly profile.
pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<Option<Self>> {
let Some(root) = root else { return Ok(None) };
if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large"));
}
let lease_path = root.join(LEASE);
regular_or_missing(&lease_path)?;
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
match lease.try_lock() {
Ok(()) => {}
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
Err(std::fs::TryLockError::Error(error)) => return Err(error),
}
let path = root.join(RECORD);
let previous_unclean = regular_or_missing(&path)?;
let own_record = serde_json::to_vec(&serde_json::json!({
"schema_version": 1,
"channel": "nightly-v1",
"version": version,
"commit": commit.filter(|value| !value.is_empty()),
}))?;
// The app already uses this durable writer; a raced destination link is replaced, not followed.
photocraft_format::atomic_write_no_follow(&path, &own_record)?;
Ok(Some(Self { _lease: lease, path, own_record, previous_unclean }))
}
pub fn previous_unclean(&self) -> bool {
self.previous_unclean
}
/// Controlled return. If an earlier session's interruption was detected but no window showed
/// it yet (a renderer failure before the app callback, including the CPU-retry handoff), the
/// record is left for the next owner to report; otherwise this is [`Self::complete`].
pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> {
if self.previous_unclean && !unclean_notice_shown {
return Ok(());
}
self.complete()
}
/// Controlled event-loop completion includes a handled startup error/CPU handoff, not only
/// exit0. Clear before releasing primary IPC so a successor cannot miss record ownership.
/// An unwind, abort, forced exit or killed process never calls this method.
pub fn complete(self) -> io::Result<()> {
if !regular_or_missing(&self.path)? {
return Ok(());
}
let mut current = Vec::new();
File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?;
if current != self.own_record {
return Err(io::Error::other("Nightly session state changed; leaving it intact"));
}
std::fs::remove_file(&self.path)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
loop {
let path = std::env::temp_dir().join(format!("photo-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&path) {
Ok(()) => return Self(path),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
}
}
}
impl Drop for Fixture {
fn drop(&mut self) {
std::fs::remove_dir_all(&self.0).unwrap();
}
}
#[test]
fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() {
let _no_spawns = crate::no_child_spawns();
let fixture = Fixture::new();
let (stable, warning) = Session::begin_with_health(None, "stable", None).unwrap();
assert!(stable.is_none() && !warning);
let (first, warning) = Session::begin_with_health(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap();
assert!(!warning);
let first = first.unwrap();
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap();
assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage");
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record);
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() {
let _no_spawns = crate::no_child_spawns();
let fixture = Fixture::new();
let first = Session::begin(Some(&fixture.0), "first", Some("recorded-commit")).unwrap().unwrap();
assert!(!first.previous_unclean());
let own = std::fs::read(fixture.0.join(RECORD)).unwrap();
assert!(Session::begin(Some(&fixture.0), "secondary", None).unwrap().is_none());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record");
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
let unfinished = Session::begin(Some(&fixture.0), "second", None).unwrap().unwrap();
assert!(!unfinished.previous_unclean());
drop(unfinished); // Unwind/abnormal-path ownership release, not a controlled completion.
let next = Session::begin(Some(&fixture.0), "third", None).unwrap().unwrap();
assert!(next.previous_unclean());
next.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn an_interruption_no_window_showed_survives_a_handled_startup_failure() {
let _no_spawns = crate::no_child_spawns();
let fixture = Fixture::new();
drop(Session::begin(Some(&fixture.0), "crashed", None).unwrap().unwrap());
// Renderer initialization failed before the app callback: no notice was shown.
let failed = Session::begin(Some(&fixture.0), "gpu-failed", None).unwrap().unwrap();
assert!(failed.previous_unclean());
failed.finish(false).unwrap();
// The CPU retry (or the next start) still sees the interruption and shows it.
let retry = Session::begin(Some(&fixture.0), "cpu-retry", None).unwrap().unwrap();
assert!(retry.previous_unclean());
retry.finish(true).unwrap();
assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record");
// Without an earlier interruption, a handled failure still clears normally.
let clean = Session::begin(Some(&fixture.0), "clean", None).unwrap().unwrap();
assert!(!clean.previous_unclean());
clean.finish(false).unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn cleanup_never_removes_an_unknown_changed_record() {
let _no_spawns = crate::no_child_spawns();
let fixture = Fixture::new();
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap();
assert!(watch.complete().is_err());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else");
}
#[test]
fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() {
let _no_spawns = crate::no_child_spawns();
let fixture = Fixture::new();
assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err());
assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0);
assert!(Session::begin(None, "", None).unwrap().is_none(), "stable has no session-health side effects");
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap();
let fields = data.as_object().unwrap().keys().map(String::as_str).collect::<std::collections::BTreeSet<_>>();
assert_eq!(fields, ["schema_version", "channel", "version", "commit"].into_iter().collect());
assert!(data["commit"].is_null(), "missing provenance must not be invented");
watch.complete().unwrap();
}
#[test]
#[cfg(unix)]
fn reserved_state_aliases_do_not_modify_external_files() {
let _no_spawns = crate::no_child_spawns();
let fixture = Fixture::new();
let external = fixture.0.join("stable-document");
std::fs::write(&external, b"stable bytes").unwrap();
for name in [LEASE, RECORD] {
let alias = fixture.0.join(name);
std::os::unix::fs::symlink(&external, &alias).unwrap();
assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err());
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
std::fs::remove_file(alias).unwrap();
}
}
}
+69
View File
@@ -0,0 +1,69 @@
//! Set the immutable nightly Windows identity before any native window or COM service.
//! Stable deliberately leaves its implicit shortcut/path identity unchanged.
use std::sync::OnceLock;
#[derive(Clone, Debug, thiserror::Error)]
pub enum IdentityError {
#[error("{0}")]
Configuration(String),
}
pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> {
configure(nightly && cfg!(windows), app_id, |id| {
static RESULT: OnceLock<Result<(), String>> = OnceLock::new();
RESULT
.get_or_init(|| {
#[cfg(windows)]
{
winsafe::SetCurrentProcessExplicitAppUserModelID(id).map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?;
let actual = winsafe::GetCurrentProcessExplicitAppUserModelID()
.map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?;
if actual != id {
return Err("the native Windows identity did not match the selected nightly channel".into());
}
Ok(())
}
#[cfg(not(windows))]
{
let _ = id;
Ok(())
}
})
.clone()
})
.map_err(IdentityError::Configuration)
}
fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> {
if explicit_nightly { set(app_id) } else { Ok(()) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stable_does_not_call_the_explicit_identity_api() {
configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap();
}
#[test]
fn nightly_applies_the_supplied_identity_once() {
let calls = std::cell::Cell::new(0);
configure(true, "nightly-id", |id| {
assert_eq!(id, "nightly-id");
calls.set(calls.get() + 1);
Ok(())
})
.unwrap();
assert_eq!(calls.get(), 1);
}
#[test]
fn native_identity_failure_is_returned_instead_of_starting_a_window() {
let started = std::cell::Cell::new(false);
let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true));
assert_eq!(result.unwrap_err(), "native identity refused");
assert!(!started.get());
}
}
+708
View File
@@ -0,0 +1,708 @@
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
use std::ffi::OsString;
use photocraft_automation::app_dirs::{PORTABLE_DATA_DIR, portable_marker};
use std::path::{Component, Path, PathBuf};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Platform {
Windows,
Linux,
Mac,
}
impl Platform {
fn current() -> Result<Self, String> {
match std::env::consts::OS {
"windows" => Ok(Self::Windows),
"linux" => Ok(Self::Linux),
"macos" => Ok(Self::Mac),
_ => Err("nightly-v1 is not defined for this operating system".into()),
}
}
fn ignores_case(self) -> bool {
self != Self::Linux
}
}
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
return Err(format!("{label} must be absolute and contain no parent traversal"));
}
Ok(path)
}
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
absolute(PathBuf::from(value), key)
}
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
match env(key).filter(|v| !v.is_empty()) {
Some(value) => absolute(PathBuf::from(value), key),
None => Ok(required_base(env, "HOME")?.join(fallback)),
}
}
/// Resolve existing ancestors before creating anything. A dangling link or inaccessible ancestor
/// is not a missing directory that may be replaced or followed later.
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
let mut parent = path;
let mut missing = Vec::new();
loop {
match std::fs::symlink_metadata(parent) {
Ok(_) => break,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
}
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
}
}
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
for part in missing.into_iter().rev() {
resolved.push(part);
}
Ok(resolved)
}
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
let parts = |p: &Path| {
p.components()
.map(|c| {
let value = c.as_os_str().to_string_lossy().into_owned();
if platform.ignores_case() { value.to_lowercase() } else { value }
})
.collect::<Vec<_>>()
};
let (a, b) = (parts(a), parts(b));
a.starts_with(&b) || b.starts_with(&a)
}
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
if platform == Platform::Mac {
// A profile in Resources is still inside the versioned install, not beside MacOS.
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
return Ok(bundle.to_path_buf());
}
}
Ok(parent.to_path_buf())
}
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
let mut roots = match platform {
Platform::Windows => {
let mut roots =
["APPDATA", "LOCALAPPDATA"].into_iter().map(|key| required_base(env, key).map(|p| p.join("Photocraft"))).collect::<Result<Vec<_>, _>>()?;
// The MSI's default per-user and per-machine folders (install-policy.wxi). A custom
// install folder is not known here; the executable's own folder is fenced below.
roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("PhotoCraft"));
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("PhotoCraft"));
}
}
roots
}
Platform::Linux => {
let mut roots =
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
.into_iter()
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("photocraft")))
.collect::<Result<Vec<_>, _>>()?;
roots.extend(["/usr/bin/photocraft", "/usr/local/bin/photocraft", "/opt/photocraft"].map(PathBuf::from));
// The stable Flatpak keeps its data in its own per-app folder.
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.photocraft"));
roots
}
Platform::Mac => {
let home = required_base(env, "HOME")?;
let library = home.join("Library");
vec![
library.join("Application Support/Photocraft"),
library.join("Caches/Photocraft"),
library.join("Caches/ai.storyteller.photocraft"),
library.join("Preferences/Photocraft"),
library.join("Preferences/ai.storyteller.photocraft.plist"),
library.join("Saved Application State/ai.storyteller.photocraft.savedState"),
home.join("Applications/PhotoCraft.app"),
PathBuf::from("/Applications/PhotoCraft.app"),
]
}
};
roots.push(installation_boundary(platform, exe)?);
roots.into_iter().map(|p| canonical_future(&p)).collect()
}
/// The nightly fallback for files made by agents. Resolving it never creates a directory and
/// never falls back to the stable Documents folder. The SDK creates it lazily if a default is
/// actually needed; explicit user-chosen document roots keep their existing semantics.
pub fn agent_directory(root: &Path) -> Result<PathBuf, String> {
private_subdirectory(root, "AgentFiles", "default agent folder")
}
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
let child = canonical_future(&chosen.join(name))?;
if child == chosen || !child.starts_with(&chosen) {
return Err(format!("the nightly {label} must stay inside its selected profile"));
}
Ok(child)
}
/// Every existing entry directly in the profile (Presets, logs, settings and so on) must resolve
/// inside it, so a link there cannot point Nightly's writes at another app's data.
fn entries_stay_inside(root: &Path) -> Result<(), String> {
let entries = match std::fs::read_dir(root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
private_subdirectory(root, entry.file_name(), "profile entry")?;
}
Ok(())
}
/// Recognise the shared portable data namespace in both the supplied and resolved path.
/// This is not an inventory of arbitrary custom Stable overrides or a Launcher ownership proof.
fn is_portable_layout(path: &Path, platform: Platform) -> bool {
// A folder under a portable copy belongs to that copy too. Above the chosen folder itself, a
// marker only counts beside a PhotoCraft executable, so an unrelated portable.txt higher up
// (in a user folder or at a drive root) does not refuse the profile.
path.ancestors().enumerate().any(|(depth, ancestor)| {
portable_marker(ancestor).is_some() && (depth == 0 || ["photocraft.exe", "photocraft"].iter().any(|exe| ancestor.join(exe).is_file()))
}) || path.components().any(|component| match component {
Component::Normal(name) if platform.ignores_case() => name.to_string_lossy().eq_ignore_ascii_case(PORTABLE_DATA_DIR),
Component::Normal(name) => name == PORTABLE_DATA_DIR,
_ => false,
})
}
/// The writable hook is the app's existing exclusive probe. Keeping it injected lets filesystem
/// boundary tests exercise the real policy without starting the app or changing global state.
pub fn validate(
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
stable_agent: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
validate_for(Platform::current()?, root, env, exe, stable_agent, writable)
}
fn validate_for(
platform: Platform,
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
stable_agent: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
absolute(root.to_path_buf(), "the nightly profile root")?;
if env("PHOTOCRAFT_CONFIG_DIR").is_some_and(|v| !v.is_empty()) {
return Err("nightly-v1 cannot be combined with PHOTOCRAFT_CONFIG_DIR".into());
}
if platform != Platform::Windows && env("FLATPAK_ID").is_some_and(|v| !v.is_empty()) {
// These rows are native tar/app-bundle launches, not a Flatpak package. Inheriting its
// runtime socket namespace could point another profile at the stable app's socket.
return Err("nightly-v1 native packages cannot inherit a Flatpak instance; launch through the native Launcher".into());
}
let chosen = canonical_future(root)?;
if is_portable_layout(root, platform) || is_portable_layout(&chosen, platform) {
return Err("the nightly root must not use a portable PhotoCraft installation or its PhotoCraftData settings folder".into());
}
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
let mut forbidden = forbidden_roots(platform, &env, &exe)?;
if let Some(agent) = stable_agent {
// Use the SDK-resolved Documents/known-folder location, including redirected Documents.
// Do not reconstruct it from HOME or create it just to establish the boundary.
forbidden.push(canonical_future(&absolute(agent.to_path_buf(), "the stable default agent folder")?)?);
}
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
return Err("the nightly root must not overlap stable data or an installation".into());
}
// Existing aliases under the profile must not redirect the default agent workspace elsewhere.
agent_directory(&chosen)?;
entries_stay_inside(&chosen)?;
// Recovery can read, adopt, overwrite and sweep entries. Never let its alias leave this
// private profile, including toward a Stable portable directory not in our known roots.
private_subdirectory(&chosen, "Recovery", "recovery folder")?;
let mut create = std::fs::DirBuilder::new();
create.recursive(true);
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt as _;
create.mode(0o700);
}
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
return Err("the nightly profile changed while it was being validated".into());
}
agent_directory(&confirmed)?;
private_subdirectory(&confirmed, "Recovery", "recovery folder")?;
entries_stay_inside(&confirmed)?;
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
Ok(confirmed)
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture {
root: PathBuf,
env: BTreeMap<String, OsString>,
exe: PathBuf,
}
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let root = loop {
let candidate = std::env::temp_dir().join(format!("photocraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&candidate) {
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
};
let home = root.join("home");
let exe = root.join("install/photocraft");
std::fs::create_dir_all(&home).unwrap();
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
std::fs::write(&exe, b"fixture executable, never run").unwrap();
let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
.into_iter()
.map(|(key, value)| (key.into(), value.into_os_string()))
.collect();
Self { root, env, exe }
}
fn get(&self, key: &str) -> Option<OsString> {
self.env.get(key).cloned()
}
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
validate_for(
platform,
root,
|key| self.get(key),
Some(&self.exe),
None,
|dir| {
let probe = dir.join("exclusive-test-probe");
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
drop(file);
std::fs::remove_file(probe)
},
)
}
fn home(&self) -> PathBuf {
PathBuf::from(self.get("HOME").unwrap())
}
}
impl Drop for Fixture {
fn drop(&mut self) {
// Only the directory successfully created by this fixture is owned for removal.
std::fs::remove_dir_all(&self.root).unwrap();
}
}
#[test]
fn portable_settings_from_another_install_are_refused_before_any_probe() {
let fixture = Fixture::new();
let stable_install = fixture.root.join("stable portable install");
let stable_data = stable_install.join(photocraft_automation::app_dirs::PORTABLE_DATA_DIR);
std::fs::create_dir_all(&stable_data).unwrap();
std::fs::write(stable_install.join("portable.txt"), b"owned portable fixture").unwrap();
std::fs::write(stable_data.join("settings.json"), b"stable settings must not change").unwrap();
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
for candidate in [&stable_data, &stable_data.join("nested nightly")] {
let probed = std::cell::Cell::new(false);
let result = validate_for(
platform,
candidate,
|key| fixture.get(key),
Some(&fixture.exe),
None,
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err(), "a different portable install is not a private Nightly profile");
assert!(!probed.get(), "reject portable data before a writable probe");
assert!(!stable_data.join("nested nightly").exists());
assert_eq!(std::fs::read(stable_data.join("settings.json")).unwrap(), b"stable settings must not change");
assert_eq!(std::fs::read_dir(&stable_data).unwrap().count(), 1);
}
}
let private = fixture.root.join("PhotoCraftData-backup-name/nightly");
assert!(fixture.check(Platform::Linux, &private).is_ok(), "a merely similar name is not a portable settings component");
}
#[cfg(unix)]
#[test]
fn recovery_aliases_cannot_redirect_to_stable_missing_or_profile_root_data() {
let fixture = Fixture::new();
let stable = fixture.home().join(".local/state/photocraft/Recovery");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap();
for (index, target) in [stable.clone(), fixture.root.join("missing recovery target")].into_iter().enumerate() {
let private = fixture.root.join(format!("nightly-{index}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&target, private.join("Recovery")).unwrap();
let probed = std::cell::Cell::new(false);
let result = validate_for(
Platform::Linux,
&private,
|key| fixture.get(key),
Some(&fixture.exe),
None,
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err(), "Recovery must not escape the private profile or follow a dangling alias");
assert!(!probed.get());
}
let private = fixture.root.join("nightly-self");
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&private, private.join("Recovery")).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_err(), "Recovery cannot treat all profile settings as recovery entries");
assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes");
assert_eq!(std::fs::read_dir(stable).unwrap().count(), 1);
}
#[cfg(unix)]
#[test]
fn recovery_alias_to_a_private_subfolder_keeps_the_profile_usable() {
let fixture = Fixture::new();
let private = fixture.root.join("nightly-private");
let recovery = private.join("private-recovery");
std::fs::create_dir_all(&recovery).unwrap();
std::os::unix::fs::symlink(&recovery, private.join("Recovery")).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_ok());
assert_eq!(std::fs::canonicalize(private.join("Recovery")).unwrap(), recovery);
}
#[test]
fn agent_default_is_private_lazy_and_preserves_stable_documents() {
let fixture = Fixture::new();
let stable = fixture.home().join("Documents/ArtCraft/Agents/PhotoCraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("existing-document"), b"stable document bytes").unwrap();
let private = fixture.check(Platform::Linux, &fixture.home().join("nightly-profile")).unwrap();
let agent = agent_directory(&private).unwrap();
assert!(agent.starts_with(&private) && agent != private);
assert!(!agent.exists(), "resolving the fallback must not create it before use");
std::fs::create_dir_all(&agent).unwrap();
std::fs::write(agent.join("new-document"), b"nightly document bytes").unwrap();
assert_eq!(std::fs::read(stable.join("existing-document")).unwrap(), b"stable document bytes");
assert_eq!(std::fs::read_dir(&stable).unwrap().count(), 1);
assert_eq!(std::fs::read(agent.join("new-document")).unwrap(), b"nightly document bytes");
}
#[test]
fn stable_agent_known_folder_and_overlaps_refuse_before_writable_probe() {
let fixture = Fixture::new();
// Models redirected Documents/known folders: not assumed to be beneath HOME.
let stable = fixture.root.join("redirected documents/ArtCraft/Agents/PhotoCraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("existing-document"), b"stable document bytes").unwrap();
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
for root in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
let calls = std::cell::Cell::new(0);
let result = validate_for(
platform,
&root,
|key| fixture.get(key),
Some(&fixture.exe),
Some(&stable),
|_| {
calls.set(calls.get() + 1);
Ok(())
},
);
assert!(result.unwrap_err().contains("overlap"));
assert_eq!(calls.get(), 0);
}
}
assert_eq!(std::fs::read(stable.join("existing-document")).unwrap(), b"stable document bytes");
assert_eq!(std::fs::read_dir(&stable).unwrap().count(), 1);
}
#[test]
#[cfg(unix)]
fn agent_default_rejects_existing_and_dangling_escape_aliases_before_writes() {
let fixture = Fixture::new();
let private = fixture.home().join("nightly-profile");
let outside = fixture.home().join("stable-agent-files");
std::fs::create_dir_all(&private).unwrap();
std::fs::create_dir_all(&outside).unwrap();
std::fs::write(outside.join("existing-document"), b"stable document bytes").unwrap();
for target in [&outside, &outside.join("missing")] {
let alias = private.join("AgentFiles");
std::os::unix::fs::symlink(target, &alias).unwrap();
assert!(agent_directory(&private).is_err());
let calls = std::cell::Cell::new(0);
assert!(
validate_for(
Platform::Linux,
&private,
|key| fixture.get(key),
Some(&fixture.exe),
Some(&outside),
|_| {
calls.set(calls.get() + 1);
Ok(())
}
)
.is_err()
);
assert_eq!(calls.get(), 0);
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 1);
std::fs::remove_file(alias).unwrap();
}
assert_eq!(std::fs::read(outside.join("existing-document")).unwrap(), b"stable document bytes");
}
#[test]
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
let fixture = Fixture::new();
let root = fixture.home().join("nightly/profiles/photocraft");
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert!(overlaps(&root, &root.join("Recovery"), platform));
assert!(overlaps(&root.join("Recovery"), &root, platform));
assert!(!overlaps(&root, &root.with_file_name("photocraft-other"), platform));
}
}
#[test]
fn linux_fences_app_xdg_subtrees_but_allows_launcher_sibling() {
let mut fixture = Fixture::new();
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
}
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("photocraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
}
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
}
let data = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap());
let nightly = data.join("ArtCraftLauncher/nightly/profiles/photocraft");
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
}
#[test]
fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() {
let mut fixture = Fixture::new();
fixture.exe = fixture.root.join("install/PhotoCraft Nightly.app/Contents/MacOS/PhotoCraft");
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
let library = fixture.home().join("Library");
for suffix in [
"Application Support/Photocraft",
"Caches/Photocraft",
"Caches/ai.storyteller.photocraft",
"Preferences/Photocraft",
"Saved Application State/ai.storyteller.photocraft.savedState",
] {
let stable = library.join(suffix);
assert!(fixture.check(Platform::Mac, &stable.join("nightly")).unwrap_err().contains("overlap"));
assert!(!stable.exists());
}
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap"));
assert!(!inside_resources.exists());
let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/photocraft");
assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid);
}
#[test]
fn windows_roaming_local_and_install_fences_remain_active() {
let fixture = Fixture::new();
for key in ["APPDATA", "LOCALAPPDATA"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("Photocraft");
assert!(fixture.check(Platform::Windows, &stable.join("nightly")).unwrap_err().contains("overlap"));
assert!(!stable.exists());
}
assert!(fixture.check(Platform::Windows, &fixture.exe.parent().unwrap().join("profile")).is_err());
assert!(fixture.check(Platform::Windows, &fixture.root.join("Launcher/profiles/photocraft")).is_ok());
}
#[test]
fn windows_default_msi_install_folders_are_fenced() {
let mut fixture = Fixture::new();
let local = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap());
let per_user = local.join("Programs").join("ArtCraft").join("PhotoCraft");
assert!(fixture.check(Platform::Windows, &per_user.join("nightly")).unwrap_err().contains("overlap"));
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
let base = fixture.root.join(format!("machine {key}"));
fixture.env.insert(key.into(), base.clone().into_os_string());
let machine = base.join("ArtCraft").join("PhotoCraft");
assert!(fixture.check(Platform::Windows, &machine.join("nightly")).unwrap_err().contains("overlap"));
assert!(!machine.exists());
}
let sibling = local.join("Programs").join("ArtCraft").join("ArtCraftLauncher").join("nightly").join("photocraft");
assert!(fixture.check(Platform::Windows, &sibling).is_ok(), "the Launcher's own Programs sibling is not PhotoCraft's install");
}
#[test]
fn folders_under_a_stable_portable_copy_are_refused_before_any_probe() {
let fixture = Fixture::new();
let portable = fixture.root.join("D/PC");
std::fs::create_dir_all(&portable).unwrap();
std::fs::write(portable.join("portable.txt"), b"stable portable copy").unwrap();
std::fs::write(portable.join("photocraft.exe"), b"stable portable executable, never run").unwrap();
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
for candidate in [portable.join("nightly"), portable.join("deeper/nightly")] {
let probed = std::cell::Cell::new(false);
let result = validate_for(
platform,
&candidate,
|key| fixture.get(key),
Some(&fixture.exe),
None,
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.unwrap_err().contains("portable"));
assert!(!probed.get());
assert!(!candidate.exists());
}
}
// A portable.txt that no PhotoCraft executable sits beside is someone else's file.
let unrelated = fixture.root.join("user folder");
std::fs::create_dir_all(&unrelated).unwrap();
std::fs::write(unrelated.join("portable.txt"), b"another app's marker").unwrap();
assert!(fixture.check(Platform::Windows, &unrelated.join("Launcher/nightly/photocraft")).is_ok());
}
#[test]
fn linux_fences_the_stable_flatpak_data_folder() {
let fixture = Fixture::new();
let flatpak = fixture.home().join(".var/app/ai.storyteller.photocraft");
for candidate in [flatpak.clone(), flatpak.join("data/nightly")] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
}
assert!(!flatpak.exists());
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok());
}
#[cfg(unix)]
#[test]
fn any_profile_entry_alias_must_stay_inside_the_profile() {
let fixture = Fixture::new();
let stable = fixture.home().join(".config/photocraft/Presets");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-preset"), b"stable preset bytes").unwrap();
for name in ["Presets", "logs", "settings.json"] {
let private = fixture.root.join(format!("nightly-{name}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&stable, private.join(name)).unwrap();
let probed = std::cell::Cell::new(false);
let result = validate_for(
Platform::Linux,
&private,
|key| fixture.get(key),
Some(&fixture.exe),
None,
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err(), "{name} must not lead outside the profile");
assert!(!probed.get());
}
let private = fixture.root.join("nightly-inside");
std::fs::create_dir_all(private.join("real-presets")).unwrap();
std::fs::write(private.join("settings.json"), b"{}").unwrap();
std::os::unix::fs::symlink(private.join("real-presets"), private.join("Presets")).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_ok(), "regular files and links that stay inside are fine");
assert_eq!(std::fs::read(stable.join("stable-preset")).unwrap(), b"stable preset bytes");
assert_eq!(std::fs::read_dir(&stable).unwrap().count(), 1);
}
#[test]
fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() {
let mut fixture = Fixture::new();
let candidate = fixture.home().join("nightly/profiles/photocraft");
fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute"));
fixture.env.remove("XDG_CACHE_HOME");
fixture.env.insert("PHOTOCRAFT_CONFIG_DIR".into(), fixture.home().join("custom-stable").into_os_string());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("PHOTOCRAFT_CONFIG_DIR"));
fixture.env.remove("PHOTOCRAFT_CONFIG_DIR");
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.photocraft".into());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak"));
fixture.env.remove("FLATPAK_ID");
fixture.env.remove("HOME");
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME"));
assert!(!candidate.exists());
}
#[test]
fn non_directory_and_failed_write_probe_never_fall_back_to_stable() {
let fixture = Fixture::new();
let file = fixture.home().join("not-a-directory");
std::fs::write(&file, b"do not replace me").unwrap();
assert!(fixture.check(Platform::Linux, &file).is_err());
assert_eq!(std::fs::read(file).unwrap(), b"do not replace me");
let candidate = fixture.home().join("nightly");
let calls = std::cell::Cell::new(0);
let result = validate_for(
Platform::Linux,
&candidate,
|key| fixture.get(key),
Some(&fixture.exe),
None,
|_| {
calls.set(calls.get() + 1);
Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "injected write refusal"))
},
);
assert!(result.unwrap_err().contains("not writable"));
assert_eq!(calls.get(), 1);
assert!(!fixture.home().join(".config/photocraft").exists());
}
#[cfg(unix)]
#[test]
fn symlink_and_dangling_aliases_cannot_create_or_modify_stable_data() {
use std::os::unix::fs::symlink;
let fixture = Fixture::new();
let stable = fixture.home().join(".config/photocraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("sentinel"), b"untouched").unwrap();
let alias = fixture.home().join("alias");
symlink(&stable, &alias).unwrap();
assert!(fixture.check(Platform::Linux, &alias.join("nightly")).unwrap_err().contains("overlap"));
let missing = fixture.home().join("missing-target");
let dangling = fixture.home().join("dangling");
symlink(&missing, &dangling).unwrap();
assert!(fixture.check(Platform::Linux, &dangling.join("nightly")).is_err());
assert!(!missing.exists());
assert!(!stable.join("nightly").exists());
assert_eq!(std::fs::read(stable.join("sentinel")).unwrap(), b"untouched");
}
}
+2 -1
View File
@@ -245,7 +245,8 @@ fn recovered_documents_survive_a_second_crash_until_saved_or_closed() {
let red = index_of(&app, RED);
app.run("file.close", json!({"document": red})).unwrap();
// Saving marks the revision saved (the file write itself is the save service's job).
assert!(app.session.set_active(index_of(&app, BLUE)));
let blue = index_of(&app, BLUE);
assert!(app.session.set_active(blue));
let st = app.session.active_mut().unwrap();
st.saved_revision = st.revision;
prefs_ui::tick(&mut app, &ctx, std::time::Instant::now());
+12
View File
@@ -44,3 +44,15 @@ details and tests the `.ico` sizes and the WiX icon references.
Replace `photocraft.svg` (and `photocraft-small.svg`), then run `packaging/icons.sh`. It needs
`resvg`, plus `iconutil` on macOS; the `.ico` is packed by `cargo xtask ico`.
## Nightly channel
The nightly derivatives keep the foreground artwork, alpha and Mac padding unchanged. Only the
background contribution changes from the stable blue to the selected deep background. There is
no letter badge or crescent; the app and Launcher also identify the channel in text.
`photocraft-nightly.png` and its nine-frame ICO use the existing own256 master. The separate
`photocraft-nightly-1024.png` and eleven-slot ICNS use the actual padded Mac1024 master, not an
upscale. Input/output hashes, the palette-fit recipe and container sizes are recorded in
[`nightly-provenance.json`](nightly-provenance.json). Stable source files are not recoloured.
The old N-marked private Windows isolation package is separate and is not rebuilt for this art.
+60
View File
@@ -0,0 +1,60 @@
{
"title": "PhotoCraft nightly deep-background icons",
"author": "@skylartaylor",
"license": "MIT OR Apache-2.0",
"source_commit": "06afefff534fb18ca7ea2725a9f476fe477dbd29",
"inputs": [
{
"path": "assets/app-icon/hicolor/256x256/apps/ai.storyteller.photocraft.png",
"sha256": "efd02e0b8ea76c59fbc3a9692ddc21faae6064cc9f9492898df1facec3b5b57d",
"purpose": "Windows/Linux native256 master"
},
{
"path": "assets/app-icon/photocraft-1024.png",
"sha256": "00a39c5ccbcb2b5f144573b1cedb6c387c4416ad06fd1cf2865b0737458ee704",
"purpose": "native padded Mac1024 master; not upscaled from256"
}
],
"method": {
"kind": "original code-generated derivative of the project-owned icon",
"original_palette": {
"ink": "#0b0b0c",
"paper": "#efe9dc",
"background": "#2f7bf5"
},
"nightly_background": "#22395d",
"transform": "Fit background contribution in the existing ink/paper/background palette and change only that contribution. Preserve alpha/padding and neutral foreground/detail RGBA. Derive native-size frames separately from their corresponding unchanged-resolution masters and pack PNG frames into ICO/ICNS. No crescent, letter or badge.",
"generator_sha256": "a04dcbba501985de729d37d352597de6ffb2ad993f1596eced6b12bffc114d85"
},
"outputs": {
"assets/app-icon/photocraft-nightly.png": "7a79aff027f9f95cef0edc0a84ce3791af302b6351ebca4d0e736477e3b3f031",
"assets/app-icon/photocraft-nightly.ico": "87f67bc7b9ce18f54ab62769d7e6849d9ed0fd2658fce7db1a1eb05140fad2f4",
"assets/app-icon/photocraft-nightly-1024.png": "8de1e42f70720c7b8c66f40f443e7f7a423690cfcb062725d2e563c5f8fd51b1",
"assets/app-icon/photocraft-nightly.icns": "9ceecf811014509cc1444f44aaa0d31715a1e2439e943aec77c510dd4b2bf8f0"
},
"ico_frame_sizes": [
16,
20,
24,
32,
40,
48,
64,
128,
256
],
"icns_png_slots": {
"icp4": 16,
"icp5": 32,
"ic11": 32,
"icp6": 64,
"ic12": 64,
"ic07": 128,
"ic08": 256,
"ic13": 256,
"ic09": 512,
"ic14": 512,
"ic10": 1024
},
"validation": "Source/input/output hashes, PNG CRC/dimensions and exact container members checked; supplied generator pixel proof preserves foreground/alpha. Visual comparison reviewed. Native Explorer/Finder/iconutil/app-package qualification remains unrun."
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 208 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

File diff suppressed because it is too large. Load diff
-658
View File
@@ -1,658 +0,0 @@
//! Shadows and Highlights as a local Laplacian filter.
//!
//! Adobe has said Camera Raw's process version 2012 rests on local Laplacian filters (S. Paris,
//! S. W. Hasinoff, J. Kautz, *Local Laplacian Filters: Edge-aware Image Processing with a
//! Laplacian Pyramid*, SIGGRAPH 2011). This follows that paper, in its fast form (M. Aubry et
//! al., *Fast Local Laplacian Filters*, ACM TOG 2014: the remapping sampled at a few reference
//! values, each pyramid coefficient interpolated between them), on the log2 luminance:
//!
//! - **Shadows** raises pixels darker than their surroundings, by an amount set by their own and
//! their surroundings' place in the image's range (1st to 99th percentile); **Highlights**
//! pulls pixels brighter than their surroundings toward them. Differences under a threshold
//! are left alone, so fine detail stays.
//! - Shadows then keeps the image's 99th percentile, Highlights its 1st (Photoshop keeps the
//! brightest content under Shadows and the darkest under Highlights).
//! - A uniform image is unchanged, edges keep no halo, and the result does not depend on the
//! image size.
//!
//! The strengths were fitted to Photoshop 25.4's Camera Raw Filter on ten public-domain photos
//! (black-box measurements, no Adobe code or data). It is an approximation: on those photos the
//! mean error against Photoshop is 2.8–9.4 levels (of 255) where the previous heuristic's was
//! 3.7–14.3.
use super::{Encoding, luma, quantile_rank};
use crate::photo_util::par_rows;
/// Spacing of the fast filter's reference values in stops. Its remapping changes within about
/// half a stop, and coefficients interpolated across wider gaps show as contour lines on smooth
/// gradients (12 references over a whole raw's range left visible steps; at an eighth of a stop a
/// ramp's slope varies by under a third, as the remapping itself makes it).
pub const REF_STEP: f32 = 0.125;
/// Most reference values one filter uses.
pub const MAX_REFS: usize = 96;
/// The lowest reference sits at this quantile of the log luminance: the deepest 0.1 % (noise down
/// to the floor) share it instead of stretching the spacing.
pub const REF_LOW_QUANTILE: f32 = 0.001;
/// The filter works on `log2(luminance + LOG_FLOOR)`.
pub const LOG_FLOOR: f32 = 1.0 / 65536.0;
/// The filter runs on a copy at most this many pixels across; the change it makes is brought back
/// to full size by a guided upsampling, so a preview and the full image agree.
pub const WORK_SIDE: usize = 1600;
/// The image range the strengths are placed in: these quantiles of the log luminance averaged
/// over cells of a copy at most [`RANGE_SIDE`] pixels across.
pub const RANGE_QUANTILES: [f32; 2] = [0.01, 0.99];
/// See [`RANGE_QUANTILES`].
pub const RANGE_SIDE: usize = 256;
/// Knots of the strength curves over the surroundings' place in the image range (0 … 1).
pub const KNOTS: usize = 5;
/// Shadows: how far a pixel darker than its surroundings rises, in stops per unit slider, as
/// a function of its own place in the image range (`own`) times a factor of its surroundings'
/// place (`around`); it rises fully once it is `sigma` stops below them. The lift depends on
/// the pixel's tone, not on the size of the difference, so it is the same at every pyramid
/// level and a big edge keeps no halo. Lowering (negative values) is `down` times as strong.
const SHADOWS: Lift = Lift { own: [-0.017, 0.466, 0.886, 1.221, -0.081], around: [4.566, 4.067, 1.088, 0.149, 0.878], sigma: 0.571, down: 0.808 };
const HIGHLIGHTS: Side = Side { pull: [0.179, 0.141, 0.196, 0.629, 2.07], push: [0.156, 0.08, 0.175, 0.049, 1.261], sigma: 0.05 };
/// See [`SHADOWS`].
struct Lift {
own: [f32; KNOTS],
around: [f32; KNOTS],
sigma: f32,
down: f32,
}
/// Highlights: strengths per unit slider over the surroundings' place in the image range, for
/// lowering (`pull`, toward the surroundings) and raising (`push`), and the detail threshold in
/// stops.
struct Side {
pull: [f32; KNOTS],
push: [f32; KNOTS],
sigma: f32,
}
/// Which remapping a [`TonePass`] uses.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ToneKind {
/// Pixels brighter than their surroundings move toward them (or away, for positive values)
/// by the part of the difference past `sigma`.
Highlights,
/// Pixels darker than their surroundings rise (or sink) by an amount set by their own and
/// their surroundings' place in the image range.
Shadows,
}
/// One pass of the filter resolved for a slider value: everything its remapping reads.
#[derive(Clone, Debug, PartialEq)]
pub struct TonePass {
pub kind: ToneKind,
/// Highlights: the slider / 100. Shadows: its strength (the slider / 100, times `down` when
/// negative).
pub amount: f32,
/// Highlights: the strengths for the slider's direction, then an unused row. Shadows: the
/// curves over the pixel's own (`own`) and its surroundings' (`around`) place.
pub knots: [[f32; KNOTS]; 2],
/// The detail threshold in stops.
pub sigma: f32,
/// The quantile of the log luminance the pass puts back where it was.
pub keep: f32,
}
/// Shadows and Highlights resolved: Highlights runs first, then Shadows on its result.
#[derive(Clone, Debug, PartialEq)]
pub struct LocalTone {
pub passes: Vec<TonePass>,
}
impl LocalTone {
/// The passes for the sliders (−100 … 100); `None` when both are 0.
pub fn new(shadows: f32, highlights: f32) -> Option<Self> {
let mut passes = Vec::new();
if highlights != 0.0 {
let amount = highlights.clamp(-100.0, 100.0) / 100.0;
let strengths = if amount < 0.0 { HIGHLIGHTS.pull } else { HIGHLIGHTS.push };
// Then the darkest content is put back where it was.
passes.push(TonePass { kind: ToneKind::Highlights, amount, knots: [strengths, [0.0; KNOTS]], sigma: HIGHLIGHTS.sigma, keep: 0.01 });
}
if shadows != 0.0 {
let amount = shadows.clamp(-100.0, 100.0) / 100.0;
let k = if amount > 0.0 { amount } else { amount * SHADOWS.down };
// Keep the brightest content.
passes.push(TonePass { kind: ToneKind::Shadows, amount: k, knots: [SHADOWS.own, SHADOWS.around], sigma: SHADOWS.sigma, keep: 0.99 });
}
(!passes.is_empty()).then_some(LocalTone { passes })
}
}
impl TonePass {
/// The remapping of log luminance `x` around the reference `g`, in an image range that
/// starts at `lo` and is `span` stops wide.
pub fn remap(&self, x: f32, g: f32, lo: f32, span: f32) -> f32 {
match self.kind {
ToneKind::Highlights => x + knot((g - lo) / span, &self.knots[0]) * self.amount * excess((x - g).max(0.0), self.sigma),
ToneKind::Shadows => {
let below = ((g - x) / self.sigma).clamp(0.0, 1.0);
if below == 0.0 {
return x;
}
let w = below * below * (3.0 - 2.0 * below);
x + self.amount * knot((x - lo) / span, &self.knots[0]) * knot((g - lo) / span, &self.knots[1]) * w
}
}
}
/// The pass on the log luminance `u`: the filter, then the kept quantile put back.
fn run(&self, u: &Plane) -> Plane {
let (lo, hi) = range(u);
let span = (hi - lo).max(1.0);
let o = llf(u, |x, g| self.remap(x, g, lo, span));
let shift = quantile(&u.v, self.keep) - quantile(&o.v, self.keep);
Plane { w: o.w, h: o.h, v: o.v.iter().map(|v| v + shift).collect() }
}
}
/// One channel, `w × h`.
struct Plane {
w: usize,
h: usize,
v: Vec<f32>,
}
/// Mirrors `i` into `0..n` (the edge sample is not repeated).
fn mirror(i: isize, n: usize) -> usize {
let n = n as isize;
if n == 1 {
return 0;
}
let p = 2 * (n - 1);
let m = i.rem_euclid(p);
(if m >= n { p - m } else { m }) as usize
}
/// The pyramid's binomial kernel.
pub const TAPS: [f32; 5] = [1.0 / 16.0, 4.0 / 16.0, 6.0 / 16.0, 4.0 / 16.0, 1.0 / 16.0];
/// Planes smaller than this run their rows on one thread: the filter builds a whole pyramid per
/// reference (up to 96), and splitting its small levels into one-row tasks cost more in rayon's
/// scheduling than the rows themselves (a fifth of a Shadows render on 36 MP, measured).
const PAR_MIN: usize = 1 << 15;
/// [`par_rows`] for a plane, on one thread when it is small (see [`PAR_MIN`]).
fn rows(buf: &mut [f32], w: usize, f: impl Fn(usize, &mut [f32]) + Sync + Send) {
if buf.len() < PAR_MIN {
buf.chunks_mut(w.max(1)).enumerate().for_each(|(y, row)| f(y, row));
} else {
par_rows(buf, w, 1, f);
}
}
/// The binomial 5-tap blur, sampled every `step` pixels from 0 (1 = full resolution).
fn blur_step(p: &Plane, step: usize) -> Plane {
let (w2, h2) = (p.w.div_ceil(step), p.h.div_ceil(step));
// Columns first at the kept rows, then rows at the kept columns. Each sum adds the same terms
// in the same order as a `mirror` per tap would, so the result is bit for bit the same; the
// source rows are found once per row and the columns mirrored only near the edges.
let mut tmp = vec![0.0f32; p.w * h2];
rows(&mut tmp, p.w, |y2, row| {
let y = (y2 * step) as isize;
let src: [&[f32]; 5] = std::array::from_fn(|k| {
let r = mirror(y + k as isize - 2, p.h);
&p.v[r * p.w..(r + 1) * p.w]
});
for (x, o) in row.iter_mut().enumerate() {
*o = (0..5).map(|k| TAPS[k] * src[k][x]).sum();
}
});
let mut out = vec![0.0f32; w2 * h2];
rows(&mut out, w2, |y2, row| {
let src = &tmp[y2 * p.w..(y2 + 1) * p.w];
for (x2, o) in row.iter_mut().enumerate() {
let x = x2 * step;
*o = if x >= 2 && x + 2 < p.w {
let s = &src[x - 2..x + 3];
(0..5).map(|k| TAPS[k] * s[k]).sum()
} else {
(0..5).map(|k| TAPS[k] * src[mirror(x as isize + k as isize - 2, p.w)]).sum()
};
}
});
Plane { w: w2, h: h2, v: out }
}
/// The next coarser level.
fn down(p: &Plane) -> Plane {
blur_step(p, 2)
}
/// `p` brought up to `w × h`: zeros between samples, then the blur times four.
///
/// Three samples in four are zero, so their taps are skipped instead of blurring a zero-filled
/// plane: the nonzero terms are added in the same order (skipping `+0.0` terms changes at most the
/// sign of a zero, and the filter only adds and exponentiates these values).
fn up(p: &Plane, w: usize, h: usize) -> Plane {
let (lh, lw) = (p.h.min(h.div_ceil(2)), p.w.min(w.div_ceil(2)));
// The source sample behind index `i` of a zero-stuffed axis of length `n` holding `lim` samples.
let src = |i: isize, n: usize, lim: usize| {
let m = mirror(i, n);
(m.is_multiple_of(2) && m / 2 < lim).then_some(m / 2)
};
// Columns first, only at the even columns (the odd ones are all zero).
let mut tmp = vec![0.0f32; lw * h];
if lw > 0 {
rows(&mut tmp, lw, |y, row| {
let taps: [Option<&[f32]>; 5] = std::array::from_fn(|k| src(y as isize + k as isize - 2, h, lh).map(|r| &p.v[r * p.w..r * p.w + lw]));
for (j, o) in row.iter_mut().enumerate() {
*o = (0..5).filter_map(|k| taps[k].map(|s| TAPS[k] * (s[j] * 4.0))).sum();
}
});
}
let mut out = vec![0.0f32; w * h];
rows(&mut out, w, |y, row| {
let t = &tmp[y * lw..(y + 1) * lw];
for (x, o) in row.iter_mut().enumerate() {
*o = if x >= 2 && x + 2 < w {
// Away from the edges no tap mirrors.
(0..5)
.filter_map(|k| {
let i = x + k - 2;
(i.is_multiple_of(2) && i / 2 < lw).then(|| TAPS[k] * t[i / 2])
})
.sum()
} else {
(0..5).filter_map(|k| src(x as isize + k as isize - 2, w, lw).map(|j| TAPS[k] * t[j])).sum()
};
}
});
Plane { w, h, v: out }
}
/// The source rows of [`up`]`(p, w, h)` at output row `y`, one per tap (`None` where the
/// zero-stuffed row is all zeros).
fn up_rows(p: &Plane, h: usize, y: usize) -> [Option<usize>; 5] {
let lh = p.h.min(h.div_ceil(2));
std::array::from_fn(|k| {
let m = mirror(y as isize + k as isize - 2, h);
(m.is_multiple_of(2) && m / 2 < lh).then_some(m / 2)
})
}
/// One sample of [`up`]`(p, w, h)`: column `x` of the output row whose [`up_rows`] are `rows`.
/// It adds the same terms in the same order as `up`, so it gives the same bits.
fn up_at(p: &Plane, w: usize, rows: &[Option<usize>; 5], x: usize) -> f32 {
let lw = p.w.min(w.div_ceil(2));
let col = |j: usize| -> f32 { (0..5).filter_map(|k| rows[k].map(|r| TAPS[k] * (p.v[r * p.w + j] * 4.0))).sum() };
if x >= 2 && x + 2 < w {
// Away from the edges no tap mirrors.
(0..5)
.filter_map(|k| {
let i = x + k - 2;
(i.is_multiple_of(2) && i / 2 < lw).then(|| TAPS[k] * col(i / 2))
})
.sum()
} else {
(0..5)
.filter_map(|k| {
let m = mirror(x as isize + k as isize - 2, w);
(m.is_multiple_of(2) && m / 2 < lw).then(|| TAPS[k] * col(m / 2))
})
.sum()
}
}
/// Levels down to about 2 pixels on the short side.
fn depth(w: usize, h: usize) -> usize {
let mut s = w.min(h);
let mut n = 1;
while s > 2 {
s = s.div_ceil(2);
n += 1;
}
n
}
fn gaussian(p: Plane, n: usize) -> Vec<Plane> {
let mut g = vec![p];
for _ in 1..n {
let next = down(&g[g.len() - 1]);
g.push(next);
}
g
}
/// The local Laplacian filter of `u` with `remap(value, reference)`; the coarsest level is kept.
fn llf(u: &Plane, remap: impl Fn(f32, f32) -> f32 + Sync) -> Plane {
let n = depth(u.w, u.h);
let g = gaussian(Plane { w: u.w, h: u.h, v: u.v.clone() }, n);
// References span the image's tones (see `REF_LOW_QUANTILE`).
let hi = u.v.iter().fold(f32::NEG_INFINITY, |a, &v| a.max(v));
let lo = quantile(&u.v, REF_LOW_QUANTILE).min(hi);
if hi - lo <= 1e-6 || (hi - lo).is_nan() {
return Plane { w: u.w, h: u.h, v: u.v.clone() };
}
let refs = (((hi - lo) / REF_STEP).ceil() as usize + 1).clamp(2, MAX_REFS);
let step = (hi - lo) / (refs - 1) as f32;
let mut lap: Vec<Vec<f32>> = g[..n - 1].iter().map(|p| vec![0.0; p.v.len()]).collect();
for k in 0..refs {
let r = lo + step * k as f32;
let mut m = Plane { w: u.w, h: u.h, v: u.v.clone() };
rows(&mut m.v, u.w, |_, row| {
for v in row.iter_mut() {
*v = remap(*v, r);
}
});
let gr = gaussian(m, n);
for l in 0..n - 1 {
let (gl, fine, lw, lh, coarse) = (&g[l].v, &gr[l].v, g[l].w, g[l].h, &gr[l + 1]);
rows(&mut lap[l], lw, |y, row| {
let taps = up_rows(coarse, lh, y);
for (x, o) in row.iter_mut().enumerate() {
let i = y * lw + x;
let wgt = (1.0 - (gl[i].clamp(lo, hi) - r).abs() / step).max(0.0);
if wgt > 0.0 {
*o += wgt * (fine[i] - up_at(coarse, lw, &taps, x));
}
}
});
}
}
let mut o = Plane { w: g[n - 1].w, h: g[n - 1].h, v: g[n - 1].v.clone() };
for l in (0..n - 1).rev() {
let mut next = up(&o, g[l].w, g[l].h);
for (a, b) in next.v.iter_mut().zip(&lap[l]) {
*a += b;
}
o = next;
}
o
}
/// The `q` quantile (0 … 1) of `v`.
fn quantile(v: &[f32], q: f32) -> f32 {
let mut s = v.to_vec();
// Selecting the one element is linear, a full sort is not (5 sorts of the work copy were a
// fifteenth of a render). `total_cmp` ties are bit-identical, so it is the sorted element.
let i = quantile_rank(s.len(), q);
*s.select_nth_unstable_by(i, f32::total_cmp).1
}
/// The image range: [`RANGE_QUANTILES`] of the log luminance on a copy at most [`RANGE_SIDE`]
/// pixels across.
fn range(u: &Plane) -> (f32, f32) {
let f = u.w.max(u.h).div_ceil(RANGE_SIDE).max(1);
let (sw, sh) = (u.w.div_ceil(f), u.h.div_ceil(f));
let mut sum = vec![(0.0f64, 0u32); sw * sh];
for y in 0..u.h {
for x in 0..u.w {
let c = &mut sum[(y / f) * sw + x / f];
c.0 += f64::from(u.v[y * u.w + x]);
c.1 += 1;
}
}
let cells: Vec<f32> = sum.iter().filter(|c| c.1 > 0).map(|c| (c.0 / f64::from(c.1)) as f32).collect();
(quantile(&cells, RANGE_QUANTILES[0]), quantile(&cells, RANGE_QUANTILES[1]))
}
/// `d` past the detail threshold: about 0 below `sigma`, `d − sigma` well above it.
fn excess(d: f32, sigma: f32) -> f32 {
d - sigma * (d / sigma).tanh()
}
fn knot(t: f32, k: &[f32; KNOTS]) -> f32 {
let x = t.clamp(0.0, 1.0) * (KNOTS - 1) as f32;
let i = (x as usize).min(KNOTS - 2);
k[i] + (k[i + 1] - k[i]) * (x - i as f32)
}
/// Applies Shadows and Highlights (−100 … 100) to straight RGBA pixels encoded with `enc`
/// (`Encoding::of(DevelopInputs::encoding_gamma)`). The filter is deterministic, so it reads no grain seed.
pub(crate) fn apply(px: &mut [[f32; 4]], w: usize, h: usize, shadows: f32, highlights: f32, enc: Encoding) {
let Some(tone) = LocalTone::new(shadows, highlights) else { return };
if w < 2 || h < 2 {
return;
}
let u = Plane { w, h, v: px.iter().map(|q| (luma([0, 1, 2].map(|c| enc.decode(q[c]))).max(0.0) + LOG_FLOOR).log2()).collect() };
// The filter on a copy at most WORK_SIDE across (box-averaged in log).
let f = w.max(h).div_ceil(WORK_SIDE).max(1);
let small = if f == 1 { Plane { w, h, v: u.v.clone() } } else { shrink(&u, f) };
let mut o = Plane { w: small.w, h: small.h, v: small.v.clone() };
for pass in &tone.passes {
o = pass.run(&o);
}
// The change in log luminance, at full size.
let change: Vec<f32> = if f == 1 {
o.v.iter().zip(&u.v).map(|(a, b)| a - b).collect()
} else {
let d: Vec<f32> = o.v.iter().zip(&small.v).map(|(a, b)| a - b).collect();
guided_upsample(&small, &d, &u)
};
par_rows(px, w, 1, |y, row| {
for (x, q) in row.iter_mut().enumerate() {
let gain = change[y * w + x].exp2();
for c in 0..3 {
q[c] = enc.encode(enc.decode(q[c]) * gain);
}
}
});
}
/// `u` averaged over `f × f` blocks.
fn shrink(u: &Plane, f: usize) -> Plane {
let (sw, sh) = (u.w.div_ceil(f), u.h.div_ceil(f));
let mut v = vec![0.0f32; sw * sh];
par_rows(&mut v, sw, 1, |y, row| {
for (x, o) in row.iter_mut().enumerate() {
let (x0, y0) = (x * f, y * f);
let (x1, y1) = ((x0 + f).min(u.w), (y0 + f).min(u.h));
let mut s = 0.0f64;
for yy in y0..y1 {
for xx in x0..x1 {
s += f64::from(u.v[yy * u.w + xx]);
}
}
*o = (s / ((x1 - x0) * (y1 - y0)) as f64) as f32;
}
});
Plane { w: sw, h: sh, v }
}
/// The change `d` computed on `small` brought to the size of `full`, following its edges: a local
/// linear model of the change against the log luminance (the guided filter of K. He, J. Sun,
/// *Fast Guided Filter*, 2015), fitted on the small copy and evaluated on the full one.
fn guided_upsample(small: &Plane, d: &[f32], full: &Plane) -> Vec<f32> {
let (sw, sh) = (small.w, small.h);
let r = 2;
let eps = 0.01;
let mean = |v: &[f32]| super::box_mean(v, sw, sh, r);
let ud: Vec<f32> = small.v.iter().zip(d).map(|(a, b)| a * b).collect();
let uu: Vec<f32> = small.v.iter().map(|a| a * a).collect();
let (mu, md, mud, muu) = (mean(&small.v), mean(d), mean(&ud), mean(&uu));
let a: Vec<f32> = (0..sw * sh).map(|i| (mud[i] - mu[i] * md[i]) / (muu[i] - mu[i] * mu[i] + eps)).collect();
let b: Vec<f32> = (0..sw * sh).map(|i| md[i] - a[i] * mu[i]).collect();
let (ma, mb) = (mean(&a), mean(&b));
let (fx, fy) = (sw as f32 / full.w as f32, sh as f32 / full.h as f32);
let mut out = vec![0.0f32; full.w * full.h];
par_rows(&mut out, full.w, 1, |y, row| {
let sy = (y as f32 + 0.5) * fy - 0.5;
for (x, o) in row.iter_mut().enumerate() {
let sx = (x as f32 + 0.5) * fx - 0.5;
let av = crate::photo_util::bilinear(&ma, sw, sh, 1, 0, sx, sy);
let bv = crate::photo_util::bilinear(&mb, sw, sh, 1, 0, sx, sy);
*o = av * full.v[y * full.w + x] + bv;
}
});
out
}
#[cfg(test)]
mod tests {
use super::*;
const SRGB: Encoding = Encoding(0.0);
/// The plain blur: a `mirror` per tap over the whole plane, the reference for [`blur_step`].
fn blur_step_reference(p: &Plane, step: usize) -> Plane {
let (w2, h2) = (p.w.div_ceil(step), p.h.div_ceil(step));
let mut tmp = vec![0.0f32; p.w * h2];
for y2 in 0..h2 {
for x in 0..p.w {
tmp[y2 * p.w + x] = (0..5).map(|k| TAPS[k] * p.v[mirror((y2 * step) as isize + k as isize - 2, p.h) * p.w + x]).sum();
}
}
let mut out = vec![0.0f32; w2 * h2];
for y2 in 0..h2 {
for x2 in 0..w2 {
out[y2 * w2 + x2] = (0..5).map(|k| TAPS[k] * tmp[y2 * p.w + mirror((x2 * step) as isize + k as isize - 2, p.w)]).sum();
}
}
Plane { w: w2, h: h2, v: out }
}
/// The plain upsampling: a zero-stuffed plane blurred whole, the reference for [`up`].
fn up_reference(p: &Plane, w: usize, h: usize) -> Plane {
let mut z = Plane { w, h, v: vec![0.0; w * h] };
for y in 0..p.h.min(h.div_ceil(2)) {
for x in 0..p.w.min(w.div_ceil(2)) {
z.v[2 * y * w + 2 * x] = p.v[y * p.w + x] * 4.0;
}
}
blur_step_reference(&z, 1)
}
fn noise_plane(w: usize, h: usize, seed: u32) -> Plane {
let mut s = seed.wrapping_mul(2_654_435_761).max(1);
let v = (0..w * h)
.map(|_| {
s ^= s << 13;
s ^= s >> 17;
s ^= s << 5;
(s % 20_000) as f32 / 1000.0 - 16.0
})
.collect();
Plane { w, h, v }
}
#[test]
fn the_fast_pyramid_matches_the_plain_one_exactly() {
// Odd, even, tiny and large-enough-to-run-in-parallel sizes, as the pyramid's levels are.
for (i, (w, h)) in [(1, 1), (1, 7), (2, 2), (3, 5), (5, 3), (8, 6), (37, 23), (64, 64), (301, 211)].into_iter().enumerate() {
let p = noise_plane(w, h, i as u32 + 1);
for step in [1, 2] {
assert_eq!(blur_step(&p, step).v, blur_step_reference(&p, step).v, "blur {w}×{h} step {step}");
}
for (uw, uh) in [(w * 2, h * 2), (w * 2 - 1, h * 2 - 1), (w * 2, h * 2 - 1), (w.max(2) * 2 - 3, h * 2)] {
let full = up(&p, uw, uh);
assert_eq!(full.v, up_reference(&p, uw, uh).v, "up {w}×{h} → {uw}×{uh}");
// The filter samples `up` one pixel at a time; every sample has the same bits.
for y in 0..uh {
let taps = up_rows(&p, uh, y);
for x in 0..uw {
assert_eq!(up_at(&p, uw, &taps, x).to_bits(), full.v[y * uw + x].to_bits(), "up_at {w}×{h} → {uw}×{uh} at {x},{y}");
}
}
}
}
}
#[test]
fn quantile_is_the_sorted_element() {
let p = noise_plane(301, 211, 9);
let mut v = p.v.clone();
// Ties and signed zeros, which `total_cmp` orders by their bits.
v.extend([0.0, -0.0, 0.0, -0.0, 3.5, 3.5, f32::MIN_POSITIVE]);
let mut sorted = v.clone();
sorted.sort_by(f32::total_cmp);
for q in [0.0, 0.001, 0.01, 0.25, 0.5, 0.99, 1.0] {
let want = sorted[((sorted.len() - 1) as f32 * q).round() as usize];
assert_eq!(quantile(&v, q).to_bits(), want.to_bits(), "q {q}");
}
}
fn grey(w: usize, h: usize, f: impl Fn(usize, usize) -> f32) -> Vec<[f32; 4]> {
(0..w * h).map(|i| f(i % w, i / w)).map(|v| [v, v, v, 1.0]).collect()
}
#[test]
fn a_flat_image_is_unchanged() {
let mut px = grey(64, 48, |_, _| 0.4);
apply(&mut px, 64, 48, 100.0, -100.0, SRGB);
assert!(px.iter().all(|q| (q[0] - 0.4).abs() < 1e-5));
}
#[test]
fn shadows_raise_a_dark_area_without_a_halo() {
// A 0.1 | 0.6 step (the dark half is the image's black point, which Photoshop barely
// moves either): the bright half stays, and no halo forms on either side of the edge.
let (w, h) = (256, 128);
let mut px = grey(w, h, |x, _| if x < w / 2 { 0.1 } else { 0.6 });
apply(&mut px, w, h, 100.0, 0.0, SRGB);
let row = &px[64 * w..65 * w];
assert!((row[w / 2 + 1][0] - 0.6).abs() < 0.002 && (row[w - 5][0] - 0.6).abs() < 0.002);
let (far, near) = (row[10][0], row[w / 2 - 1][0]);
assert!((far - 0.1).abs() < 0.004 && (far - near).abs() < 0.004, "{far} {near}");
}
#[test]
fn grey_moves_as_in_photoshop() {
// Mid-grey with 1 % black (0.015) and white (0.97) corners, Photoshop 25.4: Shadows +100
// takes the grey from 127.5 to 165.3, Highlights −100 to 89.6 (of 255).
let n = 256;
let image = |c: f32| {
grey(n, n, |x, y| {
if x >= n - 26 && y >= n - 26 {
0.97
} else if x >= n - 26 && y < 26 {
0.015
} else {
c
}
})
};
for (s, hl, want) in [(100.0, 0.0, 165.3), (0.0, -100.0, 89.6)] {
let mut px = image(0.5);
apply(&mut px, n, n, s, hl, SRGB);
let got = px[175 * n + 100][0] * 255.0;
assert!((got - want).abs() < 5.0, "{s} {hl}: {got} vs {want}");
}
}
#[test]
fn highlights_lower_a_bright_area_and_keep_the_darkest() {
let (w, h) = (192, 192);
let mut px = grey(w, h, |x, y| if (64..128).contains(&x) && (64..128).contains(&y) { 0.8 } else { 0.2 });
apply(&mut px, w, h, 0.0, -100.0, SRGB);
assert!(px[96 * w + 96][0] < 0.75, "{}", px[96 * w + 96][0]);
assert!((px[5 * w + 5][0] - 0.2).abs() < 0.01, "{}", px[5 * w + 5][0]);
}
#[test]
fn smooth_gradients_stay_smooth() {
// A soft ramp over eight stops, as in an out-of-focus background. Coefficients interpolated
// between references too far apart drew contour lines across such ramps (Shadows +100 on
// a D4 raw): the output must rise steadily, without ripples.
let (w, h) = (640, 48);
let mut px = grey(w, h, |x, _| crate::photo_util::linear_to_srgb((x as f32 / (w - 1) as f32 * 8.0 - 9.0).exp2()));
for (s, hl) in [(100.0, 0.0), (0.0, -100.0), (-100.0, 100.0)] {
let mut p = px.clone();
apply(&mut p, w, h, s, hl, SRGB);
let row: Vec<f32> = (0..w).map(|x| crate::photo_util::srgb_to_linear(p[24 * w + x][0]).max(1e-6).log2()).collect();
let steps: Vec<f32> = row.windows(2).map(|d| d[1] - d[0]).collect();
assert!(steps.iter().all(|d| *d > 0.0), "{s} {hl}: the ramp reverses");
let jumps: Vec<f32> = steps.windows(2).map(|d| (d[1] - d[0]).abs()).collect();
let ripple = jumps[16..jumps.len() - 16].iter().fold(0.0f32, |a, b| a.max(*b));
// The ramp rises 0.0125 stops per pixel; its slope may change by a third at most.
assert!(ripple < 0.004, "{s} {hl}: slope jumps by {ripple} stops per pixel");
}
px.clear();
}
#[test]
fn the_result_does_not_depend_on_the_image_size() {
let at = |n: usize| {
let mut px = grey(n, n, |x, y| if x < n / 3 || y < n / 4 { 0.08 } else { 0.7 });
apply(&mut px, n, n, 70.0, -60.0, SRGB);
[px[(n / 8) * n + n / 8][0], px[(3 * n / 4) * n + 3 * n / 4][0]]
};
let (a, b) = (at(96), at(384));
assert!((a[0] - b[0]).abs() < 0.02 && (a[1] - b[1]).abs() < 0.02, "{a:?} {b:?}");
}
}
-284
View File
@@ -1,284 +0,0 @@
//! Develop's stages resolved for one image: every constant and table the per-pixel ones use, so
//! another implementation of them (the GPU preview, `photocraft_gpu::CameraRawDevelop`) runs the
//! same maths. [`develop`](super::develop) builds its own constants with the same functions.
//! The spatial stages other than Detail come as their parameters: Dehaze, Clarity and Texture
//! (see [`spatial`](super::spatial)), Shadows and Highlights as a [`LocalTone`].
use super::local_tone::{LocalTone, WORK_SIDE};
use super::spatial::{Clarity, Dehaze, Texture};
use super::{
CameraRaw, DevelopInputs, Encoding, Wheel, calibration_neutral, curve_lut, grade_neutral, hsl_neutral, hsv_to_rgb, is_linear, luma, parametric_lut,
white_balance_gains, whites_blacks,
};
use craft::imaging::raw::VignetteStyle as StoredStyle;
pub use whites_blacks::Model as WhitesBlacksModel;
/// Entries of the tone curve tables (parametric and point curves).
pub const CURVE_LUT: usize = 1024;
/// Samples of a Whites or Blacks curve row: grey levels 0, 1/32, …, 1.
pub const WB_STEPS: usize = whites_blacks::STEPS;
/// White balance and exposure: channel gains in linear light, when the stage is on.
pub(crate) fn gains(p: &CameraRaw) -> Option<[f32; 3]> {
if p.temperature == 0.0 && p.tint == 0.0 && p.exposure == 0.0 {
return None;
}
let g = white_balance_gains(p.temperature, p.tint);
let norm = luma(g);
Some(g.map(|v| v / norm * 2f32.powf(p.exposure)))
}
/// Contrast's strength, when Contrast is set (with or without Texture and Clarity).
fn contrast(p: &CameraRaw) -> Option<f32> {
(p.contrast != 0.0).then_some(p.contrast / 100.0 * 0.6)
}
/// Whites and Blacks' tables, for an implementation that measures the image's points itself.
pub fn whites_blacks_model() -> WhitesBlacksModel {
whites_blacks::model()
}
/// Whites and Blacks as two curve rows for the image's amounts.
#[derive(Clone, Debug, PartialEq)]
pub struct WhitesBlacks {
/// The Whites curve over grey levels 0, 1/32, …, 1, when Whites is set.
pub whites: Option<[f32; WB_STEPS]>,
/// The Blacks curve, applied after Whites.
pub blacks: Option<[f32; WB_STEPS]>,
/// The clipping directions (Whites up, Blacks down) curve each channel; the others scale the
/// pixel by the change of its luminance.
pub per_channel: bool,
}
/// Color Grading's wheels resolved.
#[derive(Clone, Debug, PartialEq)]
pub struct Grade {
/// Colour offsets of the shadows, midtones, highlights and global wheels.
pub tints: [[f32; 3]; 4],
/// Luminance of the same wheels (slider units).
pub lums: [f32; 4],
pub blend: f32,
pub balance: f32,
}
impl Grade {
pub(crate) fn new(p: &CameraRaw) -> Self {
let tint = |wh: &Wheel| -> [f32; 3] {
let c = hsv_to_rgb(wh.hue, 1.0, 1.0);
let l = luma(c);
[c[0] - l, c[1] - l, c[2] - l].map(|v| v * wh.sat / 100.0 * 0.3)
};
Grade {
tints: [tint(&p.grade_shadows), tint(&p.grade_midtones), tint(&p.grade_highlights), tint(&p.grade_global)],
lums: [p.grade_shadows.lum, p.grade_midtones.lum, p.grade_highlights.lum, p.grade_global.lum],
blend: 0.15 + p.grade_blending.clamp(0.0, 100.0) / 100.0 * 0.35,
balance: p.grade_balance.clamp(-100.0, 100.0) / 100.0 * 0.25,
}
}
}
/// The vignette's `vignette_style`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VignetteStyle {
HighlightPriority,
ColorPriority,
PaintOverlay,
}
/// The post-crop vignette's shape on a `w × h` frame.
#[derive(Clone, Debug, PartialEq)]
pub struct Vignette {
/// −1 … 1.
pub amount: f32,
/// 0 … 1.
pub highlights: f32,
pub style: VignetteStyle,
/// Frame centre (pixels).
pub centre: [f32; 2],
/// Half axes of the shape (pixels).
pub axes: [f32; 2],
/// Exponent of the superellipse.
pub power: f32,
/// The mask's smoothstep edges in normalised radius.
pub edges: [f32; 2],
}
impl Vignette {
pub(crate) fn new(w: usize, h: usize, p: &CameraRaw) -> Self {
let mid = p.vignette_midpoint.clamp(0.0, 100.0) / 100.0;
let feather = p.vignette_feather.clamp(0.0, 100.0) / 100.0;
let round = p.vignette_roundness.clamp(-100.0, 100.0) / 100.0;
let (cx, cy) = (w as f32 / 2.0, h as f32 / 2.0);
// Roundness: 0 follows the frame's aspect, +1 a circle, −1 a rounded rectangle.
let (ax, ay) = if round >= 0.0 {
let r = cx.min(cy) + (cx.max(cy) - cx.min(cy)) * (1.0 - round);
(if cx >= cy { r } else { cx }, if cy > cx { r } else { cy })
} else {
(cx, cy)
};
let inner = 1.0 - mid * 0.8;
Vignette {
amount: p.vignette_amount / 100.0,
highlights: p.vignette_highlights.clamp(0.0, 100.0) / 100.0,
style: match p.vignette_style {
StoredStyle::PaintOverlay => VignetteStyle::PaintOverlay,
StoredStyle::ColorPriority => VignetteStyle::ColorPriority,
_ => VignetteStyle::HighlightPriority,
},
centre: [cx, cy],
axes: [ax, ay],
power: 2.0 + (-round).max(0.0) * 6.0,
edges: [inner - feather * 0.5 * inner, inner + feather * 0.5 * (1.4 - inner) + 0.02],
}
}
}
/// Grain: value noise sampled in full-resolution coordinates.
#[derive(Clone, Debug, PartialEq)]
pub struct Grain {
/// Noise cell size (full-resolution pixels).
pub cell: f32,
/// Weight of the finer octave.
pub roughness: f32,
pub amount: f32,
pub seed: u64,
/// Full-resolution pixels per pixel (`1 / pixel_scale`).
pub scale: f32,
}
impl Grain {
pub(crate) fn new(p: &CameraRaw, inputs: &DevelopInputs) -> Self {
Grain {
cell: 1.0 + p.grain_size / 25.0,
roughness: p.grain_roughness / 100.0,
amount: p.grain_amount / 100.0 * 0.12,
seed: u64::from(inputs.seed),
scale: 1.0 / inputs.pixel_scale.clamp(0.01, 1.0),
}
}
}
/// Develop's per-pixel stages for one image and settings, in order. `None` stages are off.
#[derive(Clone, Debug, PartialEq)]
pub struct PerPixel {
/// 1. White balance and exposure gains in linear light (sRGB-decoded values).
pub gains: Option<[f32; 3]>,
/// 2. Dehaze.
pub dehaze: Option<Dehaze>,
/// 3. Shadows and Highlights: a local Laplacian filter of the whole frame, then each pixel's
/// light scaled by the change of its log luminance.
pub local_tone: Option<LocalTone>,
/// 3. Clarity and Texture on the luminance clipped to 1, before Contrast.
pub clarity: Option<Clarity>,
pub texture: Option<Texture>,
/// 3. Contrast's strength.
pub contrast: Option<f32>,
/// 3b. Whites and Blacks, in the document's encoding.
pub whites_blacks: Option<WhitesBlacks>,
/// 3b. Whites and Blacks to measure the image's points for (the sliders, −100 … 100), when a
/// spatial stage is set: the points then depend on its output, so whatever runs it
/// measures them and picks the curves from [`whites_blacks_model`]. `whites_blacks` is
/// then `None`.
pub measure_whites_blacks: Option<[f32; 2]>,
/// The document's transfer curve: 0 for sRGB's, else a power-law gamma.
pub encoding: f32,
/// 4. Vibrance and Saturation (slider / 100).
pub presence: Option<[f32; 2]>,
/// 5. The parametric tone curve, [`CURVE_LUT`] entries over 0 … 1.
pub parametric: Option<Vec<f32>>,
/// 5. Point curves: master, red, green, blue.
pub point: [Option<Vec<f32>>; 4],
/// 6. Color Mixer hue, saturation and luminance per band.
pub hsl: Option<[[f32; 8]; 3]>,
/// 7. Color Grading.
pub grade: Option<Grade>,
/// 9. Vignette.
pub vignette: Option<Vignette>,
/// 9. Grain.
pub grain: Option<Grain>,
/// Clip RGB to 0 … 1 at the end (all but 32-bit documents).
pub clamp: bool,
}
/// Whether developing needs a stage that reads neighbouring pixels: Dehaze, Shadows and
/// Highlights, Texture, Clarity, sharpening or noise reduction.
pub fn spatial(p: &CameraRaw) -> bool {
p.dehaze != 0.0 || [p.highlights, p.shadows, p.texture, p.clarity].iter().any(|v| *v != 0.0) || detail_on(p)
}
/// Whether developing needs Detail: sharpening or noise reduction.
fn detail_on(p: &CameraRaw) -> bool {
p.sharpen_amount > 0.0 || p.noise_luminance > 0.0 || p.noise_color > 0.0
}
/// The image's black and white points that Whites and Blacks adapt to, for `px` (`w × h`,
/// display-encoded) developed per pixel with `p`: what [`develop`](super::develop) measures
/// after white balance and Contrast. `None` when Whites and Blacks are 0 or `p` needs a
/// spatial stage.
pub fn white_black_points(px: &[[f32; 4]], w: usize, h: usize, p: &CameraRaw, inputs: &DevelopInputs) -> Option<(f32, f32)> {
if (p.whites == 0.0 && p.blacks == 0.0) || spatial(p) || px.len() != w.saturating_mul(h) {
return None;
}
let enc = Encoding::of(inputs.encoding_gamma);
let (g, k_con) = (gains(p), contrast(p));
Some(super::luminance_points(px, w, h, enc, |q| {
let q = g.map_or(q, |g| super::balance(q, g));
k_con.map_or(q, |k| super::contrast(q, k))
}))
}
/// Develop's stages for settings without Detail or Calibration, on a `w × h` image; `points` are
/// the image's [`white_black_points`]. `None` when `p` needs Detail or Calibration (these stages
/// run neither), Shadows or Highlights on a frame wider than the filter's working copy (the
/// develop then filters a reduced copy) or only 2 pixels on its short side, or Whites or Blacks
/// without a spatial stage and without `points`. The points themselves leave Calibration out, so a
/// caller may cache them across Calibration changes.
pub fn per_pixel(p: &CameraRaw, inputs: &DevelopInputs, w: usize, h: usize, float: bool, points: Option<(f32, f32)>) -> Option<PerPixel> {
if detail_on(p) || !calibration_neutral(p) {
return None;
}
// The develop leaves frames under 2 pixels on a side alone.
let local_tone = if w >= 2 && h >= 2 { LocalTone::new(p.shadows, p.highlights) } else { None };
// At 2 pixels on the short side the GPU pass's pyramid has one level, so the CPU develops it.
if local_tone.is_some() && (w.max(h) > WORK_SIDE || w.min(h) <= 2) {
return None;
}
let (dehaze, clarity, texture) = (Dehaze::new(p, w, h), Clarity::new(p, w, h), Texture::new(p, inputs, w, h));
let spatial = local_tone.is_some() || dehaze.is_some() || clarity.is_some() || texture.is_some();
let identity = p.is_identity();
let wb_on = p.whites != 0.0 || p.blacks != 0.0;
let measure_whites_blacks = (wb_on && spatial).then(|| [p.whites.clamp(-100.0, 100.0), p.blacks.clamp(-100.0, 100.0)]);
let whites_blacks = if wb_on && measure_whites_blacks.is_none() {
let (bp, wp) = points?;
let (xw, xb) = whites_blacks::amounts(p.whites.clamp(-100.0, 100.0), p.blacks.clamp(-100.0, 100.0), bp, wp);
(xw != 0.0 || xb != 0.0).then(|| WhitesBlacks {
whites: (xw != 0.0).then(|| whites_blacks::whites_row(xw)),
blacks: (xb != 0.0).then(|| whites_blacks::blacks_row(xb)),
per_channel: xw > 0.0 || xb < 0.0,
})
} else {
None
};
let parametric_on = !(p.curve_highlights == 0.0 && p.curve_lights == 0.0 && p.curve_darks == 0.0 && p.curve_shadows == 0.0);
let pts = |c: &Vec<[f32; 2]>| (!is_linear(c)).then(|| curve_lut(c, CURVE_LUT));
Some(PerPixel {
gains: gains(p),
dehaze,
local_tone,
clarity,
texture,
contrast: contrast(p),
whites_blacks,
measure_whites_blacks,
encoding: Encoding::of(inputs.encoding_gamma).0,
presence: (p.vibrance != 0.0 || p.saturation != 0.0).then_some([p.vibrance / 100.0, p.saturation / 100.0]),
parametric: parametric_on.then(|| parametric_lut(p, CURVE_LUT)),
point: [pts(&p.point_curve), pts(&p.point_curve_red), pts(&p.point_curve_green), pts(&p.point_curve_blue)],
hsl: (!hsl_neutral(p)).then_some([p.hsl_hue, p.hsl_sat, p.hsl_lum]),
grade: (!grade_neutral(p)).then(|| Grade::new(p)),
vignette: (p.vignette_amount != 0.0).then(|| Vignette::new(w, h, p)),
grain: (p.grain_amount > 0.0).then(|| Grain::new(p, inputs)),
clamp: !float && !identity,
})
}
-191
View File
@@ -1,191 +0,0 @@
//! Dehaze, Clarity and Texture resolved for one frame: the sizes, radii and constants their
//! filters use, so another implementation of them (the GPU preview,
//! `photocraft_gpu::CameraRawDevelop`) runs the same filters. [`develop`](super::develop) builds
//! its own from the same constructors.
//!
//! - **Dehaze** follows the dark channel prior (K. He, J. Sun, X. Tang, *Single Image Haze Removal
//! Using Dark Channel Prior*, CVPR 2009) on a box-averaged copy at most [`DEHAZE_SIDE`] pixels
//! across, with the transmission refined by a guided filter (K. He, J. Sun, X. Tang, *Guided
//! Image Filtering*, ECCV 2010) and brought back to full size bilinearly.
//! - **Clarity** raises the luminance's difference from a fast guided filter of itself (K. He,
//! J. Sun, *Fast Guided Filter*, arXiv 2015), weighted toward the midtones.
//! - **Texture** raises its difference from a Gaussian blur (three box passes), limited to
//! ±[`TEXTURE_LIMIT`].
use super::{CameraRaw, DevelopInputs};
/// Dehaze measures the haze on a copy at most this many pixels across.
pub const DEHAZE_SIDE: usize = 768;
/// The dark channel's minimum filter has a radius of the copy's long side over this, at least
/// [`DEHAZE_MIN_RADIUS`].
pub const DEHAZE_RADIUS_DIVISOR: usize = 60;
/// See [`DEHAZE_RADIUS_DIVISOR`].
pub const DEHAZE_MIN_RADIUS: usize = 2;
/// The atmospheric light is the mean colour of the brightest 1 / this of the dark channel (at
/// least one cell).
pub const DEHAZE_AIR_FRACTION: usize = 1000;
/// Each channel of the atmospheric light is at least this.
pub const DEHAZE_AIR_FLOOR: f32 = 0.2;
/// The share of the haze the raw transmission removes (the paper's ω).
pub const DEHAZE_OMEGA: f32 = 0.95;
/// The guided filter's regularisation for the transmission.
pub const DEHAZE_EPS: f32 = 1e-3;
/// The transmission is at least this.
pub const DEHAZE_T_FLOOR: f32 = 0.1;
/// Clarity's guided filter regularisation.
pub const CLARITY_EPS: f32 = 0.005;
/// Texture moves the luminance by at most this.
pub const TEXTURE_LIMIT: f32 = 0.1;
/// Dehaze on a `w × h` frame.
#[derive(Clone, Debug, PartialEq)]
pub struct Dehaze {
/// The slider / 100 (−1 … 1).
pub amount: f32,
/// The copy averages `factor × factor` blocks.
pub factor: usize,
/// The copy's size.
pub size: [usize; 2],
/// The minimum filter's radius.
pub radius: usize,
/// The guided filter's radius.
pub guide_radius: usize,
/// How many of the copy's cells the atmospheric light averages.
pub top: usize,
}
impl Dehaze {
/// Dehaze for `p` on a `w × h` frame; `None` when it is off.
pub fn new(p: &CameraRaw, w: usize, h: usize) -> Option<Self> {
if p.dehaze == 0.0 {
return None;
}
let factor = w.max(h).div_ceil(DEHAZE_SIDE).max(1);
let size = [w.div_ceil(factor), h.div_ceil(factor)];
let radius = (size[0].max(size[1]) / DEHAZE_RADIUS_DIVISOR).max(DEHAZE_MIN_RADIUS);
Some(Dehaze { amount: p.dehaze / 100.0, factor, size, radius, guide_radius: radius * 2, top: (size[0] * size[1] / DEHAZE_AIR_FRACTION).max(1) })
}
/// The copy the haze is measured on, for `px` (`w × h`, display-encoded) before white balance
/// and exposure (`gains`, as in [`PerPixel`](super::PerPixel)): `size` cells in rows, each the
/// mean light of its block, clipped to 0 … 1. These are exactly the cells
/// [`develop`](super::develop) uses: the brightest of them set the atmospheric light, and a
/// tie between them decides which, so another implementation that computes stage 1 to a few
/// ulps should start from these. Empty when `px` isn't `w × h`.
pub fn cells(&self, px: &[[f32; 4]], w: usize, h: usize, gains: Option<[f32; 3]>) -> Vec<[f32; 3]> {
if px.len() != w.saturating_mul(h) || w.div_ceil(self.factor) != self.size[0] || h.div_ceil(self.factor) != self.size[1] {
return Vec::new();
}
super::haze_cells(px, w, h, self, |q| gains.map_or(q, |g| super::balance(q, g)))
}
}
/// Clarity on a `w × h` frame.
#[derive(Clone, Debug, PartialEq)]
pub struct Clarity {
/// The strength: the slider / 100 × 0.8.
pub amount: f32,
/// The guided filter's radius at full size.
pub radius: usize,
/// The fast guided filter works on `subsample × subsample` block means…
pub subsample: usize,
/// …with this radius…
pub sub_radius: usize,
/// …at this size.
pub sub_size: [usize; 2],
}
impl Clarity {
/// Clarity for `p` on a `w × h` frame; `None` when it is off.
pub fn new(p: &CameraRaw, w: usize, h: usize) -> Option<Self> {
if p.clarity == 0.0 {
return None;
}
let radius = ((w.max(h) as f32 * 0.02) as usize).max(3);
let (subsample, sub_radius) = fast_guided_steps(radius);
Some(Clarity { amount: p.clarity / 100.0 * 0.8, radius, subsample, sub_radius, sub_size: [w.div_ceil(subsample), h.div_ceil(subsample)] })
}
}
/// The fast guided filter's subsampling and its radius there, for radius `r` at full size. A
/// subsampling of 1 is the plain guided filter at radius `r`.
pub fn fast_guided_steps(r: usize) -> (usize, usize) {
let s = (r / 8).clamp(1, 8);
(s, if s == 1 { r } else { (r / s).max(1) })
}
/// Texture on a `w × h` frame.
#[derive(Clone, Debug, PartialEq)]
pub struct Texture {
/// The strength: the slider / 100 × 0.9.
pub amount: f32,
/// The blur's box radii, in order; empty when the blur is too small to change anything.
pub radii: Vec<usize>,
}
impl Texture {
/// Texture for `p` on a `w × h` frame; `None` when it is off.
pub fn new(p: &CameraRaw, inputs: &DevelopInputs, w: usize, h: usize) -> Option<Self> {
if p.texture == 0.0 {
return None;
}
let ps = inputs.pixel_scale.clamp(0.01, 1.0);
let sigma = (w.max(h) as f32 * 0.002).max(1.5 * ps);
Some(Texture { amount: p.texture / 100.0 * 0.9, radii: gauss_radii(sigma) })
}
}
/// The box radii of develop's Gaussian of `sigma`: none below 0.3.
pub(crate) fn gauss_radii(sigma: f32) -> Vec<usize> {
if sigma < 0.3 {
return Vec::new();
}
crate::fxutil::gauss_box_radii(sigma).to_vec()
}
#[cfg(test)]
mod tests {
use super::*;
/// `CameraRaw` with the named fields set (the type is `#[non_exhaustive]`, so no struct expression), or a copy of a base with them set.
macro_rules! cr {
($($f:ident : $v:expr),* $(,)?) => {{
let mut s = CameraRaw::default();
$(s.$f = $v;)*
s
}};
($base:expr => $($f:ident : $v:expr),* $(,)?) => {{
let mut s: CameraRaw = $base;
$(s.$f = $v;)*
s
}};
}
#[test]
fn stages_resolve_for_the_dialogs_proxy_and_are_off_at_zero() {
let p = cr! { dehaze: 40.0, clarity: -50.0, texture: 50.0};
let scale = |pixel_scale| DevelopInputs { pixel_scale, ..Default::default() };
let d = Dehaze::new(&p, 858, 572).unwrap();
assert_eq!((d.factor, d.size, d.radius, d.guide_radius, d.top), (2, [429, 286], 7, 14, 122));
let c = Clarity::new(&p, 858, 572).unwrap();
assert_eq!((c.radius, c.subsample, c.sub_radius, c.sub_size), (17, 2, 8, [429, 286]));
assert!((c.amount + 0.4).abs() < 1e-6);
assert_eq!(Texture::new(&p, &scale(0.143), 858, 572).unwrap().radii, [1, 1, 2]);
// Small frames: the plain guided filter, a blur too narrow to change anything.
assert_eq!(fast_guided_steps(3), (1, 3));
assert!(Texture::new(&cr! { texture: 10.0}, &scale(0.1), 64, 48).unwrap().radii.is_empty());
let off = CameraRaw::default();
assert!(Dehaze::new(&off, 858, 572).is_none() && Clarity::new(&off, 858, 572).is_none() && Texture::new(&off, &scale(1.0), 858, 572).is_none());
}
#[test]
fn dehaze_cells_average_blocks_after_white_balance_and_refuse_a_wrong_size() {
let d = Dehaze::new(&cr! { dehaze: 10.0}, 3, 1).unwrap();
let px = [[0.2, 0.4, 1.5, 1.0], [0.4, 0.0, 0.5, 1.0], [0.9, 0.9, 0.9, 1.0]];
assert_eq!(d.cells(&px, 3, 1, None), vec![[0.2, 0.4, 1.0], [0.4, 0.0, 0.5], [0.9, 0.9, 0.9]]);
let brighter = d.cells(&px, 3, 1, Some([2.0, 2.0, 2.0]));
assert!(brighter[0][0] > 0.2 && brighter[2] == [1.0; 3]);
assert!(d.cells(&px[..2], 3, 1, None).is_empty());
assert!(d.cells(&px, 1, 3, None).is_empty());
}
}
-494
View File
@@ -1,494 +0,0 @@
//! Whites and Blacks as Adobe Camera Raw (process version 2012) applies them.
//!
//! Measured as a black box on the Camera Raw Filter of Photoshop 25.4: grey blocks with chosen
//! histograms went through the filter by script and came back exactly; no Adobe code or data
//! was used.
//!
//! - Both are global curves of the grey level, applied after Shadows and Highlights, Whites
//! first. On an image whose darkest and lightest percent reach black and white the curve of a
//! slider value `x` is the measured row at `x` of [`WHITES`] or [`BLACKS`].
//! - The direction that only compresses (Whites down, Blacks up) is that fixed curve on every
//! image. The direction that clips (Whites up, Blacks down) adapts: the row used is
//! `x · A(BP, WP)`. On the block images BP and WP are their darkest and lightest levels; on
//! photographs Photoshop's amounts follow best with BP the 3rd percentile of the luminance and
//! WP the 99.5th of the brightest channel, and Blacks at least 1.2 times. A low
//! white point makes Whites +100 stronger (up to 2.7 times), a raised black point Blacks
//! (up to 1.45 times at −40). Whites rows past +100 come from images where `A > 1`.
//! - Not reproduced: past −40 Photoshop's Blacks grows faster on images with a raised black
//! point (on one spanning 0.6–1 its −100 blacks out everything below 0.74, here below about
//! 0.15); its curves there are not rows of the full-range family.
//! - Colour: the clipping directions act on each channel, the compressing ones scale the pixel
//! by the curve's change of its luminance (closest to Photoshop on saturated colours).
use super::Encoding;
use crate::photo_util::par_rows;
/// Grey levels the curves are sampled at: 0, 1/32, …, 1 (sRGB-encoded).
pub(crate) const STEPS: usize = 33;
/// The first row's internal amount; rows are [`ROW_STEP`] apart.
const WHITES_FROM: f32 = -100.0;
const BLACKS_FROM: f32 = -100.0;
const ROW_STEP: f32 = 10.0;
/// The image's points are measured on cells of a copy at most this many pixels across.
pub(crate) const POINTS_SIDE: usize = 256;
/// The black point's quantile of the cells' luminance, the white point's of their brightest
/// channel.
pub(crate) const POINT_QUANTILES: [f32; 2] = [0.03, 0.995];
/// Internal amounts the sliders reach: Whites, then Blacks.
const WHITES_RANGE: [f32; 2] = [-100.0, 270.0];
const BLACKS_RANGE: [f32; 2] = [-100.0, 100.0];
/// Whites and Blacks' tables and how an image's points choose from them, for another
/// implementation (the GPU preview measures the points after Shadows and Highlights itself).
#[derive(Clone, Copy, Debug)]
pub struct Model {
/// Whites curves over grey levels 0, 1/32, …, 1, at internal amounts `whites_from`,
/// `whites_from + row_step`, ….
pub whites: &'static [[f32; STEPS]],
pub whites_from: f32,
/// Blacks curves, likewise.
pub blacks: &'static [[f32; STEPS]],
pub blacks_from: f32,
pub row_step: f32,
/// Black points and white points of the adaptation tables' rows and columns.
pub black_points: &'static [f32],
pub white_points: &'static [f32],
/// How much the clipping directions adapt (Whites up, Blacks down), by black and white point.
pub whites_adapt: &'static [[f32; 8]; 9],
pub blacks_adapt: &'static [[f32; 8]; 9],
/// The least Blacks adaptation on photographs.
pub photo_blacks: f32,
/// Internal amounts the Whites and Blacks sliders reach.
pub whites_range: [f32; 2],
pub blacks_range: [f32; 2],
/// See [`POINTS_SIDE`] and [`POINT_QUANTILES`].
pub points_side: usize,
pub point_quantiles: [f32; 2],
}
/// The tables [`amounts`], [`whites_row`] and [`blacks_row`] read.
pub(crate) fn model() -> Model {
Model {
whites: &WHITES,
whites_from: WHITES_FROM,
blacks: &BLACKS,
blacks_from: BLACKS_FROM,
row_step: ROW_STEP,
black_points: &BPS,
white_points: &WPS,
whites_adapt: &AW,
blacks_adapt: &AB,
photo_blacks: PHOTO_BLACKS,
whites_range: WHITES_RANGE,
blacks_range: BLACKS_RANGE,
points_side: POINTS_SIDE,
point_quantiles: POINT_QUANTILES,
}
}
// Measured levels; some happen to lie near π/8 and π/4.
/// Whites curves at internal amounts -100, -90, …, 270 (rows) over grey levels 0, 1/32, …, 1.
#[allow(clippy::approx_constant)]
static WHITES: [[f32; 33]; 38] = [
[
0.0000, 0.0298, 0.0621, 0.0926, 0.1226, 0.1523, 0.1817, 0.2107, 0.2391, 0.2671, 0.2946, 0.3215, 0.3480, 0.3738, 0.3995, 0.4256, 0.4517, 0.4774, 0.5028,
0.5278, 0.5524, 0.5768, 0.6008, 0.6245, 0.6482, 0.6717, 0.6957, 0.7207, 0.7483, 0.7814, 0.8263, 0.8949, 0.9999,
],
[
0.0000, 0.0298, 0.0621, 0.0926, 0.1226, 0.1523, 0.1817, 0.2107, 0.2392, 0.2672, 0.2947, 0.3217, 0.3482, 0.3742, 0.4000, 0.4263, 0.4526, 0.4785, 0.5042,
0.5296, 0.5548, 0.5797, 0.6044, 0.6291, 0.6539, 0.6789, 0.7046, 0.7317, 0.7617, 0.7969, 0.8425, 0.9074, 0.9999,
],
[
0.0000, 0.0298, 0.0621, 0.0926, 0.1226, 0.1524, 0.1818, 0.2108, 0.2393, 0.2673, 0.2950, 0.3221, 0.3487, 0.3748, 0.4008, 0.4274, 0.4540, 0.4803, 0.5064,
0.5323, 0.5580, 0.5837, 0.6093, 0.6350, 0.6610, 0.6875, 0.7149, 0.7438, 0.7756, 0.8122, 0.8576, 0.9184, 0.9999,
],
[
0.0000, 0.0298, 0.0621, 0.0926, 0.1226, 0.1524, 0.1818, 0.2109, 0.2395, 0.2677, 0.2954, 0.3227, 0.3495, 0.3759, 0.4022, 0.4291, 0.4561, 0.4828, 0.5094,
0.5360, 0.5624, 0.5888, 0.6154, 0.6423, 0.6695, 0.6973, 0.7261, 0.7566, 0.7897, 0.8271, 0.8716, 0.9280, 0.9999,
],
[
0.0000, 0.0298, 0.0621, 0.0926, 0.1226, 0.1525, 0.1820, 0.2111, 0.2398, 0.2682, 0.2961, 0.3237, 0.3508, 0.3775, 0.4042, 0.4317, 0.4591, 0.4864, 0.5136,
0.5408, 0.5680, 0.5953, 0.6229, 0.6508, 0.6791, 0.7082, 0.7382, 0.7698, 0.8037, 0.8412, 0.8843, 0.9365, 0.9999,
],
[
0.0000, 0.0298, 0.0621, 0.0927, 0.1227, 0.1527, 0.1822, 0.2116, 0.2404, 0.2690, 0.2972, 0.3251, 0.3527, 0.3799, 0.4071, 0.4351, 0.4630, 0.4910, 0.5189,
0.5469, 0.5749, 0.6031, 0.6316, 0.6605, 0.6899, 0.7199, 0.7509, 0.7832, 0.8174, 0.8544, 0.8958, 0.9439, 0.9999,
],
[
0.0000, 0.0298, 0.0621, 0.0927, 0.1229, 0.1529, 0.1827, 0.2122, 0.2414, 0.2702, 0.2989, 0.3272, 0.3553, 0.3831, 0.4110, 0.4396, 0.4682, 0.4968, 0.5254,
0.5542, 0.5830, 0.6121, 0.6414, 0.6712, 0.7014, 0.7322, 0.7637, 0.7964, 0.8305, 0.8668, 0.9062, 0.9503, 0.9999,
],
[
0.0000, 0.0298, 0.0622, 0.0928, 0.1231, 0.1534, 0.1834, 0.2132, 0.2427, 0.2720, 0.3011, 0.3300, 0.3587, 0.3872, 0.4160, 0.4452, 0.4745, 0.5038, 0.5332,
0.5627, 0.5923, 0.6221, 0.6522, 0.6826, 0.7134, 0.7447, 0.7765, 0.8092, 0.8429, 0.8781, 0.9155, 0.9559, 1.0000,
],
[
0.0000, 0.0298, 0.0623, 0.0930, 0.1236, 0.1541, 0.1844, 0.2145, 0.2445, 0.2744, 0.3041, 0.3337, 0.3632, 0.3925, 0.4221, 0.4520, 0.4820, 0.5120, 0.5421,
0.5723, 0.6026, 0.6330, 0.6636, 0.6946, 0.7257, 0.7572, 0.7890, 0.8214, 0.8545, 0.8885, 0.9237, 0.9608, 1.0000,
],
[
0.0000, 0.0298, 0.0624, 0.0934, 0.1242, 0.1551, 0.1858, 0.2164, 0.2470, 0.2775, 0.3080, 0.3383, 0.3687, 0.3989, 0.4293, 0.4600, 0.4906, 0.5213, 0.5520,
0.5827, 0.6136, 0.6445, 0.6755, 0.7067, 0.7380, 0.7694, 0.8011, 0.8330, 0.8652, 0.8978, 0.9310, 0.9651, 1.0000,
],
[
0.0000, 0.0312, 0.0625, 0.0938, 0.1250, 0.1562, 0.1875, 0.2188, 0.2500, 0.2812, 0.3125, 0.3438, 0.3750, 0.4062, 0.4375, 0.4688, 0.5000, 0.5312, 0.5625,
0.5938, 0.6250, 0.6562, 0.6875, 0.7188, 0.7500, 0.7812, 0.8125, 0.8438, 0.8750, 0.9062, 0.9375, 0.9688, 1.0000,
],
[
0.0000, 0.0299, 0.0626, 0.0940, 0.1253, 0.1567, 0.1881, 0.2195, 0.2510, 0.2825, 0.3140, 0.3456, 0.3772, 0.4089, 0.4405, 0.4720, 0.5036, 0.5351, 0.5667,
0.5983, 0.6298, 0.6613, 0.6929, 0.7244, 0.7559, 0.7874, 0.8189, 0.8503, 0.8816, 0.9128, 0.9438, 0.9742, 1.0000,
],
[
0.0000, 0.0299, 0.0627, 0.0941, 0.1257, 0.1573, 0.1890, 0.2208, 0.2526, 0.2846, 0.3167, 0.3488, 0.3811, 0.4134, 0.4456, 0.4777, 0.5098, 0.5419, 0.5741,
0.6062, 0.6383, 0.6704, 0.7025, 0.7345, 0.7664, 0.7983, 0.8301, 0.8617, 0.8931, 0.9241, 0.9543, 0.9829, 1.0000,
],
[
0.0000, 0.0299, 0.0628, 0.0944, 0.1262, 0.1582, 0.1903, 0.2225, 0.2550, 0.2876, 0.3204, 0.3534, 0.3867, 0.4200, 0.4529, 0.4858, 0.5186, 0.5516, 0.5845,
0.6174, 0.6502, 0.6830, 0.7157, 0.7482, 0.7807, 0.8131, 0.8451, 0.8769, 0.9082, 0.9385, 0.9673, 0.9928, 1.0000,
],
[
0.0000, 0.0299, 0.0629, 0.0948, 0.1269, 0.1594, 0.1920, 0.2249, 0.2582, 0.2917, 0.3256, 0.3597, 0.3942, 0.4289, 0.4628, 0.4966, 0.5305, 0.5644, 0.5983,
0.6321, 0.6658, 0.6994, 0.7327, 0.7660, 0.7989, 0.8316, 0.8639, 0.8956, 0.9263, 0.9553, 0.9815, 1.0000, 1.0000,
],
[
0.0000, 0.0299, 0.0631, 0.0953, 0.1280, 0.1610, 0.1944, 0.2282, 0.2625, 0.2973, 0.3325, 0.3683, 0.4045, 0.4407, 0.4758, 0.5109, 0.5460, 0.5811, 0.6161,
0.6510, 0.6857, 0.7201, 0.7541, 0.7879, 0.8213, 0.8543, 0.8864, 0.9175, 0.9468, 0.9733, 0.9950, 1.0000, 1.0000,
],
[
0.0000, 0.0299, 0.0633, 0.0961, 0.1293, 0.1632, 0.1976, 0.2327, 0.2684, 0.3048, 0.3419, 0.3798, 0.4183, 0.4562, 0.4928, 0.5294, 0.5660, 0.6024, 0.6387,
0.6748, 0.7104, 0.7456, 0.7803, 0.8145, 0.8480, 0.8807, 0.9121, 0.9417, 0.9684, 0.9907, 1.0000, 1.0000, 1.0000,
],
[
0.0000, 0.0300, 0.0637, 0.0971, 0.1313, 0.1663, 0.2020, 0.2387, 0.2763, 0.3149, 0.3546, 0.3952, 0.4365, 0.4763, 0.5149, 0.5532, 0.5914, 0.6294, 0.6670,
0.7041, 0.7406, 0.7763, 0.8113, 0.8456, 0.8788, 0.9104, 0.9401, 0.9667, 0.9888, 1.0000, 1.0000, 1.0000, 1.0000,
],
[
0.0000, 0.0300, 0.0641, 0.0984, 0.1338, 0.1703, 0.2079, 0.2468, 0.2870, 0.3286, 0.3717, 0.4161, 0.4602, 0.5024, 0.5430, 0.5833, 0.6232, 0.6627, 0.7015,
0.7394, 0.7764, 0.8123, 0.8472, 0.8808, 0.9126, 0.9420, 0.9681, 0.9896, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
],
[
0.0000, 0.0302, 0.0647, 0.1003, 0.1374, 0.1760, 0.2160, 0.2579, 0.3016, 0.3472, 0.3949, 0.4436, 0.4908, 0.5355, 0.5784, 0.6207, 0.6622, 0.7029, 0.7424,
0.7806, 0.8176, 0.8530, 0.8868, 0.9185, 0.9474, 0.9726, 0.9926, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
],
[
0.0000, 0.0304, 0.0656, 0.1029, 0.1423, 0.1837, 0.2271, 0.2731, 0.3215, 0.3726, 0.4262, 0.4791, 0.5294, 0.5769, 0.6220, 0.6660, 0.7086, 0.7498, 0.7893,
0.8272, 0.8631, 0.8969, 0.9281, 0.9560, 0.9795, 0.9967, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
],
[
0.0000, 0.0305, 0.0679, 0.1094, 0.1509, 0.1968, 0.2459, 0.2956, 0.3510, 0.4094, 0.4680, 0.5248, 0.5781, 0.6278, 0.6742, 0.7195, 0.7624, 0.8031, 0.8417,
0.8779, 0.9113, 0.9414, 0.9675, 0.9886, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
],
[
0.0000, 0.0306, 0.0702, 0.1160, 0.1623, 0.2144, 0.2709, 0.3243, 0.3885, 0.4556, 0.5199, 0.5807, 0.6369, 0.6884, 0.7355, 0.7799, 0.8217, 0.8606, 0.8964,
0.9288, 0.9570, 0.9803, 0.9958, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
],
[
0.0000, 0.0308, 0.0725, 0.1225, 0.1737, 0.2320, 0.2960, 0.3641, 0.4393, 0.5133, 0.5825, 0.6460, 0.7032, 0.7544, 0.8003, 0.8426, 0.8817, 0.9168, 0.9475,
0.9733, 0.9924, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
],
[
0.0000, 0.0322, 0.0751, 0.1303, 0.1918, 0.2594, 0.3348, 0.4189, 0.5044, 0.5841, 0.6565, 0.7208, 0.7771, 0.8262, 0.8692, 0.9074, 0.9408, 0.9686, 0.9900,
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
],
[
0.0000, 0.0331, 0.0818, 0.1482, 0.2171, 0.2977, 0.3892, 0.4865, 0.5779, 0.6602, 0.7322, 0.7943, 0.8470, 0.8915, 0.9286, 0.9600, 0.9844, 0.9996, 1.0000,
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
],
[
0.0000, 0.0340, 0.0884, 0.1661, 0.2544, 0.3540, 0.4658, 0.5729, 0.6681, 0.7496, 0.8183, 0.8748, 0.9208, 0.9568, 0.9832, 1.0000, 1.0000, 1.0000, 1.0000,
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
],
[
0.0000, 0.3356, 0.5799, 0.6166, 0.6166, 0.6166, 0.6166, 0.6624, 0.7556, 0.8321, 0.8935, 0.9411, 0.9755, 0.9970, 0.9998, 1.0000, 1.0000, 1.0000, 1.0000,
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
],
[
0.0000, 0.5007, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
],
[
0.0000, 0.1655, 0.1655, 0.2972, 0.4728, 0.6327, 0.7616, 0.8598, 0.9317, 0.9790, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
],
[
0.0000, 0.0457, 0.1830, 0.3836, 0.5790, 0.7379, 0.8549, 0.9360, 0.9869, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
],
[
0.0000, 0.0520, 0.2329, 0.4864, 0.6989, 0.8449, 0.9403, 0.9884, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
],
[
0.0000, 0.0773, 0.3027, 0.6040, 0.8058, 0.9302, 0.9930, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
],
[
0.0000, 0.1454, 0.4738, 0.7615, 0.9074, 0.9908, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
],
[
0.0000, 0.0964, 0.5416, 0.8589, 0.9897, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
],
[
0.1538, 0.1538, 0.7080, 0.9596, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
],
[
0.8439, 0.8439, 0.8439, 0.9993, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
],
[
0.9228, 0.9228, 0.9228, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
],
];
/// Blacks curves at internal amounts -100, …, 100 in steps of 10.
#[allow(clippy::approx_constant)]
static BLACKS: [[f32; 33]; 21] = [
[
0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0290, 0.0572, 0.0879, 0.1222, 0.1580, 0.1935, 0.2287, 0.2636, 0.2988, 0.3355, 0.3741, 0.4151, 0.4571,
0.4990, 0.5406, 0.5818, 0.6226, 0.6631, 0.7031, 0.7424, 0.7811, 0.8192, 0.8568, 0.8937, 0.9300, 0.9655, 1.0000,
],
[
0.0000, 0.0000, 0.0000, 0.0000, 0.0015, 0.0363, 0.0640, 0.0956, 0.1300, 0.1651, 0.2000, 0.2345, 0.2686, 0.3026, 0.3369, 0.3727, 0.4105, 0.4495, 0.4885,
0.5272, 0.5657, 0.6039, 0.6419, 0.6796, 0.7169, 0.7538, 0.7903, 0.8264, 0.8621, 0.8974, 0.9322, 0.9664, 1.0000,
],
[
0.0000, 0.0000, 0.0000, 0.0000, 0.0346, 0.0625, 0.0934, 0.1271, 0.1616, 0.1959, 0.2298, 0.2635, 0.2969, 0.3301, 0.3638, 0.3990, 0.4357, 0.4727, 0.5094,
0.5460, 0.5824, 0.6187, 0.6547, 0.6906, 0.7262, 0.7615, 0.7965, 0.8313, 0.8657, 0.8998, 0.9336, 0.9671, 1.0000,
],
[
0.0000, 0.0000, 0.0000, 0.0235, 0.0554, 0.0850, 0.1175, 0.1514, 0.1852, 0.2187, 0.2519, 0.2849, 0.3178, 0.3505, 0.3837, 0.4183, 0.4537, 0.4891, 0.5243,
0.5594, 0.5944, 0.6292, 0.6639, 0.6985, 0.7329, 0.7671, 0.8010, 0.8347, 0.8683, 0.9016, 0.9347, 0.9676, 1.0000,
],
[
0.0000, 0.0000, 0.0020, 0.0438, 0.0724, 0.1035, 0.1365, 0.1699, 0.2030, 0.2359, 0.2686, 0.3011, 0.3336, 0.3659, 0.3986, 0.4327, 0.4669, 0.5011, 0.5352,
0.5692, 0.6031, 0.6369, 0.6706, 0.7043, 0.7378, 0.7711, 0.8043, 0.8373, 0.8702, 0.9029, 0.9355, 0.9679, 1.0000,
],
[
0.0000, 0.0000, 0.0230, 0.0567, 0.0865, 0.1182, 0.1510, 0.1839, 0.2164, 0.2489, 0.2812, 0.3133, 0.3455, 0.3775, 0.4100, 0.4433, 0.4767, 0.5100, 0.5433,
0.5765, 0.6096, 0.6426, 0.6756, 0.7086, 0.7414, 0.7741, 0.8067, 0.8392, 0.8716, 0.9039, 0.9361, 0.9682, 1.0000,
],
[
0.0000, 0.0000, 0.0368, 0.0670, 0.0976, 0.1294, 0.1619, 0.1943, 0.2265, 0.2586, 0.2906, 0.3225, 0.3544, 0.3862, 0.4184, 0.4512, 0.4839, 0.5166, 0.5492,
0.5818, 0.6144, 0.6469, 0.6793, 0.7117, 0.7441, 0.7763, 0.8085, 0.8406, 0.8727, 0.9046, 0.9365, 0.9683, 1.0000,
],
[
0.0000, 0.0000, 0.0444, 0.0749, 0.1058, 0.1377, 0.1699, 0.2020, 0.2339, 0.2657, 0.2975, 0.3292, 0.3609, 0.3926, 0.4245, 0.4568, 0.4891, 0.5213, 0.5535,
0.5857, 0.6179, 0.6499, 0.6820, 0.7140, 0.7460, 0.7779, 0.8098, 0.8416, 0.8734, 0.9052, 0.9368, 0.9685, 1.0000,
],
[
0.0000, 0.0086, 0.0511, 0.0817, 0.1128, 0.1445, 0.1763, 0.2080, 0.2397, 0.2713, 0.3029, 0.3344, 0.3660, 0.3975, 0.4292, 0.4611, 0.4930, 0.5249, 0.5567,
0.5886, 0.6204, 0.6522, 0.6839, 0.7157, 0.7475, 0.7791, 0.8108, 0.8424, 0.8740, 0.9056, 0.9371, 0.9686, 1.0000,
],
[
0.0000, 0.0198, 0.0564, 0.0874, 0.1186, 0.1501, 0.1817, 0.2133, 0.2447, 0.2762, 0.3076, 0.3390, 0.3705, 0.4018, 0.4333, 0.4649, 0.4965, 0.5281, 0.5597,
0.5912, 0.6227, 0.6543, 0.6858, 0.7173, 0.7488, 0.7802, 0.8117, 0.8431, 0.8745, 0.9059, 0.9373, 0.9686, 1.0000,
],
[
0.0000, 0.0312, 0.0625, 0.0938, 0.1250, 0.1562, 0.1875, 0.2188, 0.2500, 0.2812, 0.3125, 0.3438, 0.3750, 0.4062, 0.4375, 0.4688, 0.5000, 0.5312, 0.5625,
0.5938, 0.6250, 0.6562, 0.6875, 0.7188, 0.7500, 0.7812, 0.8125, 0.8438, 0.8750, 0.9062, 0.9375, 0.9688, 1.0000,
],
[
0.0000, 0.0313, 0.0650, 0.0979, 0.1303, 0.1624, 0.1942, 0.2260, 0.2576, 0.2891, 0.3206, 0.3520, 0.3833, 0.4146, 0.4455, 0.4763, 0.5070, 0.5378, 0.5684,
0.5991, 0.6298, 0.6605, 0.6912, 0.7219, 0.7526, 0.7833, 0.8141, 0.8450, 0.8758, 0.9067, 0.9377, 0.9688, 1.0000,
],
[
0.0000, 0.0326, 0.0677, 0.1022, 0.1357, 0.1686, 0.2010, 0.2332, 0.2652, 0.2969, 0.3286, 0.3601, 0.3915, 0.4227, 0.4532, 0.4835, 0.5138, 0.5440, 0.5741,
0.6042, 0.6344, 0.6645, 0.6946, 0.7248, 0.7550, 0.7853, 0.8156, 0.8461, 0.8766, 0.9072, 0.9380, 0.9689, 1.0000,
],
[
0.0000, 0.0341, 0.0706, 0.1066, 0.1413, 0.1749, 0.2079, 0.2405, 0.2728, 0.3048, 0.3366, 0.3682, 0.3996, 0.4307, 0.4608, 0.4906, 0.5203, 0.5500, 0.5796,
0.6092, 0.6387, 0.6683, 0.6979, 0.7276, 0.7573, 0.7871, 0.8170, 0.8472, 0.8773, 0.9077, 0.9382, 0.9690, 1.0000,
],
[
0.0000, 0.0354, 0.0736, 0.1113, 0.1472, 0.1814, 0.2149, 0.2479, 0.2805, 0.3127, 0.3446, 0.3763, 0.4077, 0.4385, 0.4681, 0.4974, 0.5267, 0.5558, 0.5849,
0.6139, 0.6429, 0.6720, 0.7011, 0.7303, 0.7595, 0.7889, 0.8184, 0.8481, 0.8780, 0.9081, 0.9384, 0.9690, 1.0000,
],
[
0.0000, 0.0368, 0.0768, 0.1162, 0.1531, 0.1881, 0.2221, 0.2554, 0.2882, 0.3206, 0.3527, 0.3843, 0.4158, 0.4461, 0.4753, 0.5041, 0.5328, 0.5615, 0.5900,
0.6185, 0.6470, 0.6755, 0.7041, 0.7328, 0.7616, 0.7906, 0.8197, 0.8491, 0.8787, 0.9085, 0.9386, 0.9691, 1.0000,
],
[
0.0000, 0.0381, 0.0802, 0.1214, 0.1593, 0.1949, 0.2293, 0.2630, 0.2961, 0.3286, 0.3607, 0.3924, 0.4236, 0.4536, 0.4823, 0.5106, 0.5388, 0.5669, 0.5949,
0.6229, 0.6509, 0.6789, 0.7070, 0.7352, 0.7636, 0.7922, 0.8209, 0.8500, 0.8793, 0.9089, 0.9388, 0.9691, 1.0000,
],
[
0.0000, 0.0394, 0.0837, 0.1267, 0.1656, 0.2018, 0.2367, 0.2707, 0.3039, 0.3365, 0.3686, 0.4003, 0.4314, 0.4608, 0.4890, 0.5168, 0.5445, 0.5721, 0.5996,
0.6271, 0.6546, 0.6822, 0.7098, 0.7375, 0.7655, 0.7937, 0.8221, 0.8509, 0.8799, 0.9092, 0.9390, 0.9692, 1.0000,
],
[
0.0000, 0.0407, 0.0875, 0.1322, 0.1720, 0.2088, 0.2441, 0.2784, 0.3118, 0.3444, 0.3765, 0.4082, 0.4389, 0.4679, 0.4955, 0.5229, 0.5501, 0.5771, 0.6042,
0.6312, 0.6582, 0.6853, 0.7124, 0.7398, 0.7673, 0.7952, 0.8233, 0.8517, 0.8804, 0.9096, 0.9391, 0.9692, 1.0000,
],
[
0.0000, 0.0421, 0.0915, 0.1379, 0.1786, 0.2160, 0.2516, 0.2861, 0.3196, 0.3523, 0.3844, 0.4159, 0.4462, 0.4747, 0.5019, 0.5287, 0.5554, 0.5820, 0.6085,
0.6351, 0.6616, 0.6882, 0.7149, 0.7419, 0.7690, 0.7965, 0.8243, 0.8524, 0.8810, 0.9099, 0.9393, 0.9693, 1.0000,
],
[
0.0000, 0.0436, 0.0957, 0.1438, 0.1853, 0.2232, 0.2592, 0.2938, 0.3274, 0.3601, 0.3922, 0.4235, 0.4533, 0.4813, 0.5080, 0.5343, 0.5605, 0.5866, 0.6127,
0.6387, 0.6648, 0.6910, 0.7173, 0.7439, 0.7707, 0.7978, 0.8253, 0.8532, 0.8815, 0.9102, 0.9394, 0.9693, 1.0000,
],
];
const BPS: [f32; 9] = [0.0000, 0.0200, 0.0500, 0.1000, 0.2000, 0.3000, 0.4500, 0.6000, 0.8000];
const WPS: [f32; 8] = [0.1000, 0.2000, 0.3000, 0.4500, 0.6000, 0.8000, 0.9000, 1.0000];
static AW: [[f32; 8]; 9] = [
[1.7750, 2.3875, 2.4000, 2.1625, 1.9438, 1.6125, 1.3875, 1.0000],
[1.8125, 2.5250, 2.3937, 2.1688, 1.9375, 1.6062, 1.3938, 0.9875],
[2.7000, 2.4688, 2.2750, 2.0688, 1.8875, 1.6000, 1.3875, 0.9938],
[2.3250, 2.3250, 2.1875, 1.9750, 1.7937, 1.5188, 1.3250, 1.0437],
[2.0187, 2.0187, 2.0187, 1.8625, 1.7063, 1.4062, 1.2250, 0.9250],
[1.7500, 1.7500, 1.7500, 1.7500, 1.6438, 1.3562, 1.1687, 0.8625],
[1.4937, 1.4937, 1.4937, 1.4937, 1.4937, 1.2875, 1.1000, 0.7875],
[1.1687, 1.1687, 1.1687, 1.1687, 1.1687, 1.1687, 1.0375, 0.7562],
[0.8250, 0.8250, 0.8250, 0.8250, 0.8250, 0.8250, 0.8250, 0.7562],
];
static AB: [[f32; 8]; 9] = [
[0.9938, 0.9812, 1.0000, 1.0125, 0.9563, 0.9688, 1.0437, 1.0000],
[1.0437, 1.0250, 1.0125, 1.0000, 1.0000, 1.0375, 1.0000, 0.9938],
[1.2312, 1.2063, 1.1875, 1.1625, 1.1438, 1.1438, 1.1375, 1.1250],
[1.2500, 1.2500, 1.2312, 1.2125, 1.2125, 1.2375, 1.2375, 1.2375],
[1.1750, 1.1750, 1.1750, 1.1750, 1.2063, 1.2688, 1.3125, 1.3375],
[1.1812, 1.1812, 1.1812, 1.1812, 1.2125, 1.2812, 1.3313, 1.4125],
[1.2375, 1.2375, 1.2375, 1.2375, 1.2375, 1.3062, 1.3562, 1.4375],
[1.3250, 1.3250, 1.3250, 1.3250, 1.3250, 1.3250, 1.3687, 1.4500],
[1.3938, 1.3938, 1.3938, 1.3938, 1.3938, 1.3938, 1.3938, 1.4312],
];
/// A curve row at a fractional internal amount `x`, at grey level `v` (both interpolated).
fn curve(rows: &[[f32; STEPS]], from: f32, x: f32, v: f32) -> f32 {
if v >= 1.0 {
return 1.0;
}
let r = ((x - from) / ROW_STEP).clamp(0.0, (rows.len() - 1) as f32);
let i = (r as usize).min(rows.len() - 2);
let t = r - i as f32;
let at = |row: &[f32; STEPS]| {
let p = v.max(0.0) * (STEPS - 1) as f32;
let j = (p as usize).min(STEPS - 2);
let s = p - j as f32;
row[j] + (row[j + 1] - row[j]) * s
};
at(&rows[i]) * (1.0 - t) + at(&rows[i + 1]) * t
}
/// The curve at a fractional internal amount `x` as one row: `curve(rows, from, x, v)` is this
/// row interpolated at `v`, because both interpolations are linear.
fn row_at(rows: &[[f32; STEPS]], from: f32, x: f32) -> [f32; STEPS] {
let r = ((x - from) / ROW_STEP).clamp(0.0, (rows.len() - 1) as f32);
let i = (r as usize).min(rows.len() - 2);
let t = r - i as f32;
std::array::from_fn(|j| rows[i][j] * (1.0 - t) + rows[i + 1][j] * t)
}
/// The Whites curve at internal amount `x` as a row over grey levels 0, 1/32, …, 1.
pub(crate) fn whites_row(x: f32) -> [f32; STEPS] {
row_at(&WHITES, WHITES_FROM, x)
}
/// The Blacks curve at internal amount `x` as a row over grey levels 0, 1/32, …, 1.
pub(crate) fn blacks_row(x: f32) -> [f32; STEPS] {
row_at(&BLACKS, BLACKS_FROM, x)
}
/// Whites at internal amount `x` (−100 … 270) of grey level `v`.
pub(crate) fn whites(v: f32, x: f32) -> f32 {
curve(&WHITES, WHITES_FROM, x, v)
}
/// Blacks at internal amount `x` (−100 … 100) of grey level `v`.
pub(crate) fn blacks(v: f32, x: f32) -> f32 {
curve(&BLACKS, BLACKS_FROM, x, v)
}
/// The least Blacks adaptation on photographs.
const PHOTO_BLACKS: f32 = 1.2;
/// Bilinear lookup of an adaptation table at black point `bp` and white point `wp`.
fn adapt(table: &[[f32; 8]; 9], bp: f32, wp: f32) -> f32 {
let idx = |grid: &[f32], v: f32| {
let v = v.clamp(grid[0], grid[grid.len() - 1]);
let i = grid.windows(2).position(|w| v <= w[1]).unwrap_or(grid.len() - 2);
(i, (v - grid[i]) / (grid[i + 1] - grid[i]))
};
let (i, s) = idx(&BPS, bp);
let (j, t) = idx(&WPS, wp);
let row = |i: usize| table[i][j] * (1.0 - t) + table[i][j + 1] * t;
row(i) * (1.0 - s) + row(i + 1) * s
}
/// The internal amounts of the Whites and Blacks sliders (−100 … 100) for an image whose 1st
/// and 99th luminance percentiles are the grey levels `bp` and `wp` (sRGB-encoded).
pub(crate) fn amounts(whites: f32, blacks: f32, bp: f32, wp: f32) -> (f32, f32) {
let w = if whites > 0.0 { whites * adapt(&AW, bp, wp) } else { whites };
// On photographs Photoshop's Blacks is about 1.2 times the block images' amount even where
// their black point is 0 (ten public-domain photos: 1.08–1.36).
let b = if blacks < 0.0 { blacks * adapt(&AB, bp, wp).max(PHOTO_BLACKS) } else { blacks };
(w.clamp(WHITES_RANGE[0], WHITES_RANGE[1]), b.clamp(BLACKS_RANGE[0], BLACKS_RANGE[1]))
}
/// Applies Whites and Blacks (internal amounts `w`, `b`) to straight RGBA pixels (`width` per
/// row) encoded with `enc`. Values above 1 (float documents) keep their excess.
pub(crate) fn apply(px: &mut [[f32; 4]], width: usize, w: f32, b: f32, enc: Encoding) {
if w == 0.0 && b == 0.0 {
return;
}
// A grey level's new level, both sRGB-encoded.
let grey = |v: f32| {
let v = if w != 0.0 { whites(v, w) } else { v };
if b != 0.0 { blacks(v, b) } else { v }
};
let per_channel = w > 0.0 || b < 0.0;
par_rows(px, width, 1, |_, row| {
for q in row.iter_mut() {
let lin = [0, 1, 2].map(|c| enc.decode(q[c]));
if per_channel {
for c in 0..3 {
let over = (lin[c] - 1.0).max(0.0);
q[c] = enc.encode(super::srgb_to_linear(grey(super::linear_to_srgb(lin[c].min(1.0)))) + over);
}
} else {
let y = super::luma_linear(lin).max(0.0);
if y <= 1e-7 {
continue;
}
let y2 = super::srgb_to_linear(grey(super::linear_to_srgb(y.min(1.0)))) + (y - 1.0).max(0.0);
let k = y2 / y;
for c in 0..3 {
q[c] = enc.encode(lin[c] * k);
}
}
}
});
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn full_range_rows_match_photoshop() {
// Photoshop 25.4 on a 64-level block image spanning black to white (sRGB levels).
assert!((whites(97.1 / 255.0, 100.0) * 255.0 - 137.4).abs() < 0.6);
assert!((whites(194.3 / 255.0, -100.0) * 255.0 - 167.6).abs() < 0.6);
assert!((blacks(97.1 / 255.0, -100.0) * 255.0 - 60.0).abs() < 0.6);
assert!((blacks(48.6 / 255.0, 100.0) * 255.0 - 67.0).abs() < 0.6);
// The compressing directions keep black and white.
assert_eq!(whites(1.0, -100.0), 1.0);
assert_eq!(blacks(0.0, 100.0), 0.0);
}
#[test]
fn the_clipping_directions_adapt_to_the_image() {
// A dark, low-contrast image needs more: Whites +50 acts like +94.5 on [0.05, 0.6].
let (w, _) = amounts(50.0, 0.0, 0.05, 0.6);
assert!((w - 94.5).abs() < 2.0, "{w}");
// A raised black point strengthens Blacks −40 to −58 on [0.6, 1].
let (_, b) = amounts(0.0, -40.0, 0.6, 1.0);
assert!((b + 58.0).abs() < 1.0, "{b}");
// Never below the photographs' 1.2.
assert!((amounts(0.0, -50.0, 0.0, 1.0).1 + 60.0).abs() < 1e-3);
// The compressing directions never adapt.
assert_eq!(amounts(-50.0, 50.0, 0.3, 0.6), (-50.0, 50.0));
}
}
+2
View File
@@ -326,6 +326,7 @@ impl Rng {
}
/// Integer hash → `0..1` (position-keyed noise, independent of tiling).
#[cfg(test)]
pub(crate) fn hash01(x: i64, y: i64, seed: u64) -> f32 {
let mut z = (x as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ (y as u64).wrapping_mul(0xC2B2_AE3D_27D4_EB4F) ^ seed.wrapping_mul(0x1656_67B1_9E37_79F9);
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
@@ -337,6 +338,7 @@ pub(crate) fn hash01(x: i64, y: i64, seed: u64) -> f32 {
pub(crate) use photocraft_color::convert::{linear_to_srgb, srgb_to_linear};
/// Bilinear sample of channel `c` of a `w × h × ch` buffer, clamped to the edges.
#[cfg(test)]
pub(crate) fn bilinear(buf: &[f32], w: usize, h: usize, ch: usize, c: usize, x: f32, y: f32) -> f32 {
let x = x.clamp(0.0, (w - 1) as f32);
let y = y.clamp(0.0, (h - 1) as f32);
+1 -1
View File
@@ -288,7 +288,7 @@ fn holds_image(dir: &Dir, relative: &Path) -> bool {
let Ok(mut file) = dir.open(relative) else { return false };
let Ok(n) = file.read(&mut head) else { return false };
let head = &head[..n];
head.starts_with(b"8BPS") || photocraft_codecs::detect(head).is_some_and(|format| format.caps().write)
photocraft_io::is_psd(head) || photocraft_codecs::detect(head).is_some_and(|format| format.caps().write)
}
fn read_to_observed_length(reader: &mut impl Read, observed_length: u64) -> Result<Vec<u8>, AutomationError> {
+1
View File
@@ -1083,6 +1083,7 @@ fn documents_filesystem_path_params(id: &str, params: &str) -> bool {
| "layer.vectorMask.add"
| "layer.vectorMask.edit"
| "layer.vectorMask.info"
| "layer.vectorMask.currentPath"
| "paint.symmetryFromPath"
| "edit.defineCustomShape"
// `"as":"path"` pastes the clipboard as a vector path (#10694).
+2 -1
View File
@@ -3,6 +3,7 @@
//! Each task uses only MCP tools (`doc_*`, `command_run`) the way an agent would, and checks the
//! outcome through `doc_inspect`, `document.pixel` or the exported files, never engine internals.
use photocraft_engine::actions_cmds::ActionsExt;
use std::io::Write;
use photocraft_automation::{AuthorizedWorkspace, PhotocraftMcp};
@@ -330,7 +331,7 @@ async fn agent_play_refuses_a_recorded_file_open() {
use photocraft_engine::actions_cmds::ActionStep;
headless
.session
.actions
.actions_mut()
.list
.push(photocraft_engine::actions_cmds::Action {
name: "Open".into(),
@@ -13,6 +13,7 @@ mod gpu_tests {
use photocraft_automation::workspace::AuthorizedWorkspace;
use photocraft_automation::{GpuRenderer, Headless};
use photocraft_engine::color_cmds::ColorExt;
fn make_test_doc(w: u32, h: u32, depth: SampleType) -> Document {
let mut doc = Document::with_background("test_doc", Size::new(w, h), ColorMode::Rgb, depth, Color::WHITE);
+3 -2
View File
@@ -1,5 +1,6 @@
//! Real-document regressions for ordered read roots and independent write authority.
use photocraft_engine::actions_cmds::ActionsExt;
use std::path::{Path, PathBuf};
use photocraft_automation::{AuthorizedWorkspace, Headless, files};
@@ -286,8 +287,8 @@ fn multiple_roots_do_not_grant_ambient_commands_or_nested_action_file_access() {
let error = headless.command_run("file.saveACopy", json!({"path": target})).unwrap_err().to_string();
assert!(error.contains("ambient filesystem paths"), "{error}");
// A writable destination still cannot be reached through an ambient engine command.
headless.session.actions.list.push(Action::new("Write work", vec![ActionStep::new("file.saveACopy", json!({"path": target}))])).unwrap();
headless.session.actions.list.push(Action::new("Nested write", vec![ActionStep::new("actions.play", json!({"action": "Write work"}))])).unwrap();
headless.session.actions_mut().list.push(Action::new("Write work", vec![ActionStep::new("file.saveACopy", json!({"path": target}))])).unwrap();
headless.session.actions_mut().list.push(Action::new("Nested write", vec![ActionStep::new("actions.play", json!({"action": "Write work"}))])).unwrap();
let played = headless.command_run("actions.play", json!({"action": "Nested write"})).unwrap();
assert!(played["failed"].to_string().contains("ambient filesystem paths"), "{played}");
assert_eq!(snapshot(&mut headless), before);
@@ -1,6 +1,7 @@
//! A failed renderer-aware save must never replace the previous file, and closing a document
//! must release its renderer caches.
use photocraft_engine::color_cmds::ColorExt;
use std::fs;
use std::sync::{Arc, Mutex};
@@ -1,4 +1,5 @@
//! Stored smart-filter parameters must not grant automation ambient filesystem access.
use photocraft_engine::actions_cmds::ActionsExt;
use std::path::Path;
use std::sync::Arc;
@@ -44,7 +45,7 @@ fn action_playback_cannot_hide_a_smart_filter_path_edit() {
let (mut h, layer) = f.setup(false);
let doc = h.session.active().unwrap().doc.clone();
h.session
.actions
.actions_mut()
.list
.push(Action::new(
"edit filter",
+8
View File
@@ -295,6 +295,14 @@ fn apply_depth_mode(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer, dept
}
}
/// What one straight-alpha sRGB colour becomes under `adj` in an 8-bit RGB document: [`apply_in`] over a 1 x 1 buffer,
/// so a UI preview of a colour runs the code a layer's pixels run.
pub fn adjust_color(adj: &Adjustment, color: [f32; 4]) -> [f32; 4] {
let mut buf = Buffer { rect: photocraft_geom::Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, px: vec![color] };
apply_in(adj, &mut buf, Transfer::Srgb, None, ColorMode::Rgb);
buf.px[0]
}
/// Applies an adjustment in a document of colour `mode`: [`apply_depth`], except that in Lab
/// and CMYK documents the adjustments Photoshop evaluates on the document's own channels do so
/// (see [`lab_channel_adjustment`] and [`cmyk_channel_adjustment`]).
+91
View File
@@ -0,0 +1,91 @@
[package]
name = "photocraft-engine-core"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[features]
# Real-file corpus tests (opt-in; `cargo xtask test-corpus`). Fail when the corpus is missing.
corpus = []
# Exposes the allocation failpoints (`allocation::fail_next_for_test`) to other engine crates' tests; only dev-dependencies turn it on.
failpoints = []
[dependencies]
craft-tracked = { workspace = true }
# `#[derive(PlainData)]` for the session areas held in `Tracked`.
craft-ui-macros = { workspace = true }
photocraft-geom = { workspace = true }
photocraft-color = { workspace = true }
craft-cms = { workspace = true }
# PCTIP codec from craft-libs#1564; isolated pin until the shared revision is adopted workspace-wide.
craft-pcraft-tip = { package = "craft-pcraft-format", git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
photocraft-raster = { workspace = true }
photocraft-doc = { workspace = true }
photocraft-ops = { workspace = true }
photocraft-compose = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
rayon = { workspace = true }
chrono = { workspace = true }
web-time = { workspace = true }
photocraft-paint = { workspace = true }
photocraft-algo = { workspace = true }
photocraft-text = { workspace = true }
photocraft-vector = { workspace = true }
photocraft-io = { workspace = true }
craft-xml = { workspace = true }
craft-psd = { workspace = true }
photocraft-format = { workspace = true }
photocraft-plugins = { workspace = true }
base64 = "0.22"
blake3 = { version = "1.8", default-features = false, features = ["pure"] }
photocraft-codecs = { workspace = true }
photocraft-formats = { workspace = true }
flate2 = { workspace = true }
craft-print = { workspace = true }
# The framework through its facade: the actions model (`craft::automation`), the `.kys` model
# (`craft::keymap`), the palette (`craft::color_ui`), preferences storage and autosave
# (`craft::settings`, `craft::platform`), and `craft::theme::ThemeId`, the theme ids the
# appearance preferences hold.
craft = { workspace = true, features = ["automation", "color-ui", "keymap", "platform", "settings"] }
# Release tags use the same semantic versions as Cargo.
semver = "1"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
tempfile = "3"
# `clock`: the local time that names History Options' snapshot on save (#2966); already in the
# tree through rmcp. The web build has no local clock here and names it "Snapshot N".
chrono = { workspace = true, features = ["clock"] }
# `file_cmds::same_file` on Windows: the volume serial number and file index, so a hard link to a
# file is that file (std's `MetadataExt::file_index` is unstable).
[target.'cfg(windows)'.dependencies]
same-file = "1"
# `file.print` loads Windows.Data.Pdf.dll before calling into it (#5884): the safe binding
# ui-egui and craft-print already use, pinned to the same version.
winsafe = { version = "=0.0.29", default-features = false, features = ["kernel"] }
# Printing on Unix: an IPP client for CUPS (pure Rust); the web build cannot print.
[target.'cfg(all(not(target_arch = "wasm32"), not(target_os = "windows")))'.dependencies]
photocraft-ipp = { workspace = true }
[dev-dependencies]
craft-affinity = { workspace = true, features = ["synth"] }
craft-develop-model = { workspace = true }
photocraft-io = { workspace = true, features = ["testgen"] }
# Synthetic camera raw files for the open tests.
photocraft-raw = { workspace = true, features = ["testgen"] }
photocraft-testkit = { workspace = true }
exr = { version = "1.73", default-features = false }
# WebAssembly text -> binary for plug-in test modules (Apache-2.0 WITH LLVM-exception).
wat = "1.228"
# Synthetic multi-part EXR fixtures for the parts-commands tests.
# Palette PNGs at 1, 2 and 4 bits and with an eXIf chunk for the Color Table index tests
# (the png 0.18 already in the tree).
png = "0.18"
@@ -1,5 +1,5 @@
//! Consolidate document history after commands finish their own atomic transactions.
use super::{EngineError, Result, Session};
use crate::{EngineError, Result, Session};
use photocraft_doc::{DocId, Document};
use photocraft_ops::{History, LayerTarget};
use std::collections::HashSet;
@@ -39,8 +39,13 @@ pub(crate) struct ActionHistory {
before: Vec<BeforeDocument>,
}
/// Active playback and retained dialog continuations keep their chosen history policy.
pub(crate) fn history_policy_in_use(s: &Session) -> bool {
s.recording.playing != 0 || s.action_history.is_some() || s.paused_action_history.iter().any(|lease| lease.strong_count() != 0)
}
/// The outer play owns one lazy scope; nested plays share its document snapshots.
pub(super) fn begin(s: &mut Session, name: &str) {
pub(crate) fn begin(s: &mut Session, name: &str) {
if s.action_history.is_none() && s.prefs().actions.create_single_history_state {
s.action_history = Some(ActionHistory { name: name.into(), external: false, before: Vec::new() });
}
@@ -171,7 +176,7 @@ fn consolidate(s: &mut Session, group: &ActionHistory) {
}
/// Publish all edited documents once the outer play, including its failure prefix, ends.
pub(super) fn finish(s: &mut Session) {
pub(crate) fn finish(s: &mut Session) {
if let Some(group) = s.action_history.take() {
consolidate(s, &group);
}
@@ -191,7 +196,7 @@ pub(crate) fn finish_document_history(s: &mut Session) {
}
/// Finish an ordinary outer playback without closing a scope owned by the surrounding Batch.
pub(super) fn finish_playback(s: &mut Session) {
pub(crate) fn finish_playback(s: &mut Session) {
if s.action_history.as_ref().is_none_or(|group| !group.external) {
finish(s);
}
@@ -272,7 +277,7 @@ impl ActionHistoryContinuation {
/// Rebind a completed nonmodal dialog edit, leaving open-dialog time outside its scope.
/// Only the scope resumed from this continuation may be taken; a parent remains untouched.
pub fn suspend_after_edit(&self, s: &mut Session) -> Result<Self> {
if s.actions.playing != 0 || s.active().map(|st| st.doc.id) != self.active {
if s.recording.playing != 0 || s.active().map(|st| st.doc.id) != self.active {
return Err(EngineError::Other("the dialog's action scope is no longer current".into()));
}
let active = self.documents.iter().find(|doc| Some(doc.id) == self.active);
@@ -321,7 +326,7 @@ impl ActionHistoryContinuation {
/// Publish the completed prefix, then release the active scope while a dialog is open.
pub fn suspend_history(s: &mut Session) -> Option<ActionHistoryContinuation> {
if s.actions.playing != 1 {
if s.recording.playing != 1 {
return None;
}
Some(ActionHistoryContinuation::capture(s))
@@ -329,18 +334,19 @@ pub fn suspend_history(s: &mut Session) -> Option<ActionHistoryContinuation> {
/// End a dialog scope if its command or continuation fails before playback starts.
pub fn finish_pending_history(s: &mut Session) {
if s.actions.playing == 0 {
if s.recording.playing == 0 {
finish_playback(s);
}
}
#[cfg(test)]
mod tests {
use crate::color_cmds::ColorExt;
/// Batch 16 review: a kept clone can't reopen a scope its continuation already resumed and
/// finished, even with the document and history unchanged.
#[test]
fn a_continuation_resumes_once() {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width":4,"height":4})).unwrap();
s.execute("actions.setHistory", json!({"singleState":true})).unwrap();
begin_document_history(&mut s, "Spell");
@@ -359,7 +365,7 @@ mod tests {
/// Keep the policy fixed until every clone of a paused continuation releases its lease, in either history mode.
fn history_policy_stays_fixed_until_all_paused_continuations_are_released() {
for single in [false, true] {
let mut s = Session::new();
let mut s = crate::session();
s.execute("actions.setHistory", json!({"singleState":single})).unwrap();
begin_document_history(&mut s, "Paused");
let continuation = ActionHistoryContinuation::capture(&mut s);
@@ -380,7 +386,7 @@ mod tests {
/// Generic preference set/reset routes must preserve the same paused-policy guard as actions.setHistory.
fn generic_preference_updates_cannot_change_a_paused_history_policy() {
for single in [false, true] {
let mut s = Session::new();
let mut s = crate::session();
s.execute("actions.setHistory", json!({"singleState":single})).unwrap();
begin_document_history(&mut s, "Paused");
let continuation = ActionHistoryContinuation::capture(&mut s);
@@ -391,10 +397,10 @@ mod tests {
json!({"path":"colorSettings.intent","value":"perceptual","values":{"actions.createSingleHistoryState":!single}}),
] {
let before = s.prefs().clone();
let color = s.color.settings.clone();
let color = s.color().settings.clone();
assert!(s.execute("prefs.set", params).is_err());
assert_eq!(s.prefs(), &before);
assert_eq!(s.color.settings, color);
assert_eq!(s.color().settings, color);
}
for params in [json!({"path":"actions.createSingleHistoryState"}), json!({"path":"actions"}), json!({})] {
assert_eq!(s.execute("prefs.reset", params).is_err(), !single);
@@ -413,7 +419,7 @@ mod tests {
fn idle_dialog_rebind_keeps_first_edit_and_clear_boundaries() {
for single in [false, true] {
for clear in [false, true] {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width":4,"height":4})).unwrap();
s.execute("actions.setHistory", json!({"singleState":single})).unwrap();
begin_document_history(&mut s, "Spell");
@@ -428,7 +434,7 @@ mod tests {
s.execute("layer.renameLayer", json!({"name":name})).unwrap();
continuation = continuation.suspend_after_edit(&mut s).unwrap();
assert!(s.action_history.is_none(), "idle time must not own a history scope");
assert_eq!(s.actions.playing, 0);
assert_eq!(s.recording.playing, 0);
}
continuation.resume(&mut s).unwrap();
finish_document_history(&mut s);
@@ -449,7 +455,7 @@ mod tests {
/// A dialog continuation cannot adopt another caller's active grouping scope.
fn idle_dialog_rebind_never_takes_an_unrelated_parent_scope() {
for single in [false, true] {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width":4,"height":4})).unwrap();
s.execute("actions.setHistory", json!({"singleState":single})).unwrap();
begin_document_history(&mut s, "Spell");
@@ -19,10 +19,40 @@
use std::sync::Arc;
use photocraft_doc::{DocId, Document, LayerContent, LayerId};
use serde_json::Value;
use serde_json::{Value, json};
use crate::Session;
/// Action recording and playback state ([`Session::recording`]): what the pipeline reads to
/// journal steps into a recording, and the depth and step counters that bound playback, batches
/// and scripts.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ActionRecording {
/// Journal length when recording started, and the action index being recorded into.
pub target: Option<(usize, usize)>,
/// Painting-tool strokes are recorded only when the user enables them for this session.
pub record_tools: bool,
/// Bumped by each `actions.record`, so a background job knows whether the recording it was
/// started in is still the one running when its result lands.
pub take: u64,
/// Nesting depth of `actions.play`, bounded by the playback stack limit.
pub playing: u8,
/// Active action names, for cycle detection in engine and desktop playback.
pub playback_stack: Vec<String>,
/// Number of steps executed by the current top-level playback tree.
pub playback_steps: u64,
/// Set for a batch nested in a played action or another batch: the playback counter it carries
/// is shared by every input, so a played action inside it does not restart the count.
pub budget_shared: bool,
/// How many batches (`file.automate.batch`, and droplets through it) are running inside one
/// another: each runs its steps in a scratch session that carries this on, plus one.
pub batch_depth: u8,
/// How many scripts (`file.scripts.browse`) are running inside one another.
pub script_depth: u8,
/// Steps run by the current top-level script and everything it calls.
pub script_steps: u64,
}
/// The active document as it was before a command ran, captured by the dispatcher.
#[derive(Clone, Default)]
pub(crate) struct Before {
@@ -56,7 +86,7 @@ pub(crate) fn portable(s: &Session, id: &str, mut params: Value, before: &Before
return serde_json::json!({"offset": offset});
}
let Some(doc) = before.doc.as_deref() else { return params };
if id == "type.create" && s.actions.recording.is_some() && params.get("box").is_none() && doc.size.width > 0 && doc.size.height > 0 {
if id == "type.create" && s.recording.target.is_some() && params.get("box").is_none() && doc.size.width > 0 && doc.size.height > 0 {
let x = params.get("x").and_then(Value::as_f64).unwrap_or(0.0);
let y = params.get("y").and_then(Value::as_f64).unwrap_or(0.0);
let x_percent = x / f64::from(doc.size.width) * 100.0;
@@ -153,7 +183,7 @@ pub(crate) fn fold_keystroke(s: &mut Session, id: &str, params: &Value, previous
}
// A new recording starts at a journal boundary. Its first edit cannot change an entry
// before that boundary, or actions.stop would miss the edit altogether.
if s.actions.recording.is_some_and(|(start, _)| s.journal.len() <= start) {
if s.recording.target.is_some_and(|(start, _)| s.journal.len() <= start) {
return Keystroke::None;
}
let Some((last, lp)) = s.journal.last_mut() else { return Keystroke::None };
@@ -165,5 +195,76 @@ pub(crate) fn fold_keystroke(s: &mut Session, id: &str, params: &Value, previous
Keystroke::Folded
}
/// Replay commands and named action calls, excluding edits to the action definitions and the
/// already-expanded Again wrapper.
pub fn replayable(id: &str) -> bool {
// Again and Again on a Copy journal their concrete steps (`edit.transform`, after
// `layer.duplicate` for the copy) and record those: the wrappers look up the last transform in
// the journal, so they fail where no transform ran yet, e.g. an action played in a new session.
// A Conditional is recorded with its predicate, not the branch it happened to play (or none),
// so playback evaluates the condition again on the current document (#7198, #7238).
matches!(id, "actions.play" | "actions.conditional")
|| (!id.starts_with("actions.")
// Browse executes its steps through Session::execute, so those concrete
// commands are already journaled. Recording the wrapper as well replays
// every script edit twice (#3057).
&& !matches!(id, "edit.transform.again" | "edit.transform.againCopy" | "file.scripts.browse")
&& (shell_view_command(id) || shell_save_command(id) || crate::commands::find(id).is_some_and(|c| c.journal)))
}
/// File › Save, Save As and Save a Copy, and File › Export › Export As, recorded by the desktop
/// shell once the file has a path (#2032, #4373, #7207). The shell replays them; batch and
/// droplets write to their destination folder instead.
pub fn shell_save_command(id: &str) -> bool {
matches!(id, "file.save" | "file.saveAs" | "file.saveACopy" | "file.export.exportAs")
}
/// View-only menu commands recorded by the desktop shell. Headless playback reports
/// them as unsupported instead of silently dropping them; Batch and droplets skip them.
pub fn shell_view_command(id: &str) -> bool {
matches!(id, "view.fitOnScreen" | "view.actualPixels" | "view.zoomIn" | "view.zoomOut")
}
/// The point-based painting tools committed by the canvas; fills and gradients remain commands.
pub(crate) fn tool_stroke(id: &str) -> bool {
matches!(
id,
"paint.stroke"
| "paint.pencil"
| "paint.mixerBrush"
| "paint.colorReplacement"
| "paint.blur"
| "paint.sharpen"
| "paint.smudge"
| "paint.dodge"
| "paint.burn"
| "paint.sponge"
| "paint.cloneStamp"
| "paint.healingBrush"
| "paint.historyBrush"
| "paint.artHistoryBrush"
| "paint.patternStamp"
| "paint.backgroundEraser"
| "paint.spotHealing"
| "paint.remove"
)
}
/// Visibility gestures name a layer for replay, since document-local ids change on another image.
pub(crate) fn recorded_params(s: &Session, id: &str, mut p: Value) -> Value {
if s.recording.target.is_none() || id != "layer.setProps" || p.get("visible").is_none() {
return p;
}
let Some(st) = s.active() else { return p };
let Some(layer) = p.get("layer").and_then(Value::as_u64).map(LayerId).or(st.active_layer).and_then(|id| st.doc.layer(id)) else { return p };
let ordinal = st.doc.walk().into_iter().filter(|(_, _, l)| l.name == layer.name).position(|(_, _, l)| l.id == layer.id).unwrap_or(0);
if let Some(object) = p.as_object_mut() {
object.remove("layer");
object.remove("coalesce");
object.insert("_actionLayer".into(), json!({"name": layer.name, "ordinal": ordinal}));
}
p
}
#[cfg(test)]
mod tests;
@@ -5,7 +5,7 @@ use crate::jobs::Started;
use crate::{EngineError, Session};
fn session() -> Session {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 32, "height": 32, "background": "white"})).unwrap();
s
}
File renamed without changes.
@@ -364,7 +364,7 @@ fn gray_point_fallback_keeps_tightly_spaced_points_round_trip_safe() {
#[test]
fn curves_eyedropper_param_drives_the_command() {
let mut s = crate::Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap();
s.execute("image.adjustments.curves", json!({"eyedropper": {"point": "white", "at": [2, 2]}})).unwrap();
@@ -391,7 +391,7 @@ fn curves_eyedropper_param_drives_the_command() {
/// that samples the image below the layer, so a repeated click keeps the same curve.
#[test]
fn layer_eyedropper_samples_below_the_curves_layer() {
let mut s = crate::Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap();
s.execute("layer.newAdjustmentLayer.curves", json!({})).unwrap();
@@ -420,7 +420,7 @@ fn layer_eyedropper_samples_below_the_curves_layer() {
#[test]
fn eyedropper_on_a_smart_object_records_the_resolved_adjustment() {
for kind in ["curves", "levels"] {
let mut s = crate::Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap();
s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap();
@@ -437,14 +437,14 @@ fn eyedropper_on_a_smart_object_records_the_resolved_adjustment() {
fn levels_eyedroppers_set_white_and_neutral_gray() {
let pixel = |s: &mut crate::Session| -> Vec<f32> { serde_json::from_value(s.execute("document.pixel", json!({"x": 2, "y": 2})).unwrap()).unwrap() };
for depth in [8, 16] {
let mut s = crate::Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth})).unwrap();
s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap();
s.execute("image.adjustments.levels", json!({"eyedropper": {"point": "white", "at": [2, 2]}})).unwrap();
let px = pixel(&mut s);
assert!(px.iter().take(3).all(|v| *v > 0.995), "{depth}-bit: the sample becomes white: {px:?}");
}
let mut s = crate::Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap();
let before = pixel(&mut s);
@@ -489,7 +489,7 @@ fn hue_range_sliders_stay_ordered() {
/// A colourful 16×16 document (`mode`, `depth`) for command tests.
fn colourful(mode: &str, depth: u32) -> crate::Session {
let mut s = crate::Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 16, "height": 16, "mode": mode, "depth": depth})).unwrap();
for (i, c) in ["#c83c28", "#3c8c50", "#2850b4", "#d2b464"].iter().enumerate() {
s.execute("select.rect", json!({"x": (i % 2) * 8, "y": (i / 2) * 8, "width": 8, "height": 8})).unwrap();
@@ -563,7 +563,7 @@ fn destructive_levels_dont_clip_in_32_bit() {
// compose-side `levels_dont_clip_in_32_bit` pins the same curve, #2592).
let params = json!({"inBlack": 15, "inWhite": 230, "gamma": 1.3, "outBlack": 10, "outWhite": 245});
for depth in [8, 16, 32] {
let mut s = crate::Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth, "background": "white"})).unwrap();
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 16})).unwrap();
s.execute("edit.fill", json!({"color": "#000000"})).unwrap();
@@ -649,7 +649,7 @@ fn destructive_levels_match_independent_signed_hdr_endpoints() {
// curve at black and white, not display-clipped values.
let params = json!({"inBlack": 15, "inWhite": 230, "gamma": 1.3, "outBlack": 10, "outWhite": 245});
for (depth, low, high, tolerance) in [(8, 10.0, 245.0, 0.6), (16, 10.0, 245.0, 0.6), (32, -20.308_89, 265.750_3, 0.01)] {
let mut s = crate::Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth, "background": "white"})).unwrap();
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 16})).unwrap();
s.execute("edit.fill", json!({"color": "#000000"})).unwrap();
@@ -2,7 +2,7 @@
use crate::{EngineError, Result};
#[cfg(test)]
#[cfg(any(test, feature = "failpoints"))]
thread_local! {
static FAIL_NEXT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
static FAIL_AFTER: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
@@ -35,7 +35,7 @@ pub(crate) fn read_file_within(path: impl AsRef<std::path::Path>, max: u64) -> s
/// Reserve a vector for a known number of operation results.
pub(crate) fn capacity<T>(len: usize, purpose: &str) -> Result<Vec<T>> {
let bytes = len.checked_mul(std::mem::size_of::<T>()).ok_or_else(|| error(purpose, "requested size overflowed"))?;
#[cfg(test)]
#[cfg(any(test, feature = "failpoints"))]
if failpoint_hits() {
return Err(error(purpose, "not enough memory"));
}
@@ -47,7 +47,7 @@ pub(crate) fn capacity<T>(len: usize, purpose: &str) -> Result<Vec<T>> {
/// `Vec::push` that reports an allocation failure instead of aborting; each call is one
/// attempt for the test failpoints.
pub(crate) fn try_push<T>(out: &mut Vec<T>, value: T, purpose: &str) -> Result<()> {
#[cfg(test)]
#[cfg(any(test, feature = "failpoints"))]
if failpoint_hits() {
return Err(error(purpose, "not enough memory"));
}
@@ -59,7 +59,7 @@ pub(crate) fn try_push<T>(out: &mut Vec<T>, value: T, purpose: &str) -> Result<(
/// Check an operation boundary where downstream encoders/decoders allocate internally.
/// The test-only failpoint lets command tests prove their transaction boundary.
pub(crate) fn checkpoint(purpose: &str) -> Result<()> {
#[cfg(test)]
#[cfg(any(test, feature = "failpoints"))]
if failpoint_hits() {
return Err(error(purpose, "not enough memory"));
}
@@ -105,22 +105,23 @@ pub(crate) fn error(purpose: &str, detail: &str) -> EngineError {
EngineError::Other(format!("not enough memory for {purpose} ({detail}); the document was not changed"))
}
#[cfg(test)]
pub(crate) fn fail_next_for_test() {
/// Fail the next fallible allocation or checkpoint on this thread, then stop.
#[cfg(any(test, feature = "failpoints"))]
pub fn fail_next_for_test() {
FAIL_NEXT.with(|flag| flag.set(true));
}
/// Fail the fallible allocation or checkpoint after `skip` clean attempts, then stop.
/// `fail_after_for_test(0)` is equivalent to [`fail_next_for_test`].
#[cfg(test)]
pub(crate) fn fail_after_for_test(skip: usize) {
#[cfg(any(test, feature = "failpoints"))]
pub fn fail_after_for_test(skip: usize) {
FAIL_AFTER.with(|flag| flag.set(Some(skip)));
}
/// Whether a test failpoint trips here: the single-shot flag, or the counted flag
/// once its `skip` attempts have passed cleanly earlier. The shot does not advance the
/// counted flag: a one-shot failure is not itself a clean attempt.
#[cfg(test)]
#[cfg(any(test, feature = "failpoints"))]
fn failpoint_hits() -> bool {
if FAIL_NEXT.with(|flag| flag.replace(false)) {
return true;
@@ -12,7 +12,7 @@ const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0];
const WHITE: [f32; 4] = [1.0, 1.0, 1.0, 1.0];
fn session() -> Session {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 64, "height": 32, "background": "white"})).unwrap();
s.tools.foreground = BLACK;
s.tools.background = GREEN;
@@ -6,7 +6,6 @@
//! these same two fields (`crates/ui-egui/src/panels/options_bar.rs`), so off here means drawn
//! off there.
use crate::Session;
use photocraft_paint::brush::BrushSettings;
use serde_json::{Value, json};
@@ -22,7 +21,7 @@ fn the_default_brush_has_neither_pressure_toggle_on() {
/// two toggles.
#[test]
fn brush_get_reports_both_pressure_toggles_off() {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 32, "height": 32})).unwrap();
let got = s.execute("brush.get", json!({})).unwrap();
assert_eq!(got["pressureSize"], json!(false), "brush.get reports Pressure for Size off (#11809)");
@@ -49,7 +48,7 @@ fn a_brush_that_omits_the_field_takes_the_off_default() {
/// same field the options-bar button is drawn from.
#[test]
fn pressure_for_size_still_switches_on_and_off() {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 32, "height": 32})).unwrap();
s.execute("tools.setBrush", json!({"brush": {"pressureSize": true}})).unwrap();
assert!(s.tools.brush.pressure_size, "the toggle still turns on");
@@ -62,7 +61,7 @@ fn pressure_for_size_still_switches_on_and_off() {
/// One stroke of a pressure ramp (0.3 → 0.65 → 1.0) across a new empty layer with `brush`: the
/// layer's pixels and what the stroke covers.
fn ramp(brush: Value) -> (Vec<f32>, photocraft_geom::Rect) {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 80, "height": 40})).unwrap();
s.execute("layer.new.layer", json!({})).unwrap();
s.execute("paint.stroke", json!({"points": [[20.0, 20.0, 0.3], [40.0, 20.0, 0.65], [60.0, 20.0, 1.0]], "size": 24.0, "color": "#ff0000", "brush": brush}))
File renamed without changes.
File renamed without changes.
@@ -32,7 +32,7 @@ fn paint(s: &mut Session, f: impl Fn(i32, i32) -> [f32; 4]) {
/// An asymmetric document: a gradient Background, a type layer, a shape layer, a raster layer
/// with a vector mask and a smart object, plus a guide, a saved path and a slice.
fn mixed(depth: u64, mode: &str) -> Session {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": W, "height": H, "depth": depth, "mode": mode})).unwrap();
paint(&mut s, |x, y| [x as f32 / W as f32, y as f32 / H as f32, 0.3, 1.0]);
s.execute("type.create", json!({"x": 4, "y": 16, "text": "Fj", "size": 14, "color": "#102080"})).unwrap();
@@ -190,7 +190,7 @@ fn gradient_fill_angle_follows_the_canvas() {
/// The gradient fill's centre offset after `cmd`, as `gradient.fill.get` reports it (% of the frame).
fn fill_offset_after(cmd: &str, p: serde_json::Value) -> (f64, f64) {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 100, "height": 100})).unwrap();
s.execute("gradient.fill.create", json!({"from": [10, 50], "to": [90, 50], "style": "radial"})).unwrap();
s.execute("gradient.fill.set", json!({"angle": 0, "offset": [25, 0]})).unwrap();
@@ -225,7 +225,7 @@ fn gradient_fill_offset_stays_a_fraction_of_the_frame() {
fn turns_carry_an_angle_gradient_fill_with_its_pixels() {
// An Angle gradient sweeps clockwise: a mirror must reverse it, a turn must not.
for t in TURNS {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": W, "height": H})).unwrap();
let p = json!({"from": [20, 14], "to": [50, 4], "style": "angle", "dither": false});
s.execute("gradient.fill.create", p).unwrap();
@@ -250,7 +250,7 @@ fn turns_carry_an_angle_gradient_fill_with_its_pixels() {
/// The shape's (fill, stroke) gradient angles after `cmd` on a shape whose fill and stroke both
/// start as a 0° (left to right) gradient.
fn shape_gradient_angles_after(cmd: &str, p: serde_json::Value) -> (f32, f32) {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": W, "height": H})).unwrap();
let g = json!({"gradient": {"stops": [[0, "#ff0000"], [1, "#0000ff"]], "angle": 0}});
s.execute("shape.create", json!({"kind": "rect", "rect": [10, 8, 30, 20], "fill": g, "stroke": {"width": 6, "fill": g}})).unwrap();
@@ -324,7 +324,7 @@ fn canvas_size_and_crop_move_vector_geometry() {
#[test]
fn guide_colours_follow_their_guides() {
const MAGENTA: [u8; 3] = [255, 0, 255];
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": W, "height": H})).unwrap();
s.execute("view.newGuide", json!({"orientation": "vertical", "position": 20, "color": "#ff00ff"})).unwrap();
s.execute("view.newGuide", json!({"orientation": "vertical", "position": 30})).unwrap();
@@ -386,7 +386,7 @@ fn arbitrary_rotation_moves_marks_and_unlinked_vector_masks() {
/// A canvas turn moves every stored video frame, not just the displayed one (#4956).
#[test]
fn turns_move_stored_video_frames() {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": W, "height": H})).unwrap();
s.execute("layer.new.layer", json!({})).unwrap();
paint(&mut s, |x, y| if (x, y) == (1, 2) { [1.0, 0.0, 0.0, 1.0] } else { [0.0; 4] });
@@ -410,14 +410,15 @@ fn turns_move_stored_video_frames() {
#[test]
fn turns_on_empty_and_tiny_documents_never_panic() {
for (w, h) in [(1, 1), (1, 7), (5, 1)] {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": w, "height": h})).unwrap();
for t in TURNS {
s.execute(command(t), json!({"junk": [1, 2]})).unwrap();
assert!(s.execute(command(t), json!({"junk": [1, 2]})).is_err(), "an undocumented key is refused (#7596)");
s.execute(command(t), json!({})).unwrap();
}
s.execute("image.rotation.arbitrary", json!({"angle": 33})).unwrap();
}
let mut s = Session::new();
let mut s = crate::session();
for t in TURNS {
assert!(s.execute(command(t), json!({})).is_err(), "no document");
}
File renamed without changes.
@@ -7,11 +7,9 @@ const H: i32 = 20;
/// A white document whose left half is #336699: red 0.2, green 0.4, blue 0.6 there.
fn session(depth: u32) -> Session {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": W, "height": H, "depth": depth})).unwrap();
s.execute("select.rect", json!({"x": 0, "y": 0, "width": W / 2, "height": H})).unwrap();
s.execute("edit.fill", json!({"color": "#336699"})).unwrap();
s.execute("select.deselect", json!({})).unwrap();
crate::tests::fill_active(&mut s, Some(Rect::new(0, 0, W / 2, H)), "#336699");
s
}
@@ -77,7 +75,7 @@ fn cmyk_channels_copy_and_paste_as_tone() {
// #5787: copying a CMYK channel gives its tone (white where there is no ink), and pasting a
// tone into a CMYK channel writes it back as ink.
for depth in [8, 16] {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": W, "height": H, "mode": "cmyk", "depth": depth, "background": "white"})).unwrap();
s.execute("select.rect", json!({"x": 0, "y": 0, "width": W / 2, "height": H})).unwrap();
s.execute("edit.fill", json!({"color": "#00ffff"})).unwrap();
@@ -102,7 +100,7 @@ fn spot_channels_copy_and_paste_as_tone() {
// #5787: a spot channel stores ink but copies as its tone, and a tone pasted into it goes back
// to ink: spot -> Black prints the spot's ink in black, Cyan -> spot gives the spot Cyan's ink.
for depth in [8, 16] {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": W, "height": H, "mode": "cmyk", "depth": depth, "background": "white"})).unwrap();
s.execute("select.rect", json!({"x": 0, "y": 0, "width": W / 2, "height": H})).unwrap();
s.execute("edit.fill", json!({"color": "#00ffff"})).unwrap();
@@ -146,7 +146,7 @@ mod tests {
/// A document holding `spec` (bottom to top, `*` = clipped) above its Background.
fn stack(spec: &str) -> Session {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 16, "height": 16})).unwrap();
for name in spec.split_whitespace() {
let id = s.execute("layer.new.layer", json!({"name": name.trim_end_matches('*')})).unwrap()["layer"].clone();
@@ -171,8 +171,8 @@ use params::{bad, set_clipped};
pub(crate) use params::{check_f32_values, cmyk_param, color_param, int, int_i32, parse_hex, u32_id, u32_id_param};
pub use photocraft_color::blend::parse_blend;
pub use crate::install::{command_specs, find};
pub use crate::registry::{CommandSpec, list_entry, list_entry_matches, search_keywords};
pub use crate::registry::{command_specs, find};
#[cfg(test)]
mod set_props_tests {
@@ -181,7 +181,7 @@ mod set_props_tests {
#[test]
fn opacity_and_fill_outside_zero_to_one_are_refused_not_clamped() {
// #5242: `55` (a percentage, as the Layer Style commands take) used to become 100 %.
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
s.execute("layer.new.layer", json!({})).unwrap();
s.execute("layer.setProps", json!({"opacity": 0.55, "fill": 0.4})).unwrap();
@@ -26,10 +26,13 @@ use crate::{EngineError, Result, Session};
/// The action model is craft-automation's: one list type for the engine, the CLI and the panel.
pub use craft::automation::actions::{Action, ActionColor, ActionList, ActionStep, ActionsFile, moved_index};
mod history;
pub(crate) use history::ActionHistory;
pub use history::{ActionHistoryContinuation, finish_pending_history, suspend_history};
pub(crate) use history::{before_edit as before_action_edit, begin_document_history, finish_document_history, history_rows, reconcile_history_removal};
pub use crate::action_history::{ActionHistoryContinuation, finish_pending_history, suspend_history};
pub(crate) use crate::action_history::{
before_edit as before_action_edit, begin_document_history, finish_document_history, history_policy_in_use, history_rows, reconcile_history_removal,
};
pub(crate) use crate::actions_record::tool_stroke;
pub use crate::actions_record::{replayable, shell_save_command, shell_view_command};
pub use crate::prefs::{PLAY_SHORTCUT_PREFIX, is_action_key};
fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
@@ -44,7 +47,7 @@ pub(crate) fn list_error(cmd: &str, error: ActionListError) -> EngineError {
pub(crate) fn note_automation_edit(s: &mut Session, idx: usize) {
if s.authorize.is_some() {
// An index past the end is a stale mark: there is no action to flag.
let _ = s.actions.list.set_automation(idx, true);
let _ = s.actions_mut().list.set_automation(idx, true);
}
}
@@ -63,9 +66,9 @@ pub fn note_automation_step(s: &mut Session, id: &str, params: &Value) {
pub(crate) fn note_step_origin(s: &mut Session, automation: bool, id: &str, params: &Value) {
if automation
&& recorded(id, params)
&& let Some((_, idx)) = s.actions.recording
&& let Some((_, idx)) = s.recording.target
{
let _ = s.actions.list.set_automation(idx, true);
let _ = s.actions_mut().list.set_automation(idx, true);
}
}
@@ -80,8 +83,8 @@ pub const MAX_PLAYBACK_STEPS: u64 = 100_000;
/// How deep batches and droplets may run inside one another (a droplet whose steps run a droplet).
pub const MAX_BATCH_DEPTH: u8 = 4;
/// The actions list and the recording / playback flags. The list holds its own sets and
/// revision (the preset store skips unchanged writes by [`ActionList::revision`]).
/// The actions list and what Clear All, Reset or Replace keep for their undo. The list holds its own
/// sets and revision (the preset store skips unchanged writes by [`ActionList::revision`]).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ActionState {
/// The recorded actions, their sets and their revision: the user's list, the only one stored.
@@ -89,35 +92,12 @@ pub struct ActionState {
/// The actions a running Batch brought along (a droplet's `calledActions`). Playback finds the
/// actions it calls here first ([`playable`](Self::playable)); the user's list stays in place.
pub called: Option<ActionList>,
/// Painting-tool strokes are recorded only when the user enables them for this session.
pub record_tools: bool,
/// Journal length when recording started, and the action index being recorded into.
pub recording: Option<(usize, usize)>,
/// Nesting depth of `actions.play`, bounded by the playback stack limit.
pub playing: u8,
/// Active action names, for cycle detection in engine and desktop playback.
pub playback_stack: Vec<String>,
/// Number of steps executed by the current top-level playback tree.
pub playback_steps: u64,
/// Set for a batch nested in a played action or another batch: the playback counter it carries
/// is shared by every input, so a played action inside it does not restart the count.
pub budget_shared: bool,
/// How many batches (`file.automate.batch`, and droplets through it) are running inside one
/// another: each runs its steps in a scratch session that carries this on, plus one.
pub batch_depth: u8,
/// How many scripts (`file.scripts.browse`) are running inside one another.
pub script_depth: u8,
/// Steps run by the current top-level script and everything it calls.
pub script_steps: u64,
/// What the undo of the last Clear All, Reset or Replace restores beside the list (which keeps
/// its own, [`ActionList::library_undo`]): the action shortcuts and the document history marks.
pub library_undo: Option<Box<crate::actions_edit_cmds::LibraryUndo>>,
/// Clear All, Reset or Replace ran before the preset store attached: the list is the whole
/// library, so attaching writes it instead of merging the stored one in.
pub(crate) replaced_before_attachment: bool,
/// Bumped by each `actions.record`, so a background job knows whether the recording it was
/// started in is still the one running when its result lands.
pub take: u64,
}
impl ActionState {
@@ -128,20 +108,22 @@ impl ActionState {
}
}
/// Visibility gestures name a layer for replay, since document-local ids change on another image.
pub(crate) fn recorded_params(s: &Session, id: &str, mut p: Value) -> Value {
if s.actions.recording.is_none() || id != "layer.setProps" || p.get("visible").is_none() {
return p;
/// Window › Actions on a session: its [`ActionState`] (a session slot of this module).
pub trait ActionsExt {
/// The Actions list and the Batch's called actions. The list persists with the preset store
/// when one is attached.
fn actions(&self) -> &ActionState;
/// The Actions state, to change it.
fn actions_mut(&mut self) -> &mut ActionState;
}
impl ActionsExt for Session {
fn actions(&self) -> &ActionState {
self.slot_or_default::<ActionState>()
}
let Some(st) = s.active() else { return p };
let Some(layer) = p.get("layer").and_then(Value::as_u64).map(photocraft_doc::LayerId).or(st.active_layer).and_then(|id| st.doc.layer(id)) else { return p };
let ordinal = st.doc.walk().into_iter().filter(|(_, _, l)| l.name == layer.name).position(|(_, _, l)| l.id == layer.id).unwrap_or(0);
if let Some(object) = p.as_object_mut() {
object.remove("layer");
object.remove("coalesce");
object.insert("_actionLayer".into(), json!({"name": layer.name, "ordinal": ordinal}));
fn actions_mut(&mut self) -> &mut ActionState {
self.slot_or_default_mut::<ActionState>()
}
p
}
/// Resolve the recorded visibility target identically in engine and shell playback, and drop
@@ -198,30 +180,6 @@ pub fn playback_params(s: &Session, id: &str, p: &Value) -> Result<Value> {
Ok(p)
}
/// Replay commands and named action calls, excluding edits to the action definitions and the
/// already-expanded Again wrapper.
pub fn replayable(id: &str) -> bool {
// Again and Again on a Copy journal their concrete steps (`edit.transform`, after
// `layer.duplicate` for the copy) and record those: the wrappers look up the last transform in
// the journal, so they fail where no transform ran yet, e.g. an action played in a new session.
// A Conditional is recorded with its predicate, not the branch it happened to play (or none),
// so playback evaluates the condition again on the current document (#7198, #7238).
matches!(id, "actions.play" | "actions.conditional")
|| (!id.starts_with("actions.")
// Browse executes its steps through Session::execute, so those concrete
// commands are already journaled. Recording the wrapper as well replays
// every script edit twice (#3057).
&& !matches!(id, "edit.transform.again" | "edit.transform.againCopy" | "file.scripts.browse")
&& (shell_view_command(id) || shell_save_command(id) || crate::commands::find(id).is_some_and(|c| c.journal)))
}
/// File › Save, Save As and Save a Copy, and File › Export › Export As, recorded by the desktop
/// shell once the file has a path (#2032, #4373, #7207). The shell replays them; batch and
/// droplets write to their destination folder instead.
pub fn shell_save_command(id: &str) -> bool {
matches!(id, "file.save" | "file.saveAs" | "file.saveACopy" | "file.export.exportAs")
}
/// The failure for a played Save step whose document `target` (the one active when the step
/// started) is no longer open: a Save Document script event closed it. Playback stops there, so
/// the next step without a document, such as the Close half of an imported Close with Save: Yes,
@@ -237,16 +195,16 @@ pub fn save_target_closed(s: &Session, id: &str, target: Option<photocraft_doc::
pub fn consume_playback_step(s: &mut Session) -> bool {
// Inside a script the step also counts against the script's total: each top-level playback
// resets its own counter, so a script playing actions in a row would never reach the limit.
if s.actions.script_depth > 0 {
if s.actions.script_steps >= crate::automate_cmds::MAX_SCRIPT_STEPS {
if s.recording.script_depth > 0 {
if s.recording.script_steps >= crate::automate_cmds::MAX_SCRIPT_STEPS {
return false;
}
s.actions.script_steps += 1;
s.recording.script_steps += 1;
}
if s.actions.playback_steps >= MAX_PLAYBACK_STEPS {
if s.recording.playback_steps >= MAX_PLAYBACK_STEPS {
false
} else {
s.actions.playback_steps += 1;
s.recording.playback_steps += 1;
true
}
}
@@ -254,7 +212,7 @@ pub fn consume_playback_step(s: &mut Session) -> bool {
/// Steps of the playback tree the next `actions.play` starts in has charged so far: a top-level
/// call starts a new tree ([`begin_playback`] resets the counter).
fn playback_steps_used(s: &Session) -> u64 {
if s.actions.playing > 0 || s.actions.budget_shared { s.actions.playback_steps } else { 0 }
if s.recording.playing > 0 || s.recording.budget_shared { s.recording.playback_steps } else { 0 }
}
/// Steps of `action` playback walks past without running them: the ones before `from` and the
@@ -266,19 +224,13 @@ fn skipped_steps(action: &Action, from: usize) -> u64 {
let disabled = action.disabled.range(from..len).count();
u64::try_from(from.saturating_add(disabled)).unwrap_or(u64::MAX)
}
/// View-only menu commands recorded by the desktop shell. Headless playback reports
/// them as unsupported instead of silently dropping them; Batch and droplets skip them.
pub fn shell_view_command(id: &str) -> bool {
matches!(id, "view.fitOnScreen" | "view.actualPixels" | "view.zoomIn" | "view.zoomOut")
}
/// Shared validation for headless and shell playback. Does not start playback. Returns the
/// action's index in [`ActionState::playable`], the action and the step playback starts at.
pub fn playback_plan(s: &Session, p: &Value) -> Result<(usize, Action, usize)> {
if s.actions.playing > 0 && s.actions.playback_stack.is_empty() {
if s.recording.playing > 0 && s.recording.playback_stack.is_empty() {
return Err(bad("actions.play", "an action is already playing"));
}
let list = s.actions.playable();
let list = s.actions().playable();
let idx = resolve(list.actions(), p, "actions.play")?;
// Every stored step of the call is charged to the playback tree (run, disabled or skipped),
// so refuse a call whose steps no longer fit before copying it: repeated calls to a large
@@ -290,11 +242,11 @@ pub fn playback_plan(s: &Session, p: &Value) -> Result<(usize, Action, usize)> {
}
let action = list.action(idx).cloned().ok_or_else(|| bad("actions.play", "no such action"))?;
// The recording's index is into the user's list, which a Batch's called actions stand in for.
let records_it = s.actions.called.is_none() && s.actions.recording.is_some_and(|(_, i)| i == idx);
if s.actions.playback_stack.iter().any(|name| name == &action.name) || records_it {
let records_it = s.actions().called.is_none() && s.recording.target.is_some_and(|(_, i)| i == idx);
if s.recording.playback_stack.iter().any(|name| name == &action.name) || records_it {
return Err(bad("actions.play", format!("recursive action call to `{}`", action.name)));
}
if s.actions.playback_stack.len() >= 16 {
if s.recording.playback_stack.len() >= 16 {
return Err(bad("actions.play", "action nesting exceeds 16 levels"));
}
let from = from_step(p, action.steps.len())?;
@@ -543,14 +495,14 @@ fn from_step(p: &Value, len: usize) -> Result<usize> {
}
fn list(s: &mut Session, _p: &Value) -> Result<Value> {
let actions: Vec<Value> = s.actions.list.actions().iter().map(|a| json!({"name": a.name, "steps": a.steps.len(), "set": a.set})).collect();
let recording = s.actions.recording.and_then(|(_, i)| s.actions.list.action(i).map(|a| a.name.clone()));
Ok(json!({"actions": actions, "sets": crate::actions_edit_cmds::set_names(s), "recording": recording, "toolRecording": s.actions.record_tools}))
let actions: Vec<Value> = s.actions().list.actions().iter().map(|a| json!({"name": a.name, "steps": a.steps.len(), "set": a.set})).collect();
let recording = s.recording.target.and_then(|(_, i)| s.actions().list.action(i).map(|a| a.name.clone()));
Ok(json!({"actions": actions, "sets": crate::actions_edit_cmds::set_names(s), "recording": recording, "toolRecording": s.recording.record_tools}))
}
fn get(s: &mut Session, p: &Value) -> Result<Value> {
let idx = resolve(s.actions.list.actions(), p, "actions.get")?;
let action = &s.actions.list.actions()[idx];
let idx = resolve(s.actions().list.actions(), p, "actions.get")?;
let action = &s.actions().list.actions()[idx];
let steps: Vec<Value> = action.steps.iter().map(|step| json!([step.command, step.params])).collect();
Ok(json!({"name": action.name, "steps": steps, "disabled": action.disabled, "dialogs": action.dialogs, "set": action.set, "color": action.color.name()}))
}
@@ -559,11 +511,11 @@ fn get(s: &mut Session, p: &Value) -> Result<Value> {
/// it as automation's when an automation gate is installed.
fn record(s: &mut Session, p: &Value) -> Result<Value> {
not_playing(s, "actions.record")?;
if s.actions.recording.is_some() {
if s.recording.target.is_some() {
return Err(bad("actions.record", "already recording; stop first"));
}
let idx = if p.get("action").is_some() {
resolve(s.actions.list.actions(), p, "actions.record")?
resolve(s.actions().list.actions(), p, "actions.record")?
} else {
let name = match p.get("name") {
None | Some(Value::Null) => None,
@@ -579,14 +531,14 @@ fn record(s: &mut Session, p: &Value) -> Result<Value> {
Some(Value::String(n)) if !n.trim().is_empty() => Some(n.trim().to_string()),
Some(_) => return Err(bad("actions.record", "\"set\" must be a set name or null")),
};
let name = name.unwrap_or_else(|| s.actions.list.unique_name(""));
let name = name.unwrap_or_else(|| s.actions().list.unique_name(""));
// `push`, not `new_action`: an existing set keeps its exact name, which `new_action` would trim.
s.actions.list.push(Action { set, ..Action::new(name, Vec::new()) }).map_err(|e| list_error("actions.record", e))?
s.actions_mut().list.push(Action { set, ..Action::new(name, Vec::new()) }).map_err(|e| list_error("actions.record", e))?
};
s.actions.recording = Some((s.journal.len(), idx));
s.recording.target = Some((s.journal.len(), idx));
note_automation_edit(s, idx);
s.actions.take = s.actions.take.wrapping_add(1);
let name = s.actions.list.action(idx).map(|a| a.name.clone()).unwrap_or_default();
s.recording.take = s.recording.take.wrapping_add(1);
let name = s.actions().list.action(idx).map(|a| a.name.clone()).unwrap_or_default();
Ok(json!({"action": name, "index": idx}))
}
@@ -601,50 +553,25 @@ const RECORDED_WITH_DIALOG: &[&str] = &["edit.checkSpelling"];
/// Replayable journal entries not yet committed to this action while recording.
pub fn pending_steps(s: &Session, action: usize) -> impl Iterator<Item = &(String, Value)> {
let from = s.actions.recording.filter(|(_, i)| *i == action).map_or(s.journal.len(), |(from, _)| from);
s.journal.iter().skip(from).filter(|(id, p)| recorded(id, p) && (s.actions.record_tools || !tool_stroke(id)))
}
/// The point-based painting tools committed by the canvas; fills and gradients remain commands.
pub(crate) fn tool_stroke(id: &str) -> bool {
matches!(
id,
"paint.stroke"
| "paint.pencil"
| "paint.mixerBrush"
| "paint.colorReplacement"
| "paint.blur"
| "paint.sharpen"
| "paint.smudge"
| "paint.dodge"
| "paint.burn"
| "paint.sponge"
| "paint.cloneStamp"
| "paint.healingBrush"
| "paint.historyBrush"
| "paint.artHistoryBrush"
| "paint.patternStamp"
| "paint.backgroundEraser"
| "paint.spotHealing"
| "paint.remove"
)
let from = s.recording.target.filter(|(_, i)| *i == action).map_or(s.journal.len(), |(from, _)| from);
s.journal.iter().skip(from).filter(|(id, p)| recorded(id, p) && (s.recording.record_tools || !tool_stroke(id)))
}
pub(crate) fn flush_recording(s: &mut Session) -> Result<()> {
let Some((_, idx)) = s.actions.recording else { return Ok(()) };
if s.actions.list.action(idx).is_none() {
let Some((_, idx)) = s.recording.target else { return Ok(()) };
if s.actions().list.action(idx).is_none() {
return Err(bad("actions.stop", "the action being recorded no longer exists"));
}
let steps = fold_recorded_nudges(pending_steps(s, idx).cloned());
s.actions.recording = Some((s.journal.len(), idx));
s.recording.target = Some((s.journal.len(), idx));
if !steps.is_empty() {
let first = s.actions.list.step_count(idx);
let first = s.actions().list.step_count(idx);
let with_dialog: Vec<usize> =
steps.iter().enumerate().filter(|(_, (id, _))| RECORDED_WITH_DIALOG.contains(&id.as_str())).map(|(i, _)| first + i).collect();
let stop = |e: ActionListError| list_error("actions.stop", e);
s.actions.list.append_recorded(idx, steps.into_iter().map(ActionStep::from)).map_err(stop)?;
s.actions_mut().list.append_recorded(idx, steps.into_iter().map(ActionStep::from)).map_err(stop)?;
for step in with_dialog {
s.actions.list.set_dialog(idx, step, true).map_err(stop)?;
s.actions_mut().list.set_dialog(idx, step, true).map_err(stop)?;
}
}
Ok(())
@@ -702,12 +629,12 @@ fn fold_recorded_nudges(steps: impl IntoIterator<Item = (String, Value)>) -> Vec
fn stop(s: &mut Session, _p: &Value) -> Result<Value> {
not_playing(s, "actions.stop")?;
let Some((_, idx)) = s.actions.recording else {
let Some((_, idx)) = s.recording.target else {
return Err(bad("actions.stop", "not recording"));
};
flush_recording(s)?;
s.actions.recording = None;
let action = &s.actions.list.actions()[idx];
s.recording.target = None;
let action = &s.actions().list.actions()[idx];
Ok(json!({"action": action.name, "steps": action.steps.len()}))
}
@@ -800,32 +727,32 @@ pub fn begin_playback_from(s: &mut Session, action: &Action, from: usize) -> Res
// scope opens, so a rejected call leaves none behind.
let skipped = skipped_steps(action, from);
let max = crate::automate_cmds::MAX_SCRIPT_STEPS;
if s.actions.script_depth > 0 && s.actions.script_steps.saturating_add(skipped) > max {
if s.recording.script_depth > 0 && s.recording.script_steps.saturating_add(skipped) > max {
return Err(bad("actions.play", format!("the script ran more than {max} steps in all")));
}
if s.actions.playing == 0 {
history::begin(s, &action.name);
if s.recording.playing == 0 {
crate::action_history::begin(s, &action.name);
// A batch nested in a played action or another batch carries the shared count on.
if !s.actions.budget_shared {
s.actions.playback_steps = 0;
if !s.recording.budget_shared {
s.recording.playback_steps = 0;
}
}
s.actions.playback_steps = s.actions.playback_steps.saturating_add(skipped);
if s.actions.script_depth > 0 {
s.actions.script_steps = s.actions.script_steps.saturating_add(skipped);
s.recording.playback_steps = s.recording.playback_steps.saturating_add(skipped);
if s.recording.script_depth > 0 {
s.recording.script_steps = s.recording.script_steps.saturating_add(skipped);
}
let recording = s.actions.recording.take();
s.actions.playing = s.actions.playing.saturating_add(1);
s.actions.playback_stack.push(action.name.clone());
let recording = s.recording.target.take();
s.recording.playing = s.recording.playing.saturating_add(1);
s.recording.playback_stack.push(action.name.clone());
Ok(recording)
}
/// Unwind the playback stack and finish grouping only at the outer boundary, then restore suspended recording.
pub fn finish_playback(s: &mut Session, recording: Option<(usize, usize)>, action: &Action, from: usize) {
s.actions.playback_stack.pop();
s.actions.playing = s.actions.playing.saturating_sub(1);
if s.actions.playing == 0 {
history::finish_playback(s);
s.recording.playback_stack.pop();
s.recording.playing = s.recording.playing.saturating_sub(1);
if s.recording.playing == 0 {
crate::action_history::finish_playback(s);
}
if let Some((_, idx)) = recording {
restore_recording(s, idx, &action.name, from);
@@ -834,7 +761,7 @@ pub fn finish_playback(s: &mut Session, recording: Option<(usize, usize)>, actio
/// Resume recording into action `idx` and journal the named call that suspended it.
pub fn restore_recording(s: &mut Session, idx: usize, action: &str, from: usize) {
s.actions.recording = Some((s.journal.len(), idx));
s.recording.target = Some((s.journal.len(), idx));
let mut params = json!({"action": action});
if from > 0 {
params["from"] = json!(from);
@@ -925,13 +852,13 @@ fn play(s: &mut Session, p: &Value) -> Result<Value> {
}
pub(crate) fn not_playing(s: &Session, cmd: &str) -> Result<()> {
if s.actions.playing > 0 { Err(bad(cmd, "cannot edit actions during playback")) } else { Ok(()) }
if s.recording.playing > 0 { Err(bad(cmd, "cannot edit actions during playback")) } else { Ok(()) }
}
/// Move to a final zero-based index, either in an action's steps or in the action list.
fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
not_playing(s, "actions.move")?;
let idx = resolve(s.actions.list.actions(), p, "actions.move")?;
let idx = resolve(s.actions().list.actions(), p, "actions.move")?;
let index = |key: &str| -> Result<usize> {
p.get(key)
.and_then(Value::as_u64)
@@ -941,21 +868,21 @@ fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
let to = index("to")?;
if p.get("step").is_some() {
let step = index("step")?;
let len = s.actions.list.step_count(idx).saturating_add(pending_steps(s, idx).count());
let len = s.actions().list.step_count(idx).saturating_add(pending_steps(s, idx).count());
if step >= len || to >= len {
return Err(bad("actions.move", "step or destination is out of range"));
}
if s.actions.recording.is_some_and(|(_, i)| i == idx) {
if s.recording.target.is_some_and(|(_, i)| i == idx) {
flush_recording(s)?;
}
s.actions.list.move_step(idx, step, idx, to).map_err(|e| list_error("actions.move", e))?;
let result = json!({"action": s.actions.list.actions()[idx].name, "step": to});
s.actions_mut().list.move_step(idx, step, idx, to).map_err(|e| list_error("actions.move", e))?;
let result = json!({"action": s.actions().list.actions()[idx].name, "step": to});
note_automation_edit(s, idx);
Ok(result)
} else {
let name = s.actions.list.actions()[idx].name.clone();
s.actions.list.move_action(idx, to).map_err(|e| list_error("actions.move", e))?;
if let Some((_, recording)) = s.actions.recording.as_mut() {
let name = s.actions().list.actions()[idx].name.clone();
s.actions_mut().list.move_action(idx, to).map_err(|e| list_error("actions.move", e))?;
if let Some((_, recording)) = s.recording.target.as_mut() {
*recording = moved_index(*recording, idx, to);
}
Ok(json!({"action": name, "index": to}))
@@ -966,28 +893,28 @@ fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
/// as automation's when an automation gate is installed).
fn delete(s: &mut Session, p: &Value) -> Result<Value> {
not_playing(s, "actions.delete")?;
let idx = resolve(s.actions.list.actions(), p, "actions.delete")?;
let idx = resolve(s.actions().list.actions(), p, "actions.delete")?;
if let Some(step) = p.get("step") {
let step = step.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad("actions.delete", "step must be a non-negative integer"))?;
let len = s.actions.list.step_count(idx).saturating_add(pending_steps(s, idx).count());
let len = s.actions().list.step_count(idx).saturating_add(pending_steps(s, idx).count());
if step >= len {
return Err(bad("actions.delete", "step is out of range"));
}
// Commit pending entries before editing the action; never erase the command
// journal or undo the edit that produced the deleted recording step.
if s.actions.recording.is_some_and(|(_, i)| i == idx) {
if s.recording.target.is_some_and(|(_, i)| i == idx) {
flush_recording(s)?;
}
s.actions.list.delete_step(idx, step).map_err(|e| list_error("actions.delete", e))?;
let action = &s.actions.list.actions()[idx];
s.actions_mut().list.delete_step(idx, step).map_err(|e| list_error("actions.delete", e))?;
let action = &s.actions().list.actions()[idx];
let result = json!({"action": action.name, "deletedStep": step, "steps": action.steps.len()});
note_automation_edit(s, idx);
return Ok(result);
}
if s.actions.recording.is_some() {
if s.recording.target.is_some() {
return Err(bad("actions.delete", "stop recording before deleting an action"));
}
let name = s.actions.list.delete_action(idx).map_err(|e| list_error("actions.delete", e))?.name;
let name = s.actions_mut().list.delete_action(idx).map_err(|e| list_error("actions.delete", e))?.name;
// Its function keys go with it, or the next action given the same name would inherit them.
remove_shortcuts(s, std::iter::once(name.as_str()));
Ok(json!({"deleted": name}))
@@ -998,7 +925,7 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> {
fn toggle(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "actions.toggle";
not_playing(s, cmd)?;
let idx = resolve(s.actions.list.actions(), p, cmd)?;
let idx = resolve(s.actions().list.actions(), p, cmd)?;
let enabled = match p.get("enabled") {
None | Some(Value::Null) => None,
Some(Value::Bool(b)) => Some(*b),
@@ -1008,43 +935,35 @@ fn toggle(s: &mut Session, p: &Value) -> Result<Value> {
None | Some(Value::Null) => None,
Some(v) => Some(v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(cmd, "step must be a non-negative integer"))?),
};
let len = s.actions.list.step_count(idx).saturating_add(pending_steps(s, idx).count());
let len = s.actions().list.step_count(idx).saturating_add(pending_steps(s, idx).count());
if step.is_some_and(|step| step >= len) {
return Err(bad(cmd, "step is out of range"));
}
if s.actions.recording.is_some_and(|(_, i)| i == idx) {
if s.recording.target.is_some_and(|(_, i)| i == idx) {
flush_recording(s)?;
}
let action = &s.actions.list.actions()[idx];
let action = &s.actions().list.actions()[idx];
let edit = match step {
Some(step) => {
let on = enabled.unwrap_or(!action.step_enabled(step));
s.actions.list.set_step(idx, step, on)
s.actions_mut().list.set_step(idx, step, on)
}
None => {
let on = enabled.unwrap_or(!action.disabled.is_empty());
s.actions.list.set_all(idx, on)
s.actions_mut().list.set_all(idx, on)
}
};
edit.map_err(|e| list_error(cmd, e))?;
let action = &s.actions.list.actions()[idx];
let action = &s.actions().list.actions()[idx];
let result = json!({"action": action.name, "disabled": action.disabled});
note_automation_edit(s, idx);
Ok(result)
}
/// Prefix of the persisted shortcut override that plays a named action (`actions.play:<name>`).
pub const PLAY_SHORTCUT_PREFIX: &str = "actions.play:";
/// Prefix of the shortcut keys PhotoCraft files of the Actions library commands era stored per
/// action id (`actions.playById:<id>`); [`name_id_shortcuts`] moves them to names on load.
const PLAY_BY_ID_PREFIX: &str = "actions.playById:";
/// Whether a shortcut key plays an action: it belongs to the Actions library, not to a set.
pub fn is_action_key(key: &str) -> bool {
key.starts_with(PLAY_SHORTCUT_PREFIX)
}
/// Remove the function keys (primary and alternate) of the actions `names`.
pub(crate) fn remove_shortcuts<'a>(s: &mut Session, names: impl IntoIterator<Item = &'a str>) {
let prefs = s.prefs();
@@ -1144,22 +1063,22 @@ pub(crate) fn name_id_shortcuts(s: &mut Session, ids: &[(String, String)]) {
/// stops working.
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
not_playing(s, "actions.rename")?;
let idx = resolve(s.actions.list.actions(), p, "actions.rename")?;
let idx = resolve(s.actions().list.actions(), p, "actions.rename")?;
let name = match p.get("name") {
Some(Value::String(n)) if !n.trim().is_empty() => n.clone(),
Some(Value::String(_)) => return Err(bad("actions.rename", "\"name\" is empty")),
Some(_) => return Err(bad("actions.rename", "\"name\" must be a string")),
None => return Err(bad("actions.rename", "needs \"name\"")),
};
let old = s.actions.list.action(idx).map(|a| a.name.clone()).ok_or_else(|| bad("actions.rename", "no such action"))?;
let pending = s.actions.recording.map_or(s.journal.len(), |(start, _)| start);
let old = s.actions().list.action(idx).map(|a| a.name.clone()).ok_or_else(|| bad("actions.rename", "no such action"))?;
let pending = s.recording.target.map_or(s.journal.len(), |(start, _)| start);
// Names are list-wide, so a call naming `old` reaches this action; a named Batch is checked
// against the list before the rename because its set can still refuse it.
let before = s.actions.list.actions().to_vec();
let before = s.actions().list.actions().to_vec();
let follow = |id: &str, params: &mut Value, old: &str, new: &str| rename_call(&before, idx, id, params, old, new);
s.actions.list.rename(idx, &name, |step, old, new| follow(&step.command, &mut step.params, old, new)).map_err(|e| list_error("actions.rename", e))?;
s.actions_mut().list.rename(idx, &name, |step, old, new| follow(&step.command, &mut step.params, old, new)).map_err(|e| list_error("actions.rename", e))?;
// The list renames its own steps; the journal entries not yet recorded are the engine's.
let name = s.actions.list.actions()[idx].name.clone();
let name = s.actions().list.actions()[idx].name.clone();
if old == name {
return Ok(json!({"action": name, "index": idx}));
}
@@ -1201,7 +1120,7 @@ fn rename_call(before: &[Action], idx: usize, id: &str, params: &mut Value, old:
fn set_color(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "actions.setColor";
not_playing(s, cmd)?;
let idx = resolve(s.actions.list.actions(), p, cmd)?;
let idx = resolve(s.actions().list.actions(), p, cmd)?;
let Some(color) = p.get("color").and_then(Value::as_str) else {
return Err(bad(cmd, "needs \"color\""));
};
@@ -1209,16 +1128,11 @@ fn set_color(s: &mut Session, p: &Value) -> Result<Value> {
let Some(chosen) = ActionColor::ALL.into_iter().find(|each| each.name() == color) else {
return Err(bad(cmd, "color must be empty, red, orange, yellow, green, blue, violet, or gray"));
};
s.actions.list.set_color(idx, chosen).map_err(|e| list_error(cmd, e))?;
let name = s.actions.list.actions()[idx].name.clone();
s.actions_mut().list.set_color(idx, chosen).map_err(|e| list_error(cmd, e))?;
let name = s.actions().list.actions()[idx].name.clone();
Ok(json!({"action": name, "color": color}))
}
/// Active playback and retained dialog continuations keep their chosen history policy.
pub(crate) fn history_policy_in_use(s: &Session) -> bool {
s.actions.playing != 0 || s.action_history.is_some() || s.paused_action_history.iter().any(|lease| lease.strong_count() != 0)
}
/// Create a single history state alone; `actions.setPlayback` sets it with the performance mode.
fn set_history(s: &mut Session, p: &Value) -> Result<Value> {
not_playing(s, "actions.setHistory")?;
@@ -1410,8 +1324,8 @@ mod security_tests {
#[test]
fn playback_budget_is_shared_by_nested_calls() {
let mut session = Session::new();
session.actions.playback_steps = MAX_PLAYBACK_STEPS - 1;
let mut session = crate::session();
session.recording.playback_steps = MAX_PLAYBACK_STEPS - 1;
assert!(consume_playback_step(&mut session));
assert!(!consume_playback_step(&mut session));
}
@@ -1420,14 +1334,14 @@ mod security_tests {
/// batch carries instead of restarting it for each input.
#[test]
fn a_nested_batch_input_does_not_reset_the_shared_playback_count() {
let mut session = Session::new();
let mut session = crate::session();
session.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
session.actions.list.push(Action::new("A", vec![ActionStep::new("select.all", json!({}))])).unwrap();
session.actions.budget_shared = true;
session.actions.playback_steps = MAX_PLAYBACK_STEPS;
session.actions_mut().list.push(Action::new("A", vec![ActionStep::new("select.all", json!({}))])).unwrap();
session.recording.budget_shared = true;
session.recording.playback_steps = MAX_PLAYBACK_STEPS;
let r = session.execute("actions.play", json!({"action": "A"}));
assert!(matches!(r, Err(EngineError::BatchLimit(_))), "the carried count leaves no room for the action: {r:?}");
session.actions.budget_shared = false;
session.recording.budget_shared = false;
let r = session.execute("actions.play", json!({"action": "A"})).unwrap();
assert_eq!(r["ran"], 1, "a top-level call starts its own count");
}
@@ -1437,13 +1351,13 @@ mod security_tests {
/// walking the whole action for free.
#[test]
fn disabled_steps_are_charged_to_the_playback_budget() {
let mut session = Session::new();
let mut session = crate::session();
let mut child = Action::new("Child", (0..1000).map(|_| ActionStep::new("select.all", json!({}))).collect());
child.disabled = (0..1000).collect();
let calls = MAX_PLAYBACK_STEPS as usize / 1000 * 2;
let parent = Action::new("Parent", (0..calls).map(|_| ActionStep::new("actions.play", json!({"action": "Child"}))).collect());
session.actions.list.push(child).unwrap();
session.actions.list.push(parent).unwrap();
session.actions_mut().list.push(child).unwrap();
session.actions_mut().list.push(parent).unwrap();
let r = session.execute("actions.play", json!({"action": "Parent"})).unwrap();
let failed = r["failed"]["error"].as_str().unwrap();
assert!(failed.contains("step limit"), "{failed}");
@@ -1,5 +1,7 @@
//! Playback Options (`actions.setPlayback`): validation, preferences and headless playback.
use super::*;
use crate::actions_cmds::ActionsExt;
use crate::prefs::SavedPrefsExt;
use serde_json::json;
fn options(s: &Session) -> (crate::prefs::PlaybackPerformance, u8, bool) {
@@ -9,7 +11,7 @@ fn options(s: &Session) -> (crate::prefs::PlaybackPerformance, u8, bool) {
#[test]
fn set_playback_refuses_bad_values_and_changes_nothing() {
let mut s = Session::new();
let mut s = crate::session();
let before = options(&s);
for bad in [
json!({"performance": "fast"}),
@@ -36,7 +38,7 @@ fn set_playback_refuses_bad_values_and_changes_nothing() {
#[test]
fn set_playback_stores_each_value_in_preferences() {
use crate::prefs::PlaybackPerformance::*;
let mut s = Session::new();
let mut s = crate::session();
assert_eq!(options(&s), (Accelerated, 1, true), "the defaults the reference application ships");
let r = s.execute("actions.setPlayback", json!({"performance": "pause", "seconds": 60})).unwrap();
assert_eq!(r, json!({"performance": "pause", "seconds": 60, "singleState": true}));
@@ -48,7 +50,7 @@ fn set_playback_stores_each_value_in_preferences() {
// A preferences file round trip keeps all three.
s.execute("actions.setPlayback", json!({"performance": "pause", "seconds": 7})).unwrap();
let saved = s.prefs_to_json();
let mut t = Session::new();
let mut t = crate::session();
assert!(t.load_prefs_json(&saved).unwrap().is_empty());
assert_eq!(options(&t), (Pause, 7, false));
// prefs.set validates the same range and names.
@@ -62,7 +64,7 @@ fn set_playback_stores_each_value_in_preferences() {
#[test]
fn older_or_hand_edited_preferences_load_within_range() {
let mut s = Session::new();
let mut s = crate::session();
// Before Playback Options: only the history flag.
assert!(s.load_prefs_json(r#"{"actions":{"createSingleHistoryState":false}}"#).unwrap().is_empty());
assert_eq!(options(&s), (crate::prefs::PlaybackPerformance::Accelerated, 1, false));
@@ -74,9 +76,9 @@ fn older_or_hand_edited_preferences_load_within_range() {
#[test]
fn set_playback_keeps_the_history_policy_of_a_running_play() {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
s.actions.list.push(Action::new("Change", vec![ActionStep::new("actions.setPlayback", json!({"singleState": false}))])).unwrap();
s.actions_mut().list.push(Action::new("Change", vec![ActionStep::new("actions.setPlayback", json!({"singleState": false}))])).unwrap();
let played = s.execute("actions.play", json!({"action": "Change"})).unwrap();
assert!(played.get("failed").is_some(), "an action can't change Playback Options while it plays: {played}");
assert!(s.prefs().actions.create_single_history_state);
@@ -88,11 +90,11 @@ fn set_playback_keeps_the_history_policy_of_a_running_play() {
fn headless_play_runs_the_whole_action_in_every_mode() {
for performance in ["accelerated", "step", "pause"] {
for single in [true, false] {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
s.execute("actions.setPlayback", json!({"performance": performance, "seconds": 60, "singleState": single})).unwrap();
let steps = ["A", "B", "C"].map(|n| ActionStep::new("layer.new.layer", json!({"name": n}))).to_vec();
s.actions.list.push(Action::new("Three", steps)).unwrap();
s.actions_mut().list.push(Action::new("Three", steps)).unwrap();
let layers = s.active().unwrap().doc.layers.len();
let past = s.active().unwrap().history.past_len();
let t0 = std::time::Instant::now();
@@ -7,6 +7,7 @@
//! per-step flag sets (`disabled`, `dialogs`) in step with the moved indices, like
//! `actions.move` and `actions.delete`.
use crate::actions_cmds::ActionsExt;
use serde_json::{Value, json};
use crate::actions_cmds::{ActionStep, flush_recording, list_error, not_playing, note_automation_edit, pending_steps, resolve, shift_action_calls};
@@ -36,16 +37,16 @@ fn allow_tool_recording(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "actions.allowToolRecording";
not_playing(s, cmd)?;
let enabled = match p.get("enabled") {
None | Some(Value::Null) => !s.actions.record_tools,
None | Some(Value::Null) => !s.recording.record_tools,
Some(Value::Bool(enabled)) => *enabled,
Some(_) => return Err(bad(cmd, "`enabled` must be true or false")),
};
if enabled != s.actions.record_tools {
if s.actions.recording.is_some() && s.tool_stroke_job_running() {
if enabled != s.recording.record_tools {
if s.recording.target.is_some() && s.tool_stroke_job_running() {
return Err(bad(cmd, "wait for the current tool stroke before changing recording"));
}
flush_recording(s)?;
s.actions.record_tools = enabled;
s.recording.record_tools = enabled;
}
Ok(json!({"enabled": enabled}))
}
@@ -78,7 +79,7 @@ fn is_step_command(id: &str) -> bool {
fn insert(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "actions.insert";
not_playing(s, cmd)?;
let idx = resolve(s.actions.list.actions(), p, cmd)?;
let idx = resolve(s.actions().list.actions(), p, cmd)?;
let id = match p.get("id") {
Some(Value::String(id)) if !id.trim().is_empty() => id.trim().to_string(),
_ => return Err(bad(cmd, "needs `id`, the command the step runs")),
@@ -94,24 +95,25 @@ fn insert(s: &mut Session, p: &Value) -> Result<Value> {
if id == "actions.play" {
// Refuse the one cycle visible here; deeper ones are caught at playback.
let target = params.get("action");
let is_self = target.and_then(Value::as_str) == Some(s.actions.list.actions()[idx].name.as_str()) || target.and_then(Value::as_u64) == Some(idx as u64);
let is_self =
target.and_then(Value::as_str) == Some(s.actions().list.actions()[idx].name.as_str()) || target.and_then(Value::as_u64) == Some(idx as u64);
if is_self {
return Err(bad(cmd, "an action cannot play itself"));
}
}
let len = s.actions.list.step_count(idx).saturating_add(pending_steps(s, idx).count());
let len = s.actions().list.step_count(idx).saturating_add(pending_steps(s, idx).count());
let at = index(p, "at", cmd)?.unwrap_or(len);
if at > len {
return Err(bad(cmd, format!("`at` {at} is past the last step ({len})")));
}
if s.actions.recording.is_some_and(|(_, i)| i == idx) {
if s.recording.target.is_some_and(|(_, i)| i == idx) {
flush_recording(s)?;
}
let is_stop = id == crate::atn_cmds::STOP_MESSAGE;
s.actions.list.insert_step(idx, at, ActionStep::new(id, params)).map_err(|e| list_error(cmd, e))?;
s.actions_mut().list.insert_step(idx, at, ActionStep::new(id, params)).map_err(|e| list_error(cmd, e))?;
// A newly inserted Stop shows its message in the app. Duplicates keep their own flags.
if is_stop {
s.actions.list.set_dialog(idx, at, true).map_err(|e| list_error(cmd, e))?;
s.actions_mut().list.set_dialog(idx, at, true).map_err(|e| list_error(cmd, e))?;
}
note_automation_edit(s, idx);
Ok(step_result(s, idx, at))
@@ -119,7 +121,7 @@ fn insert(s: &mut Session, p: &Value) -> Result<Value> {
/// The result of an insert or a step duplicate: step `at` of action `idx` as it now stands.
fn step_result(s: &Session, idx: usize, at: usize) -> Value {
let action = &s.actions.list.actions()[idx];
let action = &s.actions().list.actions()[idx];
json!({"action": action.name, "step": at, "id": action.steps[at].command, "steps": action.steps.len()})
}
@@ -133,42 +135,42 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
}
return duplicate_set(s, set.as_str().ok_or_else(|| bad(cmd, "set must be a name"))?);
}
let idx = resolve(s.actions.list.actions(), p, cmd)?;
let idx = resolve(s.actions().list.actions(), p, cmd)?;
if let Some(step) = index(p, "step", cmd)? {
let len = s.actions.list.step_count(idx).saturating_add(pending_steps(s, idx).count());
let len = s.actions().list.step_count(idx).saturating_add(pending_steps(s, idx).count());
if step >= len {
return Err(bad(cmd, "step is out of range"));
}
if s.actions.recording.is_some_and(|(_, i)| i == idx) {
if s.recording.target.is_some_and(|(_, i)| i == idx) {
flush_recording(s)?;
}
s.actions.list.duplicate_step(idx, step).map_err(|e| list_error(cmd, e))?;
s.actions_mut().list.duplicate_step(idx, step).map_err(|e| list_error(cmd, e))?;
note_automation_edit(s, idx);
let mut result = step_result(s, idx, step + 1);
result["index"] = json!(idx);
return Ok(result);
}
if s.actions.recording.is_some() {
if s.recording.target.is_some() {
return Err(bad(cmd, "stop recording before duplicating an action"));
}
let at = s.actions.list.duplicate_action(idx, shift_action_calls).map_err(|e| list_error(cmd, e))?;
let copy = &s.actions.list.actions()[at];
let at = s.actions_mut().list.duplicate_action(idx, shift_action_calls).map_err(|e| list_error(cmd, e))?;
let copy = &s.actions().list.actions()[at];
Ok(json!({"action": copy.name, "index": at, "steps": copy.steps.len()}))
}
/// Copy the named group represented by main, including a session-only empty New Set.
fn duplicate_set(s: &mut Session, source: &str) -> Result<Value> {
let cmd = "actions.duplicate";
if s.actions.recording.is_some() {
if s.recording.target.is_some() {
return Err(bad(cmd, "stop recording before duplicating a set"));
}
let sets = set_names(s);
if !sets.iter().any(|name| name == source) {
return Err(bad(cmd, "the selected set no longer exists"));
}
let name = s.actions.list.duplicate_set(source, shift_action_calls).map_err(|e| list_error(cmd, e))?;
let copies = s.actions.list.actions().iter().filter(|action| action.set.as_deref() == Some(name.as_str())).count();
match s.actions.list.actions().iter().position(|action| action.set.as_deref() == Some(name.as_str())) {
let name = s.actions_mut().list.duplicate_set(source, shift_action_calls).map_err(|e| list_error(cmd, e))?;
let copies = s.actions().list.actions().iter().filter(|action| action.set.as_deref() == Some(name.as_str())).count();
match s.actions().list.actions().iter().position(|action| action.set.as_deref() == Some(name.as_str())) {
Some(at) => Ok(json!({"set": name, "index": at, "actions": copies})),
None => Ok(json!({"set": name, "actions": 0})),
}
@@ -179,21 +181,21 @@ fn duplicate_set(s: &mut Session, source: &str) -> Result<Value> {
fn dialog(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "actions.dialog";
not_playing(s, cmd)?;
let idx = resolve(s.actions.list.actions(), p, cmd)?;
let idx = resolve(s.actions().list.actions(), p, cmd)?;
let enabled = match p.get("enabled") {
None | Some(Value::Null) => None,
Some(Value::Bool(b)) => Some(*b),
Some(_) => return Err(bad(cmd, "`enabled` must be true or false")),
};
let step = index(p, "step", cmd)?;
let len = s.actions.list.step_count(idx).saturating_add(pending_steps(s, idx).count());
let len = s.actions().list.step_count(idx).saturating_add(pending_steps(s, idx).count());
if step.is_some_and(|step| step >= len) {
return Err(bad(cmd, "step is out of range"));
}
if s.actions.recording.is_some_and(|(_, i)| i == idx) {
if s.recording.target.is_some_and(|(_, i)| i == idx) {
flush_recording(s)?;
}
let action = &s.actions.list.actions()[idx];
let action = &s.actions().list.actions()[idx];
// One step, or every step: on unless all already are.
let edits: Vec<(usize, bool)> = match step {
Some(step) => vec![(step, enabled.unwrap_or(!action.dialogs.contains(&step)))],
@@ -203,31 +205,31 @@ fn dialog(s: &mut Session, p: &Value) -> Result<Value> {
}
};
for (step, on) in edits {
s.actions.list.set_dialog(idx, step, on).map_err(|e| list_error(cmd, e))?;
s.actions_mut().list.set_dialog(idx, step, on).map_err(|e| list_error(cmd, e))?;
}
let action = &s.actions.list.actions()[idx];
let action = &s.actions().list.actions()[idx];
Ok(json!({"action": action.name, "dialogs": action.dialogs}))
}
fn assign_set(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "actions.assignSet";
not_playing(s, cmd)?;
let idx = resolve(s.actions.list.actions(), p, cmd)?;
let idx = resolve(s.actions().list.actions(), p, cmd)?;
let set = match p.get("set") {
None | Some(Value::Null) => None,
Some(Value::String(n)) if !n.trim().is_empty() => Some(n.trim().to_string()),
Some(Value::String(_)) => return Err(bad(cmd, "`set` is empty; pass null to take the action out of its set")),
Some(_) => return Err(bad(cmd, "`set` must be a name or null")),
};
s.actions.list.assign_set(idx, set).map_err(|e| list_error(cmd, e))?;
let action = &s.actions.list.actions()[idx];
s.actions_mut().list.assign_set(idx, set).map_err(|e| list_error(cmd, e))?;
let action = &s.actions().list.actions()[idx];
Ok(json!({"action": action.name, "set": action.set}))
}
/// Every set name, in the Actions panel's order: the sets of the actions as they first appear,
/// then the empty ones New Set made.
pub fn set_names(s: &Session) -> Vec<String> {
s.actions.list.sets().into_iter().map(str::to_owned).collect()
s.actions().list.sets().into_iter().map(str::to_owned).collect()
}
/// New Set…: an empty set folder, named `name` or "Set N" (the first number no set has), that New
@@ -245,7 +247,7 @@ fn new_set(s: &mut Session, p: &Value) -> Result<Value> {
if names.contains(&name) {
return Err(bad(cmd, format!("a set named `{name}` already exists")));
}
s.actions.list.new_set(&name).map_err(|e| list_error(cmd, e))?;
s.actions_mut().list.new_set(&name).map_err(|e| list_error(cmd, e))?;
Ok(json!({"set": name}))
}
@@ -505,11 +507,12 @@ pub fn specs() -> Vec<CommandSpec> {
mod tests {
use super::*;
use crate::actions_cmds::Action;
use crate::actions_cmds::ActionsExt;
fn session_with(steps: &[&str]) -> Session {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
s.actions.list.push(Action::new("A", steps.iter().map(|id| ActionStep::new(*id, json!({}))).collect())).unwrap();
s.actions_mut().list.push(Action::new("A", steps.iter().map(|id| ActionStep::new(*id, json!({}))).collect())).unwrap();
s
}
@@ -522,14 +525,14 @@ mod tests {
.execute("actions.insert", json!({"action": "A", "at": 1, "id": "actions.stopMessage", "params": {"message": "Check", "allowContinue": true}}))
.unwrap();
assert_eq!((r["step"].as_u64(), r["steps"].as_u64()), (Some(1), Some(4)));
let a = &s.actions.list.actions()[0];
let a = &s.actions().list.actions()[0];
assert_eq!(a.steps[1], ActionStep::new("actions.stopMessage", json!({"message": "Check", "allowContinue": true})));
assert_eq!(a.disabled.iter().copied().collect::<Vec<_>>(), [2], "the switched-off step moved down one");
assert_eq!(a.dialogs.iter().copied().collect::<Vec<_>>(), [1, 3], "the inserted Stop's dialog is on; the old toggle moved down one");
// Default position: the end. A bare id works for a parameterless command.
let r = s.execute("actions.insert", json!({"action": 0, "id": "layer.new.layer"})).unwrap();
assert_eq!(r["step"], 4);
assert_eq!(s.actions.list.actions()[0].steps[4].command, "layer.new.layer");
assert_eq!(s.actions().list.actions()[0].steps[4].command, "layer.new.layer");
// Playback runs the inserted stop and continues past it.
let played = s.execute("actions.play", json!({"action": "A"})).unwrap();
assert_eq!(played["ran"], 4, "{played}");
@@ -544,7 +547,7 @@ mod tests {
s.execute("actions.insert", json!({"action": "A", "at": 0, "id": "select.all"})).unwrap();
s.execute("layer.new.layer", json!({"name": "Two"})).unwrap();
s.execute("actions.stop", json!({})).unwrap();
let ids: Vec<&str> = s.actions.list.actions()[0].steps.iter().map(|step| step.command.as_str()).collect();
let ids: Vec<&str> = s.actions().list.actions()[0].steps.iter().map(|step| step.command.as_str()).collect();
assert_eq!(ids, ["select.all", "layer.new.layer", "layer.new.layer"]);
}
@@ -560,14 +563,14 @@ mod tests {
assert_eq!(s.execute("actions.get", json!({"action": "A"})).unwrap()["dialogs"], json!([0, 1]));
// Deleting a step keeps the flags of the others in place.
s.execute("actions.delete", json!({"action": "A", "step": 0})).unwrap();
assert_eq!(s.actions.list.actions()[0].dialogs.iter().copied().collect::<Vec<_>>(), [0]);
assert_eq!(s.actions().list.actions()[0].dialogs.iter().copied().collect::<Vec<_>>(), [0]);
}
#[test]
fn conditional_tests_the_document_and_plays_a_branch() {
let mut s = session_with(&[]);
s.actions.list.push(Action::new("Yes", vec![ActionStep::new("layer.new.layer", json!({"name": "yes"}))])).unwrap();
s.actions.list.push(Action::new("No", vec![ActionStep::new("layer.new.layer", json!({"name": "no"}))])).unwrap();
s.actions_mut().list.push(Action::new("Yes", vec![ActionStep::new("layer.new.layer", json!({"name": "yes"}))])).unwrap();
s.actions_mut().list.push(Action::new("No", vec![ActionStep::new("layer.new.layer", json!({"name": "no"}))])).unwrap();
let names = |s: &Session| s.active().unwrap().doc.walk().iter().map(|(_, _, l)| l.name.clone()).collect::<Vec<_>>();
// 8 × 8: square, not landscape; one Background: no layers yet.
for (cond, expect) in [
@@ -601,11 +604,11 @@ mod tests {
let r = s.execute("actions.conditional", json!({"if": "landscape", "then": "Yes"})).unwrap();
assert!(r["played"].is_null());
// A failing branch reports like a nested Play, and stops a calling action.
s.actions.list.push(Action::new("Bad", vec![ActionStep::new("layer.delete", json!({"layer": 999}))])).unwrap();
s.actions_mut().list.push(Action::new("Bad", vec![ActionStep::new("layer.delete", json!({"layer": 999}))])).unwrap();
let r = s.execute("actions.conditional", json!({"if": "always", "then": "Bad"})).unwrap();
assert!(r["failed"].is_object(), "{r}");
assert!(crate::actions_cmds::nested_failure("actions.conditional", &r).is_some());
s.actions
s.actions_mut()
.list
.push(Action::new(
"Caller",
@@ -619,7 +622,7 @@ mod tests {
assert_eq!(played["failed"]["step"], 0, "{played}");
assert_ne!(names(&s).last().map(String::as_str), Some("after"));
// Without a document only always/never answer; layer conditions are false.
let t = Session::new();
let t = crate::session();
assert!(evaluate(&t, "always").unwrap());
assert!(!evaluate(&t, "isOpen").unwrap());
assert!(!evaluate(&t, "isBackground").unwrap());
@@ -648,7 +651,7 @@ mod tests {
let r = s.execute("actions.record", json!({"set": "Retouch"})).unwrap();
s.execute("actions.stop", json!({})).unwrap();
let i = r["index"].as_u64().unwrap() as usize;
assert_eq!(s.actions.list.actions()[i].set.as_deref(), Some("Retouch"));
assert_eq!(s.actions().list.actions()[i].set.as_deref(), Some("Retouch"));
assert_eq!(set_names(&s), ["Set 1", "Retouch", "Set 2"], "Retouch now holds an action");
assert!(s.execute("actions.record", json!({"set": 3})).is_err());
}
@@ -657,16 +660,16 @@ mod tests {
fn assign_set_moves_an_action_between_folders() {
let mut s = session_with(&["select.all"]);
assert_eq!(s.execute("actions.assignSet", json!({"action": "A", "set": " Retouch "})).unwrap()["set"], "Retouch");
assert_eq!(s.actions.list.actions()[0].set.as_deref(), Some("Retouch"));
assert_eq!(s.actions().list.actions()[0].set.as_deref(), Some("Retouch"));
assert_eq!(s.execute("actions.list", json!({})).unwrap()["actions"][0]["set"], "Retouch");
assert_eq!(s.execute("actions.assignSet", json!({"action": 0, "set": null})).unwrap()["set"], Value::Null);
assert_eq!(s.actions.list.actions()[0].set, None);
assert_eq!(s.actions().list.actions()[0].set, None);
}
#[test]
fn bad_params_fail_gracefully() {
let mut s = session_with(&["select.all"]);
let before = s.actions.list.clone();
let before = s.actions().list.clone();
for p in [
json!({}),
json!({"action": "A"}),
@@ -689,17 +692,17 @@ mod tests {
for p in [json!({}), json!({"action": "A", "set": ""}), json!({"action": "A", "set": 7}), json!({"action": "B", "set": "S"})] {
assert!(s.execute("actions.assignSet", p.clone()).is_err(), "{p}");
}
assert_eq!(s.actions.list, before, "rejected edits change nothing");
assert_eq!(s.actions().list, before, "rejected edits change nothing");
// Nothing edits during playback.
s.actions.list.push(Action::new("Loop", vec![ActionStep::new("actions.insert", json!({"action": "A", "id": "select.all"}))])).unwrap();
s.actions_mut().list.push(Action::new("Loop", vec![ActionStep::new("actions.insert", json!({"action": "A", "id": "select.all"}))])).unwrap();
let played = s.execute("actions.play", json!({"action": "Loop"})).unwrap();
assert!(played["failed"]["error"].as_str().unwrap().contains("playback"), "{played}");
}
fn record_conditional(width: u32, height: u32) -> (Session, usize) {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": width, "height": height})).unwrap();
s.actions.list.push(Action::new("Tall", vec![ActionStep::new("layer.new.layer", json!({"name": "Tall"}))])).unwrap();
s.actions_mut().list.push(Action::new("Tall", vec![ActionStep::new("layer.new.layer", json!({"name": "Tall"}))])).unwrap();
let layers = s.active().unwrap().doc.walk().len();
s.execute("actions.record", json!({"name": "Parent"})).unwrap();
s.execute("actions.conditional", json!({"if": "portrait", "then": "Tall", "else": null})).unwrap();
@@ -708,7 +711,7 @@ mod tests {
}
fn parent_steps(s: &Session) -> Vec<ActionStep> {
s.actions.list.actions().iter().find(|a| a.name == "Parent").unwrap().steps.clone()
s.actions().list.actions().iter().find(|a| a.name == "Parent").unwrap().steps.clone()
}
#[test]
@@ -5,12 +5,14 @@
//! The engine keeps what lies outside the list: the action shortcuts before and after, and where
//! each document's history stood, so Edit › Undo offers the library undo only while no document
//! edit came after it.
use crate::actions_cmds::ActionsExt;
use std::collections::BTreeMap;
use craft::automation::actions::{ActionList, ActionListError, LibraryEdit};
use serde_json::{Value, json};
use crate::actions_cmds::{Action, ActionStep, ActionsFile, is_action_key, list_error, not_playing};
use crate::preset_store::PresetStoreExt;
use crate::{Result, Session};
use super::bad;
@@ -44,7 +46,7 @@ pub(crate) fn enabled(s: &Session) -> std::result::Result<(), String> {
fn idle(s: &Session, cmd: &str) -> Result<()> {
not_playing(s, cmd)?;
if s.actions.recording.is_some() {
if s.recording.target.is_some() {
return Err(bad(cmd, "stop recording before changing the Actions library"));
}
Ok(())
@@ -85,7 +87,7 @@ fn check_library_size(list: &ActionList, cmd: &str) -> Result<()> {
/// save it, then makes it the list and keeps what its undo restores outside the list.
/// `shortcuts` replaces every action shortcut (`None` keeps them).
pub(crate) fn publish_library<R>(s: &mut Session, cmd: &str, shortcuts: Option<Shortcuts>, edit: impl FnOnce(&mut ActionList) -> R) -> Result<R> {
let mut list = s.actions.list.clone();
let mut list = s.actions().list.clone();
let result = edit(&mut list);
let kind = list.library_undo().ok_or_else(|| bad(cmd, "not an Actions library command"))?;
check_library_size(&list, cmd)?;
@@ -110,24 +112,24 @@ pub(crate) fn publish_library<R>(s: &mut Session, cmd: &str, shortcuts: Option<S
alternates: before.1,
after_shortcuts: after.0,
after_alternates: after.1,
replaced_before_attachment: s.actions.replaced_before_attachment,
replaced_before_attachment: s.actions().replaced_before_attachment,
};
if replacing && s.preset_store.is_none() {
s.actions.replaced_before_attachment = true;
if replacing && s.preset_store().is_none() {
s.actions_mut().replaced_before_attachment = true;
}
s.actions.list = list;
s.actions.library_undo = Some(Box::new(undo));
s.actions_mut().list = list;
s.actions_mut().library_undo = Some(Box::new(undo));
Ok(result)
}
pub(super) fn clear(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "actions.clearAll";
confirmed_idle(s, p, CMD)?;
let count = s.actions.list.actions().len();
let count = s.actions().list.actions().len();
let prefs = s.prefs();
let keys = prefs.shortcuts.keys().chain(prefs.alternate_shortcuts.keys()).any(|id| is_action_key(id));
// Before the store attaches, an empty list still clears the stored library.
if count != 0 || !s.actions.list.sets().is_empty() || keys || (s.preset_store.is_none() && !s.actions.replaced_before_attachment) {
if count != 0 || !s.actions().list.sets().is_empty() || keys || (s.preset_store().is_none() && !s.actions().replaced_before_attachment) {
publish_library(s, CMD, Some(Shortcuts::new()), ActionList::clear_all)?;
}
Ok(json!({"cleared": count}))
@@ -151,10 +153,10 @@ pub(super) fn reset(s: &mut Session, p: &Value) -> Result<Value> {
_ => return Err(bad(CMD, "`mode` must be append or replace")),
};
// Appended beside a set of that name, the defaults get a set of their own (`PhotoCraft Basics 2`).
let set = if append { crate::preset_import_cmds::UniqueNames::new_exact(s.actions.list.sets()).unique(BASICS_SET) } else { BASICS_SET.to_owned() };
let set = if append { crate::preset_import_cmds::UniqueNames::new_exact(s.actions().list.sets()).unique(BASICS_SET) } else { BASICS_SET.to_owned() };
let defaults = basics(&set);
let merged = publish_library(s, CMD, (!append).then(Shortcuts::new), |list| list.reset(defaults, append, |_, _| {}))?;
let names: Vec<&str> = merged.added.iter().map(|&index| s.actions.list.actions()[index].name.as_str()).collect();
let names: Vec<&str> = merged.added.iter().map(|&index| s.actions().list.actions()[index].name.as_str()).collect();
Ok(json!({"set": set, "appended": append, "actions": names}))
}
@@ -171,10 +173,10 @@ fn undo_state(s: &Session) -> Result<&LibraryUndo> {
const CMD: &str = "actions.undoLibrary";
idle(s, CMD)?;
let undo = s
.actions
.actions()
.library_undo
.as_deref()
.filter(|undo| s.actions.list.library_undo() == Some(undo.edit))
.filter(|undo| s.actions().list.library_undo() == Some(undo.edit))
.ok_or_else(|| list_error(CMD, ActionListError::NothingToUndo))?;
if action_bindings(&s.prefs().shortcuts) != undo.after_shortcuts || action_bindings(&s.prefs().alternate_shortcuts) != undo.after_alternates {
return Err(bad(CMD, "Actions shortcuts changed after the library edit"));
@@ -202,10 +204,10 @@ pub(super) fn undo_enabled(s: &Session) -> std::result::Result<(), String> {
pub(super) fn undo(s: &mut Session, _: &Value) -> Result<Value> {
const CMD: &str = "actions.undoLibrary";
undo_state(s)?;
let undo = s.actions.library_undo.take().ok_or_else(|| list_error(CMD, ActionListError::NothingToUndo))?;
s.actions.list.undo_library().map_err(|error| list_error(CMD, error))?;
if s.preset_store.is_none() {
s.actions.replaced_before_attachment = undo.replaced_before_attachment;
let undo = s.actions_mut().library_undo.take().ok_or_else(|| list_error(CMD, ActionListError::NothingToUndo))?;
s.actions_mut().list.undo_library().map_err(|error| list_error(CMD, error))?;
if s.preset_store().is_none() {
s.actions_mut().replaced_before_attachment = undo.replaced_before_attachment;
}
replace_bindings(s, undo.shortcuts, undo.alternates);
Ok(json!({"undone": true}))
@@ -1,12 +1,14 @@
use crate::Session;
use crate::actions_cmds::ActionsExt;
use crate::actions_cmds::{Action, ActionStep, PLAY_SHORTCUT_PREFIX};
use crate::preset_store::PresetStoreExt;
use crate::preset_store::{ACTIONS_FILE, MemBackend, PresetBackend, open};
use craft_psd::atn::{AtnAction, AtnFile, write};
use craft_psd::descriptor::UnicodeString;
use serde_json::json;
fn names(s: &Session) -> Vec<&str> {
s.actions.list.actions().iter().map(|action| action.name.as_str()).collect()
s.actions().list.actions().iter().map(|action| action.name.as_str()).collect()
}
fn b64(bytes: &[u8]) -> String {
@@ -29,32 +31,32 @@ fn set(caption: &str, action: Option<(&str, u16)>) -> Vec<u8> {
#[test]
fn confirmed_clear_restores_both_shortcut_maps_without_document_history() {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width":8,"height":8})).unwrap();
s.actions.list.push(Action::new("Original", Vec::new())).unwrap();
s.actions.list.new_set("Empty").unwrap();
s.actions_mut().list.push(Action::new("Original", Vec::new())).unwrap();
s.actions_mut().list.new_set("Empty").unwrap();
let shortcut = format!("{PLAY_SHORTCUT_PREFIX}Original");
s.edit_prefs(|prefs| {
prefs.shortcuts.insert(shortcut.clone(), "F2".into());
prefs.alternate_shortcuts.insert(shortcut.clone(), vec!["F3".into()]);
prefs.shortcuts.insert("file.save".into(), "Ctrl+S".into());
});
let revision = s.actions.list.revision();
let revision = s.actions().list.revision();
let history = s.active().unwrap().history.past_len();
assert!(s.execute("actions.clearAll", json!({"confirm":false})).is_err());
assert_eq!(s.actions.list.revision(), revision);
assert_eq!(s.actions().list.revision(), revision);
s.execute("actions.record", json!({"action":0})).unwrap();
assert!(s.execute("actions.clearAll", json!({"confirm":true})).is_err());
s.execute("actions.stop", json!({})).unwrap();
assert_eq!(s.execute("actions.clearAll", json!({"confirm":true})).unwrap()["cleared"], 1);
assert!(s.actions.list.actions().is_empty() && s.actions.list.sets().is_empty());
assert!(s.actions().list.actions().is_empty() && s.actions().list.sets().is_empty());
assert!(!s.prefs().shortcuts.contains_key(&shortcut));
assert!(!s.prefs().alternate_shortcuts.contains_key(&shortcut));
assert_eq!(s.prefs().shortcuts["file.save"], "Ctrl+S");
assert_eq!(crate::actions_edit_cmds::undo_library_label(&s), Some("Undo Clear All Actions"));
s.execute("actions.undoLibrary", json!({})).unwrap();
assert_eq!(names(&s), ["Original"]);
assert_eq!(s.actions.list.sets(), ["Empty"]);
assert_eq!(s.actions().list.sets(), ["Empty"]);
assert_eq!(s.prefs().shortcuts[&shortcut], "F2");
assert_eq!(s.prefs().alternate_shortcuts[&shortcut], ["F3"]);
assert_eq!(s.active().unwrap().history.past_len(), history);
@@ -64,7 +66,7 @@ fn confirmed_clear_restores_both_shortcut_maps_without_document_history() {
// An edit after a library command ends its undo; so does a change to the action shortcuts.
#[test]
fn any_later_edit_ends_the_library_undo() {
let mut s = Session::new();
let mut s = crate::session();
s.execute("actions.reset", json!({"confirm":true,"mode":"replace"})).unwrap();
s.execute("actions.newSet", json!({"name":"Later"})).unwrap();
assert!(s.execute("actions.undoLibrary", json!({})).is_err());
@@ -76,33 +78,33 @@ fn any_later_edit_ends_the_library_undo() {
#[test]
fn reset_appends_a_numbered_set_and_persists_it() {
let store = MemBackend::default();
let mut s = Session::new();
let mut s = crate::session();
s.attach_preset_store(open(Box::new(store.clone())));
s.actions.list.new_set("Existing").unwrap();
s.actions_mut().list.new_set("Existing").unwrap();
assert!(s.execute("actions.reset", json!({"confirm":true,"mode":"bad"})).is_err());
assert_eq!(s.execute("actions.reset", json!({"confirm":true,"mode":"append"})).unwrap()["set"], "PhotoCraft Basics");
assert_eq!(s.execute("actions.reset", json!({"confirm":true,"mode":"append"})).unwrap()["set"], "PhotoCraft Basics 2");
assert_eq!(s.actions.list.sets(), ["PhotoCraft Basics", "PhotoCraft Basics 2", "Existing"]);
assert_eq!(s.actions().list.sets(), ["PhotoCraft Basics", "PhotoCraft Basics 2", "Existing"]);
assert_eq!(names(&s), ["Invert Colors", "Desaturate", "Invert Colors 2", "Desaturate 2"]);
assert_eq!(s.actions.list.actions()[0].steps[0].command, "image.adjustments.invert");
assert_eq!(s.actions.list.actions()[1].steps[0].command, "image.adjustments.desaturate");
assert_eq!(s.actions().list.actions()[0].steps[0].command, "image.adjustments.invert");
assert_eq!(s.actions().list.actions()[1].steps[0].command, "image.adjustments.desaturate");
s.sync_preset_store();
let mut reopened = Session::new();
let mut reopened = crate::session();
reopened.attach_preset_store(open(Box::new(store)));
assert_eq!(reopened.actions.list.actions(), s.actions.list.actions());
assert_eq!(reopened.actions.list.sets(), s.actions.list.sets());
assert_eq!(reopened.actions().list.actions(), s.actions().list.actions());
assert_eq!(reopened.actions().list.sets(), s.actions().list.sets());
s.execute("actions.reset", json!({"confirm":true,"mode":"replace"})).unwrap();
assert_eq!(s.actions.list.sets(), ["PhotoCraft Basics"]);
assert_eq!(s.actions().list.sets(), ["PhotoCraft Basics"]);
s.execute("actions.undoLibrary", json!({})).unwrap();
assert_eq!(s.actions.list.sets(), reopened.actions.list.sets());
assert_eq!(s.actions().list.sets(), reopened.actions().list.sets());
assert!(s.execute("actions.undoLibrary", json!({})).is_err());
}
#[test]
fn whole_replace_validates_the_tail_and_keeps_every_set_in_order() {
let mut s = Session::new();
let mut s = crate::session();
s.execute("actions.reset", json!({"confirm":true,"mode":"append"})).unwrap();
let prior = s.actions.list.actions().to_vec();
let prior = s.actions().list.actions().to_vec();
let mut archive = set("Repeated", Some(("Action", 2)));
archive.extend_from_slice(&set("Empty", None)[4..]);
archive.extend_from_slice(&set("Repeated", Some(("Action", 3)))[4..]);
@@ -110,10 +112,10 @@ fn whole_replace_validates_the_tail_and_keeps_every_set_in_order() {
bad.pop();
assert!(s.execute("actions.replace", json!({"confirm":true,"data":b64(&bad)})).is_err());
assert!(s.execute("actions.replace", json!({"data":b64(&archive)})).is_err());
assert_eq!(s.actions.list.actions(), prior);
assert_eq!(s.actions().list.actions(), prior);
let result = s.execute("actions.replace", json!({"confirm":true,"data":b64(&archive)})).unwrap();
assert_eq!(result["sets"], json!(["Repeated", "Empty", "Repeated 2"]));
assert_eq!(s.actions.list.sets(), ["Repeated", "Repeated 2", "Empty"]);
assert_eq!(s.actions().list.sets(), ["Repeated", "Repeated 2", "Empty"]);
assert_eq!(names(&s), ["Action", "Action 2"]);
assert_eq!(s.prefs().shortcuts[&format!("{PLAY_SHORTCUT_PREFIX}Action")], "F2");
assert_eq!(s.prefs().shortcuts[&format!("{PLAY_SHORTCUT_PREFIX}Action 2")], "F3");
@@ -123,13 +125,13 @@ fn whole_replace_validates_the_tail_and_keeps_every_set_in_order() {
assert!(empty["actions"].as_array().unwrap().is_empty());
assert_eq!(crate::actions_edit_cmds::undo_library_label(&s), Some("Undo Replace Actions"));
s.execute("actions.undoLibrary", json!({})).unwrap();
assert_eq!(s.actions.list.actions(), prior);
assert_eq!(s.actions().list.actions(), prior);
}
// Two actions one set gives the same name keep their own function keys.
#[test]
fn atn_load_keeps_function_keys_of_repeated_names_separate() {
let mut s = Session::new();
let mut s = crate::session();
let result = s.execute("actions.load", json!({"data":b64(&set_of("Keys", &[("Same", 2), ("Same", 3)]))})).unwrap();
assert_eq!(result["functionKeys"], json!([{"action":"Same","key":"F2"},{"action":"Same 2","key":"F3"}]));
assert_eq!(s.prefs().shortcuts[&format!("{PLAY_SHORTCUT_PREFIX}Same")], "F2");
@@ -139,7 +141,7 @@ fn atn_load_keeps_function_keys_of_repeated_names_separate() {
/// Imported calls look in their own set before falling back to the first archive name.
#[test]
fn whole_replace_resolves_unqualified_calls_in_their_own_set() {
let mut s = Session::new();
let mut s = crate::session();
let mut archive = set("Repeated", Some(("Child", 0)));
let child = Action::new("Child", Vec::new());
let parent = Action::new("Parent", vec![ActionStep::new("actions.play", json!({"action":"Child"}))]);
@@ -147,7 +149,7 @@ fn whole_replace_resolves_unqualified_calls_in_their_own_set() {
archive.extend_from_slice(&second[4..]);
s.execute("actions.replace", json!({"confirm":true,"data":b64(&archive)})).unwrap();
assert_eq!(names(&s), ["Child", "Child 2", "Parent"]);
assert_eq!(s.actions.list.actions()[2].steps[0].params["action"], "Child 2");
assert_eq!(s.actions().list.actions()[2].steps[0].params["action"], "Child 2");
}
// A call that names its action's set reaches that set's action, renamed or not, and names the set
@@ -166,10 +168,10 @@ fn whole_replace_follows_explicit_atn_set_scopes() {
let mut archive = set("First", Some(("Target", 0)));
let (tail, _) = crate::atn_cmds::export("Second", &[&second, &caller], &[], false).unwrap();
archive.extend_from_slice(&tail[4..]);
let mut s = Session::new();
let mut s = crate::session();
let result = s.execute("actions.replace", json!({"confirm":true,"data":b64(&archive)})).unwrap();
assert_eq!(result["actions"], json!(["Target", "Target 2", "Caller"]));
let list = s.actions.list.actions();
let list = s.actions().list.actions();
let calls: Vec<&serde_json::Value> = list[2].steps.iter().map(|step| &step.params).collect();
assert_eq!((calls[0]["action"].as_str(), calls[0]["set"].as_str()), (Some("Target 2"), Some("Second")));
assert_eq!(crate::file_cmds::batch_action(list, calls[0]).unwrap(), 1);
@@ -187,7 +189,7 @@ fn whole_replace_keeps_diagnostics_on_their_archive_actions() {
let mut archive = set("First", Some(("Target", 0)));
let (tail, _) = crate::atn_cmds::export("Second", &[&first, &second], &[], false).unwrap();
archive.extend_from_slice(&tail[4..]);
let mut s = Session::new();
let mut s = crate::session();
let result = s.execute("actions.replace", json!({"confirm":true,"data":b64(&archive)})).unwrap();
assert_eq!(result["actions"], json!(["Target", "Target 2", "Target 3"]));
assert_eq!(result["unsupported"].as_array().unwrap().len(), 1);
@@ -199,7 +201,7 @@ fn whole_replace_keeps_diagnostics_on_their_archive_actions() {
#[test]
fn shortcut_only_clear_restores_orphan_bindings_on_undo() {
let mut s = Session::new();
let mut s = crate::session();
let orphan = "actions.play:Missing";
s.edit_prefs(|prefs| {
prefs.shortcuts.insert(orphan.into(), "F2".into());
@@ -212,7 +214,7 @@ fn shortcut_only_clear_restores_orphan_bindings_on_undo() {
assert!(!s.prefs().alternate_shortcuts.contains_key(orphan));
assert_eq!(s.prefs().alternate_shortcuts["file.save"], ["F4"]);
s.execute("actions.undoLibrary", json!({})).unwrap();
assert!(s.actions.list.actions().is_empty());
assert!(s.actions().list.actions().is_empty());
assert_eq!(s.prefs().shortcuts[orphan], "F2");
assert_eq!(s.prefs().alternate_shortcuts[orphan], ["F3"]);
}
@@ -222,8 +224,8 @@ fn pre_attachment_replacement_persists_without_reloading_disk_and_keeps_undo() {
for undo_before_attachment in [false, true] {
let store = MemBackend::default();
store.write(ACTIONS_FILE, br#"{"version":1,"actions":[{"name":"Disk","set":"Saved"}]}"#).unwrap();
let mut s = Session::new();
s.actions.list.push(Action::new("Early", Vec::new())).unwrap();
let mut s = crate::session();
s.actions_mut().list.push(Action::new("Early", Vec::new())).unwrap();
s.execute("actions.reset", json!({"confirm":true,"mode":"replace"})).unwrap();
if undo_before_attachment {
s.execute("actions.undoLibrary", json!({})).unwrap();
@@ -234,17 +236,17 @@ fn pre_attachment_replacement_persists_without_reloading_disk_and_keeps_undo() {
continue;
}
assert_eq!(s.actions.list.sets(), ["PhotoCraft Basics"]);
assert_eq!(s.actions().list.sets(), ["PhotoCraft Basics"]);
assert_eq!(names(&s), ["Invert Colors", "Desaturate"]);
let mut reopened = Session::new();
let mut reopened = crate::session();
assert!(reopened.attach_preset_store(open(Box::new(store.clone()))).is_empty());
assert_eq!(reopened.actions.list.actions(), s.actions.list.actions());
assert_eq!(reopened.actions().list.actions(), s.actions().list.actions());
s.execute("actions.undoLibrary", json!({})).unwrap();
assert_eq!(names(&s), ["Early"]);
s.sync_preset_store();
let mut reopened = Session::new();
let mut reopened = crate::session();
assert!(reopened.attach_preset_store(open(Box::new(store))).is_empty());
assert_eq!(reopened.actions.list.actions(), s.actions.list.actions());
assert_eq!(reopened.actions().list.actions(), s.actions().list.actions());
}
}
@@ -252,17 +254,17 @@ fn pre_attachment_replacement_persists_without_reloading_disk_and_keeps_undo() {
fn pre_attachment_clear_remains_authoritative_after_an_ordinary_edit() {
let store = MemBackend::default();
store.write(ACTIONS_FILE, br#"{"version":1,"actions":[{"name":"Disk"}]}"#).unwrap();
let mut s = Session::new();
s.actions.list.push(Action::new("Early", Vec::new())).unwrap();
let mut s = crate::session();
s.actions_mut().list.push(Action::new("Early", Vec::new())).unwrap();
s.execute("actions.clearAll", json!({"confirm":true})).unwrap();
s.execute("actions.newSet", json!({"name":"New"})).unwrap();
assert!(s.attach_preset_store(open(Box::new(store.clone()))).is_empty());
assert!(s.actions.list.actions().is_empty());
assert_eq!(s.actions.list.sets(), ["New"]);
let mut reopened = Session::new();
assert!(s.actions().list.actions().is_empty());
assert_eq!(s.actions().list.sets(), ["New"]);
let mut reopened = crate::session();
assert!(reopened.attach_preset_store(open(Box::new(store))).is_empty());
assert!(reopened.actions.list.actions().is_empty());
assert_eq!(reopened.actions.list.sets(), ["New"]);
assert!(reopened.actions().list.actions().is_empty());
assert_eq!(reopened.actions().list.sets(), ["New"]);
}
#[test]
@@ -270,18 +272,18 @@ fn empty_pre_attachment_clear_replaces_the_saved_library() {
for undo in [false, true] {
let store = MemBackend::default();
store.write(ACTIONS_FILE, br#"{"version":1,"actions":[{"name":"Disk"}]}"#).unwrap();
let mut s = Session::new();
let mut s = crate::session();
assert_eq!(s.execute("actions.clearAll", json!({"confirm":true})).unwrap()["cleared"], 0);
let revision = s.actions.list.revision();
let revision = s.actions().list.revision();
assert_eq!(s.execute("actions.clearAll", json!({"confirm":true})).unwrap()["cleared"], 0);
assert_eq!(s.actions.list.revision(), revision, "a second empty clear keeps the first undo");
assert_eq!(s.actions().list.revision(), revision, "a second empty clear keeps the first undo");
if undo {
s.execute("actions.undoLibrary", json!({})).unwrap();
}
assert!(s.attach_preset_store(open(Box::new(store.clone()))).is_empty());
assert_eq!(s.actions.list.actions().first().map(|action| action.name.as_str()), undo.then_some("Disk"));
let mut reopened = Session::new();
assert_eq!(s.actions().list.actions().first().map(|action| action.name.as_str()), undo.then_some("Disk"));
let mut reopened = crate::session();
assert!(reopened.attach_preset_store(open(Box::new(store))).is_empty());
assert_eq!(reopened.actions.list.actions(), s.actions.list.actions());
assert_eq!(reopened.actions().list.actions(), s.actions().list.actions());
}
}
@@ -1,5 +1,6 @@
//! Record Again executes the selected command before replacing its stored settings.
use super::{Result, Session, Value, bad, index, json, not_playing, resolve};
use crate::actions_cmds::ActionsExt;
use crate::actions_cmds::{ActionStep, list_error};
const COMMAND: &str = "actions.recordAgain";
@@ -15,19 +16,19 @@ pub struct RecordAgainTarget {
/// Resolve only executable steps, without flushing recording or editing the library.
pub fn target(s: &Session, p: &Value) -> Result<RecordAgainTarget> {
not_playing(s, COMMAND)?;
if s.actions.recording.is_some() {
if s.recording.target.is_some() {
return Err(bad(COMMAND, "stop recording before recording a step again"));
}
if let Some(revision) = p.get("revision") {
let revision = revision.as_u64().ok_or_else(|| bad(COMMAND, "`revision` must be an unsigned integer"))?;
if revision != s.actions.list.revision() {
if revision != s.actions().list.revision() {
return Err(bad(COMMAND, "the actions changed; select the step again"));
}
}
let action = resolve(s.actions.list.actions(), p, COMMAND)?;
let action = resolve(s.actions().list.actions(), p, COMMAND)?;
let step = index(p, "step", COMMAND)?.ok_or_else(|| bad(COMMAND, "select a step"))?;
let ActionStep { command: id, params } =
s.actions.list.action(action).and_then(|a| a.steps.get(step)).ok_or_else(|| bad(COMMAND, "step is out of range"))?;
s.actions().list.action(action).and_then(|a| a.steps.get(step)).ok_or_else(|| bad(COMMAND, "step is out of range"))?;
let (command, params) =
if id == crate::atn_cmds::MENU_ITEM { (crate::atn_cmds::menu_item_command(params)?.to_string(), json!({})) } else { (id.clone(), params.clone()) };
if command.starts_with("actions.") || !crate::commands::find(&command).is_some_and(|c| c.journal) {
@@ -41,15 +42,15 @@ pub(super) fn run(s: &mut Session, p: &Value) -> Result<Value> {
let selected = target(s, p)?;
let params = p.get("params").filter(|p| p.is_object()).cloned().ok_or_else(|| bad(COMMAND, "supply the step's new settings in `params`"))?;
let original =
s.actions.list.action(selected.action).and_then(|a| a.steps.get(selected.step)).cloned().ok_or_else(|| bad(COMMAND, "step is out of range"))?;
let revision = s.actions.list.revision();
s.actions().list.action(selected.action).and_then(|a| a.steps.get(selected.step)).cloned().ok_or_else(|| bad(COMMAND, "step is out of range"))?;
let revision = s.actions().list.revision();
// Resolve portable recorded targets for execution; keep their portable form in the step.
let resolved = crate::actions_cmds::playback_params(s, &selected.command, &params)?;
let result = s.execute(&selected.command, resolved)?;
if s.actions.list.revision() != revision || s.actions.list.action(selected.action).and_then(|a| a.steps.get(selected.step)) != Some(&original) {
if s.actions().list.revision() != revision || s.actions().list.action(selected.action).and_then(|a| a.steps.get(selected.step)) != Some(&original) {
return Err(bad(COMMAND, "the action changed during execution; its step was not overwritten"));
}
s.actions.list.replace_step(selected.action, selected.step, ActionStep::new(selected.command.clone(), params)).map_err(|e| list_error(COMMAND, e))?;
let name = s.actions.list.actions()[selected.action].name.clone();
s.actions_mut().list.replace_step(selected.action, selected.step, ActionStep::new(selected.command.clone(), params)).map_err(|e| list_error(COMMAND, e))?;
let name = s.actions().list.actions()[selected.action].name.clone();
Ok(json!({"action": name, "step": selected.step, "id": selected.command, "result": result}))
}
@@ -221,7 +221,7 @@ mod tests {
/// A matching opaque default cannot allocate gap tiles beyond the existing adjustment budget.
#[test]
fn opaque_gap_budget_refuses_before_pixel_allocation_or_edit() {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", serde_json::json!({"width":4,"height":2,"mode":"lab","depth":32,"background":"transparent"})).unwrap();
s.edit("Distant opaque exception", |doc, active| {
let surface = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
@@ -248,7 +248,7 @@ mod tests {
#[test]
fn lab_bounds_refuse_subtracted_samples_and_click_order() {
for extra in [serde_json::json!({"subtractPoints": [[1, 1]]}), serde_json::json!({"order": ["+", "-"]}), serde_json::json!({"subtractPoints": []})] {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", serde_json::json!({"width": 4, "height": 2})).unwrap();
let before = s.active().unwrap().doc.clone();
let mut p = serde_json::json!({"labMinimum": [0, -10, -10], "labMaximum": [100, 10, 10], "lightness": 50});
@@ -4,7 +4,7 @@ const DEPTHS: [u64; 3] = [8, 16, 32];
const MODES: [&str; 4] = ["rgb", "gray", "cmyk", "lab"];
fn session(depth: u64, mode: &str) -> Session {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 48, "height": 32, "depth": depth, "mode": mode})).unwrap();
paint(&mut s, |x, y| [0.1 + x as f32 / 60.0, 0.2 + y as f32 / 50.0, 0.6 - x as f32 / 120.0, 1.0]);
s
@@ -131,7 +131,7 @@ fn disabled_without_pixels() {
assert!(!s.is_enabled(id), "{id}");
}
assert!(s.is_enabled("image.adjustments.hdrToning"));
assert!(!Session::new().is_enabled("image.adjustments.hdrToning"));
assert!(!crate::session().is_enabled("image.adjustments.hdrToning"));
}
#[test]
@@ -1242,7 +1242,7 @@ fn black_white_auto_spreads_the_greys() {
assert_eq!(auto_black_white(&[]), BW_DEFAULTS);
// The command: an adjustment layer reads the image under it; the document is unchanged.
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 20, "height": 10})).unwrap();
paint(&mut s, |x, _| if x < 10 { [0.776, 0.2, 0.2, 1.0] } else { [0.29, 0.29, 1.0, 1.0] });
let id = s.execute("layer.newAdjustmentLayer.blackWhite", json!({})).unwrap()["layer"].as_u64().unwrap();
@@ -1260,7 +1260,7 @@ fn black_white_auto_spreads_the_greys() {
assert_eq!(s.execute("image.adjustments.blackWhite.auto", json!({"layer": id})).unwrap(), r);
// Sampling a big canvas still finds a thin painted stripe.
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 512, "height": 512, "background": "transparent"})).unwrap();
paint(&mut s, |x, y| match (x, y < 256) {
(1, true) => [0.776, 0.2, 0.2, 1.0],
@@ -1273,7 +1273,7 @@ fn black_white_auto_spreads_the_greys() {
// Columns alternating with a period that divides the sampling stride (4 here): both colours
// are still sampled, not only the even columns.
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 512, "height": 512})).unwrap();
paint(&mut s, |x, _| if x % 2 == 0 { [0.776, 0.2, 0.2, 1.0] } else { [0.29, 0.29, 1.0, 1.0] });
let r = s.execute("image.adjustments.blackWhite.auto", json!({})).unwrap();
@@ -1299,7 +1299,7 @@ fn black_white_auto_reads_the_whole_input() {
let split = |x: i32, _| if x < 10 { red } else { blue };
// A selection over the red half doesn't narrow Image › Adjustments' Auto.
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 20, "height": 10})).unwrap();
paint(&mut s, split);
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
@@ -1319,7 +1319,7 @@ fn black_white_auto_reads_the_whole_input() {
assert_eq!(auto(&mut s, json!({"layer": id})), mix.to_vec());
// Nor clipping it to a layer that only covers the red half.
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 20, "height": 10})).unwrap();
paint(&mut s, |_, _| blue);
s.execute("layer.new.layer", json!({})).unwrap();
@@ -1330,7 +1330,7 @@ fn black_white_auto_reads_the_whole_input() {
assert_eq!(auto(&mut s, json!({"layer": id})), mix.to_vec());
// A Black & White smart filter: its own result is grey, its input is the colours.
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 20, "height": 10})).unwrap();
paint(&mut s, split);
s.execute("filter.convertForSmartFilters", json!({})).unwrap();
@@ -1345,7 +1345,7 @@ fn black_white_auto_reads_the_whole_input() {
assert!(s.execute("image.adjustments.blackWhite.auto", json!({"filter": 0})).is_err(), "not a smart object");
// Past the render limit there is nothing to sample.
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 40000, "height": 30000, "background": "transparent"})).unwrap();
let id = s.execute("layer.newAdjustmentLayer.blackWhite", json!({})).unwrap()["layer"].as_u64().unwrap();
assert!(s.execute("image.adjustments.blackWhite.auto", json!({"layer": id})).is_err());
@@ -11,7 +11,7 @@ use crate::Session;
const CMD: &str = "paint.adjustmentBrush";
fn doc() -> Session {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 1200, "height": 900, "background": "white"})).unwrap();
s
}
@@ -262,7 +262,7 @@ fn indexed_color_refuses_the_stroke_with_the_alert() {
#[test]
fn bad_params_are_errors_not_panics() {
let mut s = Session::new();
let mut s = crate::session();
assert!(s.execute(CMD, dab("levels")).is_err(), "no document");
let mut s = doc();
for p in [
File renamed without changes.
@@ -33,7 +33,7 @@ fn paint_scene(s: &mut Session, id: LayerId, x0: i32, x1: i32, gain: f32) {
/// The issue's document: Left (the scene at x 0..240) as the Background, its uncovered area
/// white, and Right (the scene at x 160..400, darkened) above it.
fn left_background_and_right() -> (Session, LayerId, LayerId) {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 400, "height": 300, "background": "white"})).unwrap();
let bg = s.active().unwrap().doc.background().unwrap().id;
paint_scene(&mut s, bg, 0, 240, 1.0);
@@ -39,7 +39,7 @@ fn select(s: &mut Session, ids: &[LayerId]) {
#[test]
fn auto_align_repositions_at_all_depths() {
for depth in [8, 16, 32] {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 300, "height": 240, "depth": depth, "background": "transparent"})).unwrap();
let a = texture_layer(&mut s, "A", 20, 20);
let b = texture_layer(&mut s, "B", 31, 13);
@@ -58,7 +58,7 @@ fn auto_align_repositions_at_all_depths() {
#[test]
fn auto_align_auto_projection_and_errors() {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 300, "height": 240, "background": "transparent"})).unwrap();
let a = texture_layer(&mut s, "A", 20, 20);
let b = texture_layer(&mut s, "B", 26, 25);
@@ -75,7 +75,7 @@ fn auto_align_auto_projection_and_errors() {
#[test]
fn auto_align_keeps_a_locked_layer_as_the_reference() {
for lock in ["all", "position", "pixels"] {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 300, "height": 240, "background": "transparent"})).unwrap();
let a = texture_layer(&mut s, "A", 20, 20);
let b = texture_layer(&mut s, "B", 31, 13);
@@ -113,7 +113,7 @@ fn auto_align_keeps_a_locked_layer_as_the_reference() {
#[test]
fn auto_align_moves_the_background_as_a_normal_layer() {
let setup = || {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 300, "height": 240, "background": "white"})).unwrap();
let bg = s.active().unwrap().doc.background().unwrap().id;
paint_texture(&mut s, bg, 20, 20);
@@ -155,7 +155,7 @@ fn auto_align_moves_the_background_as_a_normal_layer() {
#[test]
fn auto_align_warps_layer_masks_keeping_their_default() {
for (projection, reveal) in [("reposition", true), ("reposition", false), ("cylindrical", true)] {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 300, "height": 240, "background": "transparent"})).unwrap();
let a = texture_layer(&mut s, "A", 20, 20);
let b = texture_layer(&mut s, "B", 31, 13);
@@ -184,7 +184,7 @@ fn auto_align_warps_layer_masks_keeping_their_default() {
#[test]
fn auto_blend_panorama_masks_and_seamless_layer() {
for depth in [8, 16, 32] {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 200, "height": 60, "depth": depth, "background": "transparent"})).unwrap();
s.execute("layer.new.layer", json!({"name": "left"})).unwrap();
s.edit("l", |doc, active| {
@@ -218,7 +218,7 @@ fn auto_blend_panorama_masks_and_seamless_layer() {
/// #14214: the Background can't take a mask, and Auto-Blend leaves it the Background (no mask).
#[test]
fn auto_blend_keeps_the_background() {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 200, "height": 60, "background": "white"})).unwrap();
let bg = s.active().unwrap().doc.background().unwrap().id;
s.execute("layer.new.layer", json!({"name": "right"})).unwrap();
@@ -241,7 +241,7 @@ fn auto_blend_keeps_the_background() {
/// Seamless Tones and Colors evens out a 10% exposure step between two panorama layers.
#[test]
fn auto_blend_panorama_seamless_matches_exposure() {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 200, "height": 60, "background": "transparent"})).unwrap();
let mut ids = Vec::new();
for (name, x0, x1, gain) in [("left", 0, 130, 1.0f32), ("right", 70, 200, 1.1)] {
@@ -266,7 +266,7 @@ fn auto_blend_panorama_seamless_matches_exposure() {
/// wholly over the bottom one. It used to get an all-black mask; now it shows on its side.
#[test]
fn auto_blend_panorama_of_a_layer_the_canvas_crops_to_all_overlap() {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 200, "height": 60, "background": "transparent"})).unwrap();
s.execute("layer.new.layer", json!({"name": "left"})).unwrap();
s.edit("l", |doc, active| {
@@ -298,7 +298,7 @@ fn auto_blend_panorama_of_a_layer_the_canvas_crops_to_all_overlap() {
/// its bounds, not cut off at the canvas edge.
#[test]
fn auto_blend_panorama_masks_past_the_canvas() {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 200, "height": 60, "background": "transparent"})).unwrap();
s.execute("layer.new.layer", json!({"name": "left"})).unwrap();
s.edit("l", |doc, active| {
@@ -329,7 +329,7 @@ fn auto_blend_panorama_masks_past_the_canvas() {
/// estimate, so the extent past the canvas is capped independently: it keeps to the canvas.
#[test]
fn auto_blend_sparse_huge_bounds_keep_to_the_canvas() {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 200, "height": 200, "background": "transparent"})).unwrap();
s.execute("layer.new.layer", json!({"name": "a"})).unwrap();
s.edit("a", |doc, active| {
@@ -373,7 +373,7 @@ fn auto_blend_budget_counts_layers_and_channels() {
#[test]
fn auto_blend_stack_without_seamless() {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 64, "height": 64, "background": "transparent"})).unwrap();
s.execute("layer.new.layer", json!({"name": "sharp"})).unwrap();
s.edit("checker", |doc, active| {
@@ -430,7 +430,7 @@ fn smooth_layer(s: &mut Session, name: &str, dx: i32, dy: i32) -> LayerId {
#[test]
fn auto_align_registers_a_smooth_bracket_by_intensity() {
for depth in [8, 16, 32] {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 200, "height": 150, "depth": depth, "background": "transparent"})).unwrap();
let a = smooth_layer(&mut s, "A", 0, 0);
let b = smooth_layer(&mut s, "B", 4, 3);
@@ -460,7 +460,7 @@ fn auto_align_registers_a_smooth_bracket_by_intensity() {
/// moving them by whatever pose its search box ends at.
#[test]
fn auto_align_rejects_unrelated_layers_instead_of_guessing_a_pose() {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 200, "height": 150, "depth": 8, "background": "transparent"})).unwrap();
let a = smooth_layer(&mut s, "A", 0, 0);
s.execute("layer.new.layer", json!({"name": "stripes"})).unwrap();
@@ -498,7 +498,7 @@ fn auto_align_rejects_unrelated_layers_instead_of_guessing_a_pose() {
fn auto_blend_stack_fuses_the_sharp_halves() {
let checker = |x: i32, y: i32| if (x / 3 + y / 3) % 2 == 0 { 0.2 } else { 0.8 };
for depth in [8, 16, 32] {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 96, "height": 64, "depth": depth, "background": "transparent"})).unwrap();
let mut ids = Vec::new();
for (name, sharp_left) in [("left", true), ("right", false)] {
@@ -544,7 +544,7 @@ fn auto_blend_stack_fuses_the_sharp_halves() {
#[test]
fn auto_blend_stack_depth_map() {
for depth in [8, 16, 32] {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 96, "height": 48, "depth": depth, "background": "transparent"})).unwrap();
let mut ids = Vec::new();
for k in 0..3 {
@@ -25,7 +25,6 @@ use photocraft_color::{Color, SampleType};
use photocraft_doc::{CountGroup, Document, Layer, MeasurementScale, Ruler};
use photocraft_geom::Rect;
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use crate::commands::CommandSpec;
@@ -58,71 +57,7 @@ pub const COLUMNS: &[(&str, &str)] = &[
("angle", "Angle"),
];
const COMMON: &[&str] = &["label", "dateTime", "document", "source", "scale", "scaleUnits", "scaleFactor"];
const SELECTION_ONLY: &[&str] =
&["count", "area", "perimeter", "circularity", "height", "width", "grayMin", "grayMax", "grayMean", "grayMedian", "integratedDensity", "histogram"];
const RULER_ONLY: &[&str] = &["length", "angle"];
const COUNT_ONLY: &[&str] = &["count"];
/// Data points a measurement source can record.
pub fn available(source: &str) -> Vec<&'static str> {
let extra = match source {
"selection" => SELECTION_ONLY,
"ruler" => RULER_ONLY,
_ => COUNT_ONLY,
};
COMMON.iter().chain(extra).copied().collect()
}
/// Image › Analysis › Select Data Points: what Record Measurements writes per source.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DataPoints {
pub selection: Vec<String>,
pub ruler: Vec<String>,
pub count: Vec<String>,
}
impl Default for DataPoints {
fn default() -> Self {
let all = |s| available(s).into_iter().map(String::from).collect();
Self { selection: all("selection"), ruler: all("ruler"), count: all("count") }
}
}
impl DataPoints {
fn of(&self, source: &str) -> &[String] {
match source {
"selection" => &self.selection,
"ruler" => &self.ruler,
_ => &self.count,
}
}
fn of_mut(&mut self, source: &str) -> &mut Vec<String> {
match source {
"selection" => &mut self.selection,
"ruler" => &mut self.ruler,
_ => &mut self.count,
}
}
}
/// One Measurement Log row.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LogRow {
pub id: u64,
/// Data point values by key (see [`COLUMNS`]).
pub values: Map<String, Value>,
}
/// Session-wide analysis state (`Session::analysis`).
#[derive(Clone, Debug, Default)]
pub struct AnalysisState {
pub log: Vec<LogRow>,
next_row: u64,
/// Counter for "Measurement N" labels.
next_measurement: u64,
pub data_points: DataPoints,
}
pub use crate::state::{AnalysisState, DataPoints, LogRow, available};
// ------------------------------------------------------------------ helpers
@@ -2,7 +2,7 @@ use super::*;
use photocraft_doc::{ColorMode, LayerContent, LayerId};
fn session(w: u32, h: u32, depth: u32) -> Session {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": w, "height": h, "depth": depth, "background": "white"})).unwrap();
s
}
@@ -78,7 +78,7 @@ fn failed_compound_preserves_a_clean_document() {
fn record_measurements_refuses_an_area_too_large_to_measure() {
// #933: with no selection the whole document is measured, and `width * height` overflowed
// u32 on a legal 65536×65536 document, panicking inside `run`.
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 65536, "height": 65536, "background": "transparent"})).unwrap();
let err = s.execute("image.analysis.recordMeasurements", json!({"source": "selection"})).unwrap_err();
assert!(err.to_string().contains("too large to measure"), "{err}");
@@ -384,7 +384,7 @@ fn place_scale_marker_lays_out_its_label_in_points_at_high_resolution() {
// `fontSize` is in points and `type.create` renders it at resolution/72 px per point, but the
// layout treated it as pixels: at 300 ppi a 12 pt label (50 px) overlapped the bar.
for res in [72.0, 300.0] {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 1200, "height": 900, "resolution": res, "background": "white"})).unwrap();
let r = s.execute("image.analysis.placeScaleMarker", json!({"fontSize": 12, "textPosition": "bottom"})).unwrap();
let bar_bottom = r["barRect"][3].as_f64().unwrap();
@@ -440,7 +440,7 @@ fn place_scale_marker_on_a_short_document_errors_without_panicking() {
#[test]
fn analysis_info_and_cmyk_document() {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 30, "height": 20, "mode": "cmyk", "background": "white"})).unwrap();
assert_eq!(d(&s).mode, ColorMode::Cmyk);
s.execute("count.add", json!({"x": 3, "y": 4})).unwrap();
@@ -19,14 +19,14 @@ const CMD: &str = "image.analysis.straightenLayer";
/// A white document with a Background, as File > New makes one.
fn session(w: u32, h: u32) -> Session {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": w, "height": h, "background": "white"})).unwrap();
s
}
/// The same document in CMYK at 16 bits, which the reference also straightens.
fn cmyk_16(w: u32, h: u32) -> Session {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": w, "height": h, "mode": "cmyk", "depth": 16, "background": "white"})).unwrap();
s
}
@@ -11,7 +11,7 @@ const CMD: &str = "image.analysis.straightenLayer";
/// An 800 × 600 document with a pixel layer "Colors" painted at 100,100 to 400,300, active, and a
/// ruler that tilts it by a few degrees.
fn session() -> (Session, LayerId) {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap();
let l = LayerId(s.execute("layer.new.layer", json!({"name": "Colors"})).unwrap()["layer"].as_u64().unwrap());
s.edit("paint", |doc, _| {
@@ -1389,7 +1389,7 @@ pub fn specs() -> Vec<CommandSpec> {
"layer.new.artboardFromGroup",
"Artboard from Group",
&["Layer", "New"],
r##"{"layer":id? (a top-level group; default active),"background":…?,"color":[r,g,b]|"#rrggbb"?,"preset":str? (tag only; does not resize),"guideIDs":[int]? (ignored recording metadata),"changeBackground":int? (1 or absent applies background/color; other integers give white; legacy true = 1)} → {layer, rect}"##,
r##"{"layer":id? (a top-level group; default active),"background":…?,"color":[r,g,b]|"#rrggbb"?,"preset":str? (tag only; does not resize),"guideIDs":[int]? (ignored recording metadata),"changeBackground":int? (1 or absent applies background/color; other integers give white; legacy true = 1),"recordedColor"? (ATN round-trip of the recorded color),"backgroundTypeOmitted":bool? (ATN: the descriptor omitted the background type)} → {layer, rect}"##,
has_plain_group,
artboard_from_group
),
@@ -1429,7 +1429,7 @@ pub fn specs() -> Vec<CommandSpec> {
"file.export.artboardsToFiles",
"Artboards to Files…",
&["File", "Export"],
r##"{"dir":folder,"format":"png|png24|png8|jpg|bmp|tga|tiff|psd|pdf|…"="png" (png24 = truecolour .png, png8 = indexed .png, tga = Targa; pdf = one multi-page <prefix>.pdf, bottom artboard first, pages at 72 ppi),"prefix":str=document name ("" = none),"content":"overlapping|artboard"="overlapping" (Include Overlapping Areas: a board's file also shows the visible boards above it where they overlap it, each as a plain group with a \"Background for <board>\" layer; artboard: Artboard Content Only),"artboards":[id]? (default all),"quality":0..12? (JPEG, and the PDF pages),"iccProfile":bool=true,"bmpBits":24|32? (16 unsupported),"tgaBits":24|32?,"tiffCompression":"none|lzw|zip"="none" ("jpeg" unsupported),"pngInterlaced":bool=false (PNG, PNG-24),"transparency":bool=true (PNG, PNG-8, PNG-24; false: over white, no alpha),"maximizeCompatibility":bool? (PSD),"preserveArtboard":bool=true (PSD; false: a plain group),"includeName":bool=false (Include Artboard Name: a border of (w + h) / 20 px on each side, the name in the top one; psd and pdf keep their layers),"font":family="Arial","fontStyle":"Regular|Italic|Bold|Bold Italic|Black"="Regular","fontSize":pt|numeric str=12 (else an error),"extension":"white|black|other"|"#rrggbb"|[r,g,b]="white" (Canvas Extension; "other" takes "extensionColor":[r,g,b]),"textColor":"#rrggbb"|[r,g,b]=black} → {files, warnings} (warnings: what a file could not hold, each "<file name>: <warning>"; one "<prefix><artboard name>.<extension>" per board, no separator or index added: spaces become "-" in PNG, JPEG, BMP, Targa and TIFF and stay in PSD and other formats, characters a file name can't hold become "_", and a name an earlier board already took, ignoring case, gets "-2", "-3"…)"##,
r##"{"dir":folder,"format":"png|png24|png8|jpg|bmp|tga|tiff|psd|pdf|…"="png" (png24 = truecolour .png, png8 = indexed .png, tga = Targa; pdf = one multi-page <prefix>.pdf, bottom artboard first, pages at 72 ppi),"prefix":str=document name ("" = none),"content":"overlapping|artboard"="overlapping" (Include Overlapping Areas: a board's file also shows the visible boards above it where they overlap it, each as a plain group with a \"Background for <board>\" layer; artboard: Artboard Content Only),"artboards":[id]? (default all),"quality":0..12? (JPEG, and the PDF pages),"iccProfile":bool=true,"bmpBits":24|32? (16 unsupported),"tgaBits":24|32?,"tiffCompression":"none|lzw|zip"="none" ("jpeg" unsupported),"pngInterlaced":bool=false (PNG, PNG-24),"transparency":bool=true (PNG, PNG-8, PNG-24; false: over white, no alpha),"maximizeCompatibility":bool? (PSD),"preserveArtboard":bool=true (PSD; false: a plain group),"includeName":bool=false (Include Artboard Name: a border of (w + h) / 20 px on each side, the name in the top one; psd and pdf keep their layers),"font":family="Arial","fontStyle":"Regular|Italic|Bold|Bold Italic|Black"="Regular","fontSize":pt|numeric str=12 (else an error),"extension":"white|black|other"|"#rrggbb"|[r,g,b]="white" (Canvas Extension; "other" takes extensionColor),"extensionColor":"#rrggbb"|[r,g,b]? (used when extension is "other"),"textColor":"#rrggbb"|[r,g,b]=black} → {files, warnings} (warnings: what a file could not hold, each "<file name>: <warning>"; one "<prefix><artboard name>.<extension>" per board, no separator or index added: spaces become "-" in PNG, JPEG, BMP, Targa and TIFF and stay in PSD and other formats, characters a file name can't hold become "_", and a name an earlier board already took, ignoring case, gets "-2", "-3"…)"##,
export_artboards,
artboards_to_files
),
@@ -8,7 +8,7 @@ use photocraft_geom::Rect;
/// 64 x 48, transparent, with two boards: "Clear" (transparent, a red square inside, half the
/// board left empty) and "White" (white background, empty).
fn session() -> (Session, u64, u64) {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 64, "height": 48, "background": "transparent"})).unwrap();
s.edit("Red", |doc, active| {
let fmt = doc.pixel_format();
@@ -10,7 +10,7 @@ const MEASURED: [(&str, [u32; 4]); 3] = [("Red Board", [0, 0, 200, 150]), ("Blue
/// The issue's test document: 800 x 400, RGB, 8 bit, transparent, unsaved and named
/// `abfiles-test`, with `boards` added bottom to top.
fn session(boards: &[(&str, [u32; 4])]) -> Session {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"name": "abfiles-test", "width": 800, "height": 400, "depth": 8, "background": "transparent"})).unwrap();
for (name, rect) in boards {
s.execute("layer.new.artboard", json!({"name": name, "rect": rect, "background": "transparent"})).unwrap();
@@ -7,7 +7,7 @@ use super::*;
/// Layers panel, then Blue Board 200 x 200, then an empty transparent board on top. 300 ppi, so
/// a page sized from the document resolution would not be 72 ppi.
fn boards() -> Session {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 800, "height": 400, "name": "abfiles-test", "background": "transparent"})).unwrap();
for (name, rect, bg) in [
("Red Board", [0, 0, 200, 150], json!({"background": "custom", "color": "#ff0000"})),
@@ -171,7 +171,7 @@ fn unknown_format_is_an_error_and_writes_nothing() {
/// empty buffer (`region data length mismatch`).
#[test]
fn oversized_board_is_a_bad_params_error_for_png8_and_pdf() {
let mut s = Session::new();
let mut s = crate::session();
let mut doc = Document::new("huge", Size::new(40_000, 40_000), ColorMode::Rgb, SampleType::U8);
let mut board = Layer::group("Huge Board", Vec::new());
if let LayerContent::Group(g) = &mut board.content {
@@ -6,7 +6,7 @@ use photocraft_geom::Rect;
/// 800 x 600 with the white Background and a pixel layer "Red" at 100,100 to 300,250.
fn session(depth: u32) -> Session {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 800, "height": 600, "depth": depth, "background": "white"})).unwrap();
s.edit("Red", |doc, active| {
let fmt = doc.pixel_format();
@@ -17,7 +17,7 @@ fn square(doc: &Document, name: &str, r: Rect, rgba: [f32; 4]) -> Layer {
/// 800 x 600 with the white Background and "Group 1" holding Blue above Red; with `inner`, Blue
/// sits in its own group "Inner". Returns the session and the ids of Group 1, Red and Blue.
fn session(inner: bool) -> (Session, [LayerId; 3]) {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap();
let ids = s
.edit("Group 1", |doc, active| {
@@ -94,7 +94,7 @@ fn a_hidden_group_inside_hides_its_children_too() {
#[test]
fn a_group_with_every_layer_hidden_is_handled_like_an_empty_group() {
let mut empty = Session::new();
let mut empty = crate::session();
empty.execute("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap();
let e = empty.edit("Group 1", |doc, _| Ok(doc.insert_above(None, Layer::group("Group 1", vec![])))).unwrap();
let today = from_group(&mut empty, e);
@@ -9,7 +9,7 @@ use photocraft_doc::LayerMask;
/// 200 x 200 with a top-level group "Group" (one child "Red" with pixels) that has the given
/// blend, opacity, fill opacity and an optional mask.
fn session_with_group(blend: BlendMode, opacity: f32, fill_opacity: f32, mask: bool) -> (Session, LayerId) {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 200, "height": 200, "depth": 8, "background": "white"})).unwrap();
let gid = s
.edit("Group", |doc, active| {
@@ -5,7 +5,7 @@ use photocraft_geom::Rect;
/// 100 x 80 RGB at `depth` with a pixel layer "Red" holding a square at 10,10 to 30,30.
fn session(depth: u32) -> Session {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 100, "height": 80, "depth": depth, "background": "white"})).unwrap();
s.edit("Red", |doc, active| {
let fmt = doc.pixel_format();
@@ -11,7 +11,7 @@ const RED: [f32; 4] = [220.0 / 255.0, 30.0 / 255.0, 30.0 / 255.0, 1.0];
/// The spec's test document: 800 x 400, transparent, `Red Board` 0,0-200,150 (white, a red
/// layer at 20,20-120,100) and `Blue Board` 120,30-320,230 (white, a blue layer at 130,40-230,140).
fn session(depth: u32) -> Session {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 800, "height": 400, "depth": depth, "background": "transparent"})).unwrap();
board(&mut s, "Red Board", [0, 0, 200, 150], Rect::new(20, 20, 120, 100), RED);
board(&mut s, "Blue Board", [120, 30, 200, 200], Rect::new(130, 40, 230, 140), [30.0 / 255.0, 30.0 / 255.0, 220.0 / 255.0, 1.0]);
@@ -13,7 +13,7 @@ const WHITE: [u8; 3] = [255, 255, 255];
/// (pixel layer `Red` at 20,20-120,100), `Blue Board` 120,30-320,230 (pixel layer `Blue` at
/// 130,40-230,140) and `Empty Board` 600,0-700,100, all with white backgrounds.
fn session(depth: u32) -> (Session, [u64; 3]) {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"width": 800, "height": 400, "depth": depth, "background": "transparent"})).unwrap();
let board =
|s: &mut Session, name: &str, rect: [i64; 4]| s.execute("layer.new.artboard", json!({"rect": rect, "name": name})).unwrap()["layer"].as_u64().unwrap();
@@ -10,7 +10,7 @@ const MEASURED: [(&str, [u32; 4]); 3] = [("Red Board", [0, 0, 200, 150]), ("Blue
/// The issue's test document: 800 x 400, RGB, 8 bit, 72 ppi, named `abpdf-test`, with `boards`
/// added bottom to top.
fn session(boards: &[(&str, [u32; 4])]) -> Session {
let mut s = Session::new();
let mut s = crate::session();
s.execute("file.new", json!({"name": "abpdf-test", "width": 800, "height": 400, "depth": 8, "resolution": 72})).unwrap();
for (name, rect) in boards {
s.execute("layer.new.artboard", json!({"rect": rect, "name": name})).unwrap();
Loaded 100 of 987 files, more files were not shown because too many files have changed in this diff. Show more