Merge remote-tracking branch 'origin/main' into fix/14359-brightness-contrast-hidden-empty

This commit is contained in:
RickiNano committed 2026-11-23 20:55:35 +01:00
commit 31ac857ec0
150 files changed
+9103 -522

No files matched your search

+9
View File
@@ -92,6 +92,15 @@ success-output = "immediate"
# All cases and the 60-second warning remain unchanged.
threads-required = 2
# The slowest UI GPU tests start together (priority below) and redraw the whole app per frame on
# the Windows software GPU. Four at once starve one frame past egui_kittest's 10-second device
# poll (`PollError: ... Wait timed out`, live_stroke_canvas part_0, twice in a row in #16529).
# Two slots each keep at most two of them on the adapter at a time; no case or timeout changes.
[[profile.ci.overrides]]
platform = 'cfg(target_os = "windows")'
filter = 'package(photocraft-ui-egui) & test(/gpu_tests::(live_stroke_canvas::the_canvas_shows_the_committed_stroke_part_|checker_canvas::pixel_grid_is_solid_and_visible_|full_res_preview::)/)'
threads-required = 2
# Slowest tests start first. nextest starts higher-priority tests first, so a long test no longer
# begins at the end of the run and extends the job. Every test that took over 60 s on the Windows
# runner in the cold run of #15474 (unit and integration legs); the same tests are the slowest on
+1 -1
View File
@@ -34,7 +34,7 @@ jobs:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
with:
dry-run: ${{ github.event_name == 'schedule' }}
nightly: ${{ github.event_name == 'schedule' }}
app-name: photocraft
app-title: PhotoCraft
craft-fonts-ref: cc9269cd8d8258785dac603fba3122e5d2556795
+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
+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
+156 -155
View File
@@ -1365,12 +1365,12 @@ dependencies = [
[[package]]
name = "craft"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
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=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe)",
"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=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
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=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
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=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
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=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
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=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-docpath",
@@ -1496,11 +1496,20 @@ dependencies = [
[[package]]
name = "craft-cloud-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"egui",
]
[[package]]
name = "craft-cms"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"md-5",
"rayon",
]
[[package]]
name = "craft-cms"
version = "0.1.0"
@@ -1510,19 +1519,10 @@ dependencies = [
"rayon",
]
[[package]]
name = "craft-cms"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
dependencies = [
"md-5",
"rayon",
]
[[package]]
name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
[[package]]
name = "craft-color"
@@ -1545,10 +1545,10 @@ dependencies = [
[[package]]
name = "craft-color-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
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=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe)",
"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=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-ai-agents",
"craft-atomic",
@@ -1580,13 +1580,21 @@ dependencies = [
[[package]]
name = "craft-crs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
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=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe)",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"craft-xml",
"thiserror 2.0.21",
]
[[package]]
name = "craft-crw"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-crw"
version = "0.1.0"
@@ -1595,18 +1603,10 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-crw"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-dds"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"rayon",
]
@@ -1641,7 +1641,7 @@ dependencies = [
[[package]]
name = "craft-dialogs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"block2 0.6.2",
"craft-atomic",
@@ -1666,7 +1666,7 @@ dependencies = [
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"serde",
]
@@ -1674,7 +1674,7 @@ dependencies = [
[[package]]
name = "craft-draw"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-color-ui",
@@ -1693,12 +1693,12 @@ dependencies = [
[[package]]
name = "craft-eps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
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=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-eps",
"craft-idml",
@@ -1706,7 +1706,7 @@ dependencies = [
"craft-kra",
"craft-ora",
"craft-pcraft-bundle",
"craft-raw 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe)",
"craft-raw 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"craft-svg",
"craft-zip",
"serde",
@@ -1716,7 +1716,7 @@ dependencies = [
[[package]]
name = "craft-flags"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-atomic",
"dirs",
@@ -1726,7 +1726,7 @@ dependencies = [
[[package]]
name = "craft-font-catalog"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"fontique",
"harfrust 0.13.3",
@@ -1741,7 +1741,7 @@ dependencies = [
[[package]]
name = "craft-font-manager"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-font-catalog",
@@ -1761,7 +1761,7 @@ dependencies = [
[[package]]
name = "craft-font-store"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"cap-primitives",
"craft-atomic",
@@ -1782,7 +1782,7 @@ dependencies = [
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
[[package]]
name = "craft-geom"
@@ -1795,7 +1795,7 @@ dependencies = [
[[package]]
name = "craft-heif"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"heic-rs",
"rayon",
@@ -1804,7 +1804,7 @@ dependencies = [
[[package]]
name = "craft-host"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"bitflags 2.13.2",
"craft-i18n",
@@ -1817,7 +1817,7 @@ dependencies = [
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"chrono",
"fixed_decimal",
@@ -1845,7 +1845,7 @@ dependencies = [
[[package]]
name = "craft-idml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-xml",
"craft-zip",
@@ -1855,13 +1855,13 @@ dependencies = [
[[package]]
name = "craft-image-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
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=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe)",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe)",
"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",
@@ -1883,7 +1883,7 @@ dependencies = [
[[package]]
name = "craft-imaging"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-color-ui",
@@ -1901,12 +1901,12 @@ dependencies = [
[[package]]
name = "craft-ipp"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
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=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"thiserror 2.0.21",
]
@@ -1914,7 +1914,7 @@ dependencies = [
[[package]]
name = "craft-keymap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-host",
"craft-i18n",
@@ -1929,7 +1929,7 @@ dependencies = [
[[package]]
name = "craft-kra"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-xml",
"craft-zip",
@@ -1939,7 +1939,7 @@ dependencies = [
[[package]]
name = "craft-layers"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-i18n",
@@ -1953,7 +1953,7 @@ dependencies = [
[[package]]
name = "craft-menu"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-host",
@@ -1968,6 +1968,18 @@ dependencies = [
"serde_json",
]
[[package]]
name = "craft-metadata"
version = "0.1.0"
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=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"quick-xml 0.41.0",
"serde",
]
[[package]]
name = "craft-metadata"
version = "0.1.0"
@@ -1980,22 +1992,10 @@ dependencies = [
"serde",
]
[[package]]
name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
dependencies = [
"brotli-decompressor 6.3.2",
"chrono",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe)",
"quick-xml 0.41.0",
"serde",
]
[[package]]
name = "craft-ora"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-xml",
"craft-zip",
@@ -2005,7 +2005,7 @@ dependencies = [
[[package]]
name = "craft-pages"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-keymap",
@@ -2020,7 +2020,7 @@ dependencies = [
[[package]]
name = "craft-pcraft-bundle"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"blake3",
"craft-atomic",
@@ -2033,7 +2033,7 @@ dependencies = [
[[package]]
name = "craft-pcraft-format"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"flate2",
"serde",
@@ -2044,7 +2044,7 @@ dependencies = [
[[package]]
name = "craft-pdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"bytemuck",
"flate2",
@@ -2059,7 +2059,7 @@ dependencies = [
[[package]]
name = "craft-pdn"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"flate2",
"thiserror 2.0.21",
@@ -2068,7 +2068,7 @@ dependencies = [
[[package]]
name = "craft-platform"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"async-channel",
"async-io",
@@ -2098,7 +2098,7 @@ dependencies = [
[[package]]
name = "craft-plist"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"thiserror 2.0.21",
]
@@ -2106,7 +2106,7 @@ dependencies = [
[[package]]
name = "craft-print"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2129,7 +2129,7 @@ dependencies = [
[[package]]
name = "craft-psd"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"encoding_rs",
"flate2",
@@ -2140,7 +2140,7 @@ dependencies = [
[[package]]
name = "craft-quit"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"dispatch2",
"egui",
@@ -2148,6 +2148,24 @@ dependencies = [
"objc2-app-kit 0.3.2",
]
[[package]]
name = "craft-raw"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"chrono",
"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"
@@ -2166,28 +2184,10 @@ dependencies = [
"zune-jpeg",
]
[[package]]
name = "craft-raw"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
dependencies = [
"chrono",
"craft-crw 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe)",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe)",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe)",
"jxl-oxide",
"miniz_oxide 0.9.1",
"rayon",
"serde",
"thiserror 2.0.21",
"zune-core",
"zune-jpeg",
]
[[package]]
name = "craft-review"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2205,7 +2205,7 @@ dependencies = [
[[package]]
name = "craft-settings"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-atomic",
"craft-host",
@@ -2222,7 +2222,7 @@ dependencies = [
[[package]]
name = "craft-svg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-image-codecs",
"craft-xml",
@@ -2243,7 +2243,7 @@ dependencies = [
[[package]]
name = "craft-table"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-keymap",
@@ -2255,7 +2255,7 @@ dependencies = [
[[package]]
name = "craft-text"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-font-manager",
@@ -2278,7 +2278,7 @@ dependencies = [
[[package]]
name = "craft-theme"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"bitflags 2.13.2",
"craft-tracked",
@@ -2293,7 +2293,7 @@ dependencies = [
[[package]]
name = "craft-theme-editor"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-theme",
@@ -2304,7 +2304,7 @@ dependencies = [
[[package]]
name = "craft-theme-store"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-atomic",
"craft-behavior",
@@ -2319,26 +2319,26 @@ dependencies = [
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=b2d2a1e948c43d95aa769d4f0a06fe6b869edc39#b2d2a1e948c43d95aa769d4f0a06fe6b869edc39"
dependencies = [
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
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=b2d2a1e948c43d95aa769d4f0a06fe6b869edc39#b2d2a1e948c43d95aa769d4f0a06fe6b869edc39"
dependencies = [
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-time"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -2347,7 +2347,7 @@ dependencies = [
[[package]]
name = "craft-timeline"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-keymap",
@@ -2362,7 +2362,7 @@ dependencies = [
[[package]]
name = "craft-tracked"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"serde",
]
@@ -2370,7 +2370,7 @@ dependencies = [
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-cloud-ui",
"craft-ui-canvas",
@@ -2384,7 +2384,7 @@ dependencies = [
[[package]]
name = "craft-ui-canvas"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-i18n",
@@ -2400,7 +2400,7 @@ dependencies = [
[[package]]
name = "craft-ui-contract"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"accesskit",
"craft-behavior",
@@ -2440,7 +2440,7 @@ dependencies = [
[[package]]
name = "craft-ui-macros"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"proc-macro-crate",
"proc-macro2",
@@ -2451,7 +2451,7 @@ dependencies = [
[[package]]
name = "craft-ui-panels"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2469,7 +2469,7 @@ dependencies = [
[[package]]
name = "craft-ui-patterns"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2490,7 +2490,7 @@ dependencies = [
[[package]]
name = "craft-ui-shell"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2510,7 +2510,7 @@ dependencies = [
[[package]]
name = "craft-ui-widgets"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2527,7 +2527,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"chrono",
"craft-host",
@@ -2556,7 +2556,7 @@ dependencies = [
[[package]]
name = "craft-win32"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"winsafe",
]
@@ -2564,7 +2564,7 @@ dependencies = [
[[package]]
name = "craft-window"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"craft-atomic",
"craft-behavior",
@@ -2594,7 +2594,7 @@ dependencies = [
[[package]]
name = "craft-xcf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"flate2",
"thiserror 2.0.21",
@@ -2603,7 +2603,7 @@ dependencies = [
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"quick-xml 0.41.0",
"serde",
@@ -2613,7 +2613,7 @@ dependencies = [
[[package]]
name = "craft-zip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"flate2",
"thiserror 2.0.21",
@@ -4076,7 +4076,7 @@ dependencies = [
[[package]]
name = "hayro"
version = "0.7.1"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"bytemuck",
"hayro-interpret",
@@ -4106,7 +4106,7 @@ dependencies = [
[[package]]
name = "hayro-interpret"
version = "0.7.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"bitflags 2.13.2",
"hayro-cmap",
@@ -4124,7 +4124,7 @@ dependencies = [
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"fearless_simd",
"hayro-ccitt",
@@ -4148,7 +4148,7 @@ checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"flate2",
"hayro-ccitt",
@@ -5232,7 +5232,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
[[package]]
name = "linesweeper"
version = "0.5.0"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"arrayvec",
"kurbo 0.13.1",
@@ -6448,7 +6448,7 @@ dependencies = [
"clap",
"core-graphics2",
"craft",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe)",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"craft-image-codecs",
"craft-svg",
"craft-update",
@@ -6498,7 +6498,7 @@ dependencies = [
"craft",
"craft-develop",
"craft-develop-model",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe)",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"criterion",
"photocraft-color",
"photocraft-geom",
@@ -6550,7 +6550,7 @@ dependencies = [
"clap_complete",
"clap_mangen",
"craft",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe)",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"craft-image-codecs",
"craft-psd",
"photocraft-automation",
@@ -6573,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=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe)",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"craft-tracked",
"craft-ui-macros",
"serde",
@@ -6583,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=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe)",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"criterion",
"photocraft-color",
"photocraft-doc",
@@ -6614,7 +6614,7 @@ version = "0.23.1"
dependencies = [
"blake3",
"craft-affinity",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe)",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"craft-develop-model",
"craft-image-codecs",
"craft-psd",
@@ -6646,7 +6646,7 @@ dependencies = [
"chrono",
"craft",
"craft-affinity",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe)",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"craft-develop-model",
"craft-file-formats",
"craft-image-codecs",
@@ -6727,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=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe)",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"half",
"log",
"photocraft-algo",
@@ -6750,7 +6750,7 @@ dependencies = [
"blake3",
"craft",
"craft-affinity",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe)",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"craft-crs",
"craft-docpath",
"craft-file-formats",
@@ -6761,7 +6761,7 @@ dependencies = [
"craft-pdn",
"craft-psd",
"craft-svg",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe)",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"craft-xcf",
"craft-xml",
"crc32fast",
@@ -6819,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=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe)",
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"craft-tracked",
"craft-ui-macros",
"photocraft-color",
@@ -6871,7 +6871,7 @@ version = "0.23.1"
dependencies = [
"craft-develop",
"craft-image-codecs",
"craft-raw 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe)",
"craft-raw 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362)",
"flate2",
"image",
"photocraft-raw",
@@ -6935,6 +6935,7 @@ dependencies = [
"craft-image-codecs",
"craft-print",
"craft-psd",
"craft-xml",
"eframe",
"egui",
"egui_extras",
@@ -9666,7 +9667,7 @@ dependencies = [
[[package]]
name = "vello_common"
version = "0.0.8"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"bytemuck",
"fearless_simd",
@@ -9714,7 +9715,7 @@ dependencies = [
[[package]]
name = "vello_cpu"
version = "0.0.8"
source = "git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
dependencies = [
"bytemuck",
"glifo 0.1.1",
@@ -11350,14 +11351,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=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
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=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
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=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe#ee30b17c2199b87b3c097729e60f6b1d9c8d1afe"
source = "git+https://github.com/storytold/craft-libs?rev=5c5e0d52c387c0a4ae2908a07e476d7584f60362#5c5e0d52c387c0a4ae2908a07e476d7584f60362"
+39 -39
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 = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe", default-features = false }
craft-tracked = { git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
craft-ui-macros = { git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
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 = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe", 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 = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
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" }
@@ -46,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 = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
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 = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe", features = ["raster", "write-raster"] }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
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 = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe", features = ["tree-render", "tree-render-system-fonts"] }
craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
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 = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
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 = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
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 = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe", 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"
@@ -342,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 = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
vello_common = { git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
vello_cpu = { git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
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" }
+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 -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(&[]));
}
}
+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());
}
}
+220 -32
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.
@@ -69,7 +76,7 @@ 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];
@@ -83,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
@@ -95,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`.
@@ -163,8 +184,12 @@ fn control_port_for(cli: Option<u16>, prefs: &photocraft_engine::prefs::Integrat
/// (`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,
@@ -227,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), _) => {
@@ -390,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();
@@ -398,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);
@@ -409,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: _,
@@ -453,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());
@@ -551,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);
@@ -683,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));
@@ -754,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);
@@ -766,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.
@@ -1100,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]
@@ -1179,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");
}
}
+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

@@ -0,0 +1,7 @@
# Seeds for failure cases proptest has generated in the past. It is
# automatically read and these particular cases re-run before any
# novel cases are generated.
#
# It is recommended to check this file in to source control so that
# everyone who runs the test benefits from these saved cases.
cc 9cd32fd3b0d418f70a3535174d06eccab73fdd2345cf51e50b53c9f2e006043e # shrinks to s = Spec { w: 2, h: 2, layers: [Group { children: [Pixels { kind: Solid, blend: Normal, fills: [(Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, [0.0, 0.0, 0.54360455, 0.0, 1.0])], opacity: 1.0, fill: 1.0, clipped: false, visible: true, mask: None }, Pixels { kind: Adjust(Curves { channel: 2, points: [(0.4490113, 1.0), (1.0, 0.0)] }), blend: Normal, fills: [(Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, [0.0, 0.0, 0.0, 0.0, 0.0])], opacity: 0.6871668, fill: 1.0, clipped: false, visible: true, mask: None }], pass_through: false, blend: Normal, opacity: 1.0, fill: 1.0, mask: None }] }
+26 -5
View File
@@ -17,8 +17,8 @@ mod tone;
#[cfg(test)]
use channels::lab_denorm;
pub use channels::{
LAB_NEUTRAL, LabOp, apply_cmy, cmy_adjustment, cmyk_channel_adjustment, ink_brightness_contrast_lut, ink_luma, ink_through, lab_channel_adjustment,
lab_stored_op, stored_channel_adjustment, stored_channels, threshold_white,
LAB_NEUTRAL, LabOp, apply_cmy, cmy_adjustment, cmyk_channel_adjustment, cmyk_mixer, ink_brightness_contrast_lut, ink_luma, ink_through,
lab_channel_adjustment, lab_stored_op, mix_inks, stored_channel_adjustment, stored_channels, threshold_white,
};
use channels::{apply_lab, gray_from_srgb_lightness, legacy_brightness_contrast, legacy_brightness_contrast_hdr};
use color::gradient;
@@ -32,7 +32,8 @@ use tone::LUT_SIZE;
pub(crate) use tone::apply_tone;
pub use tone::{
TONE_SLOPE_SPAN, contour_curve_lut, curve_lut, curve_lut_mode, curve_map_lut, curve_samples, float_tone_extrapolates, float_tone_identity, levels,
levels_float, levels_gamma, levels_q, modern_brightness, modern_contrast, modern_lut, posterize, posterize_in, tone_luts, tone_luts_depth, tone_luts_q,
levels_float, levels_gamma, levels_q, modern_brightness, modern_contrast, modern_lut, posterize, posterize_in, tone_luts, tone_luts_depth,
tone_luts_depth_in, tone_luts_q,
};
use tone::{lut, map_rgb};
@@ -200,7 +201,25 @@ fn apply_depth_mode(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer, dept
let hi = if depth == Some(SampleType::F32) { f32::INFINITY } else { 1.0 };
map_rgb(buf, |c| vibrance_px(c, v, s, transfer, hi))
}
Adjustment::ChannelMixer { matrix, monochrome } if depth == Some(SampleType::F32) => {
Adjustment::ChannelMixer { cmyk: Some(rows), monochrome, .. } => {
// A CMYK mixer outside a CMYK document: on the screen colour's separation.
use photocraft_color::convert::{cmyk_to_rgb, rgb_to_cmyk};
// In a 32-bit document the change is added as a difference of two round trips, as
// [`tone::tone_in_space`] does, so samples past 0..1 the separation clips keep their
// magnitude (an identity mixer leaves an HDR highlight as it is).
let float = depth == Some(SampleType::F32);
map_rgb(buf, |c| {
let ink = rgb_to_cmyk(c);
let mut mixed = ink;
mix_inks(rows, *monochrome, &mut mixed);
if !float {
return cmyk_to_rgb(mixed);
}
let (before, after) = (cmyk_to_rgb(ink), cmyk_to_rgb(mixed));
std::array::from_fn(|i| c[i] + after[i] - before[i])
})
}
Adjustment::ChannelMixer { matrix, monochrome, .. } if depth == Some(SampleType::F32) => {
// 32-bit: each source percentage is cut to 1/1024 (toward zero), the constant counts
// 255/512 of its value, and nothing clips (photoshop corpus rgb32 channel-mixer.psd:
// pure red, green, blue, black and white all exact).
@@ -211,7 +230,7 @@ fn apply_depth_mode(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer, dept
if *monochrome { [mix(&m[0]); 3] } else { [mix(&m[0]), mix(&m[1]), mix(&m[2])] }
})
}
Adjustment::ChannelMixer { matrix, monochrome } => map_rgb(buf, |c| {
Adjustment::ChannelMixer { matrix, monochrome, .. } => map_rgb(buf, |c| {
let mix = |row: &[f32; 4]| (row[0] * c[0] + row[1] * c[1] + row[2] * c[2] + row[3]).clamp(0.0, 1.0);
if *monochrome { [mix(&matrix[0]); 3] } else { [mix(&matrix[0]), mix(&matrix[1]), mix(&matrix[2])] }
}),
@@ -408,6 +427,8 @@ mod lookup_tests {
}
}
#[cfg(test)]
mod curves_channel_composite_tests;
#[cfg(test)]
mod gradient_map_grayscale_tests;
#[cfg(test)]
+32 -3
View File
@@ -71,12 +71,40 @@ pub fn lab_channel_adjustment(adj: &Adjustment) -> bool {
/// Whether a CMYK document evaluates `adj` on its inks rather than on the screen colour: Invert
/// and Posterize (each ink, black included, so paper inverts to 400% ink), Threshold (paper or
/// 100% black ink alone) and Brightness/Contrast (each ink's stored value, 1 - ink, through the
/// tone curve; see [`ink_through`]). Photoshop corpus cmyk8 and cmyk16 invert, posterize-4,
/// tone curve; see [`ink_through`]), and a Channel Mixer with CMYK outputs ([`mix_inks`]).
/// Photoshop corpus cmyk8 and cmyk16 invert, posterize-4,
/// threshold-128 and brightness-contrast(-legacy) follow these rules on the files' own inks on
/// every pixel; here the inks are the screen colour separated through the document's CMYK
/// profile, so neutrals carry the black that profile generates rather than the file's.
pub fn cmyk_channel_adjustment(adj: &Adjustment) -> bool {
stored_channel_adjustment(adj) || cmy_adjustment(adj) || matches!(adj, Adjustment::BrightnessContrast { .. })
stored_channel_adjustment(adj) || cmy_adjustment(adj) || cmyk_mixer(adj) || matches!(adj, Adjustment::BrightnessContrast { .. })
}
/// Whether `adj` is a Channel Mixer with CMYK outputs ([`mix_inks`]).
pub fn cmyk_mixer(adj: &Adjustment) -> bool {
matches!(adj, Adjustment::ChannelMixer { cmyk: Some(_), .. })
}
/// A CMYK Channel Mixer on one pixel's inks (C, M, Y, K; 0 none): each output ink is its row's
/// mix of the four ink amounts plus the constant, clipped to 0..1, so a positive constant adds
/// ink. Photoshop corpus cmyk8 and cmyk16 channel-mixer.psd follow this on every pixel (within
/// 0.8 and 0.4 of a level of 255), black output included: its all-zero record leaves no black
/// ink. Mixing the stored values (1 - ink) instead misses by up to 255 levels there. With
/// `monochrome` the first row's mix goes to the black ink alone and cyan, magenta and yellow are
/// cleared (no Photoshop sample of a monochrome CMYK mixer yet).
pub fn mix_inks(rows: &[[f32; 5]; 4], monochrome: bool, ink: &mut [f32]) {
let inks: [f32; 4] = std::array::from_fn(|i| {
let v = ink.get(i).copied().unwrap_or(0.0);
if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }
});
let mix = |r: &[f32; 5]| {
let v = r[0] * inks[0] + r[1] * inks[1] + r[2] * inks[2] + r[3] * inks[3] + r[4];
if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }
};
let out: [f32; 4] = if monochrome { [0.0, 0.0, 0.0, mix(&rows[0])] } else { std::array::from_fn(|j| mix(&rows[j])) };
for (v, o) in ink.iter_mut().zip(out) {
*v = o;
}
}
/// Whether a CMYK document evaluates `adj` on C, M and Y as the complement of an RGB colour,
@@ -125,7 +153,7 @@ pub fn stored_channel_adjustment(adj: &Adjustment) -> bool {
matches!(adj, Adjustment::Invert | Adjustment::Posterize { .. } | Adjustment::Threshold { .. })
}
/// Invert, Posterize or Threshold on one pixel's own channels in a Lab or CMYK document of
/// Invert, Posterize or Threshold (or, in CMYK, a CMYK Channel Mixer: [`mix_inks`]) on one pixel's own channels in a Lab or CMYK document of
/// `depth` (`None`: unknown, treated as 8-bit): `ch` holds L, a, b normalised as [`lab_norm`]
/// gives them, or the C, M, Y, K inks (0: none). Lab Invert turns 8-bit bytes `v` into `255 - v`
/// (a becomes -1 - a) and mirrors a and b around neutral at 16 bits (photoshop corpus lab16
@@ -156,6 +184,7 @@ pub fn stored_channels(adj: &Adjustment, mode: ColorMode, depth: Option<SampleTy
};
ch.iter_mut().zip(out).for_each(|(v, o)| *v = o);
}
Adjustment::ChannelMixer { cmyk: Some(rows), monochrome, .. } if mode == ColorMode::Cmyk => mix_inks(rows, *monochrome, ch),
_ => {}
}
}
@@ -0,0 +1,153 @@
//! #14446: in an 8-bit document a Curves channel curve lands on a whole level before the
//! composite (master) curve is applied to it, as Levels' steps do (see [`super::levels_q`]).
//! The values below are the reference application the issue measures, Red `0,0 128,64 255,255`
//! with composite `0,0 128,200 255,255`. 16-bit, float, CMYK and Lab curves are marked *not
//! measured* there and keep today's continuous chain.
use super::*;
use photocraft_geom::Rect;
/// One Photoshop level as a sample.
fn level(v: u32) -> f32 {
v as f32 / 255.0
}
/// Curve points given in Photoshop's 0..255 units.
fn pts(p: &[(u32, u32)]) -> Vec<CurvePoint> {
p.iter().map(|&(i, o)| CurvePoint { input: level(i), output: level(o) }).collect()
}
/// The measured pair: a red channel curve that halves the midtones and a composite curve that
/// lifts them.
const RED: &[(u32, u32)] = &[(0, 0), (128, 64), (255, 255)];
const COMPOSITE: &[(u32, u32)] = &[(0, 0), (128, 200), (255, 255)];
const STRAIGHT: &[(u32, u32)] = &[(0, 0), (255, 255)];
fn measured() -> Adjustment {
Adjustment::Curves {
master: pts(COMPOSITE),
per_channel: [pts(RED), pts(STRAIGHT), pts(STRAIGHT)],
space: ToneSpace::Rgb,
black: Vec::new(),
pencil: false,
}
}
/// One gray through the compositor's real adjustment path in an 8-bit document, as whole levels.
fn gray8(adj: &Adjustment, g: u32) -> [u32; 3] {
let mut b = Buffer::filled(Rect::new(0, 0, 1, 1), [level(g), level(g), level(g), 1.0]);
apply_depth(adj, &mut b, Transfer::Srgb, Some(SampleType::U8));
[0, 1, 2].map(|i| (b.px[0][i] * 255.0 + 0.5).floor() as u32)
}
/// Round half up to a whole level (both for the reference and for the rendered result).
fn whole(v: f32) -> f32 {
(v * 255.0 + 0.5).floor()
}
/// The measured grays: 128 -> 64 -> 114, so the channel curve's output is a whole level on its
/// way to the composite curve.
#[test]
fn measured_grays_round_the_channel_before_the_composite() {
let adj = measured();
for (g, want) in [(64u32, [37, 114, 114]), (128, [114, 200, 200]), (192, [217, 241, 241])] {
assert_eq!(gray8(&adj, g), want, "gray {g}");
}
}
/// Every level of an 8-bit ramp: the red output equals the composite curve applied to the channel
/// curve rounded to a whole level, each curve the natural spline through its points.
#[test]
fn the_eight_bit_ramp_is_the_composite_of_the_rounded_channel_curve() {
let adj = measured();
let red = curve_samples::<256>(&pts(RED));
let master = curve_samples::<256>(&pts(COMPOSITE));
let mut b = Buffer { rect: Rect::new(0, 0, 256, 1), px: (0..256).map(|x| [level(x), level(x), level(x), 1.0]).collect() };
apply_depth(&adj, &mut b, Transfer::Srgb, Some(SampleType::U8));
let bad: Vec<String> = (0..256)
.filter_map(|x| {
let (got, want) = (whole(b.px[x][0]), whole(master[whole(red[x]) as usize]));
(got != want).then(|| format!("{x}: {got} vs {want}"))
})
.collect();
assert!(bad.is_empty(), "{} of 256 red levels differ from composite(round(red(x))): {bad:?}", bad.len());
}
/// Not measured, so unchanged: at 16 bits, in float documents and without a depth the channel
/// LUT still goes into the composite LUT unrounded (an 8-bit level is 1/255, far above the
/// tolerance below).
#[test]
fn other_depths_keep_the_continuous_chain() {
let adj = measured();
let master_lut = curve_lut_mode(&pts(COMPOSITE), false);
let continuous = |points: &[CurvePoint]| -> Vec<f32> { curve_lut_mode(points, false).iter().map(|&v| lut(&master_lut, v)).collect() };
let rows = [continuous(&pts(RED)), continuous(&pts(STRAIGHT)), continuous(&pts(STRAIGHT)), continuous(&[])];
for depth in [None, Some(SampleType::U16), Some(SampleType::F32)] {
let built = tone_luts_depth(&adj, depth);
for ch in 0..4 {
let drift = built[ch].iter().zip(&rows[ch]).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
assert!(drift < 1e-6, "{depth:?} channel {ch}: {drift} off the continuous chain, a whole level is {}", 1.0 / 255.0);
}
}
let eight = tone_luts_depth(&adj, Some(SampleType::U8));
let stepped = eight[0].iter().zip(&rows[0]).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
assert!(stepped > 1e-4, "the 8-bit row must be the rounded chain, and is {stepped} off the unrounded one");
}
/// Also not measured: CMYK and Lab curves keep today's chain at every depth.
#[test]
fn cmyk_and_lab_curves_keep_the_continuous_chain() {
let straight = pts(STRAIGHT);
let black = pts(RED);
for space in [ToneSpace::Cmyk, ToneSpace::Lab] {
let mut adj = measured();
if let Adjustment::Curves { space: s, black: b, .. } = &mut adj {
*s = space;
*b = black.clone();
}
let master_lut = if space == ToneSpace::Lab { curve_lut(&[]) } else { curve_lut_mode(&pts(COMPOSITE), false) };
let continuous = |points: &[CurvePoint]| -> Vec<f32> { curve_lut_mode(points, false).iter().map(|&v| lut(&master_lut, v)).collect() };
// The fourth row is the black ink only in a CMYK curve; otherwise it is the unused identity.
let ink: &[CurvePoint] = if space == ToneSpace::Cmyk { &black } else { &[] };
let want = [continuous(&pts(RED)), continuous(&straight), continuous(&straight), continuous(ink)];
for depth in [Some(SampleType::U8), Some(SampleType::U16), None] {
let built = tone_luts_depth(&adj, depth);
for ch in 0..4 {
let drift = built[ch].iter().zip(&want[ch]).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
assert!(drift < 1e-6, "{space:?} {depth:?} channel {ch}: {drift} off the continuous chain");
}
}
}
}
/// Listing a curve's points in another order describes the same curve, and the rounding follows
/// the curve, not the order its points were typed in.
#[test]
fn the_point_order_of_each_curve_does_not_change_the_result() {
let mut adj = measured();
if let Adjustment::Curves { master, per_channel, .. } = &mut adj {
master.reverse();
for c in per_channel.iter_mut() {
c.reverse();
}
}
for g in [64u32, 128, 192] {
assert_eq!(gray8(&adj, g), gray8(&measured(), g), "gray {g} with the points listed in reverse");
}
}
/// A pencil channel step between levels 128 and 129 leaves level 128 at exactly zero on its way to
/// the composite curve: read between two table entries it came out as a fraction that rounded to
/// level 4, where the composite's own step turned it into 255.
#[test]
fn a_pencil_channel_step_reaches_the_composite_at_its_exact_level() {
let adj = Adjustment::Curves {
master: pts(&[(0, 0), (3, 0), (4, 255), (5, 0), (255, 0)]),
per_channel: [pts(&[(0, 0), (128, 0), (129, 255), (255, 255)]), pts(STRAIGHT), pts(STRAIGHT)],
space: ToneSpace::Rgb,
black: Vec::new(),
pencil: true,
};
assert_eq!(gray8(&adj, 128)[0], 0);
assert_eq!(gray8(&adj, 4)[0], 0, "level 4 maps to 0 through the channel, then 0 through the composite");
}
+75 -6
View File
@@ -38,6 +38,12 @@ pub fn tone_luts(adj: &Adjustment) -> [Vec<f32>; 4] {
/// [`tone_luts`] for samples with `quantum` steps per unit (Levels works on whole levels; see
/// [`levels_q`]).
pub fn tone_luts_q(adj: &Adjustment, quantum: Option<f32>) -> [Vec<f32>; 4] {
tone_luts_qc(adj, quantum, true)
}
/// [`tone_luts_q`]; `curve_levels` false leaves an 8-bit RGB Curves channel's output where the
/// spline put it instead of on a whole level (see [`tone_luts_depth_in`]).
fn tone_luts_qc(adj: &Adjustment, quantum: Option<f32>, curve_levels: bool) -> [Vec<f32>; 4] {
let x = |k: usize| k as f32 / (LUT_SIZE - 1) as f32;
match adj {
Adjustment::Levels { master, per_channel, space, black } => {
@@ -48,8 +54,37 @@ pub fn tone_luts_q(adj: &Adjustment, quantum: Option<f32>) -> [Vec<f32>; 4] {
}
Adjustment::Curves { master, per_channel, space, black, pencil } => {
let m = if *space == ToneSpace::Lab { curve_lut(&[]) } else { curve_lut_mode(master, *pencil) };
let row = |c: &[CurvePoint]| curve_lut_mode(c, *pencil).iter().map(|&v| lut(&m, v)).collect();
[row(&per_channel[0]), row(&per_channel[1]), row(&per_channel[2]), row(if *space == ToneSpace::Cmyk { black } else { &[] })]
// In an 8-bit document the channel curve's output sits on a whole level before the
// composite curve is applied to it, as every Levels step is above (#14446, measured:
// Red 0,0 128,64 255,255 with composite 0,0 128,200 255,255 gives gray 192 as 217,
// 128 as 114 and 64 as 37). The channel's input is snapped to its level as well, so
// the row is flat across a level and the table cannot blend two levels' results at a
// document sample - the way [`levels_q`] is exact at every level. 16-bit and float
// documents were not measured, nor CMYK and Lab curves, so only the 8-bit quantum.
let level = (curve_levels && *space == ToneSpace::Rgb && quantum == Some(EIGHT_BIT_LEVELS)).then_some(EIGHT_BIT_LEVELS);
// Both curves are evaluated at the 256 exact levels, not read between two entries of
// the 4096-entry table: a pencil step between levels 128 and 129 would otherwise give
// level 128 a small fraction that rounds up to level 4 and wakes a composite step there.
let master_levels = if *space == ToneSpace::Lab { curve_samples::<LEVELS>(&[]) } else { curve_samples_mode::<LEVELS>(master, *pencil) };
let row = |c: &[CurvePoint], level: Option<f32>| match level {
Some(q) => {
let channel = curve_samples_mode::<LEVELS>(c, *pencil);
let index = |v: f32| (whole_levels(v, Some(q)) * q).round().clamp(0.0, q) as usize;
(0..LUT_SIZE)
.map(|k| {
let ch = channel.get(index(x(k))).copied().unwrap_or(0.0);
master_levels.get(index(ch)).copied().unwrap_or(0.0)
})
.collect()
}
None => curve_lut_mode(c, *pencil).iter().map(|&v| lut(&m, v)).collect(),
};
[
row(&per_channel[0], level),
row(&per_channel[1], level),
row(&per_channel[2], level),
row(if *space == ToneSpace::Cmyk { black } else { &[] }, None),
]
}
_ => std::array::from_fn(|_| (0..LUT_SIZE).map(x).collect()),
}
@@ -59,13 +94,34 @@ pub fn tone_luts_q(adj: &Adjustment, quantum: Option<f32>) -> [Vec<f32>; 4] {
/// [`levels_float`], sampled on 0..1 and kept in 0..1 for LUT consumers. Float RGB rendering
/// evaluates the formula directly instead, so samples and results outside that domain survive.
pub fn tone_luts_depth(adj: &Adjustment, depth: Option<SampleType>) -> [Vec<f32>; 4] {
tone_luts_depth_in(adj, depth, true)
}
/// [`tone_luts_depth`]; `curve_levels` false for the RGB Curves that stand in for a CMYK
/// document's ink curves on the split route (`cmyk_split`): the exact ink path doesn't put CMYK
/// curves on whole levels, so neither may their stand-ins, or the two routes part by a level.
pub fn tone_luts_depth_in(adj: &Adjustment, depth: Option<SampleType>, curve_levels: bool) -> [Vec<f32>; 4] {
match (adj, depth) {
(Adjustment::Levels { master, per_channel, space: ToneSpace::Rgb, .. }, Some(SampleType::F32)) => {
let x = |k: usize| k as f32 / (LUT_SIZE - 1) as f32;
let row = |c: &LevelsChannel| (0..LUT_SIZE).map(|k| levels_float(master, levels_float(c, x(k))).clamp(0.0, 1.0)).collect();
[row(&per_channel[0]), row(&per_channel[1]), row(&per_channel[2]), (0..LUT_SIZE).map(x).collect()]
}
_ => tone_luts_q(adj, depth.and_then(crate::adjustment_quantum)),
_ => tone_luts_qc(adj, depth.and_then(crate::adjustment_quantum), curve_levels),
}
}
/// A document's quantum in whole 8-bit levels: [`crate::adjustment_quantum`]'s 8-bit step (see
/// [`levels_q`], which rounds each of its three steps to these).
const EIGHT_BIT_LEVELS: f32 = 255.0;
/// [`levels_q`]'s round-half-up to a whole level, for a Curves channel's output; `None` (any other
/// depth) leaves the sample where the spline put it.
#[inline]
fn whole_levels(v: f32, quantum: Option<f32>) -> f32 {
match quantum {
Some(q) => (v * q + 0.5).floor() / q,
None => v,
}
}
@@ -373,13 +429,26 @@ pub fn curve_lut_mode(points: &[CurvePoint], pencil: bool) -> Vec<f32> {
/// A pencil-drawn Curves map (see [`photocraft_doc::adjust::curve_map`]): straight segments
/// between its entries, constant outside the first/last, clamped to 0..=1, sampled into a LUT.
pub fn curve_map_lut(points: &[CurvePoint]) -> Vec<f32> {
curve_map_samples::<LUT_SIZE>(points)
}
/// Whole 8-bit levels: the sample count [`tone_luts_qc`] evaluates an 8-bit RGB Curves at.
const LEVELS: usize = 256;
/// [`curve_lut_mode`] sampled at `N` evenly spaced inputs including both end points.
fn curve_samples_mode<const N: usize>(points: &[CurvePoint], pencil: bool) -> Vec<f32> {
if pencil { curve_map_samples::<N>(points) } else { curve_samples::<N>(points) }
}
/// [`curve_map_lut`] sampled at `N` evenly spaced inputs including both end points.
fn curve_map_samples<const N: usize>(points: &[CurvePoint]) -> Vec<f32> {
let mut pts: Vec<(f32, f32)> = points.iter().filter(|p| p.input.is_finite() && p.output.is_finite()).map(|p| (p.input, p.output)).collect();
pts.sort_by(|a, b| a.0.total_cmp(&b.0));
pts.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-6);
let ident = |k: usize| k as f32 / (LUT_SIZE - 1) as f32;
let (Some(&first), Some(&last)) = (pts.first(), pts.last()) else { return (0..LUT_SIZE).map(ident).collect() };
let ident = |k: usize| k as f32 / N.saturating_sub(1).max(1) as f32;
let (Some(&first), Some(&last)) = (pts.first(), pts.last()) else { return (0..N).map(ident).collect() };
let mut seg = 0;
(0..LUT_SIZE)
(0..N)
.map(|k| {
let xv = ident(k);
if xv <= first.0 {
+79 -1
View File
@@ -109,7 +109,7 @@ fn thirty_two_bit_adjustments_match_photoshop_unclipped() {
// brightness-contrast-legacy.psd
assert!(near(hdr(&bc, [0.4910, 0.0009, 0.9301]), [0.6280, -0.0721, 1.2553], 2e-4), "{:?}", hdr(&bc, [0.4910, 0.0009, 0.9301]));
// channel-mixer.psd: pure red, green, blue and black, exactly.
let mixer = Adjustment::ChannelMixer { matrix: [[0.8, 0.3, -0.1, 0.0], [0.1, 0.9, 0.0, 0.05], [0.0, 0.2, 0.7, 0.0]], monochrome: false };
let mixer = Adjustment::ChannelMixer { matrix: [[0.8, 0.3, -0.1, 0.0], [0.1, 0.9, 0.0, 0.05], [0.0, 0.2, 0.7, 0.0]], monochrome: false, cmyk: None };
for (c, want) in [
([1.0, 0.0, 0.0], [0.7998047, 0.1245117, 0.0]),
([0.0, 1.0, 0.0], [0.2998047, 0.9243164, 0.1992188]),
@@ -857,6 +857,84 @@ fn lab_gradient_map_follows_l() {
}
}
/// A CMYK Channel Mixer mixes the ink amounts (#8047): identity keeps the pixel, a mix moves
/// only the ink it targets (a positive constant adds ink), monochrome puts its mix in the black
/// ink alone, and odd values never panic.
#[test]
fn cmyk_channel_mixer_mixes_the_inks() {
let identity = photocraft_doc::adjust::CMYK_MIXER_IDENTITY;
let ink = [0.2, 0.4, 0.6, 0.1];
let mut same = ink;
mix_inks(&identity, false, &mut same);
assert!(same.iter().zip(&ink).all(|(g, w)| (g - w).abs() < 1e-6), "{same:?}");
let mut rows = identity;
rows[2] = [0.0, 0.0, 1.0, 0.0, 0.25];
let mut more_yellow = ink;
mix_inks(&rows, false, &mut more_yellow);
let want = [0.2, 0.4, 0.85, 0.1];
assert!(more_yellow.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-6), "{more_yellow:?}");
let mut mono = ink;
mix_inks(&identity, true, &mut mono);
assert!(mono[..3] == [0.0; 3] && (mono[3] - 0.2).abs() < 1e-6, "{mono:?}");
let mut odd = [f32::NAN, f32::INFINITY, -3.0, 9.0];
mix_inks(&[[f32::MAX; 5]; 4], false, &mut odd);
assert!(odd.iter().all(|v| (0.0..=1.0).contains(v)), "{odd:?}");
mix_inks(&identity, false, &mut [0.5]);
// In a CMYK document the mixer works on the screen colour's separation: identity is
// the round trip through the inks alone; elsewhere it's the same.
let mixer =
Adjustment::ChannelMixer { matrix: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], monochrome: false, cmyk: Some(identity) };
assert!(cmyk_channel_adjustment(&mixer) && cmyk_mixer(&mixer));
let c = [0.3, 0.5, 0.7, 1.0];
let round_trip = {
use photocraft_color::convert::{cmyk_to_rgb, rgb_to_cmyk};
cmyk_to_rgb(rgb_to_cmyk([c[0], c[1], c[2]]))
};
for mode in [ColorMode::Cmyk, ColorMode::Rgb] {
let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), c);
apply_in(&mixer, &mut b, Transfer::Srgb, Some(SampleType::U8), mode);
assert!((0..3).all(|i| (b.px[0][i] - round_trip[i]).abs() < 1e-5) && b.px[0][3] == 1.0, "{mode:?}: {:?}", b.px[0]);
}
let mut more_cyan = identity;
more_cyan[0][4] = 0.3;
let more_cyan =
Adjustment::ChannelMixer { matrix: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], monochrome: false, cmyk: Some(more_cyan) };
for mode in [ColorMode::Cmyk, ColorMode::Rgb] {
let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), c);
apply_in(&more_cyan, &mut b, Transfer::Srgb, Some(SampleType::U8), mode);
assert!(b.px[0][0] < round_trip[0] - 0.05, "{mode:?}: more cyan ink takes red away: {:?}", b.px[0]);
}
// In a 32-bit document an identity mixer keeps samples past 0..1, and an edit still applies.
let hdr = [2.0, 0.5, 0.25, 1.0];
let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), hdr);
apply_in(&mixer, &mut b, Transfer::Gamma(1.0), Some(SampleType::F32), ColorMode::Rgb);
assert!((0..3).all(|i| (b.px[0][i] - hdr[i]).abs() < 1e-5), "identity keeps the HDR highlight: {:?}", b.px[0]);
let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), hdr);
apply_in(&more_cyan, &mut b, Transfer::Gamma(1.0), Some(SampleType::F32), ColorMode::Rgb);
assert!(b.px[0][0] > 1.0 && b.px[0][0] < hdr[0] - 0.05, "more cyan takes red away and keeps it HDR: {:?}", b.px[0]);
}
/// Photoshop's own CMYK Channel Mixer (photoshop corpus cmyk16 channel-mixer.psd, made with
/// cyan 80/30/-10, magenta 10/90/0 +5, yellow 0/20/70 and an all-zero black record) on three of
/// its pixels: each output ink is the mix of the ink amounts, and the empty black record leaves no
/// black ink. Values are the file's 16-bit samples (stored as 1 - ink).
#[test]
fn cmyk_channel_mixer_matches_photoshop_pixels() {
let rows = [[0.8, 0.3, -0.1, 0.0, 0.0], [0.1, 0.9, 0.0, 0.0, 0.05], [0.0, 0.2, 0.7, 0.0, 0.0], [0.0; 5]];
let ink = |v: [u16; 4]| v.map(|x| 1.0 - f32::from(x) / 65535.0);
for (before, after) in [
([65535, 8738, 0, 65535], [55035, 11188, 8396, 65535]),
([31612, 37007, 37007, 60395], [32692, 33233, 39905, 65535]),
([16448, 21074, 21588, 6426], [17322, 17392, 25950, 65535]),
] {
let mut got = ink(before);
mix_inks(&rows, false, &mut got);
let want = ink(after);
assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() <= 1.0 / 255.0), "{before:?}: {got:?} vs {want:?}");
}
}
#[test]
fn other_modes_and_adjustments_keep_the_screen_colour_path() {
let c = [0.2, 0.5, 0.7, 1.0];
+3 -3
View File
@@ -316,8 +316,8 @@ fn combine(cmy: &Buffer, k: &Buffer) -> CmykBuffer {
pub(super) fn render_bands<E>(doc: &Document, rect: Rect, band_rows: i32, tile: i32, mut sink: impl FnMut(CmykBuffer) -> Result<(), E>) -> Result<(), E> {
let (cmy, k) = (stand_in(doc, CMY), stand_in(doc, K));
let no_patterns = pattern::PreparedPatterns::new(&[], pattern::PREPARED_PATTERN_BYTES);
let a = StandIn { doc: &cmy, cx: Ctx::for_doc(&cmy, &no_patterns) };
let b = StandIn { doc: &k, cx: Ctx::for_doc(&k, &no_patterns) };
let a = StandIn { doc: &cmy, cx: Ctx { curve_levels: false, ..Ctx::for_doc(&cmy, &no_patterns) } };
let b = StandIn { doc: &k, cx: Ctx { curve_levels: false, ..Ctx::for_doc(&k, &no_patterns) } };
let rows = crate::band_rows_for(rect.width(), band_rows);
let mut y = rect.y0;
while y < rect.y1 {
@@ -336,7 +336,7 @@ pub(super) fn render_bands<E>(doc: &Document, rect: Rect, band_rows: i32, tile:
pub(super) fn render_planes(doc: &Document, rect: Rect, planes: Planes) -> Buffer {
let d = stand_in(doc, planes);
let no_patterns = pattern::PreparedPatterns::new(&[], pattern::PREPARED_PATTERN_BYTES);
let s = StandIn { doc: &d, cx: Ctx::for_doc(&d, &no_patterns) };
let s = StandIn { doc: &d, cx: Ctx { curve_levels: false, ..Ctx::for_doc(&d, &no_patterns) } };
s.prepare(rect);
s.tile(rect)
}
+18 -2
View File
@@ -60,6 +60,9 @@ pub(crate) struct Ctx<'a> {
pub(crate) doc: Option<&'a Document>,
/// Effect-map identities of this render's document layers (see [`LayerKeys`]).
pub(crate) layer_keys: LayerKeys,
/// Whether 8-bit RGB Curves put each channel's output on a whole level
/// ([`adjust::tone_luts_depth_in`]); false for the split route's CMYK stand-ins.
pub(crate) curve_levels: bool,
}
/// Memo of [`layer_identity`] for the layers of the document being rendered. The identity depends
@@ -130,6 +133,7 @@ impl<'a> Ctx<'a> {
fx_over_budget: fx_over_budget(&doc.layers, doc.bounds()),
layer_keys: Default::default(),
tone_luts: prepare_tones(&doc.layers, 0),
curve_levels: true,
}
}
@@ -143,16 +147,28 @@ impl<'a> Ctx<'a> {
}
pub(crate) fn apply_adjustment(&self, adj: &photocraft_doc::Adjustment, buf: &mut Buffer) {
let cached = self.tone_luts.iter().find(|(a, _)| std::ptr::eq(*a, adj));
// Without a cached table, only a stand-in's tables (unrounded Curves) are built here;
// other documents take `apply_in`, which builds the same tables as `for_doc` would.
if let photocraft_doc::Adjustment::Levels { space, .. } | photocraft_doc::Adjustment::Curves { space, .. } = adj
&& !matches!(adj, photocraft_doc::Adjustment::Levels { space: photocraft_doc::adjust::ToneSpace::Rgb, .. } if self.depth == photocraft_color::SampleType::F32)
&& let Some((_, luts)) = self.tone_luts.iter().find(|(a, _)| std::ptr::eq(*a, adj))
&& (cached.is_some() || !self.curve_levels)
{
let identity = adjust::float_tone_identity(adj, Some(self.depth));
if identity == [true; 3] {
return;
}
let extrapolate = adjust::float_tone_extrapolates(adj, Some(self.depth), self.mode);
adjust::apply_tone(buf, *space, luts.get_or_init(|| adjust::tone_luts_depth(adj, Some(self.depth))), identity, extrapolate);
let tables = || adjust::tone_luts_depth_in(adj, Some(self.depth), self.curve_levels);
let built;
let luts = match cached {
Some((_, luts)) => luts.get_or_init(tables),
None => {
built = tables();
&built
}
};
adjust::apply_tone(buf, *space, luts, identity, extrapolate);
} else {
adjust::apply_in(adj, buf, self.transfer, Some(self.depth), self.mode);
}
+8 -1
View File
@@ -249,13 +249,20 @@ impl FxMaps {
#[cfg(test)]
mod inner_shadow_anti_alias_tests;
#[cfg(test)]
mod outer_glow_noise_tests;
mod inner_shadow_size_one_tests;
#[cfg(test)]
mod inner_shadow_noise_tests;
#[cfg(test)]
mod outer_glow_noise_tests;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod outer_glow_range_one_tests;
#[cfg(test)]
mod satin_invert_contour_tests;
#[cfg(test)]
@@ -229,21 +229,35 @@ fn the_off_path_is_bit_for_bit_unchanged() {
/// The review's first break: the issue's document with SIZE 1 (Angle 0, Distance 0, Choke 0,
/// Gaussian, Anti-aliased on). `spread_split(1, 0)` is `(0, 1)`, so `dilate` no-ops at a radius of
/// 0 and `blur(m, 1.0)` is the identity (`tent_kernel(1).0 == 0`, and `tent` returns at once): the
/// third-of-a-pixel source offset becomes the whole map. Coverage 1/3 through the Gaussian
/// contour (0.30) then lands on the bottom and right inner edges only, G 90 where the layer reads
/// its own 128, and nothing at the top and left - a one-sided black line that no measurement
/// shows, because Size 1 was never measured with the flag on. Today's Size 1 map is empty and
/// has to stay empty.
/// third-of-a-pixel source offset would become the whole map. Coverage 1/3 through the Gaussian
/// contour (0.30) would then land on the bottom and right inner edges only, G 90 where the layer
/// reads its own 128, and nothing at the top and left - a one-sided black line that no measurement
/// shows, because Size 1 was never measured with the flag on. So the offset stays off at Size 1.
/// (Written when today's Size 1 map was empty; #14933 merged in after it and gave Size 1 the
/// quarter-strength edge pixel the reference shows - with the flag off as with it on, so the
/// invariant this test pins, that Anti-aliased does not move the Size 1 map, stands.)
#[test]
fn anti_aliased_size_one_keeps_todays_empty_map() {
fn anti_aliased_size_one_leaves_the_map_the_other_pr_fixed() {
let off = map(1.0, 0.0, 0.0, 0.0, gaussian(), false);
assert!(off.v.iter().all(|v| *v == 0.0), "today's Size 1 inner shadow map is no longer empty");
let on = map(1.0, 0.0, 0.0, 0.0, gaussian(), true);
for (side, x, y) in [("bottom", 200i64, 224), ("right", 299, 150), ("top", 200, 75), ("left", 100, 150)] {
let got = g(on.get(x, y));
assert_eq!(got.round() as i32, 128, "Anti-aliased Size 1 painted the {side} inner edge: G {got:.1}");
}
assert_eq!(bit_hash(&on), bit_hash(&off), "the Size 1 inner shadow map moved with Anti-aliased on");
// The map #14933 fixed: a darkened first pixel inside every edge, the same on all four sides
// (the one-sided line the offset would paint is dark on two and clean on the other two), and
// the layer's own 128 one pixel deeper. This file's contour is the Gaussian curve, so the
// first pixel reads darker than the 96 the Size 1 test's default contour gives.
let mut firsts = [0.0f32; 4];
for (k, (side, x, y, dx, dy)) in
[("bottom", 200i64, 224, 0, -1), ("right", 299, 150, -1, 0), ("top", 200, 75, 0, 1), ("left", 100, 150, 1, 0)].into_iter().enumerate()
{
let got = g(on.get(x, y));
firsts[k] = got;
assert!(got < 126.0, "Size 1 left the {side} inner edge clean: G {got:.1}");
let deeper = g(on.get(x + dx, y + dy));
assert!((deeper - 128.0).abs() <= 2.0, "Size 1 beyond the first pixel at the {side} inner edge: G {deeper:.1}");
}
for pair in [(0usize, 1usize), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] {
assert!((firsts[pair.0] - firsts[pair.1]).abs() < 0.05, "the Size 1 inner shadow is not symmetric: {firsts:?}");
}
}
/// The second degeneracy the review names: Size 2 with Choke 50 %. `spread_split(2, 0.5)` is
@@ -0,0 +1,197 @@
//! #14933 — BUG-LAYER-STYLE-INNER-SHADOW-SIZE-ONE.
//!
//! Measured on the issue's test document: 400 × 300 px, 72 ppi, RGB 8 bit, white Background, an
//! orange (255, 128, 0) pixel layer covering x 100..299, y 75..224. Inner Shadow black, Normal,
//! 100 %, Use Global Light off, Distance 0, Choke 0, Contour Linear, Anti-aliased off, Noise 0.
//! The issue's table is the G channel of the flattened image read from a layer edge inwards:
//! 128 is the layer's own orange (no shadow), 0 is full shadow.
use super::*;
const DOC_W: usize = 400;
const DOC_H: usize = 300;
/// The layer's alpha over the whole document: solid over x 100..=299, y 75..=224.
fn document_shape() -> Map {
let mut m = Map::new(DOC_W, DOC_H, 0.0);
for y in 75..=224 {
for x in 100..=299 {
m.v[y * DOC_W + x] = 1.0;
}
}
m
}
/// The issue's Inner Shadow settings: black, Normal, 100 %, global light off, Choke `spread`.
fn shadow(size: f32, distance: f32, angle: f32, spread: f32) -> Shadow {
Shadow {
common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0),
color: photocraft_color::Color::BLACK,
angle,
use_global_light: false,
distance,
spread,
size,
contour: Contour::Linear,
anti_alias: false,
noise: 0.0,
knocks_out: false,
}
}
fn map(size: f32, distance: f32, angle: f32, spread: f32) -> Map {
shadow_map(&document_shape(), &shadow(size, distance, angle, spread), &GlobalLight::default(), true, (0, 0))
}
/// The G channel of the orange layer under a black Normal inner shadow of coverage `c`.
fn g(c: f32) -> f32 {
128.0 * (1.0 - c)
}
/// The twenty G values inwards from each of the four edges, in the order the issue reads them:
/// top = column x 200 from y 75 down, left = row y 150 from x 100, bottom = column x 200 from
/// y 224 up, right = row y 150 from x 299 left.
fn ramps(m: &Map) -> [Vec<f32>; 4] {
let line = |first: (i64, i64), step: (i64, i64)| (0..20).map(|k| g(m.get(first.0 + k * step.0, first.1 + k * step.1))).collect();
[line((200, 75), (0, 1)), line((100, 150), (1, 0)), line((200, 224), (0, -1)), line((299, 150), (-1, 0))]
}
/// Assert the ten-pixel G ramp of every edge against `want`, within 2 levels (the issue's
/// tolerance) and the same on all four sides.
fn assert_edges(m: &Map, want: &[f32], what: &str) {
let [top, left, bottom, right] = ramps(m);
for (side, r) in ["top", "left", "bottom", "right"].iter().zip([top.as_slice(), left.as_slice(), bottom.as_slice(), right.as_slice()]) {
for (d, w) in want.iter().enumerate() {
assert!((r[d] - *w).abs() <= 2.0, "{what}, {side} edge, {d} px in: {} vs measured {w}", r[d]);
}
}
}
/// Done when: Size 1, Distance 0 puts G 96 (within 2 levels) on the first pixel inside every edge
/// and leaves the second one at the layer's own 128. Today `shadow_map` blurs with a width-1 box,
/// which is the identity, so the map is still the hard inverted alpha and the clip to the layer
/// removes the shadow completely: every pixel stays 128.
#[test]
fn size_one_draws_the_measured_edge_pixel() {
assert_edges(&map(1.0, 0.0, 0.0, 0.0), &[96.0, 128.0], "Size 1");
// Outside the layer nothing changes: the map is still clipped to the shape, so white stays white
// at y 74 and x 99.
let m = map(1.0, 0.0, 0.0, 0.0);
for (x, y) in [(200i64, 74), (99, 150), (200, 225), (300, 150)] {
assert_eq!(m.get(x, y), 0.0, "no inner shadow outside the layer at ({x},{y})");
}
}
/// Done when: Sizes 3, 10 and 20 keep the measured profiles (they already match today).
#[test]
fn sizes_three_ten_and_twenty_keep_the_measured_profiles() {
let table: [(f32, &[f32]); 3] = [
(3.0, &[85.0, 114.0, 128.0]),
(10.0, &[70.0, 82.0, 92.0, 101.0, 109.0, 115.0, 120.0, 124.0, 126.0, 128.0]),
(20.0, &[67.0, 73.0, 79.0, 84.0, 89.0, 94.0, 99.0, 103.0, 107.0, 110.0, 113.0, 116.0, 119.0, 121.0, 123.0, 125.0, 126.0, 127.0, 127.0, 128.0]),
];
for (size, want) in table {
assert_edges(&map(size, 0.0, 0.0, 0.0), want, &format!("Size {size}"));
}
}
/// Done when: Size 0 keeps the hard band of Distance pixels. Measured: Size 0, Distance 5,
/// Angle 90 reads 0 for five pixels from the top edge and 128 after that; the other edges stay 128.
#[test]
fn size_zero_keeps_the_hard_band_of_distance() {
let m = map(0.0, 5.0, 90.0, 0.0);
let col: Vec<f32> = (75..81).map(|y| g(m.get(200, y))).collect();
assert_eq!(&col[..5], &[0.0f32; 5][..], "five dark pixels then 128: {col:?}");
assert_eq!(col[5], 128.0, "the band ends after Distance pixels: {col:?}");
// The other three edges read their own colour at the pixel the issue reads them from.
for k in 0..6 {
assert_eq!(g(m.get(100 + k, 150)), 128.0, "left edge keeps its own colour, x {}", 100 + k);
assert_eq!(g(m.get(299 - k, 150)), 128.0, "right edge keeps its own colour, x {}", 299 - k);
assert_eq!(g(m.get(200, 224 - k)), 128.0, "bottom edge keeps its own colour, y {}", 224 - k);
}
}
/// A hash over every coverage value of a map: the map is bit-for-bit unchanged iff this is.
fn bit_hash(m: &Map) -> u64 {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for v in &m.v {
h = (h ^ u64::from(v.to_bits())).wrapping_mul(0x0000_0100_0000_01b3);
}
h
}
/// Every other Size 1 and every other size is bit-for-bit what it was: these are the coverage
/// ramps and whole-map hashes `shadow_map` gave on upstream/main c162cb6d6 before the fix, copied
/// out of the probe run. They pin that the Size 1 kernel is taken only by the Inner Shadow of
/// Size 1 with Choke 0 — sub-1 and fractional sizes (which the issue leaves unmeasured), sizes
/// 1.5..250, the Drop Shadow of the same size (#14880 keeps its own ticket) and a choked Size 1
/// all keep today's map.
#[test]
fn other_sizes_are_unchanged() {
let pin = |m: &Map, want: &[f64]| {
let got: Vec<f32> = (75..87).map(|y| m.get(200, y)).collect();
for (d, (g, w)) in got.iter().zip(want).enumerate() {
assert!((f64::from(*g) - *w).abs() <= 1e-6, "{d} px in: {g:.8} vs {w:.8} on main");
}
};
let sizes: [(f32, &[f64]); 8] = [
(0.5, &[0.0; 12]),
(1.5, &[0.25, 0.02777778, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
(2.0, &[0.3125, 0.0625, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
(3.0, &[0.33333334, 0.11111111, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
(6.0, &[0.42361110, 0.28472221, 0.17361110, 0.09027778, 0.03472222, 0.00694444, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
(10.0, &[0.45249999, 0.36250001, 0.28250000, 0.21250001, 0.15250000, 0.10250000, 0.06250000, 0.03250000, 0.01250000, 0.00250000, 0.0, 0.0]),
(
20.0,
&[0.47562501, 0.42812499, 0.38312501, 0.34062499, 0.30062500, 0.26312500, 0.22812501, 0.19562501, 0.16562501, 0.13812500, 0.11312500, 0.09062500],
),
(
250.0,
&[0.45157880, 0.45233655, 0.45308408, 0.45382136, 0.45454839, 0.45526519, 0.45597175, 0.45666808, 0.45735416, 0.45802999, 0.45869559, 0.45935094],
),
];
let hashes: [(f32, u64); 8] = [
(0.5, 0xe94d_157b_1934_6225),
(1.5, 0xbbca_5e75_8b9f_520d),
(2.0, 0x6bd5_69ac_da8a_6225),
(3.0, 0x3109_0d74_08b1_8c1d),
(6.0, 0xe5dc_989a_bcfb_ed89),
(10.0, 0x2200_2b2d_61bc_9c2d),
(20.0, 0x8ba0_be17_19fa_7b25),
(250.0, 0x460f_fa2e_3da8_0c4d),
];
for (size, want) in sizes {
pin(&map(size, 0.0, 0.0, 0.0), want);
}
for (size, want) in hashes {
let got = bit_hash(&map(size, 0.0, 0.0, 0.0));
assert_eq!(got, want, "the whole Size {size} inner shadow map moved");
}
// A Drop Shadow of Size 1 keeps today's hard inverted alpha (#14880 is its own ticket).
let drop = |size: f32| shadow_map(&document_shape(), &shadow(size, 0.0, 0.0, 0.0), &GlobalLight::default(), false, (0, 0));
let one = drop(1.0);
let got: Vec<f32> = (72..84).map(|y| one.get(200, y)).collect();
assert_eq!(&got[..3], &[0.0f32; 3][..], "a Size 1 drop shadow still paints nothing outside the layer: {got:?}");
assert_eq!(&got[3..], &[1.0f32; 9][..], "and stays hard inside it: {got:?}");
assert_eq!(bit_hash(&one), 0xa067_0cbe_8a34_6225, "the whole Size 1 drop shadow map moved");
assert_eq!(bit_hash(&drop(3.0)), 0xc097_cc3a_25df_6ae5, "the whole Size 3 drop shadow map moved");
// Size 1 with Choke 50 % is not measured either: today it is a hard 1 px band.
let choked = map(1.0, 0.0, 0.0, 0.5);
assert_eq!(choked.get(200, 74), 0.0);
assert_eq!(choked.get(200, 75), 1.0, "a choked Size 1 inner shadow keeps its hard band");
assert_eq!(choked.get(200, 76), 0.0);
assert_eq!(bit_hash(&choked), 0xde5c_6e74_9734_6225, "the choked Size 1 map moved");
}
/// The kernel is distance-independent, so a Size 1 inner shadow away from the light keeps the
/// band of Distance pixels and gains the same ¾ / ¼ coverage where the band ends. That
/// combination is not in the issue's measured table; it is spelled out here so the consequence of
/// the kernel is visible rather than assumed.
#[test]
fn size_one_at_a_distance_adds_the_ramp_at_the_band_edge() {
let m = map(1.0, 5.0, 90.0, 0.0);
let col: Vec<f32> = (75..83).map(|y| g(m.get(200, y))).collect();
assert_eq!(&col[..4], &[0.0f32; 4][..], "the band of Distance pixels: {col:?}");
assert!((col[4] - 32.0).abs() <= 2.0 && (col[5] - 96.0).abs() <= 2.0, "the quarter ramp where the band ends: {col:?}");
assert_eq!(&col[6..], &[128.0f32; 2][..], "and nothing deeper: {col:?}");
}
@@ -0,0 +1,186 @@
//! #14958: the Outer Glow Range 1 % profile on the measured document.
//!
//! Test document: 400 x 300 px, 72 ppi, RGB 8 bit, white Background, pixel layer "Shape" with an
//! orange (255,128,0) rectangle at x 100..299, y 75..224. Outer Glow black, Normal 100 %, Softer,
//! Spread 0, Size 10, Contour Linear, Anti-aliased off, Noise 0. Profiles list the R channel of
//! the flattened image from the layer edge outwards (255 = no glow, 0 = full black glow); the
//! reference application gives `0 x8, 39, 255` at Range 1 % on all four edges (within 3 levels).
//! Range 25/50/100 keep today's profiles (the measured values, within 4 levels). The cases the
//! issue marks *not measured* (Range 2, other Sizes at Range 1, Precise at Range 1, Range 1 with
//! Spread, a custom contour at Range 1, the Inner Glow Center source at Range 1) pin today's
//! output. The last inner test mirrors #14929's measured Inner Glow Range-1 profile `0 x8, 19,
//! 128` through the shared table as a cross-check; it does not claim that issue's item.
use super::{Contour, Effect, FxPaint, Glow, GlowSource, GlowTechnique, Rect};
use photocraft_color::{BlendMode, Color, ColorMode, PixelFormat, SampleType};
use photocraft_doc::{Document, FxCommon, Layer};
use photocraft_geom::Size;
/// The measured glow with `range` (0..=1): Size 10, Spread 0, Softer, Edge, Linear contour.
fn glow(range: f32) -> Glow {
Glow {
common: FxCommon::new(BlendMode::Normal, 1.0),
paint: FxPaint::Color(Color::BLACK),
technique: GlowTechnique::Softer,
spread: 0.0,
size: 10.0,
contour: Contour::Linear,
anti_alias: false,
range,
jitter: 0.0,
noise: 0.0,
source: GlowSource::Edge,
}
}
/// The measured document with one glow effect on the orange rectangle; `inner` for an Inner Glow.
fn measured_doc(g: Glow, inner: bool) -> Document {
let mut d = Document::with_background("range one", Size::new(400, 300), ColorMode::Rgb, SampleType::U8, Color::WHITE);
let mut l = Layer::raster("Shape", PixelFormat::RGBA8);
l.surface_mut().unwrap().fill_rect(Rect::new(100, 75, 300, 225), &[1.0, 128.0 / 255.0, 0.0, 1.0]);
l.effects.items = vec![if inner { Effect::InnerGlow(g) } else { Effect::OuterGlow(g) }];
d.layers.push(l);
d
}
/// The pixel `d` (1-based) out from edge `e` (0 top, 1 left, 2 bottom, 3 right) of the rectangle.
fn out_point(e: usize, d: usize) -> (i32, i32) {
let d = d as i32;
match e {
0 => (200, 75 - d),
1 => (100 - d, 150),
2 => (200, 224 + d),
_ => (299 + d, 150),
}
}
/// The pixel `d` (1-based) in from edge `e`, for the inner-glow checks.
fn in_point(e: usize, d: usize) -> (i32, i32) {
let d = d as i32;
match e {
0 => (200, 74 + d),
1 => (99 + d, 150),
2 => (200, 225 - d),
_ => (300 - d, 150),
}
}
/// The flattened 8-bit level of channel `ch` at `(x, y)` in the already-rendered buffer `b`.
fn level(b: &crate::Buffer, x: i32, y: i32, ch: usize) -> i32 {
let w = b.rect.width() as usize;
(255.0 * b.px[(y - b.rect.y0) as usize * w + (x - b.rect.x0) as usize][ch]).round() as i32
}
/// Compares the `want.len()` pixels from each of the four edges along channel `ch` (inwards for
/// inner glows) against `want`, level by level, within `tol`.
fn assert_all_edges(doc: &Document, ch: usize, inward: bool, want: &[i32], tol: i32, what: &str) {
let b = crate::render(doc, doc.bounds());
for e in 0..4 {
for (d, &want) in want.iter().enumerate() {
let (x, y) = if inward { in_point(e, d + 1) } else { out_point(e, d + 1) };
let got = level(&b, x, y, ch);
assert!(got - want <= tol && want - got <= tol, "{what}, edge {e}, {} px from the edge: expected {want}, got {got} (want {want:?})", d + 1);
}
}
}
/// #14958 Done when 1: Range 1 % at Size 10 gives eight solid pixels, then 39, then no glow on
/// all four edges, within 3 levels. Today (main) the glow reaches one pixel further with a much
/// lighter last pixel: nine solid, then 191.
#[test]
fn outer_glow_range_one_gives_eight_solid_then_39_on_every_edge() {
assert_all_edges(&measured_doc(glow(0.01), false), 0, false, &[0, 0, 0, 0, 0, 0, 0, 0, 39, 255, 255, 255], 3, "Range 1 %");
}
/// #14958 Done when 2 (guard, passes before and after): Range 25 keeps today's profile, matching
/// the measured `0 0 0 42 103 153 194 225 245 255` within 4 levels.
#[test]
fn outer_glow_range_25_keeps_the_measured_profile() {
assert_all_edges(&measured_doc(glow(0.25), false), 0, false, &[0, 0, 0, 42, 103, 153, 194, 225, 245, 255, 255, 255], 4, "Range 25 %");
}
/// #14958 Done when 2 (guard): Range 50 keeps today's measured `26 72 113 148 179 204 225 240
/// 250 255` within 4 levels.
#[test]
fn outer_glow_range_50_keeps_the_measured_profile() {
assert_all_edges(&measured_doc(glow(0.5), false), 0, false, &[26, 72, 113, 148, 179, 204, 225, 240, 250, 255, 255, 255], 4, "Range 50 %");
}
/// #14958 Done when 2 (guard): Range 100 keeps today's measured `140 163 184 201 217 229 240
/// 247 252 255` within 4 levels.
#[test]
fn outer_glow_range_100_keeps_the_measured_profile() {
assert_all_edges(&measured_doc(glow(1.0), false), 0, false, &[140, 163, 184, 201, 217, 229, 240, 247, 252, 255, 255, 255], 4, "Range 100 %");
}
/// The first pixel inside the edge stays the layer colour: the glow never covers the layer
/// itself (guard, passes before and after).
#[test]
fn outer_glow_range_one_never_covers_the_layer_itself() {
let d = measured_doc(glow(0.01), false);
let b = crate::render(&d, d.bounds());
let inside = [level(&b, 200, 75, 0), level(&b, 200, 75, 1), level(&b, 200, 75, 2)];
assert_eq!(inside, [255, 128, 0], "(200, 75) stays the layer colour 255.128.0");
}
/// Cross-check of the shared cause with #14929 (no claim on that item): its measured Inner Glow
/// Range-1 profile is the mirror image `0 x8, 19, 128` on the G channel of the same document.
/// Today the glow reaches one pixel further inwards (nine solid, then 96).
#[test]
fn inner_glow_range_one_mirrors_the_measured_profile() {
assert_all_edges(&measured_doc(glow(0.01), true), 1, true, &[0, 0, 0, 0, 0, 0, 0, 0, 19, 128, 128, 128], 3, "inner Range 1 %");
}
/// Not measured, keeps today's behaviour: a Precise glow at Range 1 % (its coverage stays above
/// the range down to the last pixel of its falloff).
#[test]
fn outer_glow_range_one_precise_keeps_todays_profile() {
let g = Glow { technique: GlowTechnique::Precise, ..glow(0.01) };
assert_all_edges(&measured_doc(g, false), 0, false, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255], 1, "precise Range 1 %");
}
/// Not measured, keeps today's behaviour: Range 1 % with Spread 20 % (dilate 2, tent 8: solid
/// through 9 px, then 155, then no glow).
#[test]
fn outer_glow_range_one_with_spread_keeps_todays_profile() {
let g = Glow { spread: 0.2, ..glow(0.01) };
assert_all_edges(&measured_doc(g, false), 0, false, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 155, 255, 255], 1, "spread 20 % at Range 1 %");
}
/// Not measured, keeps today's behaviour: another Size at Range 1 % (Size 20: solid through 17
/// px, then 48, 175, 239, then no glow).
#[test]
fn outer_glow_range_one_other_sizes_keep_todays_profile() {
let g = Glow { size: 20.0, ..glow(0.01) };
assert_all_edges(&measured_doc(g, false), 0, false, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 48, 175, 239, 255], 1, "size 20 at Range 1 %");
}
/// Not measured, keeps today's behaviour: a whole-number Range next to 1 (2 %: solid through 8
/// px, then 96, 223, then no glow).
#[test]
fn outer_glow_range_two_keeps_todays_profile() {
assert_all_edges(&measured_doc(glow(0.02), false), 0, false, &[0, 0, 0, 0, 0, 0, 0, 0, 96, 223, 255, 255], 1, "Range 2 %");
}
/// Not measured, keeps today's behaviour: a custom (flat) contour at Range 1 % keeps the
/// #11361 reach-capped transfer (solid through 10 px, then no glow).
#[test]
fn outer_glow_range_one_custom_contour_keeps_todays_profile() {
let g = Glow {
contour: Contour::Custom {
name: "flat".into(),
points: [(0.0, 1.0), (1.0, 1.0)].iter().map(|&(input, output)| photocraft_doc::adjust::CurvePoint { input, output }).collect(),
corners: vec![],
},
..glow(0.01)
};
assert_all_edges(&measured_doc(g, false), 0, false, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255], 1, "flat contour at Range 1 %");
}
/// Not measured, keeps today's behaviour: an Inner Glow from the Center at Range 1 % (no glow
/// for the first nine pixels in, one dim step at 10 px, full towards the middle).
#[test]
fn inner_glow_range_one_center_source_keeps_todays_profile() {
let g = Glow { source: GlowSource::Center, ..glow(0.01) };
assert_all_edges(&measured_doc(g, true), 1, true, &[128, 128, 128, 128, 128, 128, 128, 128, 128, 32, 0, 0], 1, "inner center at Range 1 %");
}
+35 -2
View File
@@ -1,4 +1,4 @@
use super::blur::{blur, dilate};
use super::blur::{blur, dilate, size_one_blur};
use super::distance::{dist_inside, dist_outside};
use super::{
BlendMode, Buffer, Contour, Effect, FxPaint, GlobalLight, Glow, GlowSource, GlowTechnique, Gradient, GradientStyle, Map, Placement, PreparedPatterns, Rect,
@@ -33,7 +33,32 @@ pub(super) fn lut_at(l: &[f32], v: f32) -> f32 {
/// A glow's coverage transfer: its contour applied over the Range (Photoshop maps the glow's
/// coverage `v` through `contour(min(v / range, 1))`, so the default 50 % doubles a blurred
/// edge's 0.5 to full strength). `None` = identity.
///
/// One measured exception (#14958, and #14929 through this same table): at the Range-1 % test
/// document (Softer, Size 10, Spread 0, Linear contour, Edge source) the reference application
/// hardens the glow instead of amplifying the blur's tail to one pixel further: the coverage at
/// the tent's last tap (its reach's outermost pixel, 0.0025 at Size 10) paints nothing, and the
/// coverage one pixel inside it (0.0125) paints 0.85 - measured as 39 of 255 outside the layer
/// and 19 of 128 inside. A linear ramp from that last tap to `range` plus 3/4 of it reproduces
/// all four measured pixels within 1 level (outer 40, inner 20, both reaches exact); today's
/// `min(v / range, 1)` there paints solid one pixel wider and leaves 191 (outer) / 96 (inner)
/// at the pixel the reference stops at. Every other configuration - all other Ranges, Sizes
/// and Spreads, Precise, the Center source, and custom contours - keeps `ranged_lut` exactly.
pub fn glow_lut(g: &Glow) -> Option<Vec<f32>> {
if matches!(g.contour, Contour::Linear)
&& matches!(g.technique, GlowTechnique::Softer)
&& g.source == GlowSource::Edge
&& g.spread == 0.0
&& g.size == 10.0
&& (g.range - 0.01).abs() < 1e-6
{
// `tent_kernel` stores its weights from -r to r and never an empty list, so its last
// entry is the tap at the reach's end (for Size 10: 1/400): the straight edge's
// coverage at the reach's outermost pixel. `end` 0 (unreachable) leaves today's ramp.
let end = super::blur::tent_kernel(g.size).1.last().copied().unwrap_or(0.0);
let full = g.range + 0.75 * end;
return Some((0..GLOW_LUT_LEN).map(|k| ((k as f32 / (GLOW_LUT_LEN - 1) as f32 - end) / full).clamp(0.0, 1.0)).collect());
}
ranged_lut(&g.contour, g.range)
}
@@ -453,7 +478,15 @@ pub(super) fn shadow_map(shape: &Map, s: &Shadow, light: &GlobalLight, inner: bo
let mut m = src.shifted(dx + aa, dy + aa, if inner { 1.0 } else { 0.0 });
let (r, bw) = spread_split(s.size, s.spread);
m = dilate(&m, r);
blur(&mut m, bw);
if inner && s.size == 1.0 && s.spread == 0.0 {
// #14933: a Size 1 inner shadow with Choke 0. At that width the box blur is the identity
// (`box_width` floors it at 1 px), so the map keeps the hard inverted alpha and the clip to
// the layer below removes the shadow completely. The reference application keeps a
// quarter-strength shadow on the first pixel inside every edge: `SIZE_ONE_TAPS`.
size_one_blur(&mut m);
} else {
blur(&mut m, bw);
}
let mut m = apply_contour(m, &s.contour);
noise(&mut m, s.noise, origin.0, origin.1);
if inner {
+6 -3
View File
@@ -9,7 +9,8 @@
//! it does there.
//!
//! Plain adjustment layers that Photoshop evaluates on the inks (Invert, Posterize, Threshold,
//! Brightness/Contrast, Hue/Saturation, Color Balance, and Levels and Curves on CMYK channels)
//! Brightness/Contrast, Hue/Saturation, Color Balance, a CMYK Channel Mixer, and Levels and
//! Curves on CMYK channels)
//! join such a stack too: on the
//! stored inks their rules are exact, where the RGB compositor can only apply them to a separation
//! of its RGB composite, whose black differs from the file's. Such stacks are also rendered for
@@ -54,7 +55,7 @@ enum InkOp<'a> {
/// Each ink's stored value (1 - ink) through its channel's table: C, M, Y, K
/// (`adjust::ink_through`; Levels, Curves and Brightness/Contrast).
Tables([Vec<f32>; INKS]),
/// Invert, Posterize or Threshold (`adjust::stored_channels`).
/// Invert, Posterize, Threshold or a CMYK Channel Mixer (`adjust::stored_channels`).
Rules(&'a Adjustment),
/// Hue/Saturation or Color Balance on C, M and Y as inverted RGB (`adjust::apply_cmy`).
Cmy(&'a Adjustment),
@@ -86,7 +87,9 @@ fn ink_op(layer: &Layer, depth: SampleType) -> Option<InkOp<'_>> {
return None;
}
match adj {
Adjustment::Invert | Adjustment::Posterize { .. } | Adjustment::Threshold { .. } => Some(InkOp::Rules(adj)),
Adjustment::Invert | Adjustment::Posterize { .. } | Adjustment::Threshold { .. } | Adjustment::ChannelMixer { cmyk: Some(_), .. } => {
Some(InkOp::Rules(adj))
}
_ if adjust::cmy_adjustment(adj) => Some(InkOp::Cmy(adj)),
Adjustment::BrightnessContrast { brightness, contrast, legacy } => {
let t = adjust::ink_brightness_contrast_lut(*brightness, *contrast, *legacy);
+1
View File
@@ -378,6 +378,7 @@ pub fn render_layer(layer: &Layer, rect: Rect) -> Buffer {
fx_clip: Default::default(),
fx_over_budget: false,
tone_luts: prepare_tones(std::slice::from_ref(layer), 0),
curve_levels: true,
doc: None,
layer_keys: Default::default(),
},
+14
View File
@@ -278,9 +278,20 @@ pub enum Adjustment {
density: f32,
preserve_luminosity: bool,
},
/// `matrix`: one row per RGB output (red, green, blue), each `[red, green, blue, constant]`
/// as fractions (1 = 100 %); with `monochrome` the first row is the gray mix.
ChannelMixer {
matrix: [[f32; 4]; 3],
monochrome: bool,
/// A CMYK document's mixer (Photoshop's Cyan, Magenta, Yellow and Black outputs): one row
/// per output, each `[cyan, magenta, yellow, black, constant]`, evaluated on the ink
/// amounts (0 none, 1 full; a positive constant adds ink). When set, `matrix` is unused;
/// with `monochrome` the first row is the mix the black ink gets, and cyan, magenta and
/// yellow are cleared. `.pcraft` files from builds before #8047 have no such field and
/// load as `None`; those builds ignore it, so they reopen a CMYK mixer as `matrix`
/// (identity) and drop the ink rows on their next save.
#[serde(default, skip_serializing_if = "Option::is_none")]
cmyk: Option<[[f32; 5]; 4]>,
},
/// A 3D LUT: `size`³ RGB triplets, red varying fastest (`((b·size + g)·size + r)·3`), in 0..=1.
/// `lut` is None for a lookup Photoshop stores as an ICC profile (identity here).
@@ -334,6 +345,9 @@ pub enum Adjustment {
},
}
/// The neutral CMYK Channel Mixer: each ink from itself at 100 %, no constant.
pub const CMYK_MIXER_IDENTITY: [[f32; 5]; 4] = [[1.0, 0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0, 0.0]];
impl Adjustment {
pub fn label(&self) -> &str {
match self {
+1 -1
View File
@@ -21,7 +21,7 @@ photocraft-geom = { workspace = true }
photocraft-color = { workspace = true }
craft-cms = { workspace = true }
# PCTIP codec from craft-libs#1564; isolated pin until the shared revision is adopted workspace-wide.
craft-pcraft-tip = { package = "craft-pcraft-format", git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
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 }
+76 -26
View File
@@ -189,26 +189,7 @@ pub fn from_params(kind: &str, p: &Value, base: Option<&Adjustment>, mode: Color
preserve_luminosity: r.boolean("preserveLuminosity", p0)?,
}
}
"channelMixer" => {
let (mut matrix, mono0) = match base {
Some(Adjustment::ChannelMixer { matrix, monochrome }) => (*matrix, *monochrome),
_ => ([[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], false),
};
let monochrome = r.boolean("monochrome", mono0)?;
if monochrome && !mono0 && p.get("gray").is_none() {
// Turning Monochrome on starts from Photoshop's grey mix.
matrix[0] = [0.4, 0.4, 0.2, 0.0];
}
for (i, key) in ["red", "green", "blue"].iter().enumerate() {
if let Some(v) = r.numbers(key, 4)? {
matrix[i] = mixer_row(&v);
}
}
if let Some(v) = r.numbers("gray", 4)? {
matrix[0] = mixer_row(&v);
}
Adjustment::ChannelMixer { matrix, monochrome }
}
"channelMixer" => channel_mixer(&r, p, base, mode)?,
"gradientMap" => {
let (stops0, rev0, dither0, source0) = match base {
Some(Adjustment::GradientMap { stops, reverse, dither, source }) => (stops.clone(), *reverse, *dither, source.clone()),
@@ -327,7 +308,18 @@ pub fn to_params(adj: &Adjustment) -> Value {
Adjustment::PhotoFilter { color, density, preserve_luminosity } => {
json!({"color": hex(*color), "density": (density * 1000.0).round() / 10.0, "preserveLuminosity": preserve_luminosity})
}
Adjustment::ChannelMixer { matrix, monochrome } => {
Adjustment::ChannelMixer { cmyk: Some(rows), monochrome, .. } => {
let row = |r: &[f32; 5]| json!(r.map(|x| (x * 1000.0).round() / 10.0));
let mut v = json!({"monochrome": monochrome});
for (key, r) in MIXER_INKS.iter().zip(rows) {
v[*key] = row(r);
}
if *monochrome {
v["gray"] = row(&rows[0]);
}
v
}
Adjustment::ChannelMixer { matrix, monochrome, cmyk: None } => {
let row = |r: &[f32; 4]| json!(r.map(|x| (x * 1000.0).round() / 10.0));
let mut v = json!({"red": row(&matrix[0]), "green": row(&matrix[1]), "blue": row(&matrix[2]), "monochrome": monochrome});
if *monochrome {
@@ -449,14 +441,72 @@ fn merge(mut a: Value, b: Value) -> Value {
a
}
/// One Channel Mixer output row: every coefficient and the constant is a whole percentage.
/// Scripted values round to the nearest whole percent before clamping, as the reference
/// application measures (0.4 to 0, 0.5 to 1, 50.6 to 51, 300 to 200, #14414); halves round away
/// from zero, which is what the dialog's own slider pass already does (`f32::round`).
fn mixer_row(v: &[f32]) -> [f32; 4] {
/// One Channel Mixer output row (RGB `[r, g, b, constant]` or ink `[c, m, y, k, constant]`):
/// every coefficient and the constant is a whole percentage. Scripted values round to the nearest
/// whole percent before clamping, as the reference application measures (0.4 to 0, 0.5 to 1,
/// 50.6 to 51, 300 to 200, #14414); halves round away from zero, which is what the dialog's own
/// slider pass already does (`f32::round`).
fn mixer_row<const N: usize>(v: &[f32]) -> [f32; N] {
std::array::from_fn(|i| v.get(i).copied().unwrap_or(0.0).round().clamp(-200.0, 200.0) / 100.0)
}
/// Channel Mixer outputs of a CMYK mixer (each `[cyan, magenta, yellow, black, constant]` %).
pub const MIXER_INKS: [&str; 4] = ["cyan", "magenta", "yellow", "black"];
/// Why a CMYK Channel Mixer refuses `monochrome: true` (#8047); the UI shows it on the disabled
/// Monochrome checkbox.
pub const MONOCHROME_CMYK_UNSUPPORTED: &str = "unsupported: Monochrome is not available for a CMYK Channel Mixer yet (no Photoshop sample to match)";
/// Channel Mixer: RGB outputs (`red`, `green`, `blue`, each `[red, green, blue, constant]` %) or,
/// in CMYK documents or with CMYK keys, Photoshop's four ink outputs ([`MIXER_INKS`]); `gray` is
/// the monochrome mix. Monochrome on a CMYK mixer is refused as unsupported
/// ([`MONOCHROME_CMYK_UNSUPPORTED`]).
fn channel_mixer(r: &Reader<'_>, p: &Value, base: Option<&Adjustment>, mode: ColorMode) -> Result<Adjustment> {
let rgb_identity = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]];
let (mut matrix, mono0, cmyk0) = match base {
Some(Adjustment::ChannelMixer { matrix, monochrome, cmyk }) => (*matrix, *monochrome, *cmyk),
_ => (rgb_identity, false, None),
};
// Only CMYK keys, a CMYK base or (with neither colour's keys) a CMYK document make CMYK outputs.
let base_space = base.filter(|b| matches!(b, Adjustment::ChannelMixer { .. })).map(|_| if cmyk0.is_some() { ToneSpace::Cmyk } else { ToneSpace::Rgb });
let cmyk = space_of(r, base_space, mode) == ToneSpace::Cmyk;
let monochrome = r.boolean("monochrome", mono0)?;
if cmyk {
if monochrome {
// No Photoshop sample of a monochrome CMYK mixer yet (#8047): its rendering and saved
// layout would be guesses. An imported one still renders and saves back verbatim, but
// can only be edited by turning Monochrome off.
return Err(bad(r.cmd, MONOCHROME_CMYK_UNSUPPORTED));
}
let mut rows = cmyk0.unwrap_or(photocraft_doc::adjust::CMYK_MIXER_IDENTITY);
for (i, key) in MIXER_INKS.iter().enumerate() {
if let Some(v) = r.numbers(key, 5)? {
rows[i] = mixer_row(&v);
}
}
if let Some(v) = r.numbers("gray", 5)? {
rows[0] = mixer_row(&v);
}
return Ok(Adjustment::ChannelMixer { matrix: if cmyk0.is_some() { matrix } else { rgb_identity }, monochrome, cmyk: Some(rows) });
}
if cmyk0.is_some() {
matrix = rgb_identity;
}
if monochrome && !mono0 && p.get("gray").is_none() {
// Turning Monochrome on starts from Photoshop's grey mix.
matrix[0] = [0.4, 0.4, 0.2, 0.0];
}
for (i, key) in ["red", "green", "blue"].iter().enumerate() {
if let Some(v) = r.numbers(key, 4)? {
matrix[i] = mixer_row(&v);
}
}
if let Some(v) = r.numbers("gray", 4)? {
matrix[0] = mixer_row(&v);
}
Ok(Adjustment::ChannelMixer { matrix, monochrome, cmyk: None })
}
fn hue_saturation(r: &Reader<'_>, base: Option<&Adjustment>) -> Result<Adjustment> {
let (h, s, l, c, mut ranges) = match base {
Some(Adjustment::HueSaturation { hue, saturation, lightness, colorize, ranges }) => (*hue, *saturation, *lightness, *colorize, ranges.clone()),
+72 -1
View File
@@ -61,6 +61,75 @@ fn every_kind_round_trips_through_params() {
}
}
/// A Channel Mixer made in a CMYK document has Photoshop's four ink outputs, starting at
/// identity (#8047); RGB and other documents keep red, green and blue.
#[test]
fn channel_mixer_outputs_follow_the_document_mode() {
let ink = default_for("channelMixer", ColorMode::Cmyk).unwrap();
assert!(matches!(ink, Adjustment::ChannelMixer { cmyk: Some(rows), monochrome: false, .. } if rows == photocraft_doc::adjust::CMYK_MIXER_IDENTITY));
let p = to_params(&ink);
assert!(MIXER_INKS.iter().all(|k| p.get(*k).is_some()) && p.get("red").is_none(), "{p}");
assert_eq!(p["black"], json!([0.0, 0.0, 0.0, 100.0, 0.0]));
for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Lab] {
assert!(matches!(default_for("channelMixer", mode).unwrap(), Adjustment::ChannelMixer { cmyk: None, .. }), "{mode:?}");
}
// CMYK keys make ink outputs in any document; a partial update keeps the rest.
let a = from_params("channelMixer", &json!({"magenta": [0, 100, 0, 0, -20]}), None, ColorMode::Rgb).unwrap();
let Adjustment::ChannelMixer { cmyk: Some(rows), .. } = &a else { panic!("{a:?}") };
assert_eq!(rows[1], [0.0, 1.0, 0.0, 0.0, -0.2]);
assert_eq!(rows[3], [0.0, 0.0, 0.0, 1.0, 0.0]);
let b = from_params("channelMixer", &json!({"black": [10, 10, 10, 90, 0]}), Some(&a), ColorMode::Cmyk).unwrap();
assert!(matches!(&b, Adjustment::ChannelMixer { cmyk: Some(r), .. } if r[1] == rows[1] && r[3] == [0.1, 0.1, 0.1, 0.9, 0.0]));
assert_eq!(from_params("channelMixer", &to_params(&b), None, ColorMode::Rgb).unwrap(), b);
// RGB keys over a CMYK base switch back to RGB outputs.
let rgb = from_params("channelMixer", &json!({"red": [50, 50, 0, 0]}), Some(&b), ColorMode::Cmyk).unwrap();
assert!(matches!(rgb, Adjustment::ChannelMixer { cmyk: None, matrix, .. } if matrix[0] == [0.5, 0.5, 0.0, 0.0] && matrix[1] == [0.0, 1.0, 0.0, 0.0]));
}
/// Monochrome on a CMYK Channel Mixer has no Photoshop sample yet (#8047), so turning it on is
/// an unsupported error, never an inferred mixer: in a CMYK document, with CMYK keys, over a CMYK
/// base, and over an imported monochrome CMYK mixer unless the edit turns Monochrome off. RGB
/// mixers keep Monochrome.
#[test]
fn monochrome_cmyk_channel_mixer_is_refused_as_unsupported() {
let ink = default_for("channelMixer", ColorMode::Cmyk).unwrap();
let imported = Adjustment::ChannelMixer {
matrix: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]],
monochrome: true,
cmyk: Some([[0.3, 0.3, 0.3, 1.0, 0.0], [0.0, 1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0, 0.0]]),
};
let cases: [(Value, Option<&Adjustment>, ColorMode); 6] = [
(json!({"monochrome": true}), None, ColorMode::Cmyk),
(json!({"monochrome": true, "gray": [0, 0, 0, 100, 0]}), None, ColorMode::Cmyk),
(json!({"monochrome": true, "cyan": [100, 0, 0, 0, 0]}), None, ColorMode::Rgb),
(json!({"monochrome": true}), Some(&ink), ColorMode::Cmyk),
(json!({"gray": [10, 10, 10, 90, 0]}), Some(&imported), ColorMode::Cmyk),
(to_params(&imported), None, ColorMode::Cmyk),
];
for (p, base, mode) in cases {
let err = from_params("channelMixer", &p, base, mode).expect_err(&format!("{p} over {base:?}"));
assert!(matches!(&err, EngineError::BadParams { msg, .. } if msg == MONOCHROME_CMYK_UNSUPPORTED), "{err}");
assert!(err.to_string().contains("unsupported"), "{err}");
}
// Turning an imported one's Monochrome off is a supported CMYK mixer again.
let off = from_params("channelMixer", &json!({"monochrome": false}), Some(&imported), ColorMode::Cmyk).unwrap();
assert!(matches!(off, Adjustment::ChannelMixer { cmyk: Some(_), monochrome: false, .. }), "{off:?}");
// RGB keeps it, in any document.
for mode in [ColorMode::Rgb, ColorMode::Cmyk] {
let rgb = from_params("channelMixer", &json!({"monochrome": true, "red": [100, 0, 0, 0]}), None, mode).unwrap();
assert!(matches!(rgb, Adjustment::ChannelMixer { cmyk: None, monochrome: true, .. }), "{mode:?}: {rgb:?}");
}
// The command refuses it and leaves the layer as it was.
let mut s = crate::session();
s.execute("file.new", json!({"width": 4, "height": 4, "mode": "cmyk", "background": "white"})).unwrap();
s.execute("layer.newAdjustmentLayer.channelMixer", json!({})).unwrap();
let id = s.active().unwrap().active_layer.unwrap();
let before = s.active().unwrap().doc.layer(id).unwrap().content.clone();
let err = s.execute("layer.setAdjustment", json!({"layer": id.0, "monochrome": true})).unwrap_err();
assert!(err.to_string().contains("unsupported"), "{err}");
assert_eq!(s.active().unwrap().doc.layer(id).unwrap().content, before);
}
#[test]
fn params_reach_the_model() {
basic_params_reach_the_model();
@@ -71,7 +140,7 @@ fn basic_params_reach_the_model() {
let a = from_params("colorBalance", &json!({"midtones": [50, 0, -200]}), None, ColorMode::Rgb).unwrap();
assert_eq!(a, Adjustment::ColorBalance { shadows: [0.0; 3], midtones: [50.0, 0.0, -100.0], highlights: [0.0; 3], preserve_luminosity: true });
let a = from_params("channelMixer", &json!({"monochrome": true}), None, ColorMode::Rgb).unwrap();
assert!(matches!(a, Adjustment::ChannelMixer { matrix, monochrome: true } if matrix[0] == [0.4, 0.4, 0.2, 0.0]));
assert!(matches!(a, Adjustment::ChannelMixer { matrix, monochrome: true, .. } if matrix[0] == [0.4, 0.4, 0.2, 0.0]));
let a = from_params("photoFilter", &json!({"filter": "cooling80", "density": 60}), None, ColorMode::Rgb).unwrap();
assert!(matches!(a, Adjustment::PhotoFilter { color, density, .. } if color[2] == 1.0 && (density - 0.6).abs() < 1e-6));
let a = from_params("blackWhite", &json!({"reds": 120, "tint": true}), None, ColorMode::Rgb).unwrap();
@@ -118,6 +187,8 @@ fn bad_params_are_errors_not_panics() {
("photoFilter", json!({"filter": "nope"})),
("photoFilter", json!({"color": [1]})),
("channelMixer", json!({"red": [1, 2, 3]})),
("channelMixer", json!({"cyan": [1, 2, 3, 4]})),
("channelMixer", json!({"black": [1, 2, 3, 4, "x"]})),
("gradientMap", json!({"stops": [[0, "#000"]]})),
("gradientMap", json!({"stops": 7})),
("selectiveColor", json!({"method": 5})),
+2
View File
@@ -79,6 +79,8 @@ pub mod image_cmds;
pub mod layer_copy_cmds;
pub mod layer_css_cmds;
#[cfg(test)]
mod layer_duplicate_new_document_history_tests;
#[cfg(test)]
mod layer_from_background_name_tests;
pub mod layer_label_cmds;
pub mod layer_list_cmds;
@@ -149,7 +149,7 @@ fn starting_values_match_the_reference() {
assert_eq!(adj("blackWhite"), Adjustment::BlackWhite { weights: [40.0, 60.0, 40.0, 60.0, 20.0, 80.0], tint: None });
let Adjustment::PhotoFilter { density, preserve_luminosity, .. } = adj("photoFilter") else { panic!() };
assert!(close(density, 0.25) && preserve_luminosity);
let Adjustment::ChannelMixer { matrix, monochrome } = adj("channelMixer") else { panic!() };
let Adjustment::ChannelMixer { matrix, monochrome, .. } = adj("channelMixer") else { panic!() };
assert!(!monochrome);
let want = [[0.8, 0.1, 0.1, 0.05], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]];
assert!(matrix.iter().flatten().zip(want.iter().flatten()).all(|(a, b)| close(*a, *b)), "{matrix:?}");
+209 -1
View File
@@ -23,6 +23,8 @@ use serde_json::{Value, json};
use crate::commands::CommandSpec;
use crate::{EngineError, Result, Session};
#[cfg(test)]
mod convert_profile_fogra39_tests;
#[cfg(test)]
mod convert_profile_same_tests;
mod profile_dither;
@@ -139,6 +141,9 @@ pub struct ColorSettings {
/// Monitor profile the canvas is displayed in: `auto` (the main display's profile when the
/// platform supplies it, else sRGB), a built-in RGB profile id or an `.icc` path.
pub monitor_profile: String,
/// The Settings menu: the named setup these values come from (one of
/// [`COLOR_SETTINGS_PRESETS`]), or [`CUSTOM_SETTINGS`] once anything differs (#14229).
pub preset: String,
}
impl Default for ColorSettings {
@@ -160,10 +165,142 @@ impl Default for ColorSettings {
blend_text_gamma: photocraft_compose::psblend::TEXT_GAMMA,
spot_dot_gain: photocraft_compose::multichannel::SPOT_DOT_GAIN,
monitor_profile: "auto".into(),
// PhotoCraft's defaults match none of the named setups.
preset: CUSTOM_SETTINGS.into(),
}
}
}
/// The Settings menu's entry for values that match no named setup.
pub const CUSTOM_SETTINGS: &str = "Custom";
/// The named setups of Color Settings' Settings menu, in menu order (#14229).
pub const COLOR_SETTINGS_PRESETS: [&str; 13] = [
"Europe General Purpose 3",
"Europe Prepress 3",
"Europe Web/Internet 2",
"Monitor Color",
"Japan Color for Newspaper",
"Japan General Purpose 2",
"Japan Magazine Advertisement Color",
"Japan Prepress 2",
"Japan Web/Internet",
"North America General Purpose 2",
"North America Newspaper",
"North America Prepress 2",
"North America Web/Internet",
];
/// The named setup whose working RGB follows the monitor profile.
const MONITOR_COLOR: &str = "Monitor Color";
/// The RGB entry of "Monitor Color": the monitor profile (see [`ColorState::monitor_rgb_for`]).
const MONITOR_RGB: &str = "monitor";
/// What one named setup sets. Spaces PhotoCraft doesn't ship stand in for the closest built-in:
/// the wide-gamut RGB is `adobe-rgb-compat`; Coated FOGRA39 is `coated-fogra39`, every other
/// press (SWOP, Japan Color, Japan Web Coated (Ad), US Newsprint) the generic `coated-cmyk`
/// (#3499); Dot Gain 15 % and 25 % gray the Dot Gain 20 %-compatible gray. Spot dot gains are exact.
struct SettingsPreset {
name: &'static str,
rgb: &'static str,
cmyk: &'static str,
gray: &'static str,
spot: f32,
/// RGB, CMYK, Gray.
policies: [Policy; 3],
/// Ask When Opening (mismatch), Ask When Pasting, Missing Profiles: Ask When Opening.
ask: [bool; 3],
intent: Intent,
}
/// A row of [`SETTINGS_PRESETS`], in the table's column order.
#[allow(clippy::too_many_arguments)]
const fn preset(
name: &'static str,
rgb: &'static str,
cmyk: &'static str,
gray: &'static str,
spot: f32,
policies: [Policy; 3],
ask: [bool; 3],
intent: Intent,
) -> SettingsPreset {
SettingsPreset { name, rgb, cmyk, gray, spot, policies, ask, intent }
}
const SETTINGS_PRESETS: [SettingsPreset; 13] = {
use Intent::{Perceptual as PER, RelativeColorimetric as REL};
use Policy::{Convert as C, Off, Preserve as P};
const SRGB: &str = "srgb";
const WIDE: &str = "adobe-rgb-compat";
const FOGRA39: &str = "coated-fogra39";
const COATED: &str = "coated-cmyk";
const DOT_GAIN: &str = "dot-gain-20-compat";
const GAMMA_22: &str = "gray-gamma-2.2";
[
preset("Europe General Purpose 3", SRGB, FOGRA39, DOT_GAIN, 15.0, [P, P, P], [false, false, false], REL),
preset("Europe Prepress 3", WIDE, FOGRA39, DOT_GAIN, 15.0, [P, P, P], [true, true, true], REL),
preset("Europe Web/Internet 2", SRGB, FOGRA39, GAMMA_22, 15.0, [C, P, P], [true, true, false], REL),
preset("Monitor Color", MONITOR_RGB, COATED, GAMMA_22, 20.0, [Off, Off, Off], [true, false, false], REL),
preset("Japan Color for Newspaper", WIDE, COATED, DOT_GAIN, 25.0, [P, P, P], [true, true, true], PER),
preset("Japan General Purpose 2", SRGB, COATED, DOT_GAIN, 15.0, [P, P, P], [false, false, false], PER),
preset("Japan Magazine Advertisement Color", WIDE, COATED, DOT_GAIN, 15.0, [P, P, P], [true, true, true], PER),
preset("Japan Prepress 2", WIDE, COATED, DOT_GAIN, 15.0, [P, P, P], [true, true, true], PER),
preset("Japan Web/Internet", SRGB, COATED, GAMMA_22, 15.0, [C, P, P], [true, true, false], PER),
preset("North America General Purpose 2", SRGB, COATED, DOT_GAIN, 20.0, [P, P, P], [false, false, false], REL),
preset("North America Newspaper", WIDE, COATED, DOT_GAIN, 25.0, [P, P, P], [true, true, true], PER),
preset("North America Prepress 2", WIDE, COATED, DOT_GAIN, 20.0, [P, P, P], [true, true, true], REL),
preset("North America Web/Internet", SRGB, COATED, GAMMA_22, 20.0, [C, P, P], [true, true, false], REL),
]
};
/// `from` with the named setup `name` applied (#14229): its working spaces, policies, Ask
/// boxes, intent, and Black Point Compensation and Dither on; Blend Text Colors Using Gamma on
/// at 1.45, as a scripted preset sets it. "Monitor Color" takes `monitor_rgb` as its working RGB.
/// `None` for a name that isn't one of [`COLOR_SETTINGS_PRESETS`].
pub fn preset_setup(from: &ColorSettings, name: &str, monitor_rgb: &str) -> Option<ColorSettings> {
let p = SETTINGS_PRESETS.iter().find(|p| p.name == name)?;
let rgb = if p.rgb == MONITOR_RGB { monitor_rgb } else { p.rgb };
let [policy_rgb, policy_cmyk, policy_gray] = p.policies;
let [ask_on_mismatch, ask_on_paste, ask_on_missing] = p.ask;
Some(ColorSettings {
working_rgb: rgb.into(),
working_cmyk: p.cmyk.into(),
working_gray: p.gray.into(),
policy_rgb,
policy_cmyk,
policy_gray,
ask_on_mismatch,
ask_on_paste,
ask_on_missing,
intent: p.intent.id().into(),
bpc: true,
dither: true,
blend_text_gamma: photocraft_compose::psblend::TEXT_GAMMA,
spot_dot_gain: p.spot,
preset: p.name.into(),
// The rest (the monitor profile) is not part of a setup. A setting a setup does
// set belongs above, and in `same_setup`.
..from.clone()
})
}
/// Is `name` an entry of the Settings menu (a named setup or Custom)?
pub fn is_settings_preset(name: &str) -> bool {
name == CUSTOM_SETTINGS || COLOR_SETTINGS_PRESETS.contains(&name)
}
/// Do `a` and `b` agree on everything a named setup sets? (Blend Text Colors Using Gamma and the
/// monitor profile are not part of it.)
fn same_setup(a: &ColorSettings, b: &ColorSettings) -> bool {
(&a.working_rgb, &a.working_cmyk, &a.working_gray, a.spot_dot_gain.to_bits())
== (&b.working_rgb, &b.working_cmyk, &b.working_gray, b.spot_dot_gain.to_bits())
&& (a.policy_rgb, a.policy_cmyk, a.policy_gray) == (b.policy_rgb, b.policy_cmyk, b.policy_gray)
&& (a.ask_on_mismatch, a.ask_on_paste, a.ask_on_missing) == (b.ask_on_mismatch, b.ask_on_paste, b.ask_on_missing)
&& (&a.intent, a.bpc, a.dither) == (&b.intent, b.bpc, b.dither)
}
impl ColorSettings {
pub fn intent(&self) -> Intent {
Intent::parse(&self.intent).unwrap_or(Intent::RelativeColorimetric)
@@ -213,6 +350,9 @@ pub fn validate_settings(c: &ColorSettings) -> std::result::Result<(), String> {
if !(c.spot_dot_gain.is_finite() && (0.0..=photocraft_compose::multichannel::MAX_SPOT_DOT_GAIN).contains(&c.spot_dot_gain)) {
return Err(format!("spot dot gain must be 0..{} %", photocraft_compose::multichannel::MAX_SPOT_DOT_GAIN));
}
if !is_settings_preset(&c.preset) {
return Err(format!("unknown preset `{}` ({CUSTOM_SETTINGS}, {})", c.preset, COLOR_SETTINGS_PRESETS.join(", ")));
}
Ok(())
}
@@ -251,6 +391,30 @@ impl ColorState {
.unwrap_or_else(|| working_profile(mode))
}
/// The working RGB "Monitor Color" sets, with Monitor Profile at `monitor_profile`: that
/// profile when it names one; for `auto`, the built-in matching the main display's profile,
/// sRGB when none does (a display profile is only bytes here, so it can't be a working
/// space spec).
pub fn monitor_rgb_for(&self, monitor_profile: &str) -> String {
if !(monitor_profile.is_empty() || monitor_profile == "auto") {
return monitor_profile.to_string();
}
let display = self.main_display.and_then(|id| self.displays.iter().find(|d| d.id == id)).or(self.displays.first());
let description = display.and_then(|d| d.icc.as_deref()).and_then(|b| Profile::parse(b).ok()).map(|p| p.description);
description
.and_then(|n| Builtin::from_profile_name(&n))
.filter(|b| b.profile().color_space == ColorSpace::Rgb)
.unwrap_or(Builtin::Srgb)
.id()
.to_string()
}
/// `from` with the named setup `name` applied (see [`preset_setup`]), its Monitor RGB that
/// of `from`'s Monitor Profile ([`ColorState::monitor_rgb_for`]).
pub fn preset_settings(&self, from: &ColorSettings, name: &str) -> Option<ColorSettings> {
preset_setup(from, name, &self.monitor_rgb_for(&from.monitor_profile))
}
/// Resolve a profile spec, reading "working…" specs from Color Settings.
pub fn resolve(&self, spec: &str, doc: Option<&Document>, mode: Option<ColorMode>) -> Result<Arc<Profile>> {
match spec {
@@ -1265,6 +1429,32 @@ fn color_settings(s: &mut Session, p: &Value) -> Result<Value> {
if p.get("reset").and_then(Value::as_bool) == Some(true) {
next = ColorSettings::default();
}
// Settings menu (#14229): a named setup loads its values; the params below then change
// them, and the name stays only while they still match the setup.
let preset = match p.get("preset") {
None => None,
Some(Value::String(name)) if is_settings_preset(name) => Some(name.as_str()),
Some(v) => {
return Err(EngineError::BadParams {
cmd: cmd.into(),
msg: format!("`preset` must be {CUSTOM_SETTINGS} or one of: {} (got {v})", COLOR_SETTINGS_PRESETS.join(", ")),
});
}
};
let setup = match preset {
Some(name) if name != CUSTOM_SETTINGS => {
// "Monitor Color" follows a Monitor Profile changed in the same call.
let mut from = next.clone();
if let Some(m) = p.get("monitorProfile").and_then(Value::as_str) {
from.monitor_profile = m.to_string();
}
s.color().preset_settings(&from, name)
}
_ => None,
};
if let Some(setup) = &setup {
next = setup.clone();
}
let str_of = |k: &str| p.get(k).and_then(Value::as_str).map(str::to_string);
if let Some(v) = str_of("workingRgb") {
next.working_rgb = v;
@@ -1317,6 +1507,19 @@ fn color_settings(s: &mut Session, p: &Value) -> Result<Value> {
.ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: format!("`spotDotGain` must be a dot gain of 0..{max} %") })?;
next.spot_dot_gain = g as f32;
}
next.preset = match (preset, &setup) {
(_, Some(setup)) if same_setup(&next, setup) => setup.preset.clone(),
(Some(_), _) => CUSTOM_SETTINGS.into(),
// No preset given: any change but the monitor profile makes the values Custom.
(None, _) => {
let old = &s.color().settings;
let unchanged = ColorSettings { monitor_profile: old.monitor_profile.clone(), preset: old.preset.clone(), ..next.clone() } == *old;
// "Monitor Color" takes its working RGB from the monitor profile, so a new monitor
// profile keeps the name only while the setup still is what it would set now.
let still_monitor_color = old.preset != MONITOR_COLOR || s.color().preset_settings(&next, MONITOR_COLOR).is_some_and(|m| same_setup(&next, &m));
if unchanged && still_monitor_color && is_settings_preset(&old.preset) { old.preset.clone() } else { CUSTOM_SETTINGS.into() }
}
};
validate_settings(&next).map_err(|msg| EngineError::BadParams { cmd: cmd.into(), msg })?;
if next != s.color().settings {
photocraft_compose::psblend::set_text_gamma(next.blend_text_gamma);
@@ -1329,6 +1532,7 @@ fn color_settings(s: &mut Session, p: &Value) -> Result<Value> {
let desc = |m: ColorMode| s.color().working(m).description.clone();
Ok(json!({
"settings": c,
"preset": c.preset,
"working": {"rgb": desc(ColorMode::Rgb), "cmyk": desc(ColorMode::Cmyk), "gray": desc(ColorMode::Grayscale)},
"monitor": s.color().monitor().description,
"monitorDetected": !s.color().displays.is_empty(),
@@ -1432,7 +1636,7 @@ pub fn specs() -> Vec<CommandSpec> {
"edit.colorSettings",
"Color Settings…",
["Edit"],
r##"{"workingRgb":"srgb|display-p3|adobe-rgb-compat|prophoto-compat|linear-srgb|rec2020","workingCmyk":"coated-cmyk","workingGray":"dot-gain-20-compat|sgray|gray-gamma-2.2","policyRgb":"preserve|convert|off","policyCmyk":"preserve|convert|off","policyGray":"preserve|convert|off","askOnMismatch":bool=true,"askOnPaste":bool=true,"askOnMissing":bool=false,"intent":"relative|perceptual|saturation|absolute","blendTextGamma":1.0..2.2|bool=1.45,"spotDotGain":0..49=20,"bpc":bool=true,"dither":bool=true,"monitorProfile":"auto|srgb|display-p3|adobe-rgb-compat|prophoto-compat|rec2020","reset":bool=false} (spotDotGain = the Spot working space: the dot gain, in % at a 50 % dot, that spot channel previews add, as Photoshop's Spot menu (Dot Gain 10–30 %, or a custom value); working spaces and the monitor profile also accept .icc paths; monitor `auto` = the main display's profile when the platform provides it, else sRGB; the reply's `monitorStatus` says which profile is in use and why: source auto|manual|fallback, reason)"##,
r##"{"preset":"Custom|Europe General Purpose 3|Europe Prepress 3|Europe Web/Internet 2|Monitor Color|Japan Color for Newspaper|Japan General Purpose 2|Japan Magazine Advertisement Color|Japan Prepress 2|Japan Web/Internet|North America General Purpose 2|North America Newspaper|North America Prepress 2|North America Web/Internet","workingRgb":"srgb|display-p3|adobe-rgb-compat|prophoto-compat|linear-srgb|rec2020","workingCmyk":"coated-cmyk|coated-fogra39","workingGray":"dot-gain-20-compat|sgray|gray-gamma-2.2","policyRgb":"preserve|convert|off","policyCmyk":"preserve|convert|off","policyGray":"preserve|convert|off","askOnMismatch":bool=true,"askOnPaste":bool=true,"askOnMissing":bool=false,"intent":"relative|perceptual|saturation|absolute","blendTextGamma":1.0..2.2|bool=1.45,"spotDotGain":0..49=20,"bpc":bool=true,"dither":bool=true,"monitorProfile":"auto|srgb|display-p3|adobe-rgb-compat|prophoto-compat|rec2020","reset":bool=false} (preset = the Settings menu: a named setup sets the working spaces, policies, Ask boxes and intent, Black Point Compensation and Dither on and Blend Text Colors Using Gamma 1.45, then the other params change those values; the reply's `preset` is that name while the values still match it, else Custom, as after any change made without `preset`; spotDotGain = the Spot working space: the dot gain, in % at a 50 % dot, that spot channel previews add, as Photoshop's Spot menu (Dot Gain 10–30 %, or a custom value); working spaces and the monitor profile also accept .icc paths; monitor `auto` = the main display's profile when the platform provides it, else sRGB; the reply's `monitorStatus` says which profile is in use and why: source auto|manual|fallback, reason)"##,
always,
color_settings,
true,
@@ -1736,6 +1940,10 @@ mod tests {
#[path = "assign_profile_enabled_modes_tests.rs"]
mod assign_profile_enabled_modes_tests;
#[cfg(test)]
#[path = "../color_settings_presets_tests.rs"]
mod color_settings_presets_tests;
#[cfg(test)]
mod settings_tests {
use super::*;
@@ -0,0 +1,51 @@
//! #14267: Convert to Profile from sRGB to the built-in Coated FOGRA39 gives the reference
//! application's inks for each intent, and Perceptual and Saturation separate differently.
use super::*;
/// Inks (CMYK %) the reference application gives for an sRGB patch, per intent: relative +
/// BPC, relative, perceptual, saturation, absolute (Convert to Profile, dither on).
const REFERENCE: [(&str, [[f32; 4]; 5]); 3] = [
("#c81e1e", [[14.5, 97.7, 95.3, 4.3], [13.3, 100.0, 100.0, 5.5], [18.0, 96.9, 92.9, 8.6], [14.9, 100.0, 100.0, 5.9], [8.6, 100.0, 100.0, 2.4]]),
("#1e3cc8", [[91.8, 75.3, 0.0, 0.0], [94.5, 76.5, 0.0, 0.0], [94.5, 77.7, 0.0, 0.0], [93.7, 76.9, 0.0, 0.0], [92.6, 74.9, 0.0, 0.0]]),
("#808080", [[49.0, 38.4, 38.4, 20.0], [49.8, 39.2, 38.8, 21.2], [49.0, 38.4, 38.4, 20.0], [49.0, 38.4, 38.4, 20.0], [46.7, 36.9, 38.4, 18.4]]),
];
const INTENTS: [(&str, bool); 5] = [("relative", true), ("relative", false), ("perceptual", true), ("saturation", true), ("absolute", false)];
/// The inks of an 8-bit sRGB document filled with `background`, converted to Coated FOGRA39.
fn separate(background: &str, intent: &str, bpc: bool) -> [f32; 4] {
let mut s = crate::session();
s.execute("file.new", json!({"width": 8, "height": 8, "background": background})).unwrap();
s.execute("edit.assignProfile", json!({"profile": "srgb"})).unwrap();
s.execute("edit.convertToProfile", json!({"profile": "coated-fogra39", "intent": intent, "bpc": bpc, "dither": false})).unwrap();
let doc = &s.active().unwrap().doc;
assert_eq!(doc.mode, ColorMode::Cmyk);
let px = doc.layers[0].surface().unwrap().pixel(4, 4);
[px[0], px[1], px[2], px[3]].map(|v| v * 100.0)
}
/// Within 2 % per ink, except Saturation red: that patch lies between nodes of the profile's
/// table that are clipped to the magenta–yellow edge and nodes that are not, which costs 2.2 %
/// (a finer table closes it, at three times the profile size). It is held to 2.5 %.
#[test]
fn srgb_to_fogra39_matches_the_reference_inks() {
let mut failures = Vec::new();
for (background, want) in REFERENCE {
for ((intent, bpc), want) in INTENTS.into_iter().zip(want) {
let got = separate(background, intent, bpc);
let limit = if (background, intent) == ("#c81e1e", "saturation") { 2.5 } else { 2.0 };
// A NaN ink compares false with `>`, so it is failed explicitly.
if (0..4).any(|i| (got[i] - want[i]).abs().is_nan() || (got[i] - want[i]).abs() > limit) {
failures.push(format!("{background} {intent} bpc {bpc}: {got:.1?}, reference {want:?}, limit {limit}"));
}
}
}
assert!(failures.is_empty(), "{failures:#?}");
}
#[test]
fn perceptual_and_saturation_separate_differently() {
let (perceptual, saturation) = (separate("#c81e1e", "perceptual", true), separate("#c81e1e", "saturation", true));
assert!(saturation[1] > perceptual[1] + 1.0 && saturation[2] > perceptual[2] + 1.0, "perceptual {perceptual:?}, saturation {saturation:?}");
}
+2 -2
View File
@@ -311,7 +311,7 @@ use content_aware_scale::content_aware_scale;
pub use fade::{FadePreview, fade_preview, fade_surface};
use fade::{can_fade, fade};
pub use find_replace::find_matches;
use find_replace::{find_replace, has_type_layer};
use find_replace::{can_find_replace, find_replace};
pub(crate) use presets::current_path;
pub use presets::{PRESET_FORMAT, PresetFile};
use presets::{can_define_shape, define_brush_preset, define_custom_shape, preset_manager};
@@ -378,7 +378,7 @@ pub fn specs() -> Vec<CommandSpec> {
["Edit"],
None,
r##"{"find":text,"replace":text,"action":"changeAll|find|change|changeFind","caseSensitive":bool=false,"wholeWord":bool=false,"forward":bool=true,"allLayers":bool=true}"##,
has_type_layer,
can_find_replace,
find_replace
),
spec!(
@@ -55,9 +55,15 @@ fn start_index(doc: &Document, layers: &[LayerId], active: Option<LayerId>) -> u
walk.iter().skip(active_walk + 1).find_map(|(_, _, l)| layers.iter().position(|id| *id == l.id)).unwrap_or(0)
}
pub(super) fn has_type_layer(s: &Session) -> std::result::Result<(), String> {
pub(super) fn can_find_replace(s: &Session) -> std::result::Result<(), String> {
let d = s.active().ok_or("no document open")?;
if type_layers(&d.doc).is_empty() { Err("the document has no type layers".into()) } else { Ok(()) }
// A document without type keeps the menu available. Documents with only locked type
// retain their existing refusal.
if type_layers(&d.doc).is_empty() && d.doc.walk().iter().any(|(_, _, layer)| matches!(layer.content, LayerContent::Text(_))) {
Err("the document has no type layers".into())
} else {
Ok(())
}
}
pub(super) fn find_replace(s: &mut Session, p: &Value) -> Result<Value> {
@@ -198,3 +204,7 @@ pub(super) fn find_replace(s: &mut Session, p: &Value) -> Result<Value> {
other => Err(bad(cmd, format!("unknown action `{other}` (find|change|changeFind|changeAll)"))),
}
}
#[cfg(test)]
#[path = "find_replace_enabled_tests.rs"]
mod enabled_tests;
@@ -0,0 +1,62 @@
use super::*;
use std::sync::Arc;
const COMMAND: &str = "edit.findAndReplaceText";
#[test]
fn find_replace_without_type_is_enabled_and_leaves_the_document_unchanged() {
for depth in [8, 16, 32] {
let mut s = crate::session();
s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth})).unwrap();
let before = s.active().unwrap().doc.clone();
let revision = s.active().unwrap().revision;
let history = s.active().unwrap().history.entries();
assert!(s.is_enabled(COMMAND), "{depth}-bit document without type");
for action in ["changeAll", "find", "change", "changeFind"] {
let reply = s.execute(COMMAND, json!({"find": "word", "replace": "other", "action": action})).unwrap();
match action {
"changeAll" => assert_eq!(reply, json!({"count": 0, "layers": 0})),
"change" => assert_eq!(reply, json!({"changed": null})),
_ => assert_eq!(reply, json!({"found": null, "changed": null})),
}
let st = s.active().unwrap();
assert!(Arc::ptr_eq(&before, &st.doc));
assert_eq!(st.revision, revision);
assert_eq!(st.history.entries(), history);
}
assert!(s.execute(COMMAND, json!({})).is_err(), "the command still requires a search term");
}
}
#[test]
fn find_replace_needs_a_document_and_preserves_locked_type_refusal() {
let mut s = crate::session();
assert!(!s.is_enabled(COMMAND));
assert!(s.execute(COMMAND, json!({"find": "word"})).is_err());
s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
let layer = s.execute("type.create", json!({"text": "word", "size": 8})).unwrap()["layer"].as_u64().unwrap();
s.execute("layer.setProps", json!({"layer": layer, "locked": true})).unwrap();
assert!(!s.is_enabled(COMMAND));
let before = s.active().unwrap().doc.clone();
assert!(s.execute(COMMAND, json!({"find": "word", "replace": "other"})).is_err());
assert!(Arc::ptr_eq(&before, &s.active().unwrap().doc));
s.execute("layer.setProps", json!({"layer": layer, "locked": false})).unwrap();
assert!(s.is_enabled(COMMAND));
assert_eq!(s.execute(COMMAND, json!({"find": "word", "replace": "other"})).unwrap(), json!({"count": 1, "layers": 1}));
assert!(s.undo());
let content = &s.active().unwrap().doc.layer(LayerId(layer)).unwrap().content;
assert!(matches!(content, LayerContent::Text(text) if text.text == "word"));
}
#[test]
fn find_replace_empty_document_without_an_active_layer_is_a_noop() {
let mut s = crate::session();
s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
let st = s.active_mut().unwrap();
Arc::make_mut(st.doc_mut()).layers.clear();
st.set_active_layer(None);
st.selection_mut().clear();
assert!(s.is_enabled(COMMAND));
assert_eq!(s.execute(COMMAND, json!({"find": "word", "allLayers": false})).unwrap(), json!({"count": 0, "layers": 0}));
}
@@ -776,7 +776,7 @@ fn find_matches_cases() {
#[test]
fn find_and_replace_across_type_layers() {
let mut s = session(8);
assert!(!s.is_enabled("edit.findAndReplaceText"));
assert!(s.is_enabled("edit.findAndReplaceText"));
s.execute("type.create", json!({"text": "Hello world", "x": 4, "y": 20, "size": 12})).unwrap();
s.execute("type.create", json!({"text": "world peace, World", "x": 4, "y": 40, "size": 12})).unwrap();
let r = s.execute("edit.findAndReplaceText", json!({"find": "world", "replace": "planet"})).unwrap();
@@ -0,0 +1,194 @@
use std::{
fs,
path::{Path, PathBuf},
};
use serde_json::{Value, json};
use crate::EngineError;
const COMMAND: &str = "file.scripts.imageProcessor";
const NO_SOURCE: &str = "There were no source files that could be opened by PhotoCraft.";
fn settings(input: &Path, output: &Path, per_format: bool) -> Value {
let mut params = json!({"input": input, "output": output});
if per_format {
params["jpeg"] = json!({});
params["tiff"] = json!({});
}
params
}
fn write_image(path: &Path) -> std::io::Result<()> {
fs::write(path, b"P6\n2 1\n255\n\xff\0\0\0\xff\0")
}
#[test]
fn blank_empty_non_image_and_corrupt_sources_report_no_openable_files() {
let root = tempfile::tempdir().unwrap();
let input = root.path().join("input");
let output = root.path().join("output");
fs::create_dir(&input).unwrap();
let mut session = crate::session();
for per_format in [false, true] {
assert_eq!(session.execute(COMMAND, settings(Path::new(""), &output, per_format)), Err(EngineError::Other(NO_SOURCE.into())));
}
for file in [None, Some("notes.txt"), Some("broken.jpg")] {
if let Some(file) = file {
fs::write(input.join(file), b"not an image").unwrap();
}
for per_format in [false, true] {
assert_eq!(session.execute(COMMAND, settings(&input, &output, per_format)), Err(EngineError::Other(NO_SOURCE.into())));
}
assert!(!output.exists());
}
}
#[test]
fn image_processor_skips_non_images_and_can_find_images_in_subfolders() {
let root = tempfile::tempdir().unwrap();
let input = root.path().join("input");
let nested = input.join("nested");
fs::create_dir_all(&nested).unwrap();
fs::write(input.join("notes.txt"), b"not an image").unwrap();
fs::write(nested.join("manifest.txt"), b"not an image").unwrap();
write_image(&nested.join("test.ppm")).unwrap();
let mut session = crate::session();
for per_format in [false, true] {
let output = root.path().join(if per_format { "multi" } else { "single" });
let mut params = settings(&input, &output, per_format);
assert_eq!(session.execute(COMMAND, params.clone()), Err(EngineError::Other(NO_SOURCE.into())));
params["includeSubfolders"] = json!(true);
let result = session.execute(COMMAND, params).unwrap();
let mut expected = vec![output.join("nested/test.jpg")];
if per_format {
expected.push(output.join("nested/test.tif"));
}
let files: Vec<PathBuf> = serde_json::from_value(result["files"].clone()).unwrap();
assert_eq!(files, expected);
assert_eq!(result["errors"], json!([]));
for path in expected {
let image = photocraft_io::import(&path.to_string_lossy(), &fs::read(&path).unwrap()).unwrap();
assert_eq!((image.document.size.width, image.document.size.height), (2, 1));
}
}
}
#[test]
fn an_opened_image_can_still_report_a_processing_or_write_failure() {
let root = tempfile::tempdir().unwrap();
let input = root.path().join("input");
let output = root.path().join("output");
fs::create_dir(&input).unwrap();
write_image(&input.join("test.ppm")).unwrap();
fs::write(&output, b"not a directory").unwrap();
let mut session = crate::session();
for per_format in [false, true] {
let result = session.execute(COMMAND, settings(&input, &output, per_format)).unwrap();
assert_eq!(result["files"], json!([]));
let errors = result["errors"].as_array().unwrap();
assert_eq!(errors.len(), if per_format { 2 } else { 1 });
assert!(errors.iter().all(|error| error["file"] == json!(input.join("test.ppm"))));
}
assert_eq!(fs::read(&output).unwrap(), b"not a directory");
}
#[test]
fn missing_paths_and_missing_open_documents_keep_their_own_errors() {
let root = tempfile::tempdir().unwrap();
let missing = root.path().join("missing");
let output = root.path().join("output");
let mut session = crate::session();
for per_format in [false, true] {
let params = settings(&missing, &output, per_format);
let error = session.execute(COMMAND, params.clone()).unwrap_err().to_string();
assert!(error.contains(&missing.to_string_lossy().to_string()), "{error}");
assert_ne!(error, NO_SOURCE);
for source in ["current", "open"] {
let mut params = params.clone();
params["source"] = json!(source);
assert_eq!(session.execute(COMMAND, params), Err(EngineError::NoDocument));
}
}
}
#[test]
fn mixed_valid_and_corrupt_images_keep_the_corrupt_file_report() {
let root = tempfile::tempdir().unwrap();
let input = root.path().join("input");
fs::create_dir(&input).unwrap();
let corrupt = input.join("broken.jpg");
fs::write(&corrupt, b"not an image").unwrap();
write_image(&input.join("test.ppm")).unwrap();
let mut session = crate::session();
for per_format in [false, true] {
let output = root.path().join(if per_format { "multi" } else { "single" });
let result = session.execute(COMMAND, settings(&input, &output, per_format)).unwrap();
let mut expected = vec![output.join("test.jpg")];
if per_format {
expected.push(output.join("test.tif"));
}
let files: Vec<PathBuf> = serde_json::from_value(result["files"].clone()).unwrap();
assert_eq!(files, expected);
let errors = result["errors"].as_array().unwrap();
assert_eq!(errors.len(), if per_format { 2 } else { 1 });
assert!(errors.iter().all(|error| error["file"] == json!(corrupt)));
}
}
#[test]
fn empty_explicit_inputs_error_and_invalid_recursion_keeps_its_diagnostic() {
let root = tempfile::tempdir().unwrap();
let output = root.path().join("output");
let mut session = crate::session();
for per_format in [false, true] {
let mut params = settings(Path::new(""), &output, per_format);
params["includeSubfolders"] = json!("true");
let error = session.execute(COMMAND, params.clone()).unwrap_err();
assert!(matches!(error, EngineError::BadParams { msg, .. } if msg.contains("includeSubfolders")));
params["includeSubfolders"] = json!(false);
params["input"] = json!([]);
assert_eq!(session.execute(COMMAND, params), Err(EngineError::Other(NO_SOURCE.into())));
}
assert!(!output.exists());
}
#[test]
fn a_source_removed_between_formats_keeps_the_written_file_and_read_error() {
use super::{ProcessorInputs, image_processor_folder_inputs, processor_format, run_processor_formats};
let root = tempfile::tempdir().unwrap();
let output = root.path().join("output");
let input = root.path().join("test.ppm");
let jpeg = output.join("test.jpg");
fs::create_dir(&output).unwrap();
write_image(&input).unwrap();
let session = crate::session();
let output = output.to_str().unwrap();
let sources = image_processor_folder_inputs(&json!({"files": [input]}), output).unwrap();
let inputs = ProcessorInputs::Folder(sources);
let formats =
[processor_format(&session, "jpeg", "jpg", &json!({})).unwrap().unwrap(), processor_format(&session, "tiff", "tif", &json!({})).unwrap().unwrap()];
let result = run_processor_formats(
&session,
&inputs,
output,
formats.into_iter().inspect(|format| {
if format.extension == "tif" {
assert!(jpeg.is_file());
fs::remove_file(&input).unwrap();
}
}),
)
.unwrap();
let files = result["files"].as_array().unwrap();
assert_eq!(files.len(), 1);
assert_eq!(Path::new(files[0].as_str().unwrap()), jpeg);
let errors = result["errors"].as_array().unwrap();
assert_eq!(errors.len(), 1);
assert_eq!(errors[0]["file"], json!(input));
assert_eq!(errors[0]["format"], "tif");
}
@@ -1,3 +1,5 @@
use std::cell::Cell;
use super::batch_run::{BatchInput, TreeNaming, batch_inputs_tree, process_document_copies, process_tree};
use super::open::import_opened;
use super::paths::{file_name, list_images, read_file, stem, untitled_name};
@@ -7,6 +9,9 @@ use super::{
str_param,
};
#[cfg(all(test, not(target_arch = "wasm32")))]
#[path = "image_processor_empty_source_tests.rs"]
mod image_processor_empty_source_tests;
#[cfg(all(test, not(target_arch = "wasm32")))]
#[path = "image_processor_formats_tests.rs"]
mod image_processor_formats_tests;
@@ -101,7 +106,8 @@ pub(super) fn parse_steps(v: &Value) -> Result<Vec<(String, Value)>> {
/// Resize and export folder inputs or copies of the current/all open documents.
/// An omitted `source` keeps the folder-input contract; document sources include unsaved
/// edits without modifying the original documents. Invalid parameters and missing documents
/// return an error; processing failures and output-name collisions appear in per-file errors.
/// return an error, as does a folder source with no openable images. Processing failures and
/// output-name collisions appear in per-file errors.
pub(super) fn image_processor(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = IMAGE_PROCESSOR;
let source = match p.get("source") {
@@ -134,8 +140,11 @@ pub(super) fn image_processor(s: &mut Session, p: &Value) -> Result<Value> {
Ok(false)
};
let r = if source == "folder" {
let inputs = batch_inputs_tree(p, cmd, &output)?;
process_tree(s, &inputs, &output, format, save, TreeNaming::Unique, &process)
let inputs = image_processor_folder_inputs(p, &output)?;
let opened = Cell::new(false);
let result = process_image_processor_folder(s, &inputs, &output, format, save, &opened, &process);
require_opened_source(&opened)?;
result
} else {
let documents = if source == "current" { vec![s.active().ok_or(EngineError::NoDocument)?] } else { s.documents().iter().map(|st| &**st).collect() };
if documents.is_empty() {
@@ -148,6 +157,38 @@ pub(super) fn image_processor(s: &mut Session, p: &Value) -> Result<Value> {
const IMAGE_PROCESSOR: &str = "file.scripts.imageProcessor";
const IMAGE_PROCESSOR_NO_FORMAT: &str = "You must save to at least one file type.";
const IMAGE_PROCESSOR_NO_SOURCE: &str = "There were no source files that could be opened by PhotoCraft.";
fn image_processor_folder_inputs(p: &Value, output: &str) -> Result<Vec<BatchInput>> {
if p.get("input").or_else(|| p.get("files")).and_then(Value::as_str) == Some("") {
// Treat the empty dialog field as an empty file list while retaining normal validation.
let mut params = p.clone();
params["input"] = json!([]);
return batch_inputs_tree(&params, IMAGE_PROCESSOR, output);
}
batch_inputs_tree(p, IMAGE_PROCESSOR, output)
}
/// The runner calls `process` only after it opens an input. Export and processing failures
/// still belong in the per-file report, even when none of the opened inputs could be saved.
fn process_image_processor_folder(
s: &Session,
inputs: &[BatchInput],
output: &str,
format: &str,
save: SaveOpts,
opened: &Cell<bool>,
process: &dyn Fn(&mut Session, &str) -> Result<bool>,
) -> Value {
process_tree(s, inputs, output, format, save, TreeNaming::Unique, &|scratch, out| {
opened.set(true);
process(scratch, out)
})
}
fn require_opened_source(opened: &Cell<bool>) -> Result<()> {
if opened.get() { Ok(()) } else { Err(EngineError::Other(IMAGE_PROCESSOR_NO_SOURCE.into())) }
}
fn image_processor_param(message: impl Into<String>) -> EngineError {
EngineError::BadParams { cmd: IMAGE_PROCESSOR.into(), msg: message.into() }
@@ -224,17 +265,22 @@ fn image_processor_formats(s: &Session, p: &Value, source: &str, output: &str) -
return Err(image_processor_param(IMAGE_PROCESSOR_NO_FORMAT));
}
let inputs = match source {
"folder" => ProcessorInputs::Folder(batch_inputs_tree(p, IMAGE_PROCESSOR, output)?),
"folder" => ProcessorInputs::Folder(image_processor_folder_inputs(p, output)?),
"current" => ProcessorInputs::Documents(vec![s.active().ok_or(EngineError::NoDocument)?]),
_ if s.documents().is_empty() => return Err(EngineError::NoDocument),
_ => ProcessorInputs::Documents(s.documents().iter().map(|st| &**st).collect()),
};
run_processor_formats(s, &inputs, output, formats)
}
fn run_processor_formats(s: &Session, inputs: &ProcessorInputs<'_>, output: &str, formats: impl IntoIterator<Item = ProcessorFormat>) -> Result<Value> {
let mut files = Vec::new();
let mut errors = Vec::new();
let opened = Cell::new(false);
for format in formats {
// The existing runners prepare fresh scratch documents for each output.
let process = |scratch: &mut Session, out: &str| {
if let ProcessorInputs::Folder(inputs) = &inputs
if let ProcessorInputs::Folder(inputs) = inputs
&& super::paths::is_file(out)
&& inputs.iter().any(|input| super::paths::same_file(&input.path, out))
{
@@ -248,8 +294,8 @@ fn image_processor_formats(s: &Session, p: &Value, source: &str, output: &str) -
}
Ok(false)
};
let mut result = match &inputs {
ProcessorInputs::Folder(inputs) => process_tree(s, inputs, output, format.extension, format.save, TreeNaming::Unique, &process),
let mut result = match inputs {
ProcessorInputs::Folder(inputs) => process_image_processor_folder(s, inputs, output, format.extension, format.save, &opened, &process),
ProcessorInputs::Documents(documents) => process_document_copies(s, documents, output, format.extension, format.save, &process),
};
if let Some(Value::Array(written)) = result.get_mut("files").map(Value::take) {
@@ -265,6 +311,9 @@ fn image_processor_formats(s: &Session, p: &Value, source: &str, output: &str) -
}));
}
}
if matches!(inputs, ProcessorInputs::Folder(_)) {
require_opened_source(&opened)?;
}
Ok(json!({"files": files, "errors": errors}))
}
@@ -10,6 +10,7 @@
use crate::color_cmds::ColorExt;
use std::collections::{BTreeSet, HashMap, HashSet};
use std::sync::Arc;
use photocraft_color::ColorMode;
use photocraft_doc::text_styles::{CharacterStyleDef, ParagraphStyleDef};
@@ -406,11 +407,21 @@ pub(crate) fn duplicate_to_new_document(s: &mut Session, p: &Value) -> Result<Va
// Its own Basic Paragraph is the source's: type that inherits from it must not gain overrides.
nd.text_styles.basic.clone_from(&sdoc.text_styles.basic);
let new_ids: Vec<LayerId> = nd.layers.iter().map(|l| l.id).collect();
// Keep the copies in the opening snapshot and use a layer-free document for undo.
let layers = std::mem::take(&mut nd.layers);
let mut before = nd.clone();
nd.layers = layers;
let index = s.add_document(nd, None);
if let (Some(name), [id]) = (typed, new_ids.as_slice()) {
crate::type_cmds::note_typed_name(s, *id, &name);
}
crate::layer_multi_cmds::reselect(s, new_ids.clone(), new_ids.last().copied());
if let Some(st) = s.active_mut() {
// add_document can replace the ID to avoid collisions with open documents or clone sources.
before.id = st.doc.id;
st.history.set_current_layers(Default::default());
st.history.record("Duplicate Layer", Arc::new(before), st.layer_target());
}
let mut out = json!({"document": index, "layers": new_ids.iter().map(|l| l.0).collect::<Vec<_>>()});
if let [one] = new_ids.as_slice()
&& let Some(map) = out.as_object_mut()
@@ -0,0 +1,104 @@
use photocraft_color::{ColorMode, SampleType};
use photocraft_doc::LayerId;
use serde_json::json;
use crate::{DocState, Session};
fn check_duplicate_history(s: &mut Session, source: &DocState) {
let dst = s.active().unwrap();
assert!(dst.history.can_undo(), "the duplicate is undoable in the destination");
assert_eq!(dst.history.entries(), ["Open", "Duplicate Layer"]);
let with_copies = dst.doc.clone();
let selected = dst.selected_layers().to_vec();
let active = dst.active_layer;
let mut empty = (*with_copies).clone();
empty.layers.clear();
assert_eq!(s.execute("edit.undo", json!({})).unwrap(), true);
assert_eq!(s.active_index(), Some(1));
let dst = s.active().unwrap();
assert_eq!(*dst.doc, empty, "undo removes the copies and retains document properties");
assert_eq!(dst.active_layer, None);
assert!(dst.selected_layers().is_empty());
assert!(!dst.history.can_undo());
assert_eq!(*s.documents()[0].doc, *source.doc);
assert_eq!(s.documents()[0].history.entries(), source.history.entries());
assert_eq!(s.execute("edit.redo", json!({})).unwrap(), true);
let dst = s.active().unwrap();
assert_eq!(s.active_index(), Some(1));
assert_eq!(*dst.doc, *with_copies);
assert_eq!(dst.selected_layers(), selected);
assert_eq!(dst.active_layer, active);
assert_eq!(dst.history.entries(), ["Open", "Duplicate Layer"]);
assert_eq!(*s.documents()[0].doc, *source.doc);
assert_eq!(s.documents()[0].history.entries(), source.history.entries());
assert_eq!(s.documents()[0].selected_layers(), source.selected_layers());
}
#[test]
fn duplicate_to_a_new_document_undoes_one_layer_at_each_depth() {
for depth in [8, 16, 32] {
let mut s = crate::session();
s.execute("file.new", json!({"width": 40, "height": 30, "depth": depth})).unwrap();
let layer = s.execute("layer.new.layer", json!({"name": "Paint"})).unwrap()["layer"].clone();
s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();
let source = s.active().unwrap().clone();
let r = s.execute("layer.duplicate", json!({"document": "new", "layer": layer, "name": "Ink"})).unwrap();
assert_eq!(r["document"], 1);
assert_eq!(s.active_index(), Some(1));
let dst = s.active().unwrap();
assert_eq!(dst.doc.layers.len(), 1);
assert_eq!(dst.doc.layers[0].name, "Ink");
assert_eq!(dst.snapshots().len(), 1);
assert_eq!(dst.snapshots()[0].name, dst.doc.name);
assert_eq!(*dst.snapshots()[0].doc, *dst.doc);
check_duplicate_history(&mut s, &source);
}
}
#[test]
fn duplicate_to_a_new_document_undoes_all_selected_layers_in_one_step() {
let mut s = crate::session();
s.execute("file.new", json!({"width": 40, "height": 30})).unwrap();
s.execute("layer.new.layer", json!({"name": "Paint"})).unwrap();
let background = s.active().unwrap().doc.layers[0].id.0;
s.execute("layer.select", json!({"layer": background, "mode": "add"})).unwrap();
let source = s.active().unwrap().clone();
assert_eq!(source.selected_layers().len(), 2);
s.execute("layer.duplicate", json!({"document": "new"})).unwrap();
let dst = s.active().unwrap();
let names: Vec<_> = dst.doc.layers.iter().map(|layer| layer.name.as_str()).collect();
assert_eq!(names, ["Background", "Paint"]);
assert_eq!(dst.selected_layers().len(), 2);
assert_eq!(dst.snapshots().len(), 1);
check_duplicate_history(&mut s, &source);
}
#[test]
fn duplicate_to_a_new_document_undoes_a_group_without_a_first_snapshot() {
let mut s = crate::session();
s.execute("history.options", json!({"automaticallyCreateFirstSnapshot": false})).unwrap();
s.execute("file.new", json!({"width": 40, "height": 30, "mode": "gray", "depth": 16, "resolution": 300, "profile": "gray-gamma-2.2"})).unwrap();
let child = s.execute("layer.new.layer", json!({"name": "Child"})).unwrap()["layer"].clone();
let group = s.execute("layer.groupLayers", json!({"name": "Folder", "layer": child})).unwrap();
let source = s.active().unwrap().clone();
let r = s.execute("layer.duplicate", json!({"document": "new", "layer": group["layer"], "documentName": "Grayscale copy"})).unwrap();
let dst = s.active().unwrap();
assert!(dst.snapshots().is_empty());
assert_eq!(dst.doc.mode, ColorMode::Grayscale);
assert_eq!(dst.doc.depth, SampleType::U16);
assert_eq!(dst.doc.resolution_dpi, 300.0);
assert!(dst.doc.icc_profile.is_some());
assert_eq!(dst.doc.icc_profile, source.doc.icc_profile);
assert_eq!(dst.doc.layers.len(), 1);
let copied = dst.doc.layer(LayerId(r["layer"].as_u64().unwrap())).unwrap();
assert_eq!(copied.name, "Folder");
let children = copied.children().unwrap();
assert_eq!(children.len(), 1);
assert_eq!(children[0].name, "Child");
check_duplicate_history(&mut s, &source);
assert!(s.active().unwrap().snapshots().is_empty());
}
+5 -1
View File
@@ -89,7 +89,7 @@ pub(crate) fn rotate_arbitrary(s: &mut Session, p: &Value) -> Result<Value> {
}
/// [`rotate_arbitrary`]; `image_rotation` is true on the Image Rotation path and decides two
/// things there: count points stay where they were (#11762) and the selection is dropped, in the
/// things there: the angle rounds to hundredths of a degree, count points stay where they were (#11762) and the selection is dropped, in the
/// same history step, so one undo brings it back (#14507). The Crop tool's straighten turn and the
/// Ruler's Straighten pass false: they move count points with the image and warp the selection.
/// `keep_guides` turns the guides with the canvas (#14508, measured for Image Rotation > Arbitrary)
@@ -106,6 +106,7 @@ pub(crate) fn rotate_arbitrary_with(s: &mut Session, p: &Value, image_rotation:
"ccw" => -angle,
d => return Err(bad(CMD, format!("direction `{d}` (cw|ccw)"))),
};
let deg = if image_rotation { (deg * 100.0).round() % 36_000.0 / 100.0 } else { deg };
if deg.rem_euclid(360.0).abs() < 1e-9 {
return Ok(json!({"width": s.active().map(|d| d.doc.size.width), "height": s.active().map(|d| d.doc.size.height)}));
}
@@ -953,3 +954,6 @@ mod color_table_index_tests;
#[cfg(test)]
#[path = "rotate_canvas_interpolation_pref_tests.rs"]
mod rotate_canvas_interpolation_pref_tests;
#[cfg(test)]
#[path = "rotate_canvas_tiny_angle_tests.rs"]
mod rotate_canvas_tiny_angle_tests;
@@ -92,13 +92,13 @@ fn rotate_arbitrary_keeps_the_background_opaque_with_a_translucent_background_co
}
#[test]
fn rotate_arbitrary_keeps_the_full_precision_angle() {
fn straighten_keeps_the_full_precision_angle() {
// Rounded to f32 this angle crosses a whole pixel: 1003 px instead of 1002, so a rotated crop
// that sized its canvas with `rotated_size` at f64 would land 1 px off.
let angle = 0.114_706_514_493_370_71;
let mut s = crate::session();
s.execute("file.new", json!({"width": 1000, "height": 1000})).unwrap();
let r = s.execute("image.rotation.arbitrary", json!({"angle": angle})).unwrap();
let r = rotate_arbitrary_with(&mut s, &json!({"angle": angle}), false, false).unwrap();
assert_eq!(rotated_size(Size::new(1000, 1000), angle), Size::new(1002, 1002));
assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(1002), Some(1002)));
}
@@ -0,0 +1,38 @@
use super::*;
#[test]
fn canvas_rotation_rounds_to_hundredths_before_editing() {
for direction in ["cw", "ccw"] {
for (angle, width, height, edits) in [
(0.001, 400, 300, 0),
(0.004, 400, 300, 0),
(-0.004, 400, 300, 0),
(0.0, 400, 300, 0),
(360.0, 400, 300, 0),
(-360.0, 400, 300, 0),
(720.0, 400, 300, 0),
(359.996, 400, 300, 0),
(0.005, 401, 301, 1),
(-0.005, 401, 301, 1),
(359.99, 401, 301, 1),
(361.0, 406, 307, 1),
] {
let mut s = crate::session();
s.execute("file.new", json!({"width": 400, "height": 300})).unwrap();
let before = s.active().unwrap().history.past_len();
let result = s.execute("image.rotation.arbitrary", json!({"angle": angle, "direction": direction})).unwrap();
assert_eq!(result, json!({"width": width, "height": height}), "{direction} {angle}");
assert_eq!(s.active().unwrap().history.past_len(), before + edits, "{direction} {angle}");
}
}
}
#[test]
fn straightening_still_applies_a_sub_hundredth_turn() {
let mut s = crate::session();
s.execute("file.new", json!({"width": 40, "height": 30})).unwrap();
let before = s.active().unwrap().history.past_len();
let result = rotate_arbitrary_with(&mut s, &json!({"angle": 0.004}), false, false).unwrap();
assert_eq!(result, json!({"width": 41, "height": 31}));
assert_eq!(s.active().unwrap().history.past_len(), before + 1);
}
@@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> {
(
"channelMixer",
"Channel Mixer…",
r##"{"red":json,"green":json,"blue":json,"gray":json,"monochrome":bool=false} (per output channel [red %, green %, blue %, constant %] in -200..200; gray = the monochrome mix)"##,
r##"{"red":json,"green":json,"blue":json,"cyan":json,"magenta":json,"yellow":json,"black":json,"gray":json,"monochrome":bool=false} (per output channel [red %, green %, blue %, constant %] in -200..200; CMYK documents (or cyan/magenta/yellow/black keys): per ink output [cyan %, magenta %, yellow %, black %, constant %]; gray = the monochrome mix; monochrome is unsupported for CMYK outputs)"##,
),
("invert", "Invert", "{}"),
("posterize", "Posterize…", r##"{"levels":2..255=4}"##),
@@ -1,5 +1,5 @@
//! #13244: a Line tool drag is one History step named "Line Tool" in Shape and Path mode; the
//! commands without the tool keep "New Shape Layer" and "Work Path".
//! #13244 and #13328: a Line tool drag records one "Line Tool" step when creating a shape
//! layer, adding to that layer, or drawing a path. Scripts retain the default History names.
use serde_json::{Value, json};
@@ -65,3 +65,52 @@ fn an_unknown_history_name_is_refused_without_a_step() {
assert!(s.execute("path.set", json!({"name": "work", "path": outline(100.0), "historyName": 7})).is_err());
assert_eq!(steps(&s), n);
}
#[test]
fn adding_a_line_to_a_shape_uses_the_tool_history_name() {
let mut s = session();
let id = s.execute("shape.create", line(Some("Line Tool"))).unwrap()["layer"].as_u64().unwrap();
let before = s.active().unwrap().doc.clone();
let n = steps(&s);
// Shift, Alt and Shift+Alt send these three operations to shape.create.
for op in ["combine", "subtract", "intersect"] {
let mut params = line(Some("Line Tool"));
params["addTo"] = json!(id);
params["op"] = json!(op);
params["from"] = json!([450, 320]);
let result = s.execute("shape.create", params).unwrap();
assert_eq!(result["layer"], id, "{op}");
assert_eq!(result["path"]["subpaths"][1]["op"], op, "{op}");
assert_eq!(steps(&s), n + 1, "{op}");
assert_eq!(last_step(&s), Some("Line Tool"), "{op}");
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(*s.active().unwrap().doc, *before, "{op}");
assert_eq!(steps(&s), n, "{op}");
}
}
#[test]
fn a_scripted_shape_add_keeps_its_default_history_name() {
let mut s = session();
let id = s.execute("shape.create", line(None)).unwrap()["layer"].as_u64().unwrap();
let n = steps(&s);
let mut params = line(None);
params["addTo"] = json!(id);
params.as_object_mut().unwrap().remove("historyName");
s.execute("shape.create", params).unwrap();
assert_eq!(steps(&s), n + 1);
assert_eq!(last_step(&s), Some("Add Shape"));
}
#[test]
fn a_bad_label_for_a_shape_add_preserves_the_document_and_history() {
let mut s = session();
let id = s.execute("shape.create", line(None)).unwrap()["layer"].as_u64().unwrap();
let n = steps(&s);
let before = s.active().unwrap().doc.clone();
let mut params = line(Some("Unknown Tool"));
params["addTo"] = json!(id);
assert!(s.execute("shape.create", params).is_err());
assert_eq!(steps(&s), n);
assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &before));
}
@@ -436,10 +436,12 @@ fn default_name(kind: &str) -> &'static str {
}
/// Creates a shape layer, or adds path components to the shape identified by `addTo`.
/// A tool history override labels new layers. Additions use the Add Shape label.
/// Line Tool additions keep the tool's History name. Other shape additions use Add Shape.
pub(super) fn shape_create(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "shape.create";
let label = super::paths::pen_history_name(p, CMD, "New Shape Layer")?;
let add_to = p.get("addTo").and_then(Value::as_u64);
let default_label = if add_to.is_some() { "Add Shape" } else { "New Shape Layer" };
let label = super::paths::pen_history_name(p, CMD, default_label)?;
let kind = p.get("kind").and_then(Value::as_str).unwrap_or("rect");
let (path, live) = if kind == "path" {
let v = p.get("path").ok_or_else(|| bad(CMD, "kind \"path\" needs `path`"))?;
@@ -451,10 +453,11 @@ pub(super) fn shape_create(s: &mut Session, p: &Value) -> Result<Value> {
let (fill, stroke) = new_fill_stroke(s, CMD, p)?;
vector::flatten::validate_shape(&path, stroke.as_ref()).map_err(|e| bad(CMD, e))?;
// Add to an existing shape layer with a path operation (Shape tool in combine/subtract… mode).
if let Some(target) = p.get("addTo").and_then(Value::as_u64) {
if let Some(target) = add_to {
let op = p.get("op").and_then(Value::as_str).map_or(Some(PathOp::Combine), op_from).ok_or_else(|| bad(CMD, "unknown `op`"))?;
let id = LayerId(target);
with_shape(s, id, "Add Shape", |sh, _| {
let label = if kind == "line" && label == "Line Tool" { label } else { "Add Shape" };
with_shape(s, id, label, |sh, _| {
for mut sp in path.subpaths {
// A joined subpath (a hole) belongs to the component before it, which takes `op`.
if sp.op != PathOp::Join {
@@ -0,0 +1,202 @@
//! Edit > Color Settings' Settings menu (#14229): the 13 named setups, the stored preset name,
//! and "Custom" once anything changes.
//!
//! Running a setup sets the process-wide Spot dot gain, which races every test that renders a
//! Multichannel document. So the command runs here only with setups whose Spot is the default
//! Dot Gain 20 %; `crates/engine/tests/global_state/color_settings_presets.rs` runs all of them
//! in the `global_state` binary.
use super::*;
const CMD: &str = "edit.colorSettings";
fn setup(name: &str) -> ColorSettings {
let s = crate::session();
s.color().preset_settings(&s.color().settings, name).unwrap()
}
#[test]
fn the_menu_lists_the_thirteen_setups_in_order() {
assert_eq!(COLOR_SETTINGS_PRESETS.len(), 13);
assert_eq!(COLOR_SETTINGS_PRESETS.map(|n| n.to_string()), SETTINGS_PRESETS.map(|p| p.name.to_string()));
assert_eq!(COLOR_SETTINGS_PRESETS[0], "Europe General Purpose 3");
assert_eq!(COLOR_SETTINGS_PRESETS[3], "Monitor Color");
assert_eq!(COLOR_SETTINGS_PRESETS[12], "North America Web/Internet");
// The params doc offers Custom, then the same names.
crate::install().unwrap();
let spec = crate::commands::find(CMD).unwrap().params;
let names = format!("\"preset\":\"{CUSTOM_SETTINGS}|{}\"", COLOR_SETTINGS_PRESETS.join("|"));
assert!(spec.contains(&names), "{spec}");
}
#[test]
fn each_setup_sets_the_measured_values() {
use Policy::{Convert as C, Off, Preserve as P};
// Name, RGB, CMYK, Gray, Spot, policies, Ask open/paste/missing, intent.
type Row = (&'static str, &'static str, &'static str, &'static str, f32, [Policy; 3], [bool; 3], &'static str);
let rows: [Row; 13] = [
("Europe General Purpose 3", "srgb", "coated-fogra39", "dot-gain-20-compat", 15.0, [P, P, P], [false, false, false], "relative"),
("Europe Prepress 3", "adobe-rgb-compat", "coated-fogra39", "dot-gain-20-compat", 15.0, [P, P, P], [true, true, true], "relative"),
("Europe Web/Internet 2", "srgb", "coated-fogra39", "gray-gamma-2.2", 15.0, [C, P, P], [true, true, false], "relative"),
// Without a display profile, Monitor RGB is sRGB.
("Monitor Color", "srgb", "coated-cmyk", "gray-gamma-2.2", 20.0, [Off, Off, Off], [true, false, false], "relative"),
("Japan Color for Newspaper", "adobe-rgb-compat", "coated-cmyk", "dot-gain-20-compat", 25.0, [P, P, P], [true, true, true], "perceptual"),
("Japan General Purpose 2", "srgb", "coated-cmyk", "dot-gain-20-compat", 15.0, [P, P, P], [false, false, false], "perceptual"),
("Japan Magazine Advertisement Color", "adobe-rgb-compat", "coated-cmyk", "dot-gain-20-compat", 15.0, [P, P, P], [true, true, true], "perceptual"),
("Japan Prepress 2", "adobe-rgb-compat", "coated-cmyk", "dot-gain-20-compat", 15.0, [P, P, P], [true, true, true], "perceptual"),
("Japan Web/Internet", "srgb", "coated-cmyk", "gray-gamma-2.2", 15.0, [C, P, P], [true, true, false], "perceptual"),
("North America General Purpose 2", "srgb", "coated-cmyk", "dot-gain-20-compat", 20.0, [P, P, P], [false, false, false], "relative"),
("North America Newspaper", "adobe-rgb-compat", "coated-cmyk", "dot-gain-20-compat", 25.0, [P, P, P], [true, true, true], "perceptual"),
("North America Prepress 2", "adobe-rgb-compat", "coated-cmyk", "dot-gain-20-compat", 20.0, [P, P, P], [true, true, true], "relative"),
("North America Web/Internet", "srgb", "coated-cmyk", "gray-gamma-2.2", 20.0, [C, P, P], [true, true, false], "relative"),
];
for (name, rgb, cmyk, gray, spot, policies, ask, intent) in rows {
let c = setup(name);
assert_eq!((c.working_rgb.as_str(), c.working_cmyk.as_str(), c.working_gray.as_str()), (rgb, cmyk, gray), "{name}");
assert_eq!(c.spot_dot_gain, spot, "{name}");
assert_eq!([c.policy_rgb, c.policy_cmyk, c.policy_gray], policies, "{name}");
assert_eq!([c.ask_on_mismatch, c.ask_on_paste, c.ask_on_missing], ask, "{name}");
assert_eq!(c.intent, intent, "{name}");
// Every setup: Black Point Compensation and Dither on, Blend Text Colors Using Gamma 1.45.
assert!(c.bpc && c.dither, "{name}");
assert_eq!(c.blend_text_gamma, photocraft_compose::psblend::TEXT_GAMMA, "{name}");
assert_eq!(c.preset, name);
// Each resolves to working spaces PhotoCraft can use.
validate_settings(&c).unwrap_or_else(|e| panic!("{name}: {e}"));
}
}
#[test]
fn monitor_color_takes_a_named_monitor_profile() {
let mut s = crate::session();
s.color_mut().settings.monitor_profile = "display-p3".into();
let c = s.color().preset_settings(&s.color().settings, "Monitor Color").unwrap();
assert_eq!(c.working_rgb, "display-p3");
// The monitor profile itself is not part of the setup.
assert_eq!(c.monitor_profile, "display-p3");
// Scripted with a Monitor Profile changed in the same call, it follows that profile.
let r = s.execute(CMD, json!({"preset": "Monitor Color", "monitorProfile": "prophoto-compat"})).unwrap();
assert_eq!(r["preset"], "Monitor Color");
assert_eq!(r["settings"]["workingRgb"], "prophoto-compat");
// With `auto` and no display profile read, it is sRGB.
let r = s.execute(CMD, json!({"preset": "Monitor Color", "monitorProfile": "auto"})).unwrap();
assert_eq!((&r["preset"], &r["settings"]["workingRgb"]), (&json!("Monitor Color"), &json!("srgb")));
}
#[test]
fn a_later_monitor_profile_change_makes_monitor_color_custom() {
let mut s = crate::session();
let r = s.execute(CMD, json!({"preset": "Monitor Color", "monitorProfile": "srgb"})).unwrap();
assert_eq!((&r["preset"], &r["settings"]["workingRgb"]), (&json!("Monitor Color"), &json!("srgb")));
// Monitor Color would now set Display P3, so the sRGB values left behind are Custom.
let r = s.execute(CMD, json!({"monitorProfile": "display-p3"})).unwrap();
assert_eq!((&r["preset"], &r["settings"]["workingRgb"]), (&json!(CUSTOM_SETTINGS), &json!("srgb")));
// A monitor change that leaves the setup as Monitor Color would set it keeps the name.
let r = s.execute(CMD, json!({"preset": "Monitor Color", "monitorProfile": "srgb"})).unwrap();
assert_eq!(r["preset"], "Monitor Color");
let r = s.execute(CMD, json!({"monitorProfile": "auto"})).unwrap();
assert_eq!(r["preset"], "Monitor Color");
// Other setups don't follow the monitor profile.
s.execute(CMD, json!({"preset": "North America Prepress 2"})).unwrap();
let r = s.execute(CMD, json!({"monitorProfile": "display-p3"})).unwrap();
assert_eq!(r["preset"], "North America Prepress 2");
}
#[test]
fn fresh_settings_are_custom() {
let mut s = crate::session();
assert_eq!(ColorSettings::default().preset, CUSTOM_SETTINGS);
let r = s.execute(CMD, json!({})).unwrap();
assert_eq!(r["preset"], CUSTOM_SETTINGS);
assert_eq!(r["settings"]["preset"], CUSTOM_SETTINGS);
}
#[test]
fn a_scripted_setup_is_stored_and_reported() {
let mut s = crate::session();
// Blend Text Colors Using Gamma off: a scripted setup turns it back on at 1.45.
s.color_mut().settings.blend_text_gamma = 1.0;
let r = s.execute(CMD, json!({"preset": "North America Prepress 2"})).unwrap();
assert_eq!(r["preset"], "North America Prepress 2");
let c = &s.color().settings;
assert_eq!(c.preset, "North America Prepress 2");
assert_eq!((c.working_rgb.as_str(), c.policy_rgb, c.ask_on_missing), ("adobe-rgb-compat", Policy::Preserve, true));
assert_eq!(c.blend_text_gamma, photocraft_compose::psblend::TEXT_GAMMA);
// Reading the settings again keeps the name.
assert_eq!(s.execute(CMD, json!({})).unwrap()["preset"], "North America Prepress 2");
// So does setting a value to what it already is, and changing the monitor profile.
assert_eq!(s.execute(CMD, json!({"bpc": true, "monitorProfile": "srgb"})).unwrap()["preset"], "North America Prepress 2");
}
#[test]
fn any_change_makes_it_custom() {
let changes = [
json!({"workingRgb": "srgb"}),
json!({"policyCmyk": "off"}),
json!({"askOnPaste": false}),
json!({"intent": "perceptual"}),
json!({"bpc": false}),
json!({"dither": false}),
// Blend Text Colors Using Gamma too: in `tests/global_state/color_settings_presets.rs`, as it is process-wide.
json!({"reset": true}),
];
for change in changes {
let mut s = crate::session();
s.execute(CMD, json!({"preset": "North America Prepress 2"})).unwrap();
let r = s.execute(CMD, change.clone()).unwrap();
assert_eq!(r["preset"], CUSTOM_SETTINGS, "{change}");
}
}
#[test]
fn the_dialogs_ok_keeps_the_name_with_its_own_text_gamma() {
// OK in the dialog sends the picked setup with every value, and Blend Text Colors Using Gamma
// as the dialog kept it: the name stays, and so does that gamma.
let mut s = crate::session();
let mut params = serde_json::to_value(setup("North America Web/Internet")).unwrap();
params["blendTextGamma"] = json!(1.45);
params["preset"] = json!("North America Web/Internet");
let r = s.execute(CMD, params.clone()).unwrap();
assert_eq!(r["preset"], "North America Web/Internet");
// Changed after picking it, the dialog shows and sends Custom.
params["preset"] = json!(CUSTOM_SETTINGS);
params["bpc"] = json!(false);
let r = s.execute(CMD, params).unwrap();
assert_eq!(r["preset"], CUSTOM_SETTINGS);
assert!(!s.color().settings.bpc);
}
#[test]
fn a_setup_with_a_differing_value_is_custom() {
let mut s = crate::session();
let r = s.execute(CMD, json!({"preset": "Monitor Color", "policyRgb": "preserve"})).unwrap();
assert_eq!(r["preset"], CUSTOM_SETTINGS);
// The setup's other values still apply.
let c = &s.color().settings;
assert_eq!((c.policy_rgb, c.policy_cmyk, c.working_gray.as_str()), (Policy::Preserve, Policy::Off, "gray-gamma-2.2"));
}
#[test]
fn custom_keeps_the_values() {
let mut s = crate::session();
s.execute(CMD, json!({"preset": "North America General Purpose 2"})).unwrap();
let r = s.execute(CMD, json!({"preset": CUSTOM_SETTINGS})).unwrap();
assert_eq!(r["preset"], CUSTOM_SETTINGS);
assert!(!s.color().settings.ask_on_mismatch, "the setup's values stay");
}
#[test]
fn a_bad_preset_is_an_error_and_changes_nothing() {
let mut s = crate::session();
s.execute(CMD, json!({"preset": "North America General Purpose 2"})).unwrap();
let before = s.color().settings.clone();
for bad in [json!(null), json!("Europe"), json!(""), json!("custom"), json!(3), json!(true), json!(["Monitor Color"]), json!({"name": "Monitor Color"})] {
let e = s.execute(CMD, json!({"preset": bad.clone(), "bpc": false})).unwrap_err();
assert!(matches!(e, EngineError::BadParams { .. }), "{bad}: {e}");
assert_eq!(s.color().settings, before, "{bad}");
}
// A stored name the menu doesn't have (a hand-edited preferences file) is refused too.
let mut c = before.clone();
c.preset = "Nowhere".into();
assert!(validate_settings(&c).is_err());
}
+7 -4
View File
@@ -171,7 +171,7 @@ pub fn effect_defaults(kind: &str) -> Value {
json!({"style": "inner", "technique": "smooth", "depth": 100, "direction": "up", "size": 5, "soften": 0, "angle": 120, "useGlobalLight": true, "altitude": 30, "glossContour": "Linear", "glossAntiAlias": false, "highlightBlend": "Screen", "highlightColor": "#ffffff", "highlightOpacity": 75, "shadowBlend": "Multiply", "shadowColor": "#000000", "shadowOpacity": 75, "contour": false, "contourName": "Linear", "contourRange": 50, "contourAntiAlias": false})
}
"satin" => {
json!({"blend": "Multiply", "color": "#000000", "opacity": 50, "angle": 19, "distance": 11, "size": 14, "contour": "Linear", "antiAlias": true, "invert": true})
json!({"blend": "Multiply", "color": "#000000", "opacity": 50, "angle": 90, "distance": 50, "size": 80, "contour": "Linear", "antiAlias": true, "invert": true})
}
_ => json!({}),
}
@@ -612,9 +612,9 @@ fn fresh_effect(kind: &str) -> Option<Effect> {
"satin" => Effect::Satin(Satin {
common: FxCommon::new(BlendMode::Multiply, 0.5),
color: Color::BLACK,
angle: 19.0,
distance: 11.0,
size: 14.0,
angle: 90.0,
distance: 50.0,
size: 80.0,
contour: Contour::Linear,
anti_alias: true,
invert: true,
@@ -1286,6 +1286,9 @@ fn delete_effect(s: &mut Session, p: &Value, effect: &Value) -> Result<Value> {
Ok(Value::Null)
}
#[cfg(test)]
mod satin_defaults_tests;
#[cfg(test)]
mod outer_glow_defaults_tests;
@@ -0,0 +1,201 @@
//! #14977: the Satin page's factory values (Multiply, black, 50 %, Angle 90, Distance 50 px,
//! Size 80 px, Linear, Anti-aliased on, Invert on) and the rule that a Satin a document already
//! carries keeps its stored values. Reset to Default reads the same factory set; the saved Make
//! Default path is not measured and keeps today's behaviour. The measured pixels of the factory
//! Satin sit within 1 level of the reference application's on the white test document.
use super::*;
use crate::Session;
use serde_json::json;
/// The issue's test document: 400 x 300 px at 72 ppi, RGB 8 bit, a white Background and a pixel
/// layer with an orange (255,128,0) rectangle at x 100..299, y 75..224.
fn test_document() -> Session {
let mut s = crate::session();
s.execute("file.new", json!({"width": 400, "height": 300, "resolution": 72, "background": "#ffffff"})).unwrap();
s.execute("layer.new.layer", json!({})).unwrap();
s.execute("select.rect", json!({"x": 100, "y": 75, "width": 200, "height": 150})).unwrap();
s.execute("edit.fill", json!({"contents": "color", "color": "#ff8000"})).unwrap();
s.execute("select.deselect", json!({})).unwrap();
s
}
fn session() -> Session {
let mut s = crate::session();
s.execute("file.new", json!({"width": 32, "height": 32})).unwrap();
s.execute("layer.new.layer", json!({})).unwrap();
s
}
/// The one Satin the active layer carries.
fn satin_of(s: &Session) -> Satin {
let d = s.active().unwrap();
let l = d.doc.layer(d.active_layer.unwrap()).unwrap();
match l.effects.items.as_slice() {
[Effect::Satin(s)] => s.clone(),
other => panic!("no satin: {other:?}"),
}
}
/// The flattened test document, as one row-major pixel buffer.
fn flattened(s: &Session) -> Vec<[f32; 4]> {
let d = s.active().unwrap();
photocraft_compose::render(&d.doc, d.doc.bounds()).into_px()
}
/// One 8-bit level of the flattened test document: `channel` 0 is R, 1 G and 2 B.
fn level(px: &[[f32; 4]], channel: usize, x: usize, y: usize) -> i32 {
(px[y * 400 + x][channel] * 255.0).round() as i32
}
/// Compare an RGB triple with the reference application's, within 1 level.
fn assert_rgb(px: &[[f32; 4]], x: usize, y: usize, want: [i32; 3]) {
let got = [level(px, 0, x, y), level(px, 1, x, y), level(px, 2, x, y)];
assert!(
got.iter().zip(want).all(|(g, w)| (g - w).abs() <= 1),
"({x}, {y}) = {}.{}.{}. the reference gives {}.{}.{}",
got[0],
got[1],
got[2],
want[0],
want[1],
want[2]
);
}
/// #14977: Layer > Layer Style > Satin... on a layer without one starts from the reference
/// application's factory values. The dialog seeds a new instance from `effect_defaults`.
#[test]
fn a_new_satin_starts_at_the_factory_values() {
let d = effect_defaults("satin");
assert_eq!(d["blend"], json!("Multiply"), "blend mode");
assert_eq!(d["color"], json!("#000000"), "colour");
assert_eq!(d["opacity"], json!(50), "opacity");
assert_eq!(d["angle"], json!(90), "angle");
assert_eq!(d["distance"], json!(50), "distance");
assert_eq!(d["size"], json!(80), "size");
assert_eq!(d["contour"], json!("Linear"), "contour");
assert_eq!(d["antiAlias"], json!(true), "anti-aliased");
assert_eq!(d["invert"], json!(true), "invert");
}
/// #14977: `layer.layerStyle.satin` without params on a layer without one makes the same effect
/// the page starts at.
#[test]
fn a_satin_command_without_params_makes_the_factory_effect() {
let mut s = session();
s.execute("layer.layerStyle.satin", json!({})).unwrap();
let fx = satin_of(&s);
assert_eq!(fx.common.blend, BlendMode::Multiply, "blend mode");
assert!((fx.common.opacity * 100.0 - 50.0).abs() < 1e-4, "opacity {} %", fx.common.opacity * 100.0);
let rgb = fx.color.to_rgb();
assert!(rgb.iter().all(|v| v.abs() < 1e-4), "colour {rgb:?} is not black");
assert_eq!((fx.angle, fx.distance, fx.size), (90.0, 50.0, 80.0), "angle, distance, size");
assert!(matches!(fx.contour, Contour::Linear), "contour {:?}", fx.contour);
assert!(fx.anti_alias, "anti-aliased");
assert!(fx.invert, "invert");
}
/// #14977: Reset to Default reads these factory values through `layer.layerStyle.defaultFor`.
/// A saved Make Default still wins: that path is not measured, so it keeps today's behaviour.
#[test]
fn reset_to_default_restores_the_satin_factory_values() {
let mut s = session();
let d = s.execute("layer.layerStyle.defaultFor", json!({"kind": "satin"})).unwrap();
assert_eq!(d["user"], json!(false));
let p = &d["params"];
assert_eq!((p["blend"].as_str(), p["color"].as_str(), p["opacity"].as_f64()), (Some("Multiply"), Some("#000000"), Some(50.0)));
assert_eq!((p["angle"].as_f64(), p["distance"].as_f64(), p["size"].as_f64()), (Some(90.0), Some(50.0), Some(80.0)));
assert_eq!((p["contour"].as_str(), p["antiAlias"].as_bool(), p["invert"].as_bool()), (Some("Linear"), Some(true), Some(true)));
s.execute("layer.layerStyle.makeDefault", json!({"kind": "satin", "params": {"angle": 19, "distance": 11, "size": 14}})).unwrap();
let saved = s.execute("layer.layerStyle.defaultFor", json!({"kind": "satin"})).unwrap();
assert_eq!(saved["user"], json!(true));
assert_eq!(
(saved["params"]["angle"].as_f64(), saved["params"]["distance"].as_f64(), saved["params"]["size"].as_f64()),
(Some(19.0), Some(11.0), Some(14.0)),
"a saved default still wins"
);
}
/// #14977 measured: OK on the factory values over the white test document. The G channel down
/// the centre column x 200 (every 5 px from y 75), the darkest point at y 149 and 150, the top
/// edge and the corners, within 1 level of the reference application's.
#[test]
fn the_factory_satin_gives_the_measured_profile() {
let mut s = test_document();
s.execute("layer.layerStyle.satin", json!({})).unwrap();
let px = flattened(&s);
let column: [i32; 30] =
[119, 118, 118, 116, 115, 112, 109, 105, 101, 96, 91, 85, 80, 74, 69, 65, 70, 76, 81, 86, 92, 97, 102, 106, 110, 113, 115, 117, 118, 119];
for (i, want) in column.iter().copied().enumerate() {
let y = 75 + 5 * i;
let got = level(&px, 1, 200, y);
assert!((got - want).abs() <= 1, "centre column at (200, {y}): G {got}, the reference gives {want}");
}
for y in [149, 150] {
assert_eq!(level(&px, 1, 200, y), 65, "the darkest point at y {y}");
}
let top_edge: [i32; 20] = [92, 98, 104, 108, 112, 115, 117, 118, 119, 119, 119, 119, 119, 118, 117, 115, 112, 108, 103, 98];
for (i, want) in top_edge.iter().copied().enumerate() {
let x = 100 + 10 * i;
let got = level(&px, 1, x, 75);
assert!((got - want).abs() <= 1, "top edge at ({x}, 75): G {got}, the reference gives {want}");
}
for y in [75, 76, 77, 78, 79] {
assert_rgb(&px, 200, y, [237, 119, 0]);
}
assert_rgb(&px, 100, 75, [183, 92, 0]);
assert_rgb(&px, 100, 150, [128, 64, 0]);
assert_rgb(&px, 200, 150, [129, 65, 0]);
}
/// #14977: the values themselves, passed as params, give the same picture the factory defaults
/// now must. Guard test, passes before and after: it pins the profile to the effect's own params.
#[test]
fn the_measured_values_as_params_give_the_same_profile() {
let mut s = test_document();
s.execute("layer.layerStyle.satin", json!({"angle": 90, "distance": 50, "size": 80})).unwrap();
let px = flattened(&s);
let column: [i32; 30] =
[119, 118, 118, 116, 115, 112, 109, 105, 101, 96, 91, 85, 80, 74, 69, 65, 70, 76, 81, 86, 92, 97, 102, 106, 110, 113, 115, 117, 118, 119];
for (i, want) in column.iter().copied().enumerate() {
let y = 75 + 5 * i;
let got = level(&px, 1, 200, y);
assert!((got - want).abs() <= 1, "centre column at (200, {y}): G {got}, the reference gives {want}");
}
assert_rgb(&px, 100, 75, [183, 92, 0]);
assert_rgb(&px, 200, 150, [129, 65, 0]);
}
/// #14977: a Satin the document already carries keeps the values it was read with. The Layer
/// Style dialog's OK (and so a PSD or `.pcraft` effect edited in it) goes through
/// `layer.layerStyle.replace` with the effect's own snapshot: absent params leave it alone.
#[test]
fn a_stored_satin_keeps_its_own_values_through_replace() {
let mut s = session();
s.execute("layer.layerStyle.satin", json!({"angle": 19, "distance": 11, "size": 14})).unwrap();
let stored = satin_of(&s);
let snapshot = serde_json::to_value(Effect::Satin(stored.clone())).unwrap();
s.execute("layer.layerStyle.replace", json!({"effects": [{"kind": "satin", "params": {}, "fx": snapshot}]})).unwrap();
let kept = satin_of(&s);
assert_eq!(kept, stored, "an edited effect list left the satin's values alone");
assert_eq!((kept.angle, kept.distance, kept.size), (19.0, 11.0, 14.0), "kept {kept:?}");
}
/// #14977: the same for a saved `.pcraft` round trip -- stored Satin values are read back as they
/// were, whatever the factory defaults are.
#[test]
fn a_pcraft_satin_keeps_its_stored_values() {
let mut s = session();
s.execute("layer.layerStyle.satin", json!({"angle": 45, "distance": 7, "size": 3, "opacity": 20})).unwrap();
let stored = satin_of(&s);
let pc = photocraft_format::save_to_bytes(&s.active().unwrap().doc, &Default::default()).unwrap();
let again = photocraft_format::load_from_bytes(&pc).unwrap();
let read = again
.layers
.iter()
.find_map(|l| l.effects.items.iter().find_map(|e| if let Effect::Satin(x) = e { Some(x.clone()) } else { None }))
.expect("the saved document still carries the satin");
assert_eq!(read, stored, "the round trip kept the stored values");
assert_eq!((read.angle, read.distance, read.size), (45.0, 7.0, 3.0));
}
+5 -2
View File
@@ -227,7 +227,8 @@ fn adjusted_with_transfer(
transfer: adjust::Transfer,
) -> Vec<f32> {
let fmt = s.format();
if fmt.mode == mode && matches!(mode, photocraft_color::ColorMode::Lab | photocraft_color::ColorMode::Cmyk) && adjust::stored_channel_adjustment(adj) {
let own_channels = adjust::stored_channel_adjustment(adj) || (mode == photocraft_color::ColorMode::Cmyk && adjust::cmyk_mixer(adj));
if fmt.mode == mode && matches!(mode, photocraft_color::ColorMode::Lab | photocraft_color::ColorMode::Cmyk) && own_channels {
return adjusted_channels(s, r, selection, |ch| adjust::stored_channels(adj, fmt.mode, Some(fmt.sample), ch));
}
if fmt.mode == mode && mode == photocraft_color::ColorMode::Cmyk && adjust::cmy_adjustment(adj) {
@@ -282,8 +283,10 @@ fn adjusted_channels(s: &Surface, r: Rect, selection: Option<&Surface>, op: impl
let Some(out) = out.get_mut(..colors) else { continue };
out.copy_from_slice(ch);
op(out);
// `v·(1−k) + o·k`, as in [`mix_through_selection`]: exact at full coverage, even over
// huge 32-bit values whose difference from the result would round it away (#9483).
for (v, o) in ch.iter_mut().zip(out.iter()) {
*v += (o - *v) * k;
*v = *v * (1.0 - k) + o * k;
}
}
}
+61
View File
@@ -405,6 +405,55 @@ fn hue_saturation_and_color_balance_keep_a_cmyk_layers_black() {
}
}
/// Layer › New Adjustment Layer › Channel Mixer in a CMYK document makes a mixer with cyan,
/// magenta, yellow and black outputs (#8047); its identity leaves the inks alone, the destructive
/// command mixes the ink amounts as Photoshop does, and a mix changes only the ink it targets.
#[test]
fn channel_mixer_in_a_cmyk_document_mixes_the_inks() {
let mut s = crate::session();
s.execute("file.new", json!({"width": 4, "height": 4, "mode": "cmyk", "background": "white"})).unwrap();
s.execute("layer.newAdjustmentLayer.channelMixer", json!({})).unwrap();
let doc = &s.active().unwrap().doc;
let adj = doc
.layers
.iter()
.find_map(|l| match &l.content {
photocraft_doc::LayerContent::Adjustment(a) => Some(a.clone()),
_ => None,
})
.unwrap();
assert!(
matches!(adj, Adjustment::ChannelMixer { cmyk: Some(rows), monochrome: false, .. } if rows == photocraft_doc::adjust::CMYK_MIXER_IDENTITY),
"{adj:?}"
);
let params = crate::adjust_params::to_params(&adj);
assert!(params.get("cyan").is_some() && params.get("red").is_none(), "{params}");
let cmyk = PixelFormat::new(ColorMode::Cmyk, SampleType::U16, true);
let ink = [0.2, 0.4, 0.6, 0.1, 1.0];
let same = adjusted_pixel(cmyk, &ink, &adj, None);
assert!(same.iter().zip(&ink).all(|(g, w)| (g - w).abs() < 1e-4), "identity: {same:?}");
// Magenta from itself plus a 20 % constant: 20 % more magenta ink, the rest untouched.
let more_magenta = crate::adjust_params::from_params("channelMixer", &json!({"magenta": [0, 100, 0, 0, 20]}), None, ColorMode::Cmyk).unwrap();
let got = adjusted_pixel(cmyk, &ink, &more_magenta, None);
let want = [0.2, 0.6, 0.6, 0.1, 1.0];
assert!(got.iter().zip(&want).all(|(g, w)| (g - w).abs() < 1e-4), "magenta: {got:?}");
// Black from cyan: the black ink becomes cyan's 20 %.
let black_from_cyan = crate::adjust_params::from_params("channelMixer", &json!({"black": [100, 0, 0, 0, 0]}), None, ColorMode::Cmyk).unwrap();
let got = adjusted_pixel(cmyk, &ink, &black_from_cyan, None);
let want = [0.2, 0.4, 0.6, 0.2, 1.0];
assert!(got.iter().zip(&want).all(|(g, w)| (g - w).abs() < 1e-4), "black: {got:?}");
// An imported monochrome mixer (the command refuses to make one): the mix goes to the black
// ink alone.
let mut rows = photocraft_doc::adjust::CMYK_MIXER_IDENTITY;
rows[0] = [0.0, 0.0, 0.0, 1.0, 0.0];
let Adjustment::ChannelMixer { matrix, .. } = &adj else { panic!("{adj:?}") };
let mono = Adjustment::ChannelMixer { matrix: *matrix, monochrome: true, cmyk: Some(rows) };
let got = adjusted_pixel(cmyk, &ink, &mono, None);
let want = [0.0, 0.0, 0.0, 0.1, 1.0];
assert!(got.iter().zip(&want).all(|(g, w)| (g - w).abs() < 1e-4), "monochrome: {got:?}");
}
/// Two small blocks two billion pixels apart: the content bounds are a grid of 6·10¹³ tiles
/// that holds nothing, which no adjustment may materialize.
fn distant_blocks(fmt: PixelFormat, default: f32) -> Surface {
@@ -469,6 +518,18 @@ fn full_coverage_keeps_the_edit_over_huge_hdr_values() {
}
}
/// The same for an edit of a CMYK layer's own channels: a result of 0.5 over a stored cyan of
/// 2^26 came out as 0, the difference rounding the stored value away.
#[test]
fn full_coverage_keeps_a_stored_channel_edit_over_huge_hdr_values() {
let fmt = PixelFormat::new(ColorMode::Cmyk, SampleType::F32, true);
let mut s = Surface::new(fmt);
let big = 67_108_864.0_f32;
s.write_pixel(0, 0, &[big, 0.25, 0.25, 0.25, 1.0]);
let out = adjusted_channels(&s, Rect::new(0, 0, 1, 1), None, |ch| ch.iter_mut().for_each(|v| *v = 0.5));
assert_eq!(out[..4], [0.5, 0.5, 0.5, 0.5]);
}
/// Remapping walks the stored tiles, not the dense rectangle around them: two pixels a million
/// pixels apart (a ~4 TB rectangle) flip to their mirrored places.
#[test]
@@ -0,0 +1,36 @@
//! Edit › Color Settings' named setups (#14229) through the command, every one of them.
//!
//! In the `global_state` binary, beside `spot_dot_gain.rs` and `text_gamma.rs`, for the same
//! reason: a setup sets the process-wide Spot dot gain and Blend Text Colors Using Gamma, which
//! other tests' Multichannel and type renders read. The setups themselves are checked value by
//! value in `crates/engine/src/color_settings_presets_tests.rs`.
use photocraft_compose::multichannel::{SPOT_DOT_GAIN, spot_dot_gain};
use photocraft_compose::psblend::TEXT_GAMMA;
use photocraft_engine::Session;
use photocraft_engine::color_cmds::{COLOR_SETTINGS_PRESETS, CUSTOM_SETTINGS};
use serde_json::json;
#[test]
fn every_setup_runs_and_sets_the_compositor() {
let _process = crate::lock(&crate::PROCESS);
let mut s = Session::new();
for name in COLOR_SETTINGS_PRESETS {
// Blend Text Colors Using Gamma off before: a scripted setup turns it on at 1.45.
s.execute("edit.colorSettings", json!({"blendTextGamma": false})).unwrap();
let r = s.execute("edit.colorSettings", json!({"preset": name})).unwrap();
assert_eq!(r["preset"], name);
assert_eq!(r["settings"]["blendTextGamma"], json!(TEXT_GAMMA), "{name}");
// The compositor follows the setup's Spot dot gain.
let spot = r["settings"]["spotDotGain"].as_f64().unwrap() as f32;
assert_eq!(spot_dot_gain(), spot, "{name}");
assert!(matches!(spot, 15.0 | 20.0 | 25.0), "{name}: {spot}");
}
// Changing Blend Text Colors Using Gamma alone also makes the values Custom.
s.execute("edit.colorSettings", json!({"preset": "Europe Prepress 3"})).unwrap();
let r = s.execute("edit.colorSettings", json!({"blendTextGamma": 1.8})).unwrap();
assert_eq!(r["preset"], CUSTOM_SETTINGS);
assert_eq!(spot_dot_gain(), 15.0, "the setup's other values stay");
s.execute("edit.colorSettings", json!({"reset": true})).unwrap();
assert_eq!(spot_dot_gain(), SPOT_DOT_GAIN);
}
+1
View File
@@ -3,6 +3,7 @@
//! `it` so plain `cargo test` runs them without the rest of the suite.
mod artboard_export_scratch;
mod color_settings_presets;
mod lut_row_cache_purge;
mod mask_cache_purge;
mod memory_gate;
+18 -3
View File
@@ -62,8 +62,8 @@ pub enum FormatError {
Corrupt(String),
#[error("unsupported .pcraft feature: {0}")]
Unsupported(String),
#[error("bundle written by a newer version (format {found}, this build reads up to {supported})")]
TooNew { found: u32, supported: u32 },
#[error("bundle written by a newer version (format {found}, this build reads up to {supported}){writer}. Open it in the same or a newer build, including the pre-release if that is where it was saved; this file has not been changed", writer = newer_writer_hint(.generator.as_deref()))]
TooNew { found: u32, supported: u32, generator: Option<String> },
#[error("limit exceeded: {0}")]
LimitExceeded(String),
#[error("`{path}` is NaN or infinite, which a .pcraft manifest cannot hold; reset that value and save again")]
@@ -74,6 +74,21 @@ pub enum FormatError {
Json(#[from] serde_json::Error),
}
// Generator is untrusted manifest data. Keep complete ordinary build identities, but never
// carry a manifest-sized string into a diagnostic/Debug value or interpret it as a format version.
fn bounded_writer(value: String) -> String {
let mut chars = value.chars();
let mut bounded: String = chars.by_ref().take(256).collect();
if chars.next().is_some() {
bounded.push('…');
}
bounded
}
fn newer_writer_hint(generator: Option<&str>) -> String {
generator.filter(|value| !value.trim().is_empty()).map(|value| format!("; reported writer: {value:?}")).unwrap_or_default()
}
impl FormatError {
pub(crate) fn corrupt(msg: impl Into<String>) -> Self {
FormatError::Corrupt(msg.into())
@@ -86,7 +101,7 @@ impl From<craft_pcraft_format::Error> for FormatError {
match e {
Error::Corrupt(m) => FormatError::Corrupt(m),
Error::Unsupported(m) => FormatError::Unsupported(m),
Error::TooNew { found, supported, .. } => FormatError::TooNew { found, supported },
Error::TooNew { found, supported, generator, .. } => FormatError::TooNew { found, supported, generator: generator.map(bounded_writer) },
Error::LimitExceeded(m) => FormatError::LimitExceeded(m),
Error::Json(e) => FormatError::Json(e),
other => FormatError::Corrupt(other.to_string()),
+4 -1
View File
@@ -1126,7 +1126,10 @@ impl PcraftWriter {
convert::check_nesting(&doc.layers)?;
let mut c = Collect { hash_cache: Some(&mut self.hash_cache), blob_hash_cache: Some(&mut self.blob_hash_cache), ..Default::default() };
let document = convert::doc_m(doc, &mut c)?;
let mut model = Manifest::new(format!("photocraft-format {}", env!("CARGO_PKG_VERSION")), document);
// Reuse the existing shared build-version override; stable without it is byte-identical.
// This is writer provenance only, never a format-version bump or a migration trigger.
let writer_version = option_env!("PHOTOCRAFT_OVERRIDE_VERSION").unwrap_or(env!("CARGO_PKG_VERSION"));
let mut model = Manifest::new(format!("photocraft-format {writer_version}"), document);
model.thumbnail = opts.thumbnail.as_ref().map(|_| THUMB.to_owned());
model.composite = opts.composite.as_ref().map(|_| COMPOSITE.to_owned());
let full_composite = opts.full_composite.is_some();
@@ -0,0 +1,42 @@
//! A CMYK Channel Mixer's ink rows (`Adjustment::ChannelMixer::cmyk`, #8047) survive a `.pcraft`
//! round trip; manifests written before the field existed load as a mixer without them
//! (`cmyk: None`), as `#[serde(default)]` promises.
use photocraft_color::{ColorMode, SampleType};
use photocraft_doc::{Adjustment, Document, Layer, LayerContent, Size};
use photocraft_format::*;
/// The first layer's adjustment, if the first layer is an adjustment layer.
fn adjustment_of(d: &Document) -> Option<&Adjustment> {
match &d.layers.first()?.content {
LayerContent::Adjustment(a) => Some(a),
_ => None,
}
}
/// Saves and reloads a CMYK mixer, then drops the `cmyk` key from its manifest entry (what
/// builds before #8047 wrote) and checks the older entry still loads, with `cmyk: None` and the
/// rest of the mixer kept.
#[test]
fn cmyk_mixer_rows_round_trip_and_older_manifests_load_without_them() {
let mut doc = Document::new("mixer", Size::new(8, 8), ColorMode::Cmyk, SampleType::U8);
let matrix = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]];
let rows = [[0.8, 0.3, -0.1, 0.0, 0.0], [0.1, 0.9, 0.0, 0.0, 0.05], [0.0, 0.2, 0.7, 0.0, 0.0], [0.0; 5]];
let mixer = Adjustment::ChannelMixer { matrix, monochrome: false, cmyk: Some(rows) };
doc.layers.push(Layer::new("Channel Mixer 1", LayerContent::Adjustment(mixer.clone())));
let bytes = save_to_bytes(&doc, &SaveOptions::default()).unwrap();
assert_eq!(adjustment_of(&load_from_bytes(&bytes).unwrap()), Some(&mixer));
let m = read_manifest(&bytes).unwrap();
let mut v = serde_json::to_value(&m.document).unwrap();
let fields = &mut v["layers"][0]["content"]["adjustment"]["ChannelMixer"];
assert!(fields.as_object_mut().unwrap().remove("cmyk").is_some(), "{fields}");
let old: manifest::DocM = serde_json::from_value(v).unwrap();
let manifest::ContentM::Adjustment { adjustment } = &old.layers[0].content else { panic!("not an adjustment layer") };
assert_eq!(*adjustment, Adjustment::ChannelMixer { matrix, monochrome: false, cmyk: None });
// An RGB mixer writes no `cmyk` key, so builds before #8047 read it exactly as before.
let rgb = Adjustment::ChannelMixer { matrix: [[0.5, 0.5, 0.0, 0.0], matrix[1], matrix[2]], monochrome: false, cmyk: None };
let json = serde_json::to_value(&rgb).unwrap();
assert!(json["ChannelMixer"].get("cmyk").is_none(), "{json}");
}
+60
View File
@@ -160,6 +160,66 @@ fn too_new_version_rejected() {
assert!(matches!(load_from_bytes(&b), Err(FormatError::TooNew { found: 999, .. })));
}
// In-tree-generated manifest mutations; no third-party files or user documents.
#[test]
fn newer_format_keeps_the_reported_prerelease_identity() {
let writer = "photocraft-format 0.23.1-nightly.20261121.17.1.g0123456789ab";
let bytes = rebuild(&sample(), |name, original| {
Some(if name == "manifest.json" {
let mut manifest: serde_json::Value = serde_json::from_slice(&original).unwrap();
manifest["format_version"] = 999.into();
manifest["generator"] = writer.into();
serde_json::to_vec(&manifest).unwrap()
} else {
original
})
});
let error = load_from_bytes(&bytes).unwrap_err();
match &error {
FormatError::TooNew { found, supported, generator } => {
assert!(found > supported);
assert_eq!(generator.as_deref(), Some(writer));
}
other => panic!("expected newer-format refusal, got {other}"),
}
assert!(error.to_string().contains(writer), "the person must be able to identify the reported build");
}
#[test]
fn hostile_writer_text_cannot_expand_or_inject_lines_into_newer_file_diagnostics() {
let writer = format!("reported nightly\n\r\t\u{202e}{}", "x".repeat(100_000));
let bytes = rebuild(&sample(), |name, original| {
Some(if name == "manifest.json" {
let mut manifest: serde_json::Value = serde_json::from_slice(&original).unwrap();
manifest["format_version"] = 999.into();
manifest["generator"] = writer.clone().into();
serde_json::to_vec(&manifest).unwrap()
} else {
original
})
});
let error = load_from_bytes(&bytes).unwrap_err();
assert!(matches!(&error, FormatError::TooNew { generator: Some(value), .. } if value.len() < writer.len() / 10));
let display = error.to_string();
assert!(display.len() < writer.len() / 10 && format!("{error:?}").len() < writer.len() / 10);
assert!(!display.contains(['\n', '\r', '\t', '\u{202e}']), "reported metadata must not inject lines or directional controls");
}
#[test]
fn same_format_damage_is_not_reclassified_from_its_prerelease_generator() {
let bytes = rebuild(&sample(), |name, original| {
Some(if name == "manifest.json" {
let mut manifest: serde_json::Value = serde_json::from_slice(&original).unwrap();
manifest["generator"] = "photocraft-format 99.0.0-nightly.20990101.1.1.g0123456789ab".into();
manifest["document"] = false.into();
serde_json::to_vec(&manifest).unwrap()
} else {
original
})
});
assert!(!matches!(load_from_bytes(&bytes).unwrap_err(), FormatError::TooNew { .. }), "only format compatibility, not a writer label, decides TooNew");
}
#[test]
fn invalid_hash_strings_rejected() {
let b = rebuild(&sample(), |n, d| {
+1
View File
@@ -3,6 +3,7 @@
mod analysis;
mod autosave;
mod camera_raw_roundtrip;
mod channel_mixer_cmyk;
mod common;
mod corruption;
mod directory_symlinks;
+11 -2
View File
@@ -18,17 +18,26 @@ impl B {
// shadow_map
let angle = if s.use_global_light { light.angle } else { s.angle };
let (dx, dy) = offset(angle, s.distance);
// #14933: a Size 1 inner shadow with Choke 0. `blur_kernel(1.0)` is the identity, and the
// `× shape` step below would then remove the whole shadow, exactly as on the CPU. Both
// compositors expand the inverted shape by the ¼–½–¼ taps instead
// (`photocraft_compose::effects::size_one_kernel`, the kernel `shadow_map` applies).
// #14934: an Anti-aliased Inner Shadow takes the CPU's sub-pixel source offset, on the
// CPU's gate only (`fx::aa_shift`: the inner branch, the Gaussian contour, and a Size and
// Choke that leave the map a shift plus a blur that is not the identity). A Drop Shadow
// keeps today's map (#14881). At a Choke that dilates the CPU recomputes its dilation
// distance on the offset map while this builder shifts the whole-pixel field of the
// unshifted shape, and at a blur of width 1 the offset would be the whole map: both
// neighbours take no offset here, which is what keeps them equal on both compositors
// neighbours take no offset here — which covers the Size 1 case above —, which is what
// keeps them equal on both compositors
// (`anti_aliased_inner_shadow_gated_neighbours_match_the_cpu`).
let aa = fx::aa_shift(inner && s.anti_alias, &s.contour, s.size, s.spread);
let src = self.shift(In::Shape, dx + aa, dy + aa, if inner { 1.0 } else { 0.0 }, inner);
let m = self.spread_blur(src, (s.size, s.spread), inner, dx, dy);
let m = if inner && s.size == 1.0 && s.spread == 0.0 {
self.conv(src, fx::size_one_kernel())
} else {
self.spread_blur(src, (s.size, s.spread), inner, dx, dy)
};
self.finish(m, None, false, &s.contour, inner, 0);
1
}
+35
View File
@@ -318,6 +318,41 @@ fn bands_end_at_the_coordinate_ceiling() {
assert_eq!(super::bands(Rect::new(0, 0, 8, 10), 0).len(), 10, "a zero step still makes progress");
}
/// #14933: the Size 1 Inner Shadow program convolves the ¼–½–¼ taps the CPU's `shadow_map`
/// applies, instead of dropping the identity width-1 blur, so both compositors build the same map.
/// A Size 6 inner shadow still takes the tent of its own size, untouched.
#[test]
fn size_one_inner_shadow_convolves_the_cpus_kernel() {
use crate::plan::Kernel;
let light = GlobalLight::default();
let Effect::DropShadow(mut s) = Effect::default_drop_shadow() else { unreachable!() };
s.distance = 0.0;
s.spread = 0.0;
let mut blurs = |size: f32| {
s.size = size;
program(&Effect::InnerShadow(s.clone()), &light, false)
.stages
.into_iter()
.filter(|st| st.kernel == Kernel::MBlur)
.map(|st| (st.radius, st.lut.map(|l| (*l).clone()).unwrap_or_default()))
.collect::<Vec<_>>()
};
let one = blurs(1.0);
assert_eq!(one.len(), 2, "two separable passes over the Size 1 inner shadow map");
let (r1, w1) = photocraft_compose::effects::size_one_kernel();
for (radius, lut) in &one {
assert_eq!(*radius, r1, "the Size 1 kernel radius");
assert_eq!(lut.as_slice(), w1.as_slice(), "the taps the CPU map applies");
}
let (r6, w6) = photocraft_compose::effects::tent_kernel(6.0);
let six = blurs(6.0);
assert_eq!(six.len(), 2, "a Size 6 inner shadow still blurs twice");
for (radius, lut) in &six {
assert_eq!(*radius, r6);
assert_eq!(lut.as_slice(), w6.as_slice(), "Size 6 stays on the tent");
}
}
/// #14934: the GPU's Inner Shadow program takes the same sub-pixel source offset as the CPU's
/// `shadow_map` - without a device, by asking what stages the effect builds. The measured gate
/// (Anti-aliased on, Gaussian contour, the inner branch) is what adds the stage; a Linear contour
+4 -2
View File
@@ -159,8 +159,10 @@ fn to_row(t: &[f32]) -> [f32; 4096] {
/// and a CMYK document on its inks (`cmyk_channel_adjustment`), which only the CPU does.
pub fn adjustment_on_gpu(adj: &Adjustment, mode: photocraft_color::ColorMode) -> bool {
use photocraft_compose::adjust::{cmyk_channel_adjustment, lab_channel_adjustment};
// A CMYK Channel Mixer mixes inks, in any document.
let tone_in_space =
matches!(adj, Adjustment::Levels { space: ToneSpace::Cmyk | ToneSpace::Lab, .. } | Adjustment::Curves { space: ToneSpace::Cmyk | ToneSpace::Lab, .. });
matches!(adj, Adjustment::Levels { space: ToneSpace::Cmyk | ToneSpace::Lab, .. } | Adjustment::Curves { space: ToneSpace::Cmyk | ToneSpace::Lab, .. })
|| photocraft_compose::adjust::cmyk_mixer(adj);
let own_channels = match mode {
photocraft_color::ColorMode::Lab => lab_channel_adjustment(adj),
photocraft_color::ColorMode::Cmyk => cmyk_channel_adjustment(adj),
@@ -257,7 +259,7 @@ pub fn adjustment_program(adj: &Adjustment, transfer: Transfer, depth: photocraf
p[2] = [b[4], b[5], b[6], 0.0];
(9, p, None)
}
Adjustment::ChannelMixer { matrix, monochrome } => {
Adjustment::ChannelMixer { matrix, monochrome, .. } => {
// compose::adjust: 32-bit documents cut each percentage to 1/1024, count 255/512 of
// the constant and don't clip (the shader checks F_HDR).
let hdr = depth == photocraft_color::SampleType::F32;
+4 -4
View File
@@ -68,8 +68,8 @@ fn hdr_adjustments_preserve_range_and_cpu_parity() {
// 32-bit Photoshop rules: unclipped, legacy pivot 127, the mixer's 1/1024 steps and halved constant.
Adjustment::BrightnessContrast { brightness: 25.0, contrast: 30.0, legacy: true },
Adjustment::BrightnessContrast { brightness: -20.0, contrast: -30.0, legacy: true },
Adjustment::ChannelMixer { matrix: [[0.8, 0.3, -0.1, 0.0], [0.1, 0.9, 0.0, 0.05], [0.0, 0.2, 0.7, 0.0]], monochrome: false },
Adjustment::ChannelMixer { matrix: [[0.4, 0.4, 0.2, 0.1], [0.0; 4], [0.0; 4]], monochrome: true },
Adjustment::ChannelMixer { matrix: [[0.8, 0.3, -0.1, 0.0], [0.1, 0.9, 0.0, 0.05], [0.0, 0.2, 0.7, 0.0]], monochrome: false, cmyk: None },
Adjustment::ChannelMixer { matrix: [[0.4, 0.4, 0.2, 0.1], [0.0; 4], [0.0; 4]], monochrome: true, cmyk: None },
Adjustment::PhotoFilter { color: [0.97, 0.76, 0.0], density: 0.4, preserve_luminosity: true },
Adjustment::PhotoFilter { color: [0.2, 0.6, 0.9], density: 0.3, preserve_luminosity: false },
Adjustment::BlackWhite { weights: [70.0, 20.0, 50.0, 10.0, 90.0, 30.0], tint: Some([0.9, 0.7, 0.5]) },
@@ -767,8 +767,8 @@ fn adjustments() -> Vec<Adjustment> {
Adjustment::Vibrance { vibrance: 50.0, saturation: -20.0 },
Adjustment::Vibrance { vibrance: -60.0, saturation: 0.0 },
Adjustment::Vibrance { vibrance: 0.0, saturation: -100.0 },
Adjustment::ChannelMixer { matrix: [[0.5, 0.3, 0.2, 0.0], [0.1, 0.8, 0.1, 0.05], [0.0, 0.2, 0.9, -0.05]], monochrome: false },
Adjustment::ChannelMixer { matrix: [[0.4, 0.4, 0.2, 0.0], [0.0; 4], [0.0; 4]], monochrome: true },
Adjustment::ChannelMixer { matrix: [[0.5, 0.3, 0.2, 0.0], [0.1, 0.8, 0.1, 0.05], [0.0, 0.2, 0.9, -0.05]], monochrome: false, cmyk: None },
Adjustment::ChannelMixer { matrix: [[0.4, 0.4, 0.2, 0.0], [0.0; 4], [0.0; 4]], monochrome: true, cmyk: None },
Adjustment::PhotoFilter { color: [0.9, 0.6, 0.2], density: 0.4, preserve_luminosity: true },
Adjustment::PhotoFilter { color: [0.2, 0.6, 0.9], density: 0.3, preserve_luminosity: false },
Adjustment::BlackWhite { weights: [40.0, 60.0, 40.0, 60.0, 20.0, 80.0], tint: None },
+90 -6
View File
@@ -7,7 +7,7 @@
//! Every [`Adjustment`] kind is written (`vibA`, `blnc`, `blwh`, `phfl` and `mixr` included);
//! a Color Lookup without a table is written as an identity cube and a Gradient Map with fewer
//! than two stops as the equivalent two-stop gradient, so nothing is dropped on save. Blocks
//! that cannot be read (noise gradients, profile lookups, CMYK channel mixers, unknown versions)
//! that cannot be read (noise gradients, profile lookups, ink channel mixers outside CMYK documents, unknown versions)
//! stay [`Adjustment::Unsupported`] and are written back verbatim.
use craft_psd::descriptor::{Descriptor, Value, VersionedDescriptor};
@@ -167,9 +167,13 @@ pub fn unreadable_reason(key: &[u8; 4], data: &[u8]) -> Option<String> {
/// (modern brightness/contrast parameters). Levels/Curves store the
/// composite record first, then one per document channel (see [`Channels`]).
pub fn parse(key: &[u8; 4], data: &[u8], cged: Option<&[u8]>, channels: Channels) -> Adjustment {
// A CMYK Channel Mixer (any record using the fourth, black, source) has no RGB meaning:
// keep it raw. Mixers written by `write` leave that source at 0 and map in every mode.
if key == b"mixr" && matches!(channels, Channels::Cmyk | Channels::Other) && (0..).map_while(|r| bei16(data, 4 + r * 10 + 6)).any(|k| k != 0) {
// A CMYK document's mixer has Photoshop's four ink outputs.
if key == b"mixr" && channels == Channels::Cmyk && !legacy_rgb_mixer(data) {
return parse_cmyk_mixer(data).unwrap_or_else(|| unsupported(key, data));
}
// In other modes a mixer using the fourth (black) source has no RGB meaning: keep it raw.
// Mixers written by `write` from RGB outputs leave that source at 0.
if key == b"mixr" && channels != Channels::Cmyk && (0..).map_while(|r| bei16(data, 4 + r * 10 + 6)).any(|k| k != 0) {
return unsupported(key, data);
}
let mut a = parse_any(key, data, cged);
@@ -668,7 +672,48 @@ fn parse_channel_mixer(d: &[u8]) -> Option<Adjustment> {
let first = rec(0)?;
// A monochrome block may carry only the gray record.
let (g, b) = if monochrome { (rec(1).unwrap_or([0.0; 4]), rec(2).unwrap_or([0.0; 4])) } else { (rec(1)?, rec(2)?) };
Some(Adjustment::ChannelMixer { matrix: [first, g, b], monochrome })
Some(Adjustment::ChannelMixer { matrix: [first, g, b], monochrome, cmyk: None })
}
/// `mixr` in a CMYK document: the same layout with four output records (cyan, magenta,
/// yellow, black), each using all four sources (cyan, magenta, yellow, black) and the constant,
/// on ink amounts. Photoshop writes exactly these four records (photoshop corpus cmyk8 and
/// cmyk16 channel-mixer.psd: a 44-byte block whose black record is all zeros, and whose merged
/// image has no black ink). A monochrome block may carry only its first record (the mix the
/// black ink gets); no Photoshop sample of one exists yet, and an unedited one is saved back as
/// it was read.
/// A Channel Mixer block PhotoCraft wrote in its RGB layout before CMYK mixers were read
/// ([`encode::channel_mixer`]): its fourth record repeats the first and no record uses the black
/// source. Read as CMYK rows, that fourth record would set the black ink to the cyan mix
/// (`K' = C`), so such a block in a CMYK document keeps the RGB reading it had. A CMYK block
/// whose black output is exactly the cyan mix with no black source would read the same way.
fn legacy_rgb_mixer(d: &[u8]) -> bool {
let record = |r: usize| d.get(4 + r * 10..4 + (r + 1) * 10);
let no_black = (0..4).all(|r| record(r).and_then(|rec| rec.get(6..8)) == Some(&[0, 0][..]));
d.len() == 44 && no_black && record(0).is_some() && record(0) == record(3)
}
fn parse_cmyk_mixer(d: &[u8]) -> Option<Adjustment> {
if be16(d, 0)? != 1 {
return None;
}
let monochrome = be16(d, 2)? != 0;
let rec = |r: usize| -> Option<[f32; 5]> {
let at = 4 + r * 10;
let v = |k: usize| bei16(d, at + k * 2).map(|x| f32::from(x).clamp(-200.0, 200.0) / 100.0);
Some([v(0)?, v(1)?, v(2)?, v(3)?, v(4)?])
};
let identity = photocraft_doc::adjust::CMYK_MIXER_IDENTITY;
let mut rows = identity;
for (r, row) in rows.iter_mut().enumerate() {
*row = match rec(r) {
Some(v) => v,
None if monochrome && r > 0 => identity[r],
None => return None,
};
}
let matrix = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]];
Some(Adjustment::ChannelMixer { matrix, monochrome, cmyk: Some(rows) })
}
fn put16(v: &mut Vec<u8>, x: u16) {
@@ -689,6 +734,44 @@ fn levels_write(v: &mut Vec<u8>, c: &LevelsChannel) {
put16(v, (c.gamma * 100.0).round().clamp(1.0, 999.0) as u16);
}
/// The Channel Mixer `adj` reshaped for a document whose `mixr` records are `channels`, or None
/// when it already has that shape (or is not a mixer). A PSD stores no output shape: a CMYK
/// document reads four ink records and every other mode three RGB records, so a mixer of the
/// other shape could not be read back as it is. An RGB mixer in a CMYK document becomes ink
/// outputs (cyan from the red row, magenta from green, yellow from blue, sources red, green,
/// blue as cyan, magenta, yellow) with black passed through; a CMYK mixer elsewhere keeps its
/// cyan, magenta and yellow rows as red, green and blue without the black source. A CMYK mixer
/// mixes ink amounts and an RGB one light (ink = 1 - light, ignoring black), so each row keeps
/// its sources and its constant becomes `complement_constant`. Either is an approximation, so
/// the caller warns.
pub fn mixer_for(adj: &Adjustment, channels: Channels) -> Option<Adjustment> {
let Adjustment::ChannelMixer { matrix, monochrome, cmyk } = adj else { return None };
match (cmyk, channels == Channels::Cmyk) {
(None, true) => {
let mut rows = photocraft_doc::adjust::CMYK_MIXER_IDENTITY;
for (row, m) in rows.iter_mut().zip(matrix) {
*row = [m[0], m[1], m[2], 0.0, complement_constant(m[0], m[1], m[2], m[3])];
}
let matrix = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]];
Some(Adjustment::ChannelMixer { matrix, monochrome: *monochrome, cmyk: Some(rows) })
}
(Some(rows), false) => {
let matrix = std::array::from_fn(|i| rows.get(i).map_or([0.0; 4], |r| [r[0], r[1], r[2], complement_constant(r[0], r[1], r[2], r[4])]));
Some(Adjustment::ChannelMixer { matrix, monochrome: *monochrome, cmyk: None })
}
_ => None,
}
}
/// The constant of a mixer row with sources `a`, `b`, `c` and constant `k` once it mixes the
/// complements of its inputs and output (ink for light, or light for ink): 1 - a - b - c - k,
/// since 1 - (a(1 - x) + b(1 - y) + c(1 - z) + k) = ax + by + cz + (1 - a - b - c - k). It is
/// rounded to the whole percent a `mixr` record stores and kept to its -200..200 %, so the saved
/// block reads back the same.
fn complement_constant(a: f32, b: f32, c: f32, k: f32) -> f32 {
((1.0 - a - b - c - k) * 100.0).round().clamp(-200.0, 200.0) / 100.0
}
/// Serializes an adjustment into its PSD blocks: `(key, data)` pairs
/// (Brightness/Contrast also writes a `CgEd` descriptor). Every evaluated kind has an
/// encoding; the result is empty only for an [`Adjustment::Unsupported`] with a malformed key.
@@ -729,7 +812,8 @@ pub fn write(adj: &Adjustment) -> Vec<([u8; 4], Vec<u8>)> {
Adjustment::PhotoFilter { color, density, preserve_luminosity } => {
return block(b"phfl", encode::photo_filter(*color, *density, *preserve_luminosity));
}
Adjustment::ChannelMixer { matrix, monochrome } => {
Adjustment::ChannelMixer { cmyk: Some(rows), monochrome, .. } => return block(b"mixr", encode::channel_mixer_cmyk(rows, *monochrome)),
Adjustment::ChannelMixer { matrix, monochrome, cmyk: None } => {
return block(b"mixr", encode::channel_mixer(matrix, *monochrome));
}
Adjustment::Unsupported { psd_key, raw } => {
+13
View File
@@ -237,3 +237,16 @@ pub(super) fn channel_mixer(matrix: &[[f32; 4]; 3], monochrome: bool) -> Vec<u8>
}
v
}
/// CMYK Channel Mixer payload: the cyan, magenta, yellow and black records (each C, M, Y, K and
/// constant), 44 bytes as Photoshop writes them (photoshop corpus cmyk8 and cmyk16
/// channel-mixer.psd). With `monochrome` the first record is the black ink's mix.
pub(super) fn channel_mixer_cmyk(rows: &[[f32; 5]; 4], monochrome: bool) -> Vec<u8> {
let mut v = words(&[1, u16::from(monochrome)]);
for row in rows {
for x in row {
v.extend_from_slice(&clamp_i16((x * 100.0).clamp(-200.0, 200.0)).to_be_bytes());
}
}
v
}
+95 -11
View File
@@ -221,8 +221,8 @@ fn roundtrips() {
let q = |v: u16| f32::from(v) / 65535.0;
rt(Adjustment::PhotoFilter { color: [q(60000), q(30000), q(0)], density: 0.25, preserve_luminosity: true });
rt(Adjustment::PhotoFilter { color: [q(0), q(40000), q(65535)], density: 1.0, preserve_luminosity: false });
rt(Adjustment::ChannelMixer { matrix: [[0.5, 0.3, 0.2, 0.0], [0.1, 0.8, 0.1, 0.05], [0.0, 0.2, 0.9, -0.05]], monochrome: false });
rt(Adjustment::ChannelMixer { matrix: [[0.4, 0.4, 0.2, 0.1], [0.0, 1.0, 0.0, 0.0], [-2.0, 0.0, 2.0, 0.0]], monochrome: true });
rt(Adjustment::ChannelMixer { matrix: [[0.5, 0.3, 0.2, 0.0], [0.1, 0.8, 0.1, 0.05], [0.0, 0.2, 0.9, -0.05]], monochrome: false, cmyk: None });
rt(Adjustment::ChannelMixer { matrix: [[0.4, 0.4, 0.2, 0.1], [0.0, 1.0, 0.0, 0.0], [-2.0, 0.0, 2.0, 0.0]], monochrome: true, cmyk: None });
let id = craft_cms::lutfile::LutFile::identity(5).unwrap();
let cube = craft_cms::lutfile::write_cube(&id).into_bytes();
let source = Some(LutSource { format: LutFormat::Cube, bytes: std::sync::Arc::new(cube) });
@@ -452,17 +452,35 @@ fn malformed_adjustments_are_unsupported() {
}
fn malformed_channel_mixers_are_unsupported() {
// A CMYK mixer (black source used) maps to ink outputs in CMYK documents and stays raw
// in modes without inks; our own RGB layout maps there.
let mut cmyk = i16s(&[1, 0]);
for r in 0..4 {
cmyk.extend(i16s(&std::array::from_fn::<i16, 5, _>(|k| if k == r { 100 } else { 0 })));
}
for channels in [Channels::Cmyk, Channels::Other] {
assert!(matches!(parse(b"mixr", &cmyk, None, channels), Adjustment::Unsupported { .. }));
}
let ours = write(&Adjustment::ChannelMixer { matrix: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], monochrome: false });
for channels in [Channels::Cmyk, Channels::Other] {
assert!(matches!(parse(b"mixr", &ours[0].1, None, channels), Adjustment::ChannelMixer { .. }));
}
assert!(
matches!(parse(b"mixr", &cmyk, None, Channels::Cmyk), Adjustment::ChannelMixer { cmyk: Some(rows), .. } if rows == photocraft_doc::adjust::CMYK_MIXER_IDENTITY)
);
assert!(matches!(parse(b"mixr", &cmyk, None, Channels::Other), Adjustment::Unsupported { .. }));
// Truncated CMYK blocks stay raw (a monochrome one may carry its first record alone).
assert!(matches!(parse(b"mixr", &cmyk[..4 + 3 * 10], None, Channels::Cmyk), Adjustment::Unsupported { .. }));
assert!(matches!(parse(b"mixr", &[0, 1, 0, 1, 0, 100], None, Channels::Cmyk), Adjustment::Unsupported { .. }));
let mut mono = i16s(&[1, 1]);
mono.extend(i16s(&[30, 30, 30, 100, 0]));
assert!(
matches!(parse(b"mixr", &mono, None, Channels::Cmyk), Adjustment::ChannelMixer { cmyk: Some(rows), monochrome: true, .. } if rows[0] == [0.3, 0.3, 0.3, 1.0, 0.0])
);
let ours = write(&Adjustment::ChannelMixer { matrix: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], monochrome: false, cmyk: None });
assert!(matches!(parse(b"mixr", &ours[0].1, None, Channels::Other), Adjustment::ChannelMixer { .. }));
// Our RGB layout in a CMYK document (written before CMYK mixers were read: its fourth record
// repeats the red row) keeps its RGB reading: read as ink rows, the black ink became the cyan mix.
let legacy = [[0.8, 0.2, 0.0, 0.05], [0.1, 0.9, 0.0, 0.0], [0.0, 0.3, 0.7, 0.0]];
let block = write(&Adjustment::ChannelMixer { matrix: legacy, monochrome: false, cmyk: None });
assert!(
matches!(parse(b"mixr", &block[0].1, None, Channels::Cmyk), Adjustment::ChannelMixer { cmyk: None, matrix, .. } if matrix == legacy),
"{:?}",
parse(b"mixr", &block[0].1, None, Channels::Cmyk)
);
assert!(matches!(parse(b"mixr", &[0, 1, 0, 0, 0, 100], None, Channels::Rgb), Adjustment::Unsupported { .. }));
}
@@ -608,7 +626,7 @@ fn channel_mixer_golden_blocks() {
let mut d = i16s(&[1, 0]);
d.extend(i16s(&[100, 0, 0, 0, 20, 50, 50, 0, 0, 0, 0, -50, 150, 0, -10]));
let a = parse(b"mixr", &d, None, Channels::Rgb);
assert_eq!(a, Adjustment::ChannelMixer { matrix: [[1.0, 0.0, 0.0, 0.2], [0.5, 0.5, 0.0, 0.0], [0.0, -0.5, 1.5, -0.1]], monochrome: false });
assert_eq!(a, Adjustment::ChannelMixer { matrix: [[1.0, 0.0, 0.0, 0.2], [0.5, 0.5, 0.0, 0.0], [0.0, -0.5, 1.5, -0.1]], monochrome: false, cmyk: None });
// Written with the trailing gray record (a copy of the first row).
let w = write(&a);
assert_eq!(w[0].1[..d.len()], d[..]);
@@ -616,10 +634,76 @@ fn channel_mixer_golden_blocks() {
// Monochrome with only the gray record: 30/59/11.
let mut m = i16s(&[1, 1]);
m.extend(i16s(&[30, 59, 11, 0, 0]));
let Adjustment::ChannelMixer { matrix, monochrome: true } = parse(b"mixr", &m, None, Channels::Rgb) else { panic!() };
let Adjustment::ChannelMixer { matrix, monochrome: true, .. } = parse(b"mixr", &m, None, Channels::Rgb) else { panic!() };
assert_eq!(matrix[0], [0.3, 0.59, 0.11, 0.0]);
}
/// CMYK `mixr` blocks hold four ink records (cyan, magenta, yellow, black), each C, M, Y, K and
/// constant, and are written back in Photoshop's own 44-byte layout (photoshop corpus cmyk8 and
/// cmyk16 channel-mixer.psd), monochrome or not.
#[test]
fn cmyk_channel_mixer_blocks_round_trip_with_four_ink_outputs() {
// Cyan = 100 % C + 20 % K - 10 % const; magenta = 50 % M + 50 % Y; yellow = 100 % Y;
// black = 30 % C + 30 % M + 30 % Y + 100 % K.
let rows = [[1.0, 0.0, 0.0, 0.2, -0.1], [0.0, 0.5, 0.5, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0, 0.0], [0.3, 0.3, 0.3, 1.0, 0.0]];
let mut d = i16s(&[1, 0]);
d.extend(i16s(&[100, 0, 0, 20, -10, 0, 50, 50, 0, 0, 0, 0, 100, 0, 0, 30, 30, 30, 100, 0]));
let a = parse(b"mixr", &d, None, Channels::Cmyk);
let Adjustment::ChannelMixer { cmyk: Some(got), monochrome: false, .. } = &a else { panic!("{a:?}") };
assert_eq!(*got, rows);
// Written as the same four ink records, and read back.
let w = write(&a);
assert_eq!(w[0].0, *b"mixr");
assert_eq!(w[0].1, d);
assert_eq!(parse(b"mixr", &w[0].1, None, Channels::Cmyk), a);
// Photoshop's block (photoshop corpus cmyk8 channel-mixer.psd, set to cyan 80/30/-10,
// magenta 10/90/0 +5, yellow 0/20/70 and no black record): read as four ink rows, the black
// one empty (the file's merged image has no black ink), and written back byte for byte.
let mut ps = i16s(&[1, 0]);
ps.extend(i16s(&[80, 30, -10, 0, 0, 10, 90, 0, 0, 5, 0, 20, 70, 0, 0, 0, 0, 0, 0, 0]));
assert_eq!(ps.len(), 44);
let a = parse(b"mixr", &ps, None, Channels::Cmyk);
let Adjustment::ChannelMixer { cmyk: Some(got), monochrome: false, .. } = &a else { panic!("{a:?}") };
assert_eq!(*got, [[0.8, 0.3, -0.1, 0.0, 0.0], [0.1, 0.9, 0.0, 0.0, 0.05], [0.0, 0.2, 0.7, 0.0, 0.0], [0.0; 5]]);
assert_eq!(write(&a)[0].1, ps);
for mono in [false, true] {
let m = Adjustment::ChannelMixer {
matrix: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]],
monochrome: mono,
cmyk: Some([[0.3, 0.3, 0.3, 1.0, 0.05], [0.0, 1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0, 0.0], [-2.0, 0.0, 0.0, 2.0, 0.0]]),
};
let b = write(&m);
assert_eq!(parse(&b[0].0, &b[0].1, None, Channels::Cmyk), m, "monochrome {mono}");
}
}
/// A mixer whose outputs don't match the document's mode is reshaped to the mode's own before it
/// is written, so the reopened `mixr` block reads back as what was saved (no black output
/// borrowed from the gray record, no CMYK block kept raw in an RGB file).
#[test]
fn channel_mixers_are_reshaped_to_the_document_mode() {
let rgb = Adjustment::ChannelMixer { matrix: [[0.0, 1.0, 0.0, 0.1], [1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, -0.2]], monochrome: false, cmyk: None };
let Some(ink) = mixer_for(&rgb, Channels::Cmyk) else { panic!("an RGB mixer in CMYK is reshaped") };
let Adjustment::ChannelMixer { cmyk: Some(rows), .. } = &ink else { panic!("{ink:?}") };
// Ink = 1 - light, so each constant becomes 1 - sources - constant.
assert_eq!(*rows, [[0.0, 1.0, 0.0, 0.0, -0.1], [1.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0, 0.2], [0.0, 0.0, 0.0, 1.0, 0.0]]);
let b = write(&ink);
assert_eq!(parse(&b[0].0, &b[0].1, None, Channels::Cmyk), ink);
let cmyk = Adjustment::ChannelMixer {
matrix: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]],
monochrome: true,
cmyk: Some([[0.3, 0.3, 0.2, 1.0, 0.05], [0.0, 1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0, 0.0]]),
};
let Some(screen) = mixer_for(&cmyk, Channels::Rgb) else { panic!("a CMYK mixer in RGB is reshaped") };
assert_eq!(screen, Adjustment::ChannelMixer { matrix: [[0.3, 0.3, 0.2, 0.15], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], monochrome: true, cmyk: None });
let b = write(&screen);
assert_eq!(parse(&b[0].0, &b[0].1, None, Channels::Rgb), screen);
// Matching shapes and other adjustments are left alone.
assert_eq!(mixer_for(&rgb, Channels::Rgb), None);
assert_eq!(mixer_for(&cmyk, Channels::Cmyk), None);
assert_eq!(mixer_for(&Adjustment::Invert, Channels::Cmyk), None);
}
fn vdesc(d: Descriptor) -> Vec<u8> {
VersionedDescriptor::new(d).to_bytes()
}
+73 -52
View File
@@ -420,6 +420,78 @@ impl Ex<'_> {
}
}
/// The adjustment part of [`Self::content_blocks`] for layer `l` holding `a`: keeps a preserved
/// block of `raw` that still decodes to `a` (or a Gradient Map retargeted in place, or the
/// verbatim block of an unknown type); otherwise drops the stale blocks from `raw` and pushes
/// the regenerated ones onto `regenerated`, warning about anything PSD cannot hold as it is.
fn adjustment_blocks(&mut self, l: &Layer, a: &photocraft_doc::Adjustment, raw: &mut Vec<([u8; 4], Vec<u8>)>, regenerated: &mut Vec<([u8; 4], Vec<u8>)>) {
let channels = match self.fmt.mode {
ColorMode::Rgb => adjust_map::Channels::Rgb,
ColorMode::Grayscale => adjust_map::Channels::Gray,
ColorMode::Cmyk => adjust_map::Channels::Cmyk,
ColorMode::Lab => adjust_map::Channels::Lab,
_ => adjust_map::Channels::Other,
};
let cged = raw.iter().find(|(k, _)| k == b"CgEd").map(|(_, d)| d.clone());
let keep = raw.iter().any(|(k, d)| {
// A previously saved PhotoCraft v2 Photo Filter block may be 18 bytes.
// It parses here, but Photoshop requires four-byte alignment, so repair
// that legacy record on re-save rather than preserving the broken bytes.
let legacy_phfl = k == b"phfl" && d.starts_with(&[0, 2]) && d.len() % 4 != 0;
// Older PhotoCraft builds wrote `grdm` 2 bytes short of four-byte alignment,
// which makes Photoshop refuse the file (#8070): regenerate it too.
let legacy_grdm = k == b"grdm" && adjust_map::is_unpadded_photocraft_gradient_map(d);
!legacy_phfl && !legacy_grdm && adjust_map::ADJUSTMENT_KEYS.contains(&k) && adjust_map::parse(k, d, cged.as_deref(), channels) == *a
});
// A Gradient Map whose stops are unchanged keeps the file's own block (stops in
// the document's CMYK/Lab/Gray space, smoothness, method) with Reverse and Dither
// updated in place.
let keep = keep
|| (matches!(a, photocraft_doc::Adjustment::GradientMap { .. })
&& raw
.iter_mut()
.any(|(k, d)| k == b"grdm" && !adjust_map::is_unpadded_photocraft_gradient_map(d) && adjust_map::retarget_gradient_map(d, a, channels)));
// An adjustment type no mapper knows (#6575) is its block: kept verbatim, and
// never written a second time beside a stale copy.
let own = match a {
photocraft_doc::Adjustment::Unsupported { psd_key, .. } => Some(psd_key.as_bytes()),
_ => None,
};
let keep =
keep || matches!(a, photocraft_doc::Adjustment::Unsupported { raw: r, .. } if raw.iter().any(|(k, d)| own == Some(&k[..]) && d[..] == r[..]));
if !keep {
raw.retain(|(k, _)| !adjust_map::ADJUSTMENT_KEYS.contains(&k) && k != b"CgEd" && own != Some(&k[..]));
// A Channel Mixer whose outputs don't match the document's mode has no
// PSD encoding that reads back as it is: save its nearest equivalent.
let reshaped = adjust_map::mixer_for(a, channels);
let target = reshaped.as_ref().unwrap_or(a);
// No Photoshop sample shows a monochrome CMYK `mixr` yet (#8047), so its layout would
// be a guess: such a mixer is saved only as the imported block it came from (kept
// above), never regenerated, whether it was a CMYK mixer or an RGB one reshaped here.
let unconfirmed = matches!(target, photocraft_doc::Adjustment::ChannelMixer { cmyk: Some(_), monochrome: true, .. });
if unconfirmed {
self.warnings
.push(format!("layer \"{}\": monochrome CMYK Channel Mixer is not written to PSD (its Photoshop layout is not confirmed yet)", l.name));
return;
}
if reshaped.is_some() {
let shape = if channels == adjust_map::Channels::Cmyk { "cyan, magenta, yellow and black" } else { "red, green and blue" };
self.warnings.push(format!("layer \"{}\": Channel Mixer saved with {shape} outputs, the document mode's own", l.name));
}
let w = adjust_map::write(target);
if w.is_empty() {
self.warnings.push(format!("layer \"{}\": {} adjustment is not yet written to PSD", l.name, a.label()));
}
// Photoshop's `clrL` descriptor has no interpolation setting, so the
// reopened layer renders trilinear.
if matches!(a, photocraft_doc::Adjustment::ColorLookup { tetrahedral: true, .. }) {
self.warnings
.push(format!("layer \"{}\": Color Lookup tetrahedral interpolation is saved as trilinear (PSD has no interpolation setting)", l.name));
}
regenerated.extend(w);
}
}
/// Content blocks for `l`: preserved raw blocks (with `psd_raw`
/// overrides) plus regenerated adjustment/fill blocks. A preserved
/// adjustment or fill block is reused verbatim while it still decodes to
@@ -496,58 +568,7 @@ impl Ex<'_> {
}
};
match &l.content {
LayerContent::Adjustment(a) => {
let channels = match self.fmt.mode {
ColorMode::Rgb => adjust_map::Channels::Rgb,
ColorMode::Grayscale => adjust_map::Channels::Gray,
ColorMode::Cmyk => adjust_map::Channels::Cmyk,
ColorMode::Lab => adjust_map::Channels::Lab,
_ => adjust_map::Channels::Other,
};
let cged = raw.iter().find(|(k, _)| k == b"CgEd").map(|(_, d)| d.clone());
let keep = raw.iter().any(|(k, d)| {
// A previously saved PhotoCraft v2 Photo Filter block may be 18 bytes.
// It parses here, but Photoshop requires four-byte alignment, so repair
// that legacy record on re-save rather than preserving the broken bytes.
let legacy_phfl = k == b"phfl" && d.starts_with(&[0, 2]) && d.len() % 4 != 0;
// Older PhotoCraft builds wrote `grdm` 2 bytes short of four-byte alignment,
// which makes Photoshop refuse the file (#8070): regenerate it too.
let legacy_grdm = k == b"grdm" && adjust_map::is_unpadded_photocraft_gradient_map(d);
!legacy_phfl && !legacy_grdm && adjust_map::ADJUSTMENT_KEYS.contains(&k) && adjust_map::parse(k, d, cged.as_deref(), channels) == *a
});
// A Gradient Map whose stops are unchanged keeps the file's own block (stops in
// the document's CMYK/Lab/Gray space, smoothness, method) with Reverse and Dither
// updated in place.
let keep = keep
|| (matches!(a, photocraft_doc::Adjustment::GradientMap { .. })
&& raw.iter_mut().any(|(k, d)| {
k == b"grdm" && !adjust_map::is_unpadded_photocraft_gradient_map(d) && adjust_map::retarget_gradient_map(d, a, channels)
}));
// An adjustment type no mapper knows (#6575) is its block: kept verbatim, and
// never written a second time beside a stale copy.
let own = match a {
photocraft_doc::Adjustment::Unsupported { psd_key, .. } => Some(psd_key.as_bytes()),
_ => None,
};
let keep = keep
|| matches!(a, photocraft_doc::Adjustment::Unsupported { raw: r, .. } if raw.iter().any(|(k, d)| own == Some(&k[..]) && d[..] == r[..]));
if !keep {
raw.retain(|(k, _)| !adjust_map::ADJUSTMENT_KEYS.contains(&k) && k != b"CgEd" && own != Some(&k[..]));
let w = adjust_map::write(a);
if w.is_empty() {
self.warnings.push(format!("layer \"{}\": {} adjustment is not yet written to PSD", l.name, a.label()));
}
// Photoshop's `clrL` descriptor has no interpolation setting, so the
// reopened layer renders trilinear.
if matches!(a, photocraft_doc::Adjustment::ColorLookup { tetrahedral: true, .. }) {
self.warnings.push(format!(
"layer \"{}\": Color Lookup tetrahedral interpolation is saved as trilinear (PSD has no interpolation setting)",
l.name
));
}
regenerated.extend(w);
}
}
LayerContent::Adjustment(a) => self.adjustment_blocks(l, a, &mut raw, &mut regenerated),
LayerContent::Fill(f) => fill_rule(&mut raw, &mut regenerated, f),
LayerContent::Shape(sh) => {
if let Some(f) = &sh.fill {
+7
View File
@@ -546,6 +546,13 @@ impl Ctx<'_> {
if light { "Light" } else { adjust_map::label(k) }
));
}
// Photoshop's CMYK Channel Mixer is checked against its own files, but not yet with
// Monochrome on (#8047): say so. Unedited, its block is saved back as it was read.
if matches!(adj, photocraft_doc::Adjustment::ChannelMixer { cmyk: Some(_), monochrome: true, .. }) {
self.warn(format!(
"layer \"{name}\": a monochrome CMYK Channel Mixer may not render as in Photoshop yet; unless edited, it is saved back unchanged"
));
}
LayerContent::Adjustment(adj)
} else if let Some(block) = rec.block(b"TySh") {
// Only canonical type data with a safe transform can become a text layer. A retained
+2 -2
View File
@@ -78,8 +78,8 @@ fn adjustments() -> Vec<(Adjustment, bool)> {
(Adjustment::BlackWhite { weights: [70.0, 20.0, 50.0, -10.0, 90.0, 130.0], tint: Some([0.9, 0.7, 0.5]) }, true),
(Adjustment::PhotoFilter { color: [q16(60620), q16(35455), q16(0)], density: 0.4, preserve_luminosity: true }, true),
(Adjustment::PhotoFilter { color: [q16(0), q16(39321), q16(65535)], density: 0.3, preserve_luminosity: false }, true),
(Adjustment::ChannelMixer { matrix: [[0.5, 0.3, 0.2, 0.0], [0.1, 0.8, 0.1, 0.05], [0.0, 0.2, 0.9, -0.05]], monochrome: false }, true),
(Adjustment::ChannelMixer { matrix: [[0.4, 0.4, 0.2, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], monochrome: true }, true),
(Adjustment::ChannelMixer { matrix: [[0.5, 0.3, 0.2, 0.0], [0.1, 0.8, 0.1, 0.05], [0.0, 0.2, 0.9, -0.05]], monochrome: false, cmyk: None }, true),
(Adjustment::ChannelMixer { matrix: [[0.4, 0.4, 0.2, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], monochrome: true, cmyk: None }, true),
// The LUT file is embedded as loaded (here a .cube), so it reads back with its source.
(
Adjustment::ColorLookup {
+164
View File
@@ -0,0 +1,164 @@
//! A CMYK document's Channel Mixer (`mixr` with four ink records, #8047) through PSD: an imported
//! block nobody edited is saved back exactly as it was read, whatever its layout; an edited one
//! is written in Photoshop's own 44-byte layout, except a monochrome one, whose layout no
//! Photoshop sample confirms yet: that is not written. With the `corpus` feature, Photoshop's own CMYK
//! mixers (photoshop corpus cmyk8 and cmyk16 channel-mixer.psd) are read, rendered on their inks
//! against the files' merged images, and saved back byte for byte.
use craft_psd::PsdFile;
use photocraft_color::{Color, ColorMode, SampleType};
use photocraft_doc::{Adjustment, Document, Layer, LayerContent, Size};
use photocraft_io::*;
/// The identity RGB matrix a CMYK mixer carries unused.
const RGB_IDENTITY: [[f32; 4]; 3] = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]];
/// Big-endian i16 words, as a `mixr` block stores them.
fn i16s(v: &[i16]) -> Vec<u8> {
v.iter().flat_map(|x| x.to_be_bytes()).collect()
}
/// The `mixr` block data of the first layer record that has one.
fn mixr(file: &PsdFile) -> Option<Vec<u8>> {
file.layers().iter().find_map(|l| l.block(b"mixr")).map(|b| b.data.clone())
}
/// The document's first adjustment.
fn first_adjustment(d: &Document) -> Option<Adjustment> {
d.layers.iter().find_map(|l| match &l.content {
LayerContent::Adjustment(a) => Some(a.clone()),
_ => None,
})
}
/// Exports `d` and parses the PSD it became.
fn exported(d: &Document) -> PsdFile {
PsdFile::from_bytes(&export(d, "x.psd", &ExportOptions::default()).unwrap().bytes).unwrap()
}
/// A CMYK PSD with a Channel Mixer layer over a white background whose `mixr` block is `block`,
/// as another writer could have stored it.
fn psd_with_mixr(block: &[u8]) -> Vec<u8> {
let mut d = Document::with_background("mixer", Size::new(4, 4), ColorMode::Cmyk, SampleType::U8, Color::WHITE);
let adj = Adjustment::ChannelMixer { matrix: RGB_IDENTITY, monochrome: false, cmyk: Some(photocraft_doc::adjust::CMYK_MIXER_IDENTITY) };
d.layers.push(Layer::new("Channel Mixer 1", LayerContent::Adjustment(adj)));
let mut file = exported(&d);
let b = file.layers_mut().iter_mut().flat_map(|l| l.blocks.iter_mut()).find(|b| b.key == *b"mixr").unwrap();
b.data = block.to_vec();
file.to_bytes().unwrap()
}
/// A monochrome block carrying its first record alone (padded), and a four-record block followed
/// by bytes our writer never emits: both import as CMYK mixers (the monochrome one with a
/// warning, as no Photoshop sample confirms how it renders), are saved back unchanged while
/// unedited; once edited, the four-record one is rewritten as Photoshop's 44 bytes and the
/// monochrome one is not written (its layout is unconfirmed).
#[test]
fn unedited_cmyk_mixer_blocks_are_saved_back_as_read() {
let mut mono = i16s(&[1, 1, 30, 30, 30, 100, 0]);
mono.extend([0, 0]);
let mut long = i16s(&[1, 0, 80, 30, -10, 0, 0, 10, 90, 0, 0, 5, 0, 20, 70, 0, 0, 0, 0, 0, 0, 0]);
long.extend([0, 0, 0, 0]);
for (block, monochrome) in [(mono, true), (long, false)] {
let imp = import("x.psd", &psd_with_mixr(&block)).unwrap();
let warned = imp.warnings.iter().any(|w| w.contains("monochrome CMYK Channel Mixer"));
assert_eq!(warned, monochrome, "{:?}", imp.warnings);
let adj = first_adjustment(&imp.document).unwrap();
assert!(matches!(adj, Adjustment::ChannelMixer { cmyk: Some(_), monochrome: m, .. } if m == monochrome), "{adj:?}");
assert_eq!(mixr(&exported(&imp.document)), Some(block.clone()), "monochrome {monochrome}: saved back as read");
let mut doc = imp.document;
for l in &mut doc.layers {
if let LayerContent::Adjustment(Adjustment::ChannelMixer { cmyk: Some(rows), .. }) = &mut l.content {
rows[1][4] = 0.1;
}
}
let r = export(&doc, "x.psd", &ExportOptions::default()).unwrap();
let edited = mixr(&PsdFile::from_bytes(&r.bytes).unwrap());
let skipped = r.warnings.iter().any(|w| w.contains("monochrome CMYK Channel Mixer is not written"));
assert_eq!(skipped, monochrome, "{:?}", r.warnings);
if monochrome {
// No Photoshop sample confirms the layout: an edited one is not regenerated.
assert_eq!(edited, None, "monochrome: edited");
} else {
let edited = edited.unwrap();
assert_eq!(edited.len(), 44, "edited");
assert_ne!(edited, block);
}
}
}
/// An RGB monochrome mixer in a CMYK document (from a `.pcraft` or a mode change) would be
/// reshaped into a monochrome CMYK mixer, whose `mixr` layout no Photoshop sample confirms yet
/// (#8047): it is not written, with a warning naming the layer; without Monochrome it is
/// reshaped and written as before.
#[test]
fn rgb_monochrome_mixer_in_a_cmyk_document_is_not_written_as_cmyk() {
for monochrome in [true, false] {
let mut d = Document::with_background("mixer", Size::new(4, 4), ColorMode::Cmyk, SampleType::U8, Color::WHITE);
let matrix = [[0.4, 0.4, 0.2, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]];
d.layers.push(Layer::new("Gray Mix", LayerContent::Adjustment(Adjustment::ChannelMixer { matrix, monochrome, cmyk: None })));
let r = export(&d, "x.psd", &ExportOptions::default()).unwrap();
let block = mixr(&PsdFile::from_bytes(&r.bytes).unwrap());
let skipped = r.warnings.iter().any(|w| w.contains("\"Gray Mix\"") && w.contains("monochrome CMYK Channel Mixer is not written"));
assert_eq!(skipped, monochrome, "{:?}", r.warnings);
if monochrome {
assert_eq!(block, None, "no inferred monochrome CMYK block");
} else {
assert_eq!(block.map(|b| b.len()), Some(44), "reshaped to Photoshop's CMYK layout");
}
}
}
#[cfg(feature = "corpus")]
mod corpus {
use super::*;
use std::path::Path;
/// Photoshop's CMYK Channel Mixer (photoshop corpus cmyk8 and cmyk16 channel-mixer.psd, made
/// with cyan 80/30/-10, magenta 10/90/0 +5 and yellow 0/20/70 and no black record): read as
/// four ink rows with an empty black one, composited on the inks within 2 levels of 255 of
/// Photoshop's merged image (black ink cleared everywhere), and saved back byte for byte.
#[test]
fn photoshop_cmyk_channel_mixers_read_render_and_save_back() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/photoshop/adjustments");
let rows = [[0.8, 0.3, -0.1, 0.0, 0.0], [0.1, 0.9, 0.0, 0.0, 0.05], [0.0, 0.2, 0.7, 0.0, 0.0], [0.0; 5]];
for dir in ["cmyk8", "cmyk16"] {
let path = root.join(dir).join("channel-mixer.psd");
let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e} (run `cargo xtask corpus --all`)", path.display()));
let file = PsdFile::from_bytes(&bytes).unwrap();
assert_eq!(mixr(&file).map(|d| d.len()), Some(44), "{dir}: Photoshop's block");
let imp = import("channel-mixer.psd", &bytes).unwrap();
let doc = &imp.document;
assert_eq!(first_adjustment(doc), Some(Adjustment::ChannelMixer { matrix: RGB_IDENTITY, monochrome: false, cmyk: Some(rows) }), "{dir}");
// Photoshop's merged image: planar big-endian samples, each stored as 1 - ink.
let h = &file.header;
let (w, ht) = (h.width as usize, h.height as usize);
let wide = h.depth == 16;
let merged = file.decode_merged().unwrap();
let plane = w * ht * if wide { 2 } else { 1 };
let ink = |c: usize, i: usize| -> f32 {
let stored = if wide {
let at = c * plane + i * 2;
f32::from(u16::from_be_bytes([merged[at], merged[at + 1]])) / 65535.0
} else {
f32::from(merged[c * plane + i]) / 255.0
};
1.0 - stored
};
let flat = photocraft_compose::flatten_to_surface(doc, doc.pixel_format(), None);
let mut worst = 0.0f32;
for y in 0..ht {
for x in 0..w {
for (c, ours) in flat.pixel(x as i32, y as i32).into_iter().take(4).enumerate() {
worst = worst.max((ours - ink(c, y * w + x)).abs());
}
}
}
assert!(worst <= 2.0 / 255.0, "{dir}: inks differ from Photoshop's by up to {:.2} of 255", worst * 255.0);
assert_eq!(mixr(&exported(doc)), mixr(&file), "{dir}: saved back as read");
}
}
}
+11 -2
View File
@@ -181,9 +181,18 @@ pub fn gen_doc(mode: ColorMode, depth: SampleType, f: Features) -> Document {
Adjustment::ColorBalance { shadows: [10.0, 0.0, -5.0], midtones: [0.0, 20.0, 0.0], highlights: [-30.0, 0.0, 15.0], preserve_luminosity: true },
Adjustment::BlackWhite { weights: [50.0, 60.0, 40.0, 60.0, 20.0, 70.0], tint: Some([1.0, 0.8, 0.6]) },
Adjustment::PhotoFilter { color: [1.0, f32::from(32768u16) / 65535.0, 0.0], density: 0.25, preserve_luminosity: false },
Adjustment::ChannelMixer { matrix: [[0.8, 0.2, 0.0, 0.0], [0.0, 1.0, 0.0, 0.1], [0.1, 0.0, 0.9, 0.0]], monochrome: false },
Adjustment::ChannelMixer { matrix: [[0.8, 0.2, 0.0, 0.0], [0.0, 1.0, 0.0, 0.1], [0.1, 0.0, 0.9, 0.0]], monochrome: false, cmyk: None },
];
let adjs = adjs.into_iter().chain(colour.into_iter().filter(|_| mode != ColorMode::Grayscale));
// A CMYK document's Channel Mixer has ink outputs (#8047).
let colour = colour.into_iter().map(|a| match a {
Adjustment::ChannelMixer { monochrome, .. } if mode == ColorMode::Cmyk => Adjustment::ChannelMixer {
matrix: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]],
monochrome,
cmyk: Some([[0.8, 0.2, 0.0, 0.1, 0.0], [0.0, 1.0, 0.0, 0.0, 0.1], [0.1, 0.0, 0.9, 0.0, 0.0], [0.2, 0.2, 0.2, 0.8, -0.05]]),
},
other => other,
});
let adjs = adjs.into_iter().chain(colour.filter(|_| mode != ColorMode::Grayscale));
for (i, a) in adjs.enumerate() {
let mut l = Layer::new(format!("adj {i}"), LayerContent::Adjustment(a));
l.opacity = g(if i % 2 == 0 { 255 } else { 128 });
+1
View File
@@ -11,6 +11,7 @@ mod banded;
mod blend_modes_corpus;
mod cancel;
mod channels;
mod cmyk_channel_mixer;
mod cmyk_composite_export;
mod cmyk_export;
mod color;
+1 -1
View File
@@ -7,7 +7,7 @@ license.workspace = true
rust-version.workspace = true
[dependencies]
craft-ipp = { git = "https://github.com/storytold/craft-libs", rev = "ee30b17c2199b87b3c097729e60f6b1d9c8d1afe" }
craft-ipp = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
[lints]
workspace = true
+203 -19
View File
@@ -218,6 +218,26 @@ pub struct FontDb {
face_aliases: HashMap<(String, usize), String>,
/// This is the shared engine's database: registrations also move [`shared_generation`].
shared: bool,
/// The installed font files registered, by canonical path.
#[cfg(not(target_arch = "wasm32"))]
installed: HashSet<std::path::PathBuf>,
/// The [`Catalog::generation`] the installed fonts were last read at.
#[cfg(not(target_arch = "wasm32"))]
catalog_seen: u64,
}
/// Installed fonts the [`catalog`] lists that a [`FontDb`] hasn't registered yet
/// ([`FontDb::installed_update`]), for [`FontDb::apply_installed`].
#[cfg(not(target_arch = "wasm32"))]
pub struct InstalledUpdate {
generation: u64,
/// (canonical path, path) of each new file.
files: Vec<(std::path::PathBuf, std::path::PathBuf)>,
/// New faces without a file (a suitcase font).
unfiled: Vec<craft::font_catalog::FaceInfo>,
/// The families text lays out differently with once the update is applied: those of the new
/// faces (legacy names too, as PSD files give them) and those removed.
pub families: Vec<String>,
}
impl Default for FontDb {
@@ -240,6 +260,10 @@ impl FontDb {
traits_cache: HashMap::new(),
face_aliases: HashMap::new(),
shared: false,
#[cfg(not(target_arch = "wasm32"))]
installed: HashSet::new(),
#[cfg(not(target_arch = "wasm32"))]
catalog_seen: 0,
};
for (_, bytes) in BUNDLED {
db.register_static_font(bytes.as_slice());
@@ -284,26 +308,124 @@ impl FontDb {
{
let _ = installed_catalog().add_file(&path, Source::App, &Limits::default());
}
// One call per file: fontique's directory scan is much slower on large folders.
for path in installed_font_files() {
self.fcx.collection.load_fonts_from_paths([path]);
self.load_installed(installed_catalog());
}
}
/// Registers the installed fonts of `catalog` (waits for its first scan).
#[cfg(not(target_arch = "wasm32"))]
fn load_installed(&mut self, catalog: &Catalog) {
// After the first scan, so the faces read below are of this generation or newer.
let _ = catalog.faces();
self.catalog_seen = catalog.generation();
let faces = catalog.faces();
// One call per file: fontique's directory scan is much slower on large folders.
for path in new_font_files(faces.iter().filter(|f| is_installed_face(f)), &mut self.installed) {
self.fcx.collection.load_fonts_from_paths([path]);
}
// Faces without a file (a suitcase font, added bytes) load from the Catalog. The
// Catalog is the source, so they register without the mirror back into it.
self.register_unfiled(catalog, faces.iter().filter(|f| is_installed_face(f) && f.path.is_none()));
self.ps_cache.clear();
self.face_cache.clear();
self.traits_cache.clear();
self.refresh_generics();
}
/// Registers `faces` (faces without a file) from the bytes `catalog` loads, each blob once.
#[cfg(not(target_arch = "wasm32"))]
fn register_unfiled<'a>(&mut self, catalog: &Catalog, faces: impl Iterator<Item = &'a craft::font_catalog::FaceInfo>) {
let mut loaded = Vec::new();
let mut seen = HashSet::new();
for face in faces {
let Ok(data) = catalog.load(face) else { continue };
if seen.insert(Arc::as_ptr(&data.bytes).cast::<u8>() as usize) {
self.register_bytes(Blob::new(Arc::new(data.bytes.to_vec())), None);
}
// Faces without a file (a suitcase font, added bytes) load from the Catalog. The
// Catalog is the source, so they register without the mirror back into it.
let mut loaded = Vec::new();
let mut seen = HashSet::new();
for face in installed_catalog().faces().iter().filter(|f| is_installed_face(f) && f.path.is_none()) {
let Ok(data) = installed_catalog().load(face) else { continue };
if seen.insert(Arc::as_ptr(&data.bytes).cast::<u8>() as usize) {
self.register_bytes(Blob::new(Arc::new(data.bytes.to_vec())), None);
// Kept until the loop ends so a freed buffer's address cannot repeat.
loaded.push(data);
}
}
/// The installed fonts the [`installed_catalog`] gained since this database read them (a family the
/// launcher installed while the app runs), or `None` when it has none or never read them.
/// Fonts removed from the system stay registered until the next start; their families are in
/// [`InstalledUpdate::families`] all the same.
#[cfg(not(target_arch = "wasm32"))]
pub fn installed_update(&self) -> Option<InstalledUpdate> {
self.installed_update_in(installed_catalog())
}
#[cfg(not(target_arch = "wasm32"))]
fn installed_update_in(&self, catalog: &Catalog) -> Option<InstalledUpdate> {
if !self.system_loaded || catalog.generation() == self.catalog_seen {
return None;
}
let changes = catalog.changes_since(self.catalog_seen);
// `full`: the catalog no longer knows what changed, so every installed face is checked.
let wanted: Option<HashSet<String>> = (!changes.full).then(|| changes.added.iter().chain(&changes.changed).map(|f| f.to_lowercase()).collect());
let added: HashSet<String> = changes.added.iter().map(|f| f.to_lowercase()).collect();
let mut update = InstalledUpdate { generation: changes.generation, files: Vec::new(), unfiled: Vec::new(), families: changes.removed };
let mut new_keys = HashSet::new();
for face in catalog.faces().iter().filter(|f| is_installed_face(f)) {
let family = face.family.to_lowercase();
if wanted.as_ref().is_some_and(|w| !w.contains(&family)) {
continue;
}
let new = match &face.path {
Some(path) if is_private_font_path(path) => false,
Some(path) => {
let key = path.canonicalize().unwrap_or_else(|_| path.clone());
let new = !self.installed.contains(&key);
if new && new_keys.insert(key.clone()) {
update.files.push((key, path.clone()));
}
new
}
// Only a family new to the catalog: a changed one has its unfiled faces registered.
None => {
let new = added.contains(&family);
if new {
update.unfiled.push(face.clone());
}
new
}
};
if new {
for name in std::iter::once(&face.family).chain(&face.legacy_family) {
if !update.families.contains(name) {
update.families.push(name.clone());
}
}
// Kept until the loop ends so a freed buffer's address cannot repeat.
loaded.push(data);
}
self.ps_cache.clear();
self.face_cache.clear();
self.traits_cache.clear();
self.refresh_generics();
}
Some(update)
}
/// Registers what [`Self::installed_update`] found.
#[cfg(not(target_arch = "wasm32"))]
pub fn apply_installed(&mut self, update: InstalledUpdate) {
self.apply_installed_in(installed_catalog(), update);
}
#[cfg(not(target_arch = "wasm32"))]
fn apply_installed_in(&mut self, catalog: &Catalog, update: InstalledUpdate) {
self.catalog_seen = self.catalog_seen.max(update.generation);
if update.files.is_empty() && update.unfiled.is_empty() {
return;
}
for (key, path) in update.files {
self.fcx.collection.load_fonts_from_paths([path]);
self.installed.insert(key);
}
self.register_unfiled(catalog, update.unfiled.iter());
self.ps_cache.clear();
self.face_cache.clear();
self.traits_cache.clear();
self.refresh_generics();
GENERATION.fetch_add(1, Ordering::Relaxed);
if self.shared {
SHARED_GENERATION.fetch_add(1, Ordering::Relaxed);
}
}
@@ -925,6 +1047,23 @@ pub fn installed_catalog() -> &'static Arc<Catalog> {
Catalog::global()
}
/// Starts the [`catalog`] for the desktop app, before its first window: the first scan on a
/// background thread, and a poll of the suite's font store, so a family the launcher installs
/// shows while the app runs. `wake` runs on a worker thread after a family was added, removed or
/// changed; the app then finds the update with [`FontDb::installed_update`].
#[cfg(not(target_arch = "wasm32"))]
pub fn start_catalog(wake: impl Fn() + Send + Sync + 'static) {
use craft::font_catalog::app::{self, AppFonts};
app::start(AppFonts { on_change: Some(Arc::new(move |_: &Catalog| wake())), ..AppFonts::default() });
}
/// For a window's activation once [`start_catalog`] ran: checks the font folders for changes on
/// a worker thread, without blocking.
#[cfg(not(target_arch = "wasm32"))]
pub fn catalog_activated() {
craft::font_catalog::app::on_activated();
}
/// Fonts reserved for the system UI (PingFangUI.ttc among them). Core Text offers them, but
/// fontique can't draw their outlines (it works around PingFangUI for the same reason), so they
/// are not registered.
@@ -946,9 +1085,15 @@ fn is_installed_face(face: &craft::font_catalog::FaceInfo) -> bool {
/// consumer of the installed fonts (the shaper, the script fallbacks, the SVG renderer) uses.
#[cfg(not(target_arch = "wasm32"))]
pub fn installed_font_files() -> Vec<std::path::PathBuf> {
let mut seen = HashSet::new();
new_font_files(installed_catalog().faces().iter().filter(|f| is_installed_face(f)), &mut HashSet::new())
}
/// The files of `faces` whose canonical path isn't in `seen` yet (each added to it), in order,
/// without the macOS private UI fonts.
#[cfg(not(target_arch = "wasm32"))]
fn new_font_files<'a>(faces: impl Iterator<Item = &'a craft::font_catalog::FaceInfo>, seen: &mut HashSet<std::path::PathBuf>) -> Vec<std::path::PathBuf> {
let mut files = Vec::new();
for face in installed_catalog().faces().iter().filter(|f| is_installed_face(f)) {
for face in faces {
let Some(path) = &face.path else { continue };
if is_private_font_path(path) {
continue;
@@ -984,6 +1129,45 @@ pub fn is_hidden_family(name: &str) -> bool {
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
/// A family the launcher installs into the font store while the app runs reaches the database
/// once the catalog's generation moves, and no file registers twice.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_family_installed_into_the_store_reaches_the_database() {
use craft::font_catalog::{FontEnv, Os};
let family = "Zetbrains Test";
let dir = std::env::temp_dir().join(format!("photocraft-store-test-{}", std::process::id()));
let store = dir.join("store");
std::fs::create_dir_all(&store).unwrap();
let catalog = super::Catalog::new(FontEnv { os: Os::None, font_store: Some(store.clone()), ..FontEnv::default() }).with_font_service(false);
let mut db = super::FontDb::new();
db.system_loaded = true;
db.load_installed(&catalog);
assert!(db.installed_update_in(&catalog).is_none(), "nothing new yet");
assert!(!db.has_family(family));
// JetBrains Mono renamed in its name table (ASCII and UTF-16BE records; same length).
let mut bytes = super::JETBRAINS_MONO_REGULAR.clone();
let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
for (from, to) in [(b"JetBrains Mono".to_vec(), family.as_bytes().to_vec()), (utf16("JetBrains Mono"), utf16(family))] {
let mut i = 0;
while let Some(at) = bytes[i..].windows(from.len()).position(|w| w == from) {
bytes[i + at..i + at + to.len()].copy_from_slice(&to);
i += at + to.len();
}
}
std::fs::create_dir_all(store.join(family)).unwrap();
std::fs::write(store.join(family).join("ZetbrainsTest-Regular.ttf"), &bytes).unwrap();
catalog.rescan();
let update = db.installed_update_in(&catalog).expect("the catalog changed");
assert!(update.families.iter().any(|f| f == family), "{:?}", update.families);
db.apply_installed_in(&catalog, update);
assert!(db.has_family(family));
assert!(db.installed_update_in(&catalog).is_none(), "applied");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn hidden_families_sort_last_and_are_not_listed() {
assert!(super::is_hidden_family(".Hiragino Kaku Gothic Interface"));
+1
View File
@@ -16,6 +16,7 @@ suite = ["craft/suite"]
[dependencies]
chrono = { workspace = true }
craft-print = { workspace = true }
craft-xml = { workspace = true }
craft = { workspace = true, features = ["ui", "layers", "color-ui", "draw", "imaging", "window", "keymap", "automation", "theme-store", "print", "menu", "timeline", "text", "text-font-picker", "font-manager", "quit", "cms", "tracked-serde"] }
# Interface translations over the embedded craft-i18n catalogs (`build.rs`, `src/i18n.rs`).
craft-i18n = { workspace = true }
+2
View File
@@ -278,6 +278,8 @@ impl eframe::App for PhotocraftApp {
fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
let frame_start = gpu_canvas::now_ms();
self.framework_before_input(ctx);
#[cfg(not(target_arch = "wasm32"))]
crate::text::installed_fonts::on_input(raw_input);
if let Some(tablet_poll) = self.services.tablet_poll.as_mut() {
tablet_poll(raw_input.focused);
}
+26
View File
@@ -221,6 +221,9 @@ impl PhotocraftApp {
}
}
Err(e) => {
if id == "file.scripts.imageProcessor" && e == "There were no source files that could be opened by PhotoCraft." {
crate::dialogs::alerts::alert(self, e.clone());
}
self.ui.status = translated_refusal(e).map_or_else(|| e.clone(), |reason| tl!(reason).into());
self.ui.status_error = true;
// The reference application refuses a locked type layer (#14499) and a missing
@@ -444,3 +447,26 @@ fn translated_refusal(error: &str) -> Option<&'static str> {
.into_iter()
.find(|reason| error == *reason || error.strip_suffix(reason).is_some_and(|rest| rest.ends_with(": ")))
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod image_processor_empty_source_tests {
use super::*;
#[test]
fn confirming_image_processor_with_no_source_replaces_the_form_with_an_alert() {
let input = tempfile::tempdir().unwrap();
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
let ctx = app.ctx().clone();
crate::menus::invoke(&mut app, &ctx, "file.scripts.imageProcessor", json!({})).unwrap();
let id = app.framework.dialogs.stack().top().unwrap();
let output = input.path().join("processed");
app.framework.dialogs.set_json_field(&ctx, id, "input", json!(input.path())).unwrap();
app.framework.dialogs.set_json_field(&ctx, id, "output", json!(output)).unwrap();
crate::dialogs::confirm(&mut app, &ctx, id).unwrap();
assert!(app.framework.dialogs.get_dyn(id).is_none());
assert_eq!(crate::dialogs::alerts::alerts(&app).len(), 1);
assert_eq!(app.ui.status, "There were no source files that could be opened by PhotoCraft.");
assert!(!output.exists());
}
}
+2
View File
@@ -90,6 +90,8 @@ impl PhotocraftApp {
transform_tool::end_if_left(self);
prefs_ui::tick(self, ctx, std::time::Instant::now());
updates_ui::tick(self);
#[cfg(not(target_arch = "wasm32"))]
crate::text::installed_fonts::tick(self, ctx);
monitor_status::poll_frame(self, ctx, frame);
// Control requests and persisted preferences can change the language in this frame.
i18n::sync_context(ctx, &self.session.prefs().interface.language);
+5 -1
View File
@@ -50,7 +50,7 @@ pub(crate) fn install(ctx: &egui::Context, fonts: &UiFonts<'_>, frame: Option<De
let wake = ctx.clone();
let mut spec = InstallSpec::new(ShellInfo::default().backend(Backend::from_env()), Arc::new(SystemWindows))
.wheel(wheel)
.app_id(crate::os_window::APP_ID)
.app_id(crate::os_window::app_id())
.system(SystemReader::start(move || wake.request_repaint()));
if let Some(decision) = frame {
spec = spec.frame(decision);
@@ -372,6 +372,10 @@ impl Framework {
/// in-memory suite the app starts with.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn open_suite(&mut self, ctx: &egui::Context) {
// A nightly keeps its in-memory suite; never open the stable shared theme store.
if !crate::os_window::stable_services_allowed() {
return;
}
use craft::theme_store::{StoreOptions, SuiteDir, SuiteWatch};
let ctx = ctx.clone();
let options = StoreOptions::new(concat!("photocraft ", env!("CARGO_PKG_VERSION")));
+32 -4
View File
@@ -104,10 +104,11 @@ pub struct CanvasToolMenu {
/// Opened with the Content-Aware Move tool inside the active selection (#12194).
#[serde(default)]
pub inside_selection: bool,
/// Opened with the Delete Anchor Point or Convert Point tool over an anchor or a segment of the
/// targeted path (#12771, #12744): the engine command that entry runs and its params. It heads
/// the path menu, above a separator. The third part is the document id and revision it was read
/// from: the knot index means something only there, so the entry expires once either moves on.
/// Opened with the Delete Anchor Point or Convert Point tool, or the Pen (#12771, #12744,
/// #12915), over an anchor or a segment of the targeted path: the engine command that entry
/// runs and its params. It heads the path menu, above a separator. The third part is the
/// document id and revision it was read from: the knot index means something only there, so
/// the entry expires once either moves on.
#[serde(default)]
pub point: Option<(String, Value, (u64, u64))>,
}
@@ -1039,6 +1040,26 @@ fn point_at(app: &PhotocraftApp, target: PathRef, hit: BezierHit) -> Option<(Str
Some((command.to_string(), params, stamp))
}
/// The Pen's menu takes the `target`/`hit` the right-click reported as its point entry only in
/// the measured configuration (#12915): the Pen in Path mode with no path being drawn, and the
/// part on a CLOSED subpath. Its overlay reports the hit exactly as the anchor tools' does (the
/// Auto Add/Delete mode the Pen runs by default). The Shape-mode and Pixels-mode right-click and
/// an open path's parts are not measured and keep today's plain list, and so does every other case.
/// The gate reads no modifiers: `capture` never receives the click's, and with ⌥ held the overlay
/// is Convert, which senses the closed path's anchors and straight segments as well, so the row
/// appears there too - observed and pinned, not measured.
fn pen_point_allowed(app: &PhotocraftApp, target: PathRef, hit: &BezierHit) -> bool {
if app.ui.pen.is_some() || app.ui.tool_options.vector_mode != craft::draw::ui::VectorMode::Path {
return false;
}
let subpath = match *hit {
BezierHit::Anchor { knot, .. } => knot.subpath,
BezierHit::Segment { segment, .. } => segment.subpath,
_ => return false,
};
crate::direct_select::path_of(app, &target).is_some_and(|path| path.subpaths.get(subpath).is_some_and(|sub| sub.closed))
}
const POINT_DELETE: &str = "path.deleteAnchor";
const POINT_ADD: &str = "path.addAnchor";
@@ -1547,6 +1568,10 @@ fn capture(app: &mut PhotocraftApp, menu: &mut CanvasToolMenu, doc: [f64; 2], po
{
select_right_clicked_anchor(app, target, [knot.subpath, knot.knot]);
}
} else if menu.tool == Tool::Pen && menu.has_path {
// The Pen's overlay reports the right-click's hit as the anchor tools' does; only the
// measured configuration heads the menu with the entry (#12915).
menu.point = point.filter(|(target, hit)| pen_point_allowed(app, *target, hit)).and_then(|(target, hit)| point_at(app, target, hit));
}
menu.inside_selection = menu.tool == Tool::ContentAwareMove && selected_at(app, doc);
if menu.tool == Tool::ColorSampler {
@@ -1863,6 +1888,9 @@ pub(crate) mod tests;
#[cfg(test)]
pub(crate) mod count_tests;
#[cfg(test)]
mod pen_anchor_row_tests;
#[cfg(test)]
mod pen_free_transform_label_tests;
@@ -0,0 +1,211 @@
//! #12915: with the Pen (Path mode) a right-click on a part of the active CLOSED path heads the
//! path menu with one entry above the separator and the usual Pen list: Add Anchor Point on a
//! segment, Delete Anchor Point on an anchor; choosing it runs the engine command, one history
//! step. On empty canvas, on an open subpath, while a path is being drawn, and in Shape or Pixels
//! mode the menu keeps today's list with no top entry; with ⌥ held the row stays, as the menu does
//! not read the click's modifiers (pinned below). The shared path document and menu assertions
//! come from `delete_anchor_menu_tests` (#12771).
use egui_kittest::kittest::{NodeT, Queryable as _};
use serde_json::json;
use super::delete_anchor_menu_tests::{assert_top_entry, saved, setup, steps};
use super::tests::{harness, pen_clicks, right_click, screen_of};
use super::{PEN_MENU, rows};
use crate::PhotocraftApp;
use crate::state::Tool;
use egui::Modifiers;
/// The Pen in the measured configuration: reset (Auto Add/Delete on) in Path mode, Path 1 targeted.
fn pen_setup() -> Box<PhotocraftApp> {
let mut app = setup(Tool::Pen);
app.ui.tool_options.vector_mode = craft::draw::ui::VectorMode::Path;
app.ui.tool_options.pen_auto_add_delete = true;
app
}
/// A harness over [`pen_setup`] with a Pen right-click at document point `at` done.
fn pen_right_clicked(at: [f32; 2]) -> egui_kittest::Harness<'static, Box<PhotocraftApp>> {
let mut h = harness(pen_setup());
let p = screen_of(h.state(), at);
right_click(&mut h, p, Modifiers::NONE);
h
}
/// The Pen's list is open with no anchor-point entry above it.
fn assert_no_top_entry(h: &egui_kittest::Harness<'static, Box<PhotocraftApp>>, tool: Tool) {
assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.tool == tool && rows(m) == PEN_MENU), "{tool:?}: the path menu is open");
assert!(h.query_by_label("Add Anchor Point").is_none() && h.query_by_label("Delete Anchor Point").is_none(), "{tool:?}: no anchor row on top");
}
/// Right-click the middle of the square's top edge (200,300): Add Anchor Point heads the menu,
/// above Create Vector Mask; choosing it adds one anchor there, one history step of that name,
/// and undo restores the whole path.
#[test]
fn pen_right_click_on_a_segment_offers_add_anchor_point_on_top_and_it_adds() {
let mut h = pen_right_clicked([200.0, 300.0]);
assert_top_entry(&h, Tool::Pen, "Add Anchor Point");
let before = steps(h.state());
let original = saved(h.state());
h.get_by_label("Add Anchor Point").click();
h.run_steps(2);
let path = saved(h.state());
assert_eq!(path.subpaths[0].knots.len(), 5);
let added = &path.subpaths[0].knots[1].anchor;
assert!((added.x - 200.0).abs() < 3.0 && (added.y - 300.0).abs() < 3.0, "the anchor lands where it was clicked: {added:?}");
assert_eq!(steps(h.state()), before + 1);
assert_eq!(h.state().session.active().unwrap().history.undo_label(), Some("Add Anchor Point"));
h.state_mut().run("edit.undo", json!({})).unwrap();
assert_eq!(&saved(h.state()), &original, "undo restores the whole path");
}
/// Right-click the corner (300,300): Delete Anchor Point heads the menu; choosing it leaves the
/// square closed with three anchors, one history step of that name.
#[test]
fn pen_right_click_on_an_anchor_offers_delete_anchor_point_on_top_and_it_deletes() {
let mut h = pen_right_clicked([300.0, 300.0]);
assert_top_entry(&h, Tool::Pen, "Delete Anchor Point");
let before = steps(h.state());
let original = saved(h.state());
h.get_by_label("Delete Anchor Point").click();
h.run_steps(2);
let path = saved(h.state());
assert!(path.subpaths[0].closed, "the square stays closed");
assert_eq!(path.subpaths[0].knots.len(), 3);
assert!(path.subpaths[0].knots.iter().all(|k| (k.anchor.x, k.anchor.y) != (300.0, 300.0)), "(300,300) is gone");
assert_eq!(steps(h.state()), before + 1);
assert_eq!(h.state().session.active().unwrap().history.undo_label(), Some("Delete Anchor Point"));
h.state_mut().run("edit.undo", json!({})).unwrap();
assert_eq!(&saved(h.state()), &original, "undo restores the whole path");
}
/// Right-click on empty canvas: today's list, no top row, and opening it records no step.
#[test]
fn pen_right_click_on_empty_canvas_keeps_todays_list() {
let mut h = harness(pen_setup());
let before = steps(h.state());
let p = screen_of(h.state(), [600.0, 100.0]);
right_click(&mut h, p, Modifiers::NONE);
assert_no_top_entry(&h, Tool::Pen);
assert_eq!(steps(h.state()), before, "opening the menu records no history step");
}
/// The click on an OPEN subpath is not measured: it keeps today's list (the guard for the
/// closed-path gate in the menu's point entry).
#[test]
fn pen_right_click_on_an_open_subpath_keeps_todays_list() {
let h = pen_right_clicked([550.0, 300.0]);
assert_no_top_entry(&h, Tool::Pen);
}
/// The issue names an open path's ENDPOINT as not measured: an anchor click there keeps today's
/// list too.
#[test]
fn pen_right_click_on_an_open_paths_endpoint_keeps_todays_list() {
let h = pen_right_clicked([700.0, 300.0]);
assert_no_top_entry(&h, Tool::Pen);
}
/// Auto Add/Delete off: the Pen's overlay then senses no part and reports no hit, and the menu
/// invents none either - today's list stays (guard test, passes before and after).
#[test]
fn pen_right_click_without_auto_add_delete_keeps_todays_list() {
let mut app = pen_setup();
app.ui.tool_options.pen_auto_add_delete = false;
let mut h = harness(app);
let p = screen_of(h.state(), [200.0, 300.0]);
right_click(&mut h, p, Modifiers::NONE);
assert_no_top_entry(&h, Tool::Pen);
}
/// While a path is being drawn, the measured case names the plain list: no anchor row, even on
/// the open draft's own segment.
#[test]
fn pen_while_drawing_an_open_path_offers_no_top_entry() {
let mut app = pen_setup();
pen_clicks(&mut app, &[(150.0, 150.0), (350.0, 150.0)]);
assert!(app.ui.pen.is_some(), "a path is being drawn");
let mut h = harness(app);
let p = screen_of(h.state(), [250.0, 150.0]);
right_click(&mut h, p, Modifiers::NONE);
assert_no_top_entry(&h, Tool::Pen);
}
/// The Shape-mode right-click is not measured: today's list, no top row.
#[test]
fn pen_right_click_in_shape_mode_keeps_todays_list() {
let mut app = setup(Tool::Pen);
app.ui.tool_options.vector_mode = craft::draw::ui::VectorMode::Shape;
let mut h = harness(app);
let p = screen_of(h.state(), [200.0, 300.0]);
right_click(&mut h, p, Modifiers::NONE);
assert_no_top_entry(&h, Tool::Pen);
}
/// Pixels mode is not measured either and keeps today's list (the gate names Path, so every other
/// mode is out). The Pen's options bar shows Pixels disabled, so no click can select it and the
/// option is set directly, as the shape tool's Pixels tests do.
#[test]
fn pen_right_click_in_pixels_mode_keeps_todays_list() {
let mut app = setup(Tool::Pen);
app.ui.tool_options.vector_mode = craft::draw::ui::VectorMode::Pixels;
let mut h = harness(app);
let p = screen_of(h.state(), [200.0, 300.0]);
right_click(&mut h, p, Modifiers::NONE);
assert_no_top_entry(&h, Tool::Pen);
}
/// ⌥ is held for the Convert overlay (craft-libs `pen::mode::resolve`), which senses the closed
/// square's anchors and straight segments too, and the framework reports that secondary click's
/// hit whatever the modifiers are: the menu's gate reads the mode and the subpath, not the click's
/// modifiers, so the row appears. Observed, and pinned as it is today; choosing it with ⌥ down is
/// not measured.
#[test]
fn pen_right_click_with_option_held_still_gets_the_anchor_row() {
let mut h = harness(pen_setup());
let p = screen_of(h.state(), [200.0, 300.0]);
right_click(&mut h, p, Modifiers::ALT);
assert_top_entry(&h, Tool::Pen, "Add Anchor Point");
}
/// The entry is about the path as it was when the menu opened: a control-channel edit meanwhile
/// shifts the knots, so choosing the stale entry deletes nothing and adds no step. It is drawn
/// disabled for the Pen as well, not only rejected on click (#12771 pattern).
#[test]
fn a_pen_point_entry_expires_once_the_path_is_edited() {
let mut h = pen_right_clicked([300.0, 300.0]);
assert_top_entry(&h, Tool::Pen, "Delete Anchor Point");
assert!(!h.get_by_label("Delete Anchor Point").accesskit_node().is_disabled(), "enabled while the path is as it was");
h.state_mut().run("path.addAnchor", json!({"name": "Path 1", "subpath": 0, "knot": 0, "t": 0.5})).unwrap();
let after_add = saved(h.state());
assert_eq!(after_add.subpaths[0].knots.len(), 5, "the anchor went in");
h.run();
assert!(h.get_by_label("Delete Anchor Point").accesskit_node().is_disabled(), "disabled once the path is edited");
let n = steps(h.state());
let ctx = h.ctx.clone();
super::choose(h.state_mut(), &ctx, "path.deleteAnchor");
assert_eq!(&saved(h.state()), &after_add, "the stale entry deleted nothing");
assert_eq!(steps(h.state()), n, "and added no history step");
}
/// #1056: the Path Selection tool's path menu does not cover these rows — unchanged, guard test
/// that passes before and after this change.
#[test]
fn the_path_selection_tool_still_gets_no_anchor_point_row() {
let mut app = setup(Tool::PathSelection);
app.ui.tool_options.vector_mode = craft::draw::ui::VectorMode::Path;
let mut h = harness(app);
let p = screen_of(h.state(), [200.0, 300.0]);
right_click(&mut h, p, Modifiers::NONE);
assert_no_top_entry(&h, Tool::PathSelection);
}
/// The Delete Anchor Point tool's menu keeps its point entry (the shared mechanism stays wired) —
/// guard test that passes before and after this change.
#[test]
fn the_delete_anchor_point_tool_keeps_its_point_entry() {
let mut h = harness(setup(Tool::DeleteAnchorPoint));
let p = screen_of(h.state(), [200.0, 300.0]);
right_click(&mut h, p, Modifiers::NONE);
assert_top_entry(&h, Tool::DeleteAnchorPoint, "Add Anchor Point");
}
+63
View File
@@ -0,0 +1,63 @@
//! Photo's native/drawn caption rules, with an explicitly selected channel name.
pub(crate) fn os_title(app_name: &str, document: Option<(&str, bool)>, show_file_name: bool) -> String {
let Some((name, dirty)) = document else { return app_name.into() };
let prefix = if dirty { "*" } else { "" };
if show_file_name { format!("{prefix}{name} \u{2014} {app_name}") } else { format!("{prefix}{app_name}") }
}
pub(crate) fn drawn_title(app_name: &str, document: Option<(&str, bool)>, show_file_name: bool, mark_document_channel: bool) -> String {
let Some((name, dirty)) = document else { return app_name.into() };
let label = if show_file_name { name } else { app_name };
let channel = if show_file_name && mark_document_channel { format!(" \u{2014} {app_name}") } else { String::new() };
format!("{label}{channel}{}", if dirty { " •" } else { "" })
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nightly_native_caption_keeps_channel_across_document_dirty_and_hidden_name_updates() {
let channel = "PhotoCraft Nightly";
assert_eq!(os_title(channel, None, true), channel);
for dirty in [false, true] {
let shown = os_title(channel, Some(("my document.psd", dirty)), true);
assert!(shown.contains("my document.psd"));
assert!(shown.ends_with(channel));
assert_eq!(shown.starts_with('*'), dirty);
let hidden = os_title(channel, Some(("my document.psd", dirty)), false);
assert!(hidden.ends_with(channel));
assert!(!hidden.contains("my document.psd"));
assert_eq!(hidden.starts_with('*'), dirty);
}
}
#[test]
fn drawn_nightly_caption_keeps_channel_when_a_document_is_open() {
let channel = "PhotoCraft Nightly";
for show_name in [false, true] {
for dirty in [false, true] {
let title = drawn_title(channel, Some(("work.psd", dirty)), show_name, true);
assert!(title.contains(channel));
assert_eq!(title.contains("work.psd"), show_name);
assert_eq!(title.ends_with('•'), dirty);
}
}
}
#[test]
fn stable_drawn_caption_preserves_the_document_only_style_and_dirty_dot() {
let stable = "PhotoCraft";
assert_eq!(drawn_title(stable, None, true, false), stable);
let clean = drawn_title(stable, Some(("work.psd", false)), true, false);
assert_eq!(clean, "work.psd");
let dirty = drawn_title(stable, Some(("work.psd", true)), true, false);
assert!(dirty.starts_with(&clean));
assert!(dirty.ends_with('•'));
assert!(!dirty.contains(stable));
let hidden = drawn_title(stable, Some(("work.psd", true)), false, false);
assert!(hidden.starts_with(stable));
assert!(hidden.ends_with('•'));
assert!(!hidden.contains("work.psd"));
}
}
+7 -1
View File
@@ -552,7 +552,13 @@ fn agent_can_inspect_and_choose_pen_make_selection_from_full_context_menu() {
let inspected = call(&mut app, &ctx, "ui.inspect", json!({}));
assert_eq!(app.ui.canvas_tool_menu.as_ref().unwrap().pos, screen_point(&app, 8.0, 8.0));
let entries = inspected.pointer("/result/canvasToolMenu/entries").and_then(Value::as_array).unwrap();
assert_eq!(entries.iter().filter(|row| row.get("separator") == Some(&json!(true))).count(), 9);
// #12915: (8,8) lies on the closed work path's diagonal, so the menu now leads with the
// segment's Add Anchor Point entry above one more separator.
assert_eq!(entries.iter().filter(|row| row.get("separator") == Some(&json!(true))).count(), 10);
assert!(
entries.iter().any(|row| row.get("id") == Some(&json!("path.addAnchor")) && row.get("enabled") == Some(&json!(true))),
"the segment entry heads the menu"
);
assert!(entries.iter().any(|row| row.get("id") == Some(&json!("path.toSelection")) && row.get("enabled") == Some(&json!(true))));
assert_eq!(call(&mut app, &ctx, "ui.context.choose", json!({"id":"file.new"}))["ok"], false);
let chosen = call(&mut app, &ctx, "ui.context.choose", json!({"id":"path.toSelection"}));
+5
View File
@@ -299,6 +299,9 @@ pub(crate) mod params {
if let (Some(action), Some(footer)) = (footer, family.and_then(|family| family.footer)) {
footer(app, ctx, id, &action);
}
if key.as_deref() == Some(image_processor_ui::COMMAND) {
image_processor_ui::take_settings_action(app, ctx, id);
}
}
}
@@ -481,6 +484,8 @@ pub(crate) fn take_results(app: &mut PhotocraftApp, ctx: &egui::Context) {
for taker in TAKERS {
taker(app, ctx);
}
// Color Settings' Settings menu follows each pick and edit, a script's `ui.dialog.set` included (#14229).
crate::filter_dialog::reconcile_color_settings(app, ctx);
}
/// One pass of the dialogs: the guide edit follows its dialog, the palette shows, the filter preview and the Preferences window are fed, the
Loaded 100 of 150 files, more files were not shown because too many files have changed in this diff. Show more