diff --git a/.config/nextest.toml b/.config/nextest.toml index 9fd42ed9f3..809629453c 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -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 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 51a46be5a3..4bb487874e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -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 diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index f84ad336b5..c9535b1706 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -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 diff --git a/.gitignore b/.gitignore index 0e71c973d8..7f91efd6ac 100644 --- a/.gitignore +++ b/.gitignore @@ -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 diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index fea885a3a0..40f765acb9 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -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 `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 | | 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 | | 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, (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. diff --git a/Cargo.lock b/Cargo.lock index 5267f2df82..e728d98c8a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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" diff --git a/Cargo.toml b/Cargo.toml index eae34e8bee..e6c80d47e0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" } diff --git a/apps/photocraft-cli/src/lib.rs b/apps/photocraft-cli/src/lib.rs index 7e815db5d2..4c62f446ac 100644 --- a/apps/photocraft-cli/src/lib.rs +++ b/apps/photocraft-cli/src/lib.rs @@ -40,6 +40,16 @@ where T: Into, { let args: Vec = 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`, ` --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")); + } +} diff --git a/apps/photocraft/Cargo.toml b/apps/photocraft/Cargo.toml index f93f70752a..02445b1971 100644 --- a/apps/photocraft/Cargo.toml +++ b/apps/photocraft/Cargo.toml @@ -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] diff --git a/apps/photocraft/build.rs b/apps/photocraft/build.rs index 48ce637a52..a4bcba0756 100644 --- a/apps/photocraft/build.rs +++ b/apps/photocraft/build.rs @@ -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}"); diff --git a/apps/photocraft/src/app_dirs.rs b/apps/photocraft/src/app_dirs.rs index f1c20cfa6a..c70ef077ad 100644 --- a/apps/photocraft/src/app_dirs.rs +++ b/apps/photocraft/src/app_dirs.rs @@ -31,7 +31,10 @@ pub fn current() -> &'static DataDir { static DIR: OnceLock = 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}"); diff --git a/apps/photocraft/src/app_icon.rs b/apps/photocraft/src/app_icon.rs index 4fb8765e52..4dbe4f137d 100644 --- a/apps/photocraft/src/app_icon.rs +++ b/apps/photocraft/src/app_icon.rs @@ -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 ``, 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"); diff --git a/apps/photocraft/src/build_channel.rs b/apps/photocraft/src/build_channel.rs new file mode 100644 index 0000000000..8d0457f43e --- /dev/null +++ b/apps/photocraft/src/build_channel.rs @@ -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)); + } + } +} diff --git a/apps/photocraft/src/build_flavor.rs b/apps/photocraft/src/build_flavor.rs new file mode 100644 index 0000000000..b14e633370 --- /dev/null +++ b/apps/photocraft/src/build_flavor.rs @@ -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(&[])); + } +} diff --git a/apps/photocraft/src/launch_args.rs b/apps/photocraft/src/launch_args.rs index 83715f8918..e54f423d9c 100644 --- a/apps/photocraft/src/launch_args.rs +++ b/apps/photocraft/src/launch_args.rs @@ -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::::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 diff --git a/apps/photocraft/src/launch_profile.rs b/apps/photocraft/src/launch_profile.rs new file mode 100644 index 0000000000..00b80447e1 --- /dev/null +++ b/apps/photocraft/src/launch_profile.rs @@ -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, +} + +static PROFILE: OnceLock = 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) -> Result { + 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, compatibility_retry: bool) -> Result { + 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) -> Result { + 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, exe: Option<&Path>) -> Result { + 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 { + 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 { + 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()); + } +} diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index c6ec5f2c2a..d40f24a9ce 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -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), 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, +) -> Result<(photocraft_automation::workspace::AuthorizedWorkspace, Option), 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, 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, ) -> std::ops::ControlFlow<(), Option> { 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> { + // 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::>()) { + 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::>()) + { 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 diff --git a/apps/photocraft/src/nightly_session.rs b/apps/photocraft/src/nightly_session.rs new file mode 100644 index 0000000000..1c1c9eb6a8 --- /dev/null +++ b/apps/photocraft/src/nightly_session.rs @@ -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, + previous_unclean: bool, +} + +fn regular_or_missing(path: &Path) -> io::Result { + 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, 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> { + 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::>(); + 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(); + } + } +} diff --git a/apps/photocraft/src/process_identity.rs b/apps/photocraft/src/process_identity.rs new file mode 100644 index 0000000000..ba8c063161 --- /dev/null +++ b/apps/photocraft/src/process_identity.rs @@ -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> = 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()); + } +} diff --git a/apps/photocraft/src/profile_root.rs b/apps/photocraft/src/profile_root.rs new file mode 100644 index 0000000000..8e515c65d9 --- /dev/null +++ b/apps/photocraft/src/profile_root.rs @@ -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 { + 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 { + 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, key: &str) -> Result { + 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, key: &str, fallback: &str) -> Result { + 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 { + 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::>() + }; + let (a, b) = (parts(a), parts(b)); + a.starts_with(&b) || b.starts_with(&a) +} + +fn installation_boundary(platform: Platform, exe: &Path) -> Result { + 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, exe: &Path) -> Result, 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::, _>>()?; + // 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::, _>>()?; + 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 { + private_subdirectory(root, "AgentFiles", "default agent folder") +} + +fn private_subdirectory(root: &Path, name: impl AsRef, label: &str) -> Result { + 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, + exe: Option<&Path>, + stable_agent: Option<&Path>, + writable: impl FnOnce(&Path) -> std::io::Result<()>, +) -> Result { + validate_for(Platform::current()?, root, env, exe, stable_agent, writable) +} + +fn validate_for( + platform: Platform, + root: &Path, + env: impl Fn(&str) -> Option, + exe: Option<&Path>, + stable_agent: Option<&Path>, + writable: impl FnOnce(&Path) -> std::io::Result<()>, +) -> Result { + 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, + 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 { + self.env.get(key).cloned() + } + + fn check(&self, platform: Platform, root: &Path) -> Result { + 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"); + } +} diff --git a/assets/app-icon/README.md b/assets/app-icon/README.md index b229aadee4..66c6370b68 100644 --- a/assets/app-icon/README.md +++ b/assets/app-icon/README.md @@ -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. diff --git a/assets/app-icon/nightly-provenance.json b/assets/app-icon/nightly-provenance.json new file mode 100644 index 0000000000..d44682abe0 --- /dev/null +++ b/assets/app-icon/nightly-provenance.json @@ -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." +} diff --git a/assets/app-icon/photocraft-nightly-1024.png b/assets/app-icon/photocraft-nightly-1024.png new file mode 100644 index 0000000000..7d061a7f95 Binary files /dev/null and b/assets/app-icon/photocraft-nightly-1024.png differ diff --git a/assets/app-icon/photocraft-nightly.icns b/assets/app-icon/photocraft-nightly.icns new file mode 100644 index 0000000000..4e567c14a0 Binary files /dev/null and b/assets/app-icon/photocraft-nightly.icns differ diff --git a/assets/app-icon/photocraft-nightly.ico b/assets/app-icon/photocraft-nightly.ico new file mode 100644 index 0000000000..cb81b19133 Binary files /dev/null and b/assets/app-icon/photocraft-nightly.ico differ diff --git a/assets/app-icon/photocraft-nightly.png b/assets/app-icon/photocraft-nightly.png new file mode 100644 index 0000000000..c4eb18dd80 Binary files /dev/null and b/assets/app-icon/photocraft-nightly.png differ diff --git a/crates/compose/proptest-regressions/cmyk/tests.txt b/crates/compose/proptest-regressions/cmyk/tests.txt new file mode 100644 index 0000000000..98770e5156 --- /dev/null +++ b/crates/compose/proptest-regressions/cmyk/tests.txt @@ -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 }] } diff --git a/crates/compose/src/adjust.rs b/crates/compose/src/adjust.rs index 640c0648da..453446642c 100644 --- a/crates/compose/src/adjust.rs +++ b/crates/compose/src/adjust.rs @@ -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)] diff --git a/crates/compose/src/adjust/channels.rs b/crates/compose/src/adjust/channels.rs index 87ed60eb03..820c4b9543 100644 --- a/crates/compose/src/adjust/channels.rs +++ b/crates/compose/src/adjust/channels.rs @@ -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 mix_inks(rows, *monochrome, ch), _ => {} } } diff --git a/crates/compose/src/adjust/curves_channel_composite_tests.rs b/crates/compose/src/adjust/curves_channel_composite_tests.rs new file mode 100644 index 0000000000..6bca632301 --- /dev/null +++ b/crates/compose/src/adjust/curves_channel_composite_tests.rs @@ -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 { + 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 = (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 { 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 { 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"); +} diff --git a/crates/compose/src/adjust/tone.rs b/crates/compose/src/adjust/tone.rs index 5c57608e02..60d52f3a1a 100644 --- a/crates/compose/src/adjust/tone.rs +++ b/crates/compose/src/adjust/tone.rs @@ -38,6 +38,12 @@ pub fn tone_luts(adj: &Adjustment) -> [Vec; 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) -> [Vec; 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, curve_levels: bool) -> [Vec; 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) -> [Vec; 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::(&[]) } else { curve_samples_mode::(master, *pencil) }; + let row = |c: &[CurvePoint], level: Option| match level { + Some(q) => { + let channel = curve_samples_mode::(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) -> [Vec; 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) -> [Vec; 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, curve_levels: bool) -> [Vec; 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 { + 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 { /// 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 { + curve_map_samples::(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(points: &[CurvePoint], pencil: bool) -> Vec { + if pencil { curve_map_samples::(points) } else { curve_samples::(points) } +} + +/// [`curve_map_lut`] sampled at `N` evenly spaced inputs including both end points. +fn curve_map_samples(points: &[CurvePoint]) -> Vec { 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 { diff --git a/crates/compose/src/adjust/tone_tests.rs b/crates/compose/src/adjust/tone_tests.rs index 32913c62ad..d189f95a01 100644 --- a/crates/compose/src/adjust/tone_tests.rs +++ b/crates/compose/src/adjust/tone_tests.rs @@ -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]; diff --git a/crates/compose/src/cmyk_split.rs b/crates/compose/src/cmyk_split.rs index 39040c7e94..f3bf9065cb 100644 --- a/crates/compose/src/cmyk_split.rs +++ b/crates/compose/src/cmyk_split.rs @@ -316,8 +316,8 @@ fn combine(cmy: &Buffer, k: &Buffer) -> CmykBuffer { pub(super) fn render_bands(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(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) } diff --git a/crates/compose/src/ctx.rs b/crates/compose/src/ctx.rs index 6fe541678d..cada57212f 100644 --- a/crates/compose/src/ctx.rs +++ b/crates/compose/src/ctx.rs @@ -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); } diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rs index d5d1d31aea..7053158613 100644 --- a/crates/compose/src/effects.rs +++ b/crates/compose/src/effects.rs @@ -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)] diff --git a/crates/compose/src/effects/inner_shadow_anti_alias_tests.rs b/crates/compose/src/effects/inner_shadow_anti_alias_tests.rs index 1b3f97315d..97831c75ba 100644 --- a/crates/compose/src/effects/inner_shadow_anti_alias_tests.rs +++ b/crates/compose/src/effects/inner_shadow_anti_alias_tests.rs @@ -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 diff --git a/crates/compose/src/effects/inner_shadow_size_one_tests.rs b/crates/compose/src/effects/inner_shadow_size_one_tests.rs new file mode 100644 index 0000000000..cbc479da9d --- /dev/null +++ b/crates/compose/src/effects/inner_shadow_size_one_tests.rs @@ -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; 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 = (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 = (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 = (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 = (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:?}"); +} diff --git a/crates/compose/src/effects/outer_glow_range_one_tests.rs b/crates/compose/src/effects/outer_glow_range_one_tests.rs new file mode 100644 index 0000000000..e022fe501f --- /dev/null +++ b/crates/compose/src/effects/outer_glow_range_one_tests.rs @@ -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 %"); +} diff --git a/crates/compose/src/effects/paint.rs b/crates/compose/src/effects/paint.rs index a1783051da..194964f358 100644 --- a/crates/compose/src/effects/paint.rs +++ b/crates/compose/src/effects/paint.rs @@ -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> { + 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 { diff --git a/crates/compose/src/native.rs b/crates/compose/src/native.rs index b5e05e49c6..20e256d9b4 100644 --- a/crates/compose/src/native.rs +++ b/crates/compose/src/native.rs @@ -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; 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> { 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); diff --git a/crates/compose/src/render.rs b/crates/compose/src/render.rs index a31e227a3d..ba7b9b45cb 100644 --- a/crates/compose/src/render.rs +++ b/crates/compose/src/render.rs @@ -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(), }, diff --git a/crates/doc/src/adjust.rs b/crates/doc/src/adjust.rs index fc8d78a611..94e2632c1c 100644 --- a/crates/doc/src/adjust.rs +++ b/crates/doc/src/adjust.rs @@ -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 { diff --git a/crates/engine-core/Cargo.toml b/crates/engine-core/Cargo.toml index 092dbf35b6..e91fa8af21 100644 --- a/crates/engine-core/Cargo.toml +++ b/crates/engine-core/Cargo.toml @@ -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 } diff --git a/crates/engine-core/src/adjust_params.rs b/crates/engine-core/src/adjust_params.rs index 0823835d93..930d47c3f8 100644 --- a/crates/engine-core/src/adjust_params.rs +++ b/crates/engine-core/src/adjust_params.rs @@ -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(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 { + 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 { let (h, s, l, c, mut ranges) = match base { Some(Adjustment::HueSaturation { hue, saturation, lightness, colorize, ranges }) => (*hue, *saturation, *lightness, *colorize, ranges.clone()), diff --git a/crates/engine-core/src/adjust_params/tests.rs b/crates/engine-core/src/adjust_params/tests.rs index 61a7ffa99f..2da18f4403 100644 --- a/crates/engine-core/src/adjust_params/tests.rs +++ b/crates/engine-core/src/adjust_params/tests.rs @@ -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})), diff --git a/crates/engine-core/src/cmd.rs b/crates/engine-core/src/cmd.rs index 6b4d0a3d58..11ddbae034 100644 --- a/crates/engine-core/src/cmd.rs +++ b/crates/engine-core/src/cmd.rs @@ -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; diff --git a/crates/engine-core/src/cmd/adjustment_brush_cmds_tests.rs b/crates/engine-core/src/cmd/adjustment_brush_cmds_tests.rs index f1cf749ba4..fbdbc493ae 100644 --- a/crates/engine-core/src/cmd/adjustment_brush_cmds_tests.rs +++ b/crates/engine-core/src/cmd/adjustment_brush_cmds_tests.rs @@ -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:?}"); diff --git a/crates/engine-core/src/cmd/color_cmds.rs b/crates/engine-core/src/cmd/color_cmds.rs index c875bfb8e5..1ec4f68b6d 100644 --- a/crates/engine-core/src/cmd/color_cmds.rs +++ b/crates/engine-core/src/cmd/color_cmds.rs @@ -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 { + 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 { + 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) -> Result> { match spec { @@ -1265,6 +1429,32 @@ fn color_settings(s: &mut Session, p: &Value) -> Result { 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 { .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 { 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 { "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::*; diff --git a/crates/engine-core/src/cmd/color_cmds/convert_profile_fogra39_tests.rs b/crates/engine-core/src/cmd/color_cmds/convert_profile_fogra39_tests.rs new file mode 100644 index 0000000000..8526609945 --- /dev/null +++ b/crates/engine-core/src/cmd/color_cmds/convert_profile_fogra39_tests.rs @@ -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:?}"); +} diff --git a/crates/engine-core/src/cmd/edit_menu_cmds.rs b/crates/engine-core/src/cmd/edit_menu_cmds.rs index 652c2fd857..0886fdfdc8 100644 --- a/crates/engine-core/src/cmd/edit_menu_cmds.rs +++ b/crates/engine-core/src/cmd/edit_menu_cmds.rs @@ -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 { ["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!( diff --git a/crates/engine-core/src/cmd/edit_menu_cmds/find_replace.rs b/crates/engine-core/src/cmd/edit_menu_cmds/find_replace.rs index 55cb540344..df8c3a38fb 100644 --- a/crates/engine-core/src/cmd/edit_menu_cmds/find_replace.rs +++ b/crates/engine-core/src/cmd/edit_menu_cmds/find_replace.rs @@ -55,9 +55,15 @@ fn start_index(doc: &Document, layers: &[LayerId], active: Option) -> 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 { @@ -198,3 +204,7 @@ pub(super) fn find_replace(s: &mut Session, p: &Value) -> Result { other => Err(bad(cmd, format!("unknown action `{other}` (find|change|changeFind|changeAll)"))), } } + +#[cfg(test)] +#[path = "find_replace_enabled_tests.rs"] +mod enabled_tests; diff --git a/crates/engine-core/src/cmd/edit_menu_cmds/find_replace_enabled_tests.rs b/crates/engine-core/src/cmd/edit_menu_cmds/find_replace_enabled_tests.rs new file mode 100644 index 0000000000..f4dd49e7de --- /dev/null +++ b/crates/engine-core/src/cmd/edit_menu_cmds/find_replace_enabled_tests.rs @@ -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})); +} diff --git a/crates/engine-core/src/cmd/edit_menu_cmds/tests.rs b/crates/engine-core/src/cmd/edit_menu_cmds/tests.rs index d2a9a2dd3b..f6c2f342e5 100644 --- a/crates/engine-core/src/cmd/edit_menu_cmds/tests.rs +++ b/crates/engine-core/src/cmd/edit_menu_cmds/tests.rs @@ -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(); diff --git a/crates/engine-core/src/cmd/file_cmds/image_processor_empty_source_tests.rs b/crates/engine-core/src/cmd/file_cmds/image_processor_empty_source_tests.rs new file mode 100644 index 0000000000..dc261d89a6 --- /dev/null +++ b/crates/engine-core/src/cmd/file_cmds/image_processor_empty_source_tests.rs @@ -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 = 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 = 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"); +} diff --git a/crates/engine-core/src/cmd/file_cmds/processing.rs b/crates/engine-core/src/cmd/file_cmds/processing.rs index 68d55fe0e9..6f8f9d2e79 100644 --- a/crates/engine-core/src/cmd/file_cmds/processing.rs +++ b/crates/engine-core/src/cmd/file_cmds/processing.rs @@ -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> { /// 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 { 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 { 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 { 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> { + 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(¶ms, 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, + process: &dyn Fn(&mut Session, &str) -> Result, +) -> Value { + process_tree(s, inputs, output, format, save, TreeNaming::Unique, &|scratch, out| { + opened.set(true); + process(scratch, out) + }) +} + +fn require_opened_source(opened: &Cell) -> Result<()> { + if opened.get() { Ok(()) } else { Err(EngineError::Other(IMAGE_PROCESSOR_NO_SOURCE.into())) } +} fn image_processor_param(message: impl Into) -> 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) -> Result { 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})) } diff --git a/crates/engine-core/src/cmd/layer_copy_cmds.rs b/crates/engine-core/src/cmd/layer_copy_cmds.rs index c08b055858..176518f937 100644 --- a/crates/engine-core/src/cmd/layer_copy_cmds.rs +++ b/crates/engine-core/src/cmd/layer_copy_cmds.rs @@ -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 = 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::>()}); if let [one] = new_ids.as_slice() && let Some(map) = out.as_object_mut() diff --git a/crates/engine-core/src/cmd/layer_duplicate_new_document_history_tests.rs b/crates/engine-core/src/cmd/layer_duplicate_new_document_history_tests.rs new file mode 100644 index 0000000000..ec2b183f58 --- /dev/null +++ b/crates/engine-core/src/cmd/layer_duplicate_new_document_history_tests.rs @@ -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()); +} diff --git a/crates/engine-core/src/cmd/mode_cmds.rs b/crates/engine-core/src/cmd/mode_cmds.rs index ab39dfc3a7..b7a5ba6377 100644 --- a/crates/engine-core/src/cmd/mode_cmds.rs +++ b/crates/engine-core/src/cmd/mode_cmds.rs @@ -89,7 +89,7 @@ pub(crate) fn rotate_arbitrary(s: &mut Session, p: &Value) -> Result { } /// [`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; diff --git a/crates/engine-core/src/cmd/mode_cmds/tests.rs b/crates/engine-core/src/cmd/mode_cmds/tests.rs index ace2013133..a4aed09e9b 100644 --- a/crates/engine-core/src/cmd/mode_cmds/tests.rs +++ b/crates/engine-core/src/cmd/mode_cmds/tests.rs @@ -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))); } diff --git a/crates/engine-core/src/cmd/rotate_canvas_tiny_angle_tests.rs b/crates/engine-core/src/cmd/rotate_canvas_tiny_angle_tests.rs new file mode 100644 index 0000000000..2e6edee103 --- /dev/null +++ b/crates/engine-core/src/cmd/rotate_canvas_tiny_angle_tests.rs @@ -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); +} diff --git a/crates/engine-core/src/cmd/table/image/adjustments.rs b/crates/engine-core/src/cmd/table/image/adjustments.rs index f6bd895d04..b04e5d90fa 100644 --- a/crates/engine-core/src/cmd/table/image/adjustments.rs +++ b/crates/engine-core/src/cmd/table/image/adjustments.rs @@ -43,7 +43,7 @@ pub fn specs() -> Vec { ( "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}"##), diff --git a/crates/engine-core/src/cmd/vector_cmds/line_tool_history_name_tests.rs b/crates/engine-core/src/cmd/vector_cmds/line_tool_history_name_tests.rs index fc299c2959..7d1ee6a348 100644 --- a/crates/engine-core/src/cmd/vector_cmds/line_tool_history_name_tests.rs +++ b/crates/engine-core/src/cmd/vector_cmds/line_tool_history_name_tests.rs @@ -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)); +} diff --git a/crates/engine-core/src/cmd/vector_cmds/shape.rs b/crates/engine-core/src/cmd/vector_cmds/shape.rs index 614a10ff89..9d59ac44c5 100644 --- a/crates/engine-core/src/cmd/vector_cmds/shape.rs +++ b/crates/engine-core/src/cmd/vector_cmds/shape.rs @@ -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 { 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 { 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 { diff --git a/crates/engine-core/src/color_settings_presets_tests.rs b/crates/engine-core/src/color_settings_presets_tests.rs new file mode 100644 index 0000000000..d1e652d1ab --- /dev/null +++ b/crates/engine-core/src/color_settings_presets_tests.rs @@ -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()); +} diff --git a/crates/engine-core/src/layer_style.rs b/crates/engine-core/src/layer_style.rs index e5f527f93b..252abc7076 100644 --- a/crates/engine-core/src/layer_style.rs +++ b/crates/engine-core/src/layer_style.rs @@ -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 { "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 { Ok(Value::Null) } +#[cfg(test)] +mod satin_defaults_tests; + #[cfg(test)] mod outer_glow_defaults_tests; diff --git a/crates/engine-core/src/layer_style/satin_defaults_tests.rs b/crates/engine-core/src/layer_style/satin_defaults_tests.rs new file mode 100644 index 0000000000..056c1a215c --- /dev/null +++ b/crates/engine-core/src/layer_style/satin_defaults_tests.rs @@ -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)); +} diff --git a/crates/engine-core/src/pixels.rs b/crates/engine-core/src/pixels.rs index ae27445174..db5b4189b9 100644 --- a/crates/engine-core/src/pixels.rs +++ b/crates/engine-core/src/pixels.rs @@ -227,7 +227,8 @@ fn adjusted_with_transfer( transfer: adjust::Transfer, ) -> Vec { 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; } } } diff --git a/crates/engine-core/src/pixels/tests.rs b/crates/engine-core/src/pixels/tests.rs index 0b3999fa56..8e89488696 100644 --- a/crates/engine-core/src/pixels/tests.rs +++ b/crates/engine-core/src/pixels/tests.rs @@ -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] diff --git a/crates/engine/tests/global_state/color_settings_presets.rs b/crates/engine/tests/global_state/color_settings_presets.rs new file mode 100644 index 0000000000..14bb9707c3 --- /dev/null +++ b/crates/engine/tests/global_state/color_settings_presets.rs @@ -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); +} diff --git a/crates/engine/tests/global_state/main.rs b/crates/engine/tests/global_state/main.rs index 4d78ec0606..4f3d3b7438 100644 --- a/crates/engine/tests/global_state/main.rs +++ b/crates/engine/tests/global_state/main.rs @@ -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; diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 23a137be9b..54d71c3f1d 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -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 }, #[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) -> Self { FormatError::Corrupt(msg.into()) @@ -86,7 +101,7 @@ impl From 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()), diff --git a/crates/format/src/store.rs b/crates/format/src/store.rs index f42e2d49b8..c1a353a3ab 100644 --- a/crates/format/src/store.rs +++ b/crates/format/src/store.rs @@ -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(); diff --git a/crates/format/tests/it/channel_mixer_cmyk.rs b/crates/format/tests/it/channel_mixer_cmyk.rs new file mode 100644 index 0000000000..cc79be3d0b --- /dev/null +++ b/crates/format/tests/it/channel_mixer_cmyk.rs @@ -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}"); +} diff --git a/crates/format/tests/it/corruption.rs b/crates/format/tests/it/corruption.rs index b31c83156a..fbbb7742c0 100644 --- a/crates/format/tests/it/corruption.rs +++ b/crates/format/tests/it/corruption.rs @@ -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| { diff --git a/crates/format/tests/it/main.rs b/crates/format/tests/it/main.rs index 8da62a3e54..351eb451d9 100644 --- a/crates/format/tests/it/main.rs +++ b/crates/format/tests/it/main.rs @@ -3,6 +3,7 @@ mod analysis; mod autosave; mod camera_raw_roundtrip; +mod channel_mixer_cmyk; mod common; mod corruption; mod directory_symlinks; diff --git a/crates/gpu/src/fx/builders.rs b/crates/gpu/src/fx/builders.rs index f1c18f975a..633382b8fe 100644 --- a/crates/gpu/src/fx/builders.rs +++ b/crates/gpu/src/fx/builders.rs @@ -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 } diff --git a/crates/gpu/src/fx/tests.rs b/crates/gpu/src/fx/tests.rs index af9ab806be..c57a079904 100644 --- a/crates/gpu/src/fx/tests.rs +++ b/crates/gpu/src/fx/tests.rs @@ -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::>() + }; + 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 diff --git a/crates/gpu/src/plan/lower.rs b/crates/gpu/src/plan/lower.rs index 9c9ab96856..29e9d8c657 100644 --- a/crates/gpu/src/plan/lower.rs +++ b/crates/gpu/src/plan/lower.rs @@ -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; diff --git a/crates/gpu/tests/it/parity.rs b/crates/gpu/tests/it/parity.rs index 02217478cb..3c75393aeb 100644 --- a/crates/gpu/tests/it/parity.rs +++ b/crates/gpu/tests/it/parity.rs @@ -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::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 }, diff --git a/crates/io/src/adjust_map.rs b/crates/io/src/adjust_map.rs index 7a91786fd1..75b5e209f3 100644 --- a/crates/io/src/adjust_map.rs +++ b/crates/io/src/adjust_map.rs @@ -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 { /// (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 { 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 { + 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, x: u16) { @@ -689,6 +734,44 @@ fn levels_write(v: &mut Vec, 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 { + 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)> { 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 } => { diff --git a/crates/io/src/adjust_map/encode.rs b/crates/io/src/adjust_map/encode.rs index 114da29f35..666065aab6 100644 --- a/crates/io/src/adjust_map/encode.rs +++ b/crates/io/src/adjust_map/encode.rs @@ -237,3 +237,16 @@ pub(super) fn channel_mixer(matrix: &[[f32; 4]; 3], monochrome: bool) -> Vec } 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 { + 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 +} diff --git a/crates/io/src/adjust_map/tests.rs b/crates/io/src/adjust_map/tests.rs index 455fb0e510..8415d9702c 100644 --- a/crates/io/src/adjust_map/tests.rs +++ b/crates/io/src/adjust_map/tests.rs @@ -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::(|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 { VersionedDescriptor::new(d).to_bytes() } diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index 5302f68a5d..5a06cf25b1 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -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)>, regenerated: &mut Vec<([u8; 4], Vec)>) { + 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 { diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs index cfde287306..aaf59c0685 100644 --- a/crates/io/src/psd_import.rs +++ b/crates/io/src/psd_import.rs @@ -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 diff --git a/crates/io/tests/it/adjust_blend_roundtrip.rs b/crates/io/tests/it/adjust_blend_roundtrip.rs index 1b3606d254..95e2c1fa1f 100644 --- a/crates/io/tests/it/adjust_blend_roundtrip.rs +++ b/crates/io/tests/it/adjust_blend_roundtrip.rs @@ -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 { diff --git a/crates/io/tests/it/cmyk_channel_mixer.rs b/crates/io/tests/it/cmyk_channel_mixer.rs new file mode 100644 index 0000000000..c2a476c837 --- /dev/null +++ b/crates/io/tests/it/cmyk_channel_mixer.rs @@ -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 { + 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> { + 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 { + 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 { + 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"); + } + } +} diff --git a/crates/io/tests/it/common/mod.rs b/crates/io/tests/it/common/mod.rs index 093c7985b1..ccda061c63 100644 --- a/crates/io/tests/it/common/mod.rs +++ b/crates/io/tests/it/common/mod.rs @@ -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 }); diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 9b6239fa37..ffaf2972a0 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -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; diff --git a/crates/ipp/Cargo.toml b/crates/ipp/Cargo.toml index 5b1ada5db5..bd5993a6bc 100644 --- a/crates/ipp/Cargo.toml +++ b/crates/ipp/Cargo.toml @@ -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 diff --git a/crates/text/src/fonts.rs b/crates/text/src/fonts.rs index c443df1d9d..458c8769bf 100644 --- a/crates/text/src/fonts.rs +++ b/crates/text/src/fonts.rs @@ -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, + /// 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, + /// 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, } 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) { + 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::() 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::() 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 { + self.installed_update_in(installed_catalog()) + } + + #[cfg(not(target_arch = "wasm32"))] + fn installed_update_in(&self, catalog: &Catalog) -> Option { + 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> = (!changes.full).then(|| changes.added.iter().chain(&changes.changed).map(|f| f.to_lowercase()).collect()); + let added: HashSet = 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::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 { - 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, seen: &mut HashSet) -> Vec { 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::>(); + 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")); diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index e2ef8d367e..e91a63dc85 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -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 } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 47cf6e3885..bcf7d61c5c 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -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); } diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index a6e4829878..073ee8b992 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -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()); + } +} diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index f96e15d422..0b0524829a 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -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); diff --git a/crates/ui-egui/src/app/framework.rs b/crates/ui-egui/src/app/framework.rs index 1adbb3c532..ec118f1545 100644 --- a/crates/ui-egui/src/app/framework.rs +++ b/crates/ui-egui/src/app/framework.rs @@ -50,7 +50,7 @@ pub(crate) fn install(ctx: &egui::Context, fonts: &UiFonts<'_>, frame: Option, } @@ -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; diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu/pen_anchor_row_tests.rs b/crates/ui-egui/src/canvas/canvas_tool_menu/pen_anchor_row_tests.rs new file mode 100644 index 0000000000..98da28d1de --- /dev/null +++ b/crates/ui-egui/src/canvas/canvas_tool_menu/pen_anchor_row_tests.rs @@ -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 { + 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> { + 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>, 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"); +} diff --git a/crates/ui-egui/src/channel_titles.rs b/crates/ui-egui/src/channel_titles.rs new file mode 100644 index 0000000000..7d255db5fb --- /dev/null +++ b/crates/ui-egui/src/channel_titles.rs @@ -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")); + } +} diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index c918adc87f..12ef75dc3a 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -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"})); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 46a359792d..4b262ed4f7 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -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 diff --git a/crates/ui-egui/src/dialogs/adjust_dialog.rs b/crates/ui-egui/src/dialogs/adjust_dialog.rs index f6034e670b..a83ecc39be 100644 --- a/crates/ui-egui/src/dialogs/adjust_dialog.rs +++ b/crates/ui-egui/src/dialogs/adjust_dialog.rs @@ -372,7 +372,7 @@ fn last_confirmed(app: &PhotocraftApp, kind: &str) -> Option { /// Opens the dialog for `command` at the kind's neutral settings, except the [`KEEPS_LAST`] ones, /// which keep their last confirmed value. pub fn open(app: &mut PhotocraftApp, command: &str) -> Result { - let id = open_neutral(app, command).ok_or_else(|| refusal(app, command))?; + let id = open_with_params_checked(app, command, &json!({})).map_err(|reason| reason.unwrap_or_else(|| refusal(app, command)))?; let kind = command.strip_prefix(PREFIX).unwrap_or_default(); let last = last_confirmed(app, kind); let kept: Map = KEEPS_LAST @@ -389,11 +389,16 @@ pub fn open(app: &mut PhotocraftApp, command: &str) -> Result Ok(id) } -/// Why `command` has no dialog to open: no document, or no adjustment of that name. +/// Why `command` has no dialog to open when the editor gave no reason of its own: no document, or no adjustment of +/// that name. fn refusal(app: &PhotocraftApp, command: &str) -> String { if app.session.active().is_none() { "no document".to_string() } else { format!("{command} has no dialog") } } +/// Why a dialog did not open: `Some` is the editor's refusal of these parameters, to show the user (a CMYK Channel +/// Mixer, #8047); `None` means there is no dialog for them. +pub(crate) type Refused = Option; + /// Opens a neutral adjustment dialog using the current edit target. pub fn open_neutral(app: &mut PhotocraftApp, command: &str) -> Option { open_with_params(app, command, &json!({})) @@ -402,7 +407,12 @@ pub fn open_neutral(app: &mut PhotocraftApp, command: &str) -> Option /// Seed an Action's dialog only after resolving its recorded target, so document-space /// defaults cannot overwrite the target's neutral grayscale values. pub(crate) fn open_with_params(app: &mut PhotocraftApp, command: &str, params: &Value) -> Option { - let params = if params.is_null() { json!({}) } else { Value::Object(params.as_object()?.clone()) }; + open_with_params_checked(app, command, params).ok() +} + +/// [`open_with_params`], with the reason it did not open. +pub(crate) fn open_with_params_checked(app: &mut PhotocraftApp, command: &str, params: &Value) -> Result { + let params = if params.is_null() { json!({}) } else { Value::Object(params.as_object().ok_or(None)?.clone()) }; let params = complete_params(app, command, ¶ms).unwrap_or(params); let mut params = app.with_mask_target(command, params); if params.get("target").is_none() @@ -414,13 +424,20 @@ pub(crate) fn open_with_params(app: &mut PhotocraftApp, command: &str, params: & open_hosted(app, command, params, None, None) } -/// Reopen a captured Smart Filter with document-colour defaults, independent of channel targeting. -/// Only the caller's validated snapshot may supply the Smart Filter target. +/// [`open_smart_filter_checked`] without the reason (the tests' form). +#[cfg(test)] pub(crate) fn open_smart_filter(app: &mut PhotocraftApp, command: &str, params: &Value, target: Value) -> Option { + open_smart_filter_checked(app, command, params, target).ok() +} + +/// Reopen a captured Smart Filter with document-colour defaults, independent of channel targeting. +/// Only the caller's validated snapshot may supply the Smart Filter target. When it does not open, the reason: the +/// Layers panel shows an editor's refusal (#8047). +pub(crate) fn open_smart_filter_checked(app: &mut PhotocraftApp, command: &str, params: &Value, target: Value) -> Result { let completed = complete_params(app, command, params); let mut recorded = completed.as_ref().unwrap_or(params).as_object().cloned().unwrap_or_default(); recorded.retain(|key, _| !key.starts_with("__")); - let index = target.get("index").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok())?; + let index = target.get("index").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()).ok_or(None)?; open_hosted(app, command, Value::Object(recorded), Some((index, target)), Some(params.clone())) } @@ -439,12 +456,12 @@ struct Seeded { /// `colors` row kept. With `normalized` (a Smart Filter edit: the captured parameters) those then replace the parameters /// through the engine's own reading of them, so a Lab `lightness` default cannot be read over recorded `points`. An /// unresolved Levels/Curves target opens with defaults and seeds again in [`take`] once it resolves. -fn seed(app: &PhotocraftApp, kind: &str, recorded: &Value, smart: Option<&(usize, Value)>, normalized: Option<&Value>) -> Option { +fn seed(app: &PhotocraftApp, kind: &str, recorded: &Value, smart: Option<&(usize, Value)>, normalized: Option<&Value>) -> Result { let resolved = target_context(app, smart, recorded); let valid_target = !matches!(kind, "levels" | "curves") || resolved.is_ok(); let target = resolved.unwrap_or_else(|_| ToneTarget { layer: app.session.active().and_then(|s| s.active_layer), channel: None }); let mode = curve_mode(app, kind, &target); - let defaults = if valid_target { Some(photocraft_engine::adjust_params::default_for(kind, mode).ok()?) } else { None }; + let defaults = if valid_target { Some(photocraft_engine::adjust_params::default_for(kind, mode).map_err(|_| None)?) } else { None }; let tone_kind = matches!(kind, "levels" | "curves"); let gray_target = tone_kind && target.channel.as_ref().is_some_and(|c| c.gray.is_some()); let color_set = if tone_kind { target.channel.as_ref().and_then(|c| c.components) } else { None }; @@ -502,8 +519,19 @@ fn seed(app: &PhotocraftApp, kind: &str, recorded: &Value, smart: Option<&(usize } let base = Value::Object(params); let cx = value_cx(mode, target.channel.clone(), base.clone()); - let value = values::from_params(kind, &base, &cx).or_else(|_| values::from_params(kind, &Value::Object(defaults_only), &cx)).unwrap_or_default(); - Some(Seeded { value, cx, target, mode, unresolved: !valid_target }) + // A CMYK Channel Mixer has no framework editor yet (#8047): no dialog, rather than RGB sliders over its inks. Checked + // before the defaults fallback too, which in an RGB or Lab document reads (RGB defaults) and would open the RGB + // editor over a Smart Filter's ink keys. + let value = match values::from_params(kind, &base, &cx) { + Err(err) if err == values::CMYK_MIXER_UNAVAILABLE => return Err(Some(err)), + read => read.or_else(|_| values::from_params(kind, &Value::Object(defaults_only), &cx)), + }; + let value = match value { + Ok(value) => value, + Err(err) if err == values::CMYK_MIXER_UNAVAILABLE => return Err(Some(err)), + Err(_) => AdjustValue::default(), + }; + Ok(Seeded { value, cx, target, mode, unresolved: !valid_target }) } /// Whether the kind's editor shows a histogram. @@ -593,9 +621,9 @@ fn reset_target(kind: String) -> impl Fn(&DialogValue, &DialogValue) -> DialogVa } /// Opens the dialog for `command` over `recorded` parameters (and a captured Smart Filter's `smart` index and target). -fn open_hosted(app: &mut PhotocraftApp, command: &str, recorded: Value, smart: Option<(usize, Value)>, normalized: Option) -> Option { - let kind = command.strip_prefix(PREFIX).filter(|k| adjust_editors::has_editor(k))?.to_owned(); - let spec = photocraft_engine::commands::find(command)?; +fn open_hosted(app: &mut PhotocraftApp, command: &str, recorded: Value, smart: Option<(usize, Value)>, normalized: Option) -> Result { + let kind = command.strip_prefix(PREFIX).filter(|k| adjust_editors::has_editor(k)).ok_or(None)?.to_owned(); + let spec = photocraft_engine::commands::find(command).ok_or(None)?; let seeded = seed(app, &kind, &recorded, smart.as_ref(), normalized.as_ref())?; // A dialog this one replaces on the host ends its Actions step with it. if let Some(previous) = app.adjust_open.take() @@ -639,14 +667,14 @@ fn open_hosted(app: &mut PhotocraftApp, command: &str, recorded: Value, smart: O recorded, normalized, }); - Some(id) + Ok(id) } /// Opens the dialog for `command` at the settings last confirmed in it (Photoshop's ⌥ plus the /// adjustment's shortcut, ⌥⌘L / ⌥⌘M, #8900), or at the neutral ones when there are none or they /// don't fit the current colour mode. pub fn open_last(app: &mut PhotocraftApp, command: &str) -> Result { - let id = open_neutral(app, command).ok_or_else(|| refusal(app, command))?; + let id = open_with_params_checked(app, command, &json!({})).map_err(|reason| reason.unwrap_or_else(|| refusal(app, command)))?; let kind = command.strip_prefix(PREFIX).unwrap_or_default(); let Some(open) = app.adjust_open.as_ref().filter(|open| open.id == id) else { return Ok(id) }; if matches!(kind, "levels" | "curves") && open.unresolved { @@ -802,7 +830,7 @@ fn follow_target(app: &mut PhotocraftApp, id: DialogId) { if resolved.is_err() { return; } - let Some(seeded) = seed(app, &open.kind, &open.recorded, open.smart_filter.as_ref(), open.normalized.as_ref()) else { return }; + let Ok(seeded) = seed(app, &open.kind, &open.recorded, open.smart_filter.as_ref(), open.normalized.as_ref()) else { return }; let kind = open.kind.clone(); let setup = build_setup(app, &kind, &seeded.target, seeded.mode, false); let Some(open) = app.adjust_open.as_mut() else { return }; diff --git a/crates/ui-egui/src/dialogs/adjust_editors.rs b/crates/ui-egui/src/dialogs/adjust_editors.rs index 59e59af12a..b1a687f321 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors.rs @@ -218,13 +218,20 @@ fn lifted(events: EditEvents, wrap: impl Fn(T) -> AdjustValue) -> AdjustOu AdjustOut { ask: None, edit: events.map(wrap) } } +fn reset_legacy_toggle(value: BrightnessContrast, previous_legacy: bool, reset: bool) -> BrightnessContrast { + if reset && value.legacy != previous_legacy { BrightnessContrast::new(0.0, 0.0, value.legacy) } else { value } +} + /// Shows the editor of `kind` over `value` for one pass. fn show(kind: &str, setup: &EditorSetup, ui: &mut Ui, value: &mut AdjustValue, cx: &mut AdjustDialogCx<'_>) -> AdjustOut { let context = cx.context; match (kind, value) { ("brightnessContrast", AdjustValue::BrightnessContrast { value }) => { - let out = BrightnessContrastEditor::new("Brightness/Contrast", Bind::bound(value)).context(context).show(ui); - lifted(out.events, |value| AdjustValue::BrightnessContrast { value }) + let legacy = value.legacy; + let out = BrightnessContrastEditor::new("Brightness/Contrast", Bind::bound(&mut *value)).context(context).show(ui); + let reset = context.is_dialog(); + *value = reset_legacy_toggle(*value, legacy, reset); + lifted(out.events.map(|value| reset_legacy_toggle(value, legacy, reset)), |value| AdjustValue::BrightnessContrast { value }) } ("levels", AdjustValue::Levels { levels }) => { let mut panel = LevelsPanel::new("Levels", Bind::bound(levels), setup.channels.clone()) @@ -483,6 +490,19 @@ mod tests { assert!(answer_color(&mut map, &format!("{GRADIENT_STOP_KEY}1"), Srgba::rgb(0.0, 1.0, 0.0))); assert!(!answer_color(&mut map, &format!("{GRADIENT_STOP_KEY}9"), Srgba::BLACK), "no such stop"); } + + /// Toggling Use Legacy in the Brightness/Contrast dialog starts both sliders over at 0 in the + /// new mode; an edit that keeps the mode, and the Properties panel (no reset), keep the values. + #[test] + fn toggling_use_legacy_in_the_dialog_resets_brightness_and_contrast() { + for legacy in [false, true] { + let toggled = BrightnessContrast::new(40.0, -80.0, !legacy); + assert_eq!(reset_legacy_toggle(toggled, legacy, true), BrightnessContrast::new(0.0, 0.0, !legacy)); + assert_eq!(reset_legacy_toggle(toggled, legacy, false), toggled, "the Properties panel keeps its values"); + let kept = BrightnessContrast::new(40.0, -80.0, legacy); + assert_eq!(reset_legacy_toggle(kept, legacy, true), kept, "an edit in the same mode is kept"); + } + } } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/adjust_editors/session.rs b/crates/ui-egui/src/dialogs/adjust_editors/session.rs index 9497cb8cbd..2c0b85ca45 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/session.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/session.rs @@ -158,6 +158,12 @@ pub fn layer_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj let vcx = value_cx(mode, &committed_params); let committed = match values::from_params(kind, &committed_params, &vcx) { Ok(value) => value, + // A CMYK Channel Mixer has no framework editor yet (#8047): say so in the panel, like an unsupported adjustment + // above, rather than in the status bar on every frame the layer is shown. The layer is kept as it is. + Err(err) if err == values::CMYK_MIXER_UNAVAILABLE => { + ui.label(egui::RichText::new(tl!(values::CMYK_MIXER_UNAVAILABLE)).color(t.text_faint)); + return; + } Err(err) => { app.ui.status = err; return; diff --git a/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs b/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs index a37518b779..fa23887d65 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs @@ -155,6 +155,13 @@ fn every_adjustment_layer_edits_through_properties() { assert_eq!(h.state().session.active().unwrap().doc.layers.len(), 2, "{kind} {mode}: the background and this kind's layer"); let (_, before) = layer(&h); let steps = history_len(&h); + if kind == "channelMixer" && mode == "cmyk" { + // No framework editor for ink outputs yet (#8047): `cmyk_channel_mixer_is_kept_out_of_the_rgb_editor`. + let why = crate::adjust_editors::values::CMYK_MIXER_UNAVAILABLE; + assert!(label_rect(&h, why).is_some(), "{kind} {mode}: the Properties panel says why"); + assert_ne!(h.state().ui.status, why, "{kind} {mode}: not in the status bar"); + continue; + } let slider = sliders(&h).first().copied(); if SLIDER_KINDS.contains(&kind) { let r = slider.unwrap_or_else(|| panic!("{kind} {mode}: no slider in the Properties editor")); @@ -174,6 +181,49 @@ fn every_adjustment_layer_edits_through_properties() { } } +/// #8047: the framework Channel Mixer editor has red, green and blue outputs only, so a CMYK +/// document's mixer (cyan, magenta, yellow and black outputs) is not opened in it. The Properties +/// panel says why and edits nothing, the Image › Adjustments dialog refuses with the same reason, +/// and the layer keeps its ink rows. RGB mixers still open. +#[test] +fn cmyk_channel_mixer_is_kept_out_of_the_rgb_editor() { + use crate::adjust_editors::values::{self, CMYK_MIXER_UNAVAILABLE, ValueCx}; + use photocraft_doc::ColorMode; + use photocraft_engine::adjust_params; + + // The conversion refuses ink outputs: a CMYK mixer, an imported monochrome one, a CMYK document's defaults. + let ink = adjust_params::to_params(&adjust_params::default_for("channelMixer", ColorMode::Cmyk).unwrap()); + let mut mono = ink.clone(); + mono["monochrome"] = json!(true); + mono["gray"] = json!([30, 30, 30, 100, 0]); + for params in [&ink, &mono, &json!({})] { + let read = values::from_params("channelMixer", params, &ValueCx::new(ColorMode::Cmyk, params.clone())); + assert_eq!(read.err().as_deref(), Some(CMYK_MIXER_UNAVAILABLE), "{params}"); + } + let rgb = json!({"red": [50, 50, 0, 0]}); + let read = values::from_params("channelMixer", &rgb, &ValueCx::new(ColorMode::Rgb, rgb.clone())); + assert!(matches!(read, Ok(crate::adjust_editors::AdjustValue::ChannelMixer { .. })), "RGB mixers read: {read:?}"); + + // A CMYK document: the Properties panel shows no editor but a faint label saying why (not the status bar, which + // it would overwrite on every frame), the dialog refuses with the same reason, the mixer is unchanged. + let mut h = app_harness("channelMixer", "cmyk", 8); + let (_, before) = layer(&h); + assert!(matches!(&before, Adjustment::ChannelMixer { cmyk: Some(_), .. }), "{before:?}"); + let steps = history_len(&h); + h.run_steps(4); + assert!(label_rect(&h, CMYK_MIXER_UNAVAILABLE).is_some(), "the Properties panel says why"); + assert_ne!(h.state().ui.status, CMYK_MIXER_UNAVAILABLE, "the status bar is left alone"); + let err = crate::adjust_dialog::open(h.state_mut(), "image.adjustments.channelMixer").unwrap_err(); + assert_eq!(err, CMYK_MIXER_UNAVAILABLE); + h.run_steps(4); + assert_eq!(layer(&h).1, before, "the mixer is kept as it is"); + assert_eq!(history_len(&h), steps, "nothing was edited"); + + // An RGB document's mixer still opens in the dialog. + let mut h = app_harness("channelMixer", "rgb", 8); + assert!(crate::adjust_dialog::open(h.state_mut(), "image.adjustments.channelMixer").is_ok(), "RGB mixers open"); +} + /// #3264: wheel browsing previews without recording one edit per selected LUT. #[test] fn color_lookup_picker_cycles_luts_with_the_mouse_wheel() { diff --git a/crates/ui-egui/src/dialogs/adjust_editors/values.rs b/crates/ui-egui/src/dialogs/adjust_editors/values.rs index 6bc265b5e1..f8a0e12e62 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/values.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/values.rs @@ -242,6 +242,10 @@ fn object(base: &Value) -> Map { // --------------------------------------------------------------------------------------------- // Params -> value +/// Why [`from_params`] refuses a CMYK document's Channel Mixer (cyan, magenta, yellow and black outputs, #8047). +pub const CMYK_MIXER_UNAVAILABLE: &str = + "Editing a CMYK Channel Mixer (cyan, magenta, yellow and black outputs) is not available in this editor yet; the mixer is kept as it is"; + /// The typed value of the adjustment `kind` the engine reads from `params`. /// /// The engine parses and clamps first (`adjust_params::from_params`), so the value holds what the engine would apply. @@ -251,8 +255,20 @@ pub fn from_params(kind: &str, params: &Value, cx: &ValueCx) -> Result Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.color_mut().settings = settings; + app +} + +/// Opens the dialog from the menu and runs `passes` passes of the dialog host. +fn open_dialog(app: &mut PhotocraftApp, passes: usize) -> DialogId { + let ctx = app.ctx().clone(); + crate::menus::invoke(app, &ctx, COMMAND, json!({})).unwrap(); + let id = top(app); + show(app, passes); + id +} + +fn show(app: &mut PhotocraftApp, passes: usize) { + for _ in 0..passes { + crate::dialogs::testing::show(app); + } +} + +/// The open dialog's values as JSON. +fn fields(app: &PhotocraftApp, id: DialogId) -> Map { + fields_map(crate::new_layer_ui::testing::fields(app, id)) +} + +/// `ui.dialog.set`, as a script sends it. +fn dialog_set(app: &mut PhotocraftApp, id: DialogId, field: &str, value: Value) { + let ctx = app.ctx().clone(); + let (request, _) = ControlRequest::new("ui.dialog.set", json!({"dialog": id.value().to_string(), "field": field, "value": value})); + let Reply::Done(reply) = crate::control::handle(app, &ctx, &request) else { panic!("ui.dialog.set should finish immediately") }; + assert_eq!(reply["ok"], true, "{field} = {value}: {reply}"); +} + +#[test] +fn opening_shows_the_stored_setup_and_keeps_its_values() { + let stored = preset_setup(&ColorSettings::default(), "North America Prepress 2", "srgb").unwrap(); + let mut app = app_with(stored.clone()); + let id = open_dialog(&mut app, 3); + let f = fields(&app, id); + assert_eq!(f["preset"], "North America Prepress 2"); + let stored = serde_json::to_value(&stored).unwrap(); + let stored = stored.as_object().unwrap(); + for (k, v) in stored.iter().filter(|(k, _)| f.contains_key(*k)) { + assert!(same(v, &f[k]), "{k}: {v} became {}", f[k]); + } +} + +#[test] +fn picking_a_setup_loads_it_but_keeps_the_text_gamma() { + // Blend Text Colors Using Gamma off (1.0) before the pick. + let mut app = app_with(ColorSettings { blend_text_gamma: 1.0, ..ColorSettings::default() }); + let id = open_dialog(&mut app, 1); + assert_eq!(fields(&app, id)["preset"], CUSTOM_SETTINGS, "PhotoCraft's defaults match no setup"); + dialog_set(&mut app, id, "preset", json!("Europe Prepress 3")); + show(&mut app, 3); + let f = fields(&app, id); + assert_eq!(f["preset"], "Europe Prepress 3", "loading the values is no edit"); + assert_eq!((&f["workingRgb"], &f["workingCmyk"], &f["workingGray"]), (&json!("adobe-rgb-compat"), &json!("coated-fogra39"), &json!("dot-gain-20-compat"))); + assert_eq!((&f["askOnMismatch"], &f["askOnPaste"], &f["askOnMissing"]), (&json!(true), &json!(true), &json!(true))); + assert!(same(&f["spotDotGain"], &json!(15.0)), "{}", f["spotDotGain"]); + assert!(same(&f["blendTextGamma"], &json!(1.0)), "kept: {}", f["blendTextGamma"]); +} + +#[test] +fn changing_any_control_shows_custom() { + for (key, value) in [ + ("workingRgb", json!("display-p3")), + ("policyGray", json!("off")), + ("askOnPaste", json!(false)), + ("intent", json!("saturation")), + ("bpc", json!(false)), + ("spotDotGain", json!(30.0)), + ("blendTextGamma", json!(1.8)), + ("reset", json!(true)), + ] { + let mut app = app_with(ColorSettings::default()); + let id = open_dialog(&mut app, 1); + dialog_set(&mut app, id, "preset", json!("Japan Prepress 2")); + show(&mut app, 2); + assert_eq!(fields(&app, id)["preset"], "Japan Prepress 2"); + // As the control would change it. + crate::new_layer_ui::testing::set(&mut app, id, key, value).unwrap(); + show(&mut app, 1); + assert_eq!(fields(&app, id)["preset"], CUSTOM_SETTINGS, "{key}"); + // It stays Custom, and keeps the values. + show(&mut app, 2); + let f = fields(&app, id); + assert_eq!(f["preset"], CUSTOM_SETTINGS, "{key}"); + assert_eq!(f["workingCmyk"], "coated-cmyk", "{key}"); + } +} + +#[test] +fn the_monitor_profile_is_no_change() { + let mut app = app_with(ColorSettings::default()); + let id = open_dialog(&mut app, 1); + dialog_set(&mut app, id, "preset", json!("North America Web/Internet")); + show(&mut app, 2); + dialog_set(&mut app, id, "monitorProfile", json!("display-p3")); + show(&mut app, 2); + assert_eq!(fields(&app, id)["preset"], "North America Web/Internet"); +} + +#[test] +fn monitor_color_takes_the_monitor_profile_the_dialog_shows() { + let mut app = app_with(ColorSettings { monitor_profile: "display-p3".into(), ..ColorSettings::default() }); + let id = open_dialog(&mut app, 1); + dialog_set(&mut app, id, "preset", json!("Monitor Color")); + show(&mut app, 2); + let f = fields(&app, id); + assert_eq!(f["preset"], "Monitor Color"); + assert_eq!(f["workingRgb"], app.session.color().monitor_rgb_for("display-p3")); + assert_eq!((&f["policyRgb"], &f["policyCmyk"], &f["policyGray"]), (&json!("off"), &json!("off"), &json!("off"))); +} + +#[test] +fn the_greyed_label_and_unknown_names_are_no_entry() { + for bad in [json!("Other"), json!("Nowhere")] { + let mut app = app_with(ColorSettings::default()); + let id = open_dialog(&mut app, 1); + dialog_set(&mut app, id, "preset", bad.clone()); + show(&mut app, 1); + assert_eq!(fields(&app, id)["preset"], CUSTOM_SETTINGS, "{bad}"); + } +} + +#[test] +fn ok_stores_the_setup_and_cancel_discards_it() { + let mut app = app_with(ColorSettings::default()); + // Cancel: nothing changes. + let id = open_dialog(&mut app, 1); + dialog_set(&mut app, id, "preset", json!("North America General Purpose 2")); + show(&mut app, 2); + crate::dialogs::testing::cancel(&mut app, id).unwrap(); + assert_eq!(app.session.color().settings, ColorSettings::default()); + // OK: the setup's name and values. + let id = open_dialog(&mut app, 1); + dialog_set(&mut app, id, "preset", json!("North America General Purpose 2")); + show(&mut app, 2); + crate::dialogs::testing::confirm(&mut app, id).unwrap(); + let c = &app.session.color().settings; + assert_eq!(c.preset, "North America General Purpose 2"); + assert_eq!((c.ask_on_mismatch, c.ask_on_paste, c.ask_on_missing), (false, false, false)); + // Opened again, it shows that setup; an edit then OK stores Custom. + let id = open_dialog(&mut app, 1); + assert_eq!(fields(&app, id)["preset"], "North America General Purpose 2"); + dialog_set(&mut app, id, "dither", json!(false)); + assert_eq!(fields(&app, id)["preset"], CUSTOM_SETTINGS); + crate::dialogs::testing::confirm(&mut app, id).unwrap(); + assert_eq!(app.session.color().settings.preset, CUSTOM_SETTINGS); + assert!(!app.session.color().settings.dither); +} + +#[test] +fn a_setup_set_by_script_loads_before_the_next_draw() { + let expected = preset_setup(&ColorSettings::default(), "Europe Prepress 3", "srgb").unwrap(); + let mut app = app_with(ColorSettings::default()); + let id = open_dialog(&mut app, 1); + dialog_set(&mut app, id, "preset", json!("Europe Prepress 3")); + crate::dialogs::testing::confirm(&mut app, id).unwrap(); + let c = &app.session.color().settings; + assert_eq!(c.preset, "Europe Prepress 3"); + assert_eq!((&c.working_rgb, &c.working_cmyk), (&expected.working_rgb, &expected.working_cmyk)); + assert_eq!((c.ask_on_mismatch, c.ask_on_paste, c.ask_on_missing), (true, true, true)); +} + +#[test] +fn a_control_set_by_script_shows_custom_before_the_next_draw() { + let name = "North America General Purpose 2"; + let stored = preset_setup(&ColorSettings::default(), name, "srgb").unwrap(); + // The engine keeps a named setup's name over the first two (gamma is no part of a setup, and + // the setup loads over a reset), so only the dialog can tell they changed. Setting the value a + // control already shows is no change. + for (key, value, expected) in + [("blendTextGamma", json!(1.8), CUSTOM_SETTINGS), ("reset", json!(true), CUSTOM_SETTINGS), ("blendTextGamma", json!(1.45), name)] + { + // A fresh app each time: the dialog reopens with the last confirmed values. + let mut app = app_with(stored.clone()); + let id = open_dialog(&mut app, 1); + dialog_set(&mut app, id, key, value.clone()); + assert_eq!(fields(&app, id)["preset"], expected, "{key} {value}"); + crate::dialogs::testing::confirm(&mut app, id).unwrap(); + assert_eq!(app.session.color().settings.preset, expected, "{key} {value}"); + } +} + +#[test] +fn a_control_set_before_the_first_pass_shows_custom() { + let name = "North America General Purpose 2"; + let stored = preset_setup(&ColorSettings::default(), name, "srgb").unwrap(); + // Before the first pass the dialog has no baseline yet: a changed control is still an edit, + // and setting the value it already shows is none. + for (value, expected) in [(json!(1.8), CUSTOM_SETTINGS), (json!(1.45), name)] { + let mut app = app_with(stored.clone()); + let id = open_dialog(&mut app, 0); + dialog_set(&mut app, id, "blendTextGamma", value.clone()); + assert_eq!(fields(&app, id)["preset"], expected, "{value}"); + show(&mut app, 2); + assert_eq!(fields(&app, id)["preset"], expected, "{value} after a draw"); + crate::dialogs::testing::confirm(&mut app, id).unwrap(); + assert_eq!(app.session.color().settings.preset, expected, "{value}"); + } +} + +#[test] +fn reset_set_before_the_first_pass_shows_custom() { + let name = "North America General Purpose 2"; + let stored = preset_setup(&ColorSettings::default(), name, "srgb").unwrap(); + for (value, expected) in [(json!(true), CUSTOM_SETTINGS), (json!(false), name)] { + let mut app = app_with(stored.clone()); + let id = open_dialog(&mut app, 0); + dialog_set(&mut app, id, "reset", value.clone()); + assert_eq!(fields(&app, id)["preset"], expected, "reset {value}"); + } +} + +#[test] +fn monitor_color_follows_a_monitor_profile_set_before_the_first_pass() { + let stored = preset_setup(&ColorSettings { monitor_profile: "srgb".into(), ..ColorSettings::default() }, "Monitor Color", "srgb").unwrap(); + let mut app = app_with(stored); + let id = open_dialog(&mut app, 0); + dialog_set(&mut app, id, "monitorProfile", json!("display-p3")); + let f = fields(&app, id); + assert_eq!((&f["preset"], &f["workingRgb"]), (&json!("Monitor Color"), &json!("display-p3")), "loaded at once"); + crate::dialogs::testing::confirm(&mut app, id).unwrap(); + let c = &app.session.color().settings; + assert_eq!((c.preset.as_str(), c.working_rgb.as_str()), ("Monitor Color", "display-p3")); +} + +#[test] +fn a_setup_set_before_the_first_pass_loads_too() { + let expected = preset_setup(&ColorSettings::default(), "Europe Prepress 3", "srgb").unwrap(); + let mut app = app_with(ColorSettings::default()); + let id = open_dialog(&mut app, 0); + dialog_set(&mut app, id, "preset", json!("Europe Prepress 3")); + let f = fields(&app, id); + assert_eq!((&f["workingRgb"], &f["workingCmyk"]), (&json!(expected.working_rgb), &json!(expected.working_cmyk)), "loaded at once"); + crate::dialogs::testing::confirm(&mut app, id).unwrap(); + let c = &app.session.color().settings; + assert_eq!(c.preset, "Europe Prepress 3"); + assert_eq!((&c.working_rgb, &c.working_cmyk), (&expected.working_rgb, &expected.working_cmyk)); + assert_eq!((c.ask_on_mismatch, c.ask_on_paste, c.ask_on_missing), (true, true, true)); +} + +#[test] +fn monitor_color_follows_a_monitor_profile_change() { + let mut app = app_with(ColorSettings { monitor_profile: "srgb".into(), ..ColorSettings::default() }); + let id = open_dialog(&mut app, 1); + dialog_set(&mut app, id, "preset", json!("Monitor Color")); + show(&mut app, 2); + assert_eq!(fields(&app, id)["workingRgb"], "srgb"); + dialog_set(&mut app, id, "monitorProfile", json!("display-p3")); + let f = fields(&app, id); + assert_eq!(f["preset"], "Monitor Color"); + assert_eq!(f["workingRgb"], "display-p3", "the working RGB follows the monitor profile"); + show(&mut app, 2); + crate::dialogs::testing::confirm(&mut app, id).unwrap(); + let c = &app.session.color().settings; + assert_eq!((c.preset.as_str(), c.working_rgb.as_str(), c.monitor_profile.as_str()), ("Monitor Color", "display-p3", "display-p3")); +} diff --git a/crates/ui-egui/src/dialogs/credits.rs b/crates/ui-egui/src/dialogs/credits.rs index ebc6689f5a..d3518b9f33 100644 --- a/crates/ui-egui/src/dialogs/credits.rs +++ b/crates/ui-egui/src/dialogs/credits.rs @@ -79,16 +79,31 @@ pub fn credits() -> Credits { /// The About tab's contents: name, blurb, version, the community button and the project links. pub fn about_info(_app: &PhotocraftApp) -> AboutInfo { - AboutInfo::new("PhotoCraft", tl!("PhotoCraft — an open-source, native image editor written in Rust."), photocraft_engine::build_info::long_version()) + about_info_for(crate::os_window::identity(), photocraft_engine::build_info::long_version(), photocraft_engine::build_info::git_sha()) +} + +fn about_info_for(identity: crate::os_window::LaunchIdentity, version: String, commit: Option<&str>) -> AboutInfo { + let nightly = identity == crate::os_window::LaunchIdentity::NightlyV1; + let mut links = vec![ + AboutLink::new(tl!("PhotoCraft website"), crate::links::APP_PAGE), + AboutLink::new(tl!("GitHub"), crate::links::GITHUB), + AboutLink::new(tl!("ArtCraft"), crate::links::ARTCRAFT_WEBSITE), + ]; + if nightly { + // Opens only after a user click. No diagnostics, paths or documents are sent automatically. + links.push(AboutLink::new(tl!("Report a problem"), crate::links::ISSUES)); + } + let version = if nightly { nightly_about_version(&version, commit) } else { version }; + AboutInfo::new(crate::os_window::name_for(identity), tl!("PhotoCraft — an open-source, native image editor written in Rust."), version) .community(AboutLink::new(tl!("Join us on Discord"), crate::links::DISCORD)) - .links([ - AboutLink::new(tl!("PhotoCraft website"), crate::links::APP_PAGE), - AboutLink::new(tl!("GitHub"), crate::links::GITHUB), - AboutLink::new(tl!("ArtCraft"), crate::links::ARTCRAFT_WEBSITE), - ]) + .links(links) .built_with("egui · wgpu · photocraft-engine") } +fn nightly_about_version(version: &str, commit: Option<&str>) -> String { + format!("{version}\nCommit: {}", commit.filter(|value| !value.is_empty()).unwrap_or("unavailable")) +} + /// Opens the About dialog on `tab`. pub fn open_about(app: &mut PhotocraftApp, tab: AboutTab) -> DialogId { let dialog = HostedAbout::new(about_info(app), credits()).tab(tab); @@ -113,3 +128,44 @@ pub(crate) fn take(app: &mut PhotocraftApp, ctx: &egui::Context) { ctx.copy_text(crate::gpu_status::system_info(app).join("\n")); } } + +#[cfg(test)] +mod nightly_about_tests { + use super::*; + use crate::os_window::LaunchIdentity; + + #[test] + fn stable_about_preserves_its_name_version_and_existing_links() { + let info = about_info_for(LaunchIdentity::Stable, "0.23.1 (dev build)".into(), None); + let expected = AboutInfo::new("PhotoCraft", "", "0.23.1 (dev build)".to_owned()); + assert_eq!(info.app_name, expected.app_name); + assert_eq!(info.version, expected.version); + assert_eq!( + info.links.iter().map(|link| link.url.as_str()).collect::>(), + [crate::links::APP_PAGE, crate::links::GITHUB, crate::links::ARTCRAFT_WEBSITE] + ); + assert_eq!(info.community.unwrap().url, crate::links::DISCORD); + } + + #[test] + fn nightly_about_names_its_channel_and_adds_a_user_initiated_report_link() { + let commit = "0123456789abcdef0123456789abcdef01234567"; + let version = "0.23.1-nightly.20261121.17.1.g0123456789ab"; + let info = about_info_for(LaunchIdentity::NightlyV1, version.into(), Some(commit)); + let expected = AboutInfo::new("PhotoCraft Nightly", "", nightly_about_version(version, Some(commit))); + assert_eq!(info.app_name, expected.app_name); + assert_eq!(info.version, expected.version); + assert_eq!(info.links.len(), 4); + assert_eq!(info.links.last().unwrap().url, crate::links::ISSUES); + assert_eq!(info.community.unwrap().url, crate::links::DISCORD); + } + + #[test] + fn nightly_about_retains_the_full_tag_and_commit_without_inventing_missing_provenance() { + let commit = "0123456789abcdef0123456789abcdef01234567"; + let version = "0.23.1-nightly.20261121.17.1.g0123456789ab"; + assert_eq!(nightly_about_version(version, Some(commit)), format!("{version}\nCommit: {commit}")); + assert_eq!(nightly_about_version(version, None), format!("{version}\nCommit: unavailable")); + assert_eq!(nightly_about_version(version, Some("")), format!("{version}\nCommit: unavailable")); + } +} diff --git a/crates/ui-egui/src/dialogs/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index e0ae91fea7..eeb780c4ff 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -25,7 +25,9 @@ use serde_json::{Map, Value, json}; use crate::PhotocraftApp; +mod color_settings_presets; mod rows; +pub(crate) use color_settings_presets::reconcile as reconcile_color_settings; pub(crate) use rows::{REPLACE_COLOR, replace_color_sample}; const MATCH_COLOR: &str = "image.adjustments.matchColor"; @@ -372,7 +374,11 @@ pub(crate) fn params(app: &mut PhotocraftApp, command: &str, spec: &str) -> Vec< list = super::rotate_canvas_ui::params(); } rows::custom_rows(app, command, &mut list); - if command == "edit.colorSettings" { + if command == color_settings_presets::COMMAND { + // The Settings menu: Custom, a greyed group label and the named setups in groups (#14229). + if let Some(p) = list.iter_mut().find(|p| p.key == "preset") { + *p = color_settings_presets::row(Label::from(tl!("Settings"))); + } // The monitor line under the rows: the cell holds the text each frame refreshes, which the build closure cannot read from the app. let note = crate::monitor_status::note_cell(app); list.push(craft::ui::patterns::form_dialogs::Param::custom("monitorNote", craft::ui::runtime::env::Label::Empty, move |ui, _, _| { diff --git a/crates/ui-egui/src/dialogs/filter_dialog/color_settings_presets.rs b/crates/ui-egui/src/dialogs/filter_dialog/color_settings_presets.rs new file mode 100644 index 0000000000..c58fce0540 --- /dev/null +++ b/crates/ui-egui/src/dialogs/filter_dialog/color_settings_presets.rs @@ -0,0 +1,196 @@ +//! Color Settings' Settings menu (#14229): picking a named setup loads its values into the +//! dialog's controls, except Blend Text Colors Using Gamma, which keeps what it shows; changing +//! any control afterwards shows "Custom" at once. OK sends the menu's entry as `preset`. +//! +//! The menu is a custom row ([`row`]); [`reconcile`] does the rest after each pass of the dialog +//! host and after each `ui.dialog.set`, so a confirm that follows a script's set sends the same +//! name and values a draw would have shown. + +use craft::ui::contract::{Bind, Entry, Outcome as _, Show as _}; +use craft::ui::dialog::dialog_id; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param}; +use craft::ui::pickers::Select; +use craft::ui::runtime::env::Label; +use photocraft_engine::color_cmds::{COLOR_SETTINGS_PRESETS, CUSTOM_SETTINGS, ColorExt, ColorSettings, is_settings_preset, preset_setup}; +use serde_json::{Map, Value, json}; + +use crate::PhotocraftApp; + +pub(super) const COMMAND: &str = "edit.colorSettings"; +const KEY: &str = "preset"; +/// The menu's greyed group label: never a value. +const OTHER: &str = "Other"; +/// The entries a separator line goes above. +const GROUP_STARTS: [&str; 3] = [OTHER, "Europe General Purpose 3", "Japan Color for Newspaper"]; +/// The menu entry the controls last took their values from (or showed on opening). +const APPLIED: &str = "__presetApplied"; +/// The controls' values at that moment: an edit makes them differ. +const BASE: &str = "__presetBase"; +/// The setup whose working RGB is the monitor profile. +const MONITOR_COLOR: &str = "Monitor Color"; +/// What a setup leaves as the controls show it. +const KEPT: [&str; 2] = ["blendTextGamma", "monitorProfile"]; + +/// The menu entry `value` names (Custom for anything the menu doesn't have). +fn entry_of(value: Option<&str>) -> String { + value.filter(|n| is_settings_preset(n)).unwrap_or(CUSTOM_SETTINGS).to_string() +} + +/// The Settings row, in place of the spec's plain choice: Custom, the greyed Other label and the +/// named setups in their groups. +pub(super) fn row(label: Label) -> Param { + let name = label.clone(); + Param::custom(KEY, label, move |ui, fields, _| { + let mut entries = Vec::new(); + let named = COLOR_SETTINGS_PRESETS.iter().map(|n| (*n, *n)); + for (value, label) in [(CUSTOM_SETTINGS, tl!("Custom")), (OTHER, tl!("Other"))].into_iter().chain(named) { + if GROUP_STARTS.contains(&value) { + entries.push(Entry::separator()); + } + entries.push(Entry::new(value.to_string(), Label::from(label)).enabled(value != OTHER)); + } + let out = Select::new(name.clone(), Bind::given(entry_of(fields.text(KEY))), &entries).show(ui); + if let Some(picked) = out.value().cloned() { + fields.set(KEY, FieldValue::Text(picked)); + } + out.response().clone() + }) +} + +/// After a pass or a set: shows Custom for a name the menu doesn't have, loads a newly picked setup +/// (from the menu or `ui.dialog.set`), or shows Custom once a control differs from the values the +/// shown setup gave. +pub(crate) fn reconcile(app: &mut PhotocraftApp, ctx: &egui::Context) { + let Some(dialog) = app.framework.dialogs.get_by_id::(dialog_id(COMMAND)) else { return }; + let f = fields_map(dialog.fields()); + let shown = entry_of(f.get(KEY).and_then(Value::as_str)); + if f.get(KEY).and_then(Value::as_str) != Some(shown.as_str()) { + set_hidden(app, KEY, json!(shown)); + } + let Some(applied) = f.get(APPLIED).and_then(Value::as_str).map(str::to_string) else { + // Opening: the controls hold the stored setup's values. A `ui.dialog.set` that picked + // another entry before the first pass loads it. + if shown != entry_of(Some(&app.session.color().settings.preset)) { + load(app, ctx, &f, &shown); + return; + } + // A control a `ui.dialog.set` changed before the first pass is an edit, not the baseline. + if shown != CUSTOM_SETTINGS && differs_from_stored(app, &f) { + set_hidden(app, KEY, json!(CUSTOM_SETTINGS)); + set_hidden(app, APPLIED, json!(CUSTOM_SETTINGS)); + return; + } + let base = tracked(&f); + // A monitor profile set before the first pass moves Monitor Color's working RGB too. + if shown == MONITOR_COLOR && monitor_rgb_moved(app, &f, &base) { + load(app, ctx, &f, &shown); + return; + } + set_hidden(app, APPLIED, json!(shown)); + set_hidden(app, BASE, Value::Object(base)); + return; + }; + if shown != applied { + load(app, ctx, &f, &shown); + return; + } + if shown == CUSTOM_SETTINGS { + return; + } + let mut base = match f.get(BASE) { + Some(Value::Object(b)) => b.clone(), + _ => Map::new(), + }; + let (mut edited, mut grew) = (false, false); + for (k, v) in tracked(&f) { + match base.get(&k) { + Some(b) => edited |= !same(b, &v), + // A control that filled in its default after opening is no edit. + None => { + base.insert(k, v); + grew = true; + } + } + } + if edited { + set_hidden(app, KEY, json!(CUSTOM_SETTINGS)); + set_hidden(app, APPLIED, json!(CUSTOM_SETTINGS)); + } else if shown == MONITOR_COLOR && monitor_rgb_moved(app, &f, &base) { + // Monitor Color's working RGB follows the monitor profile the dialog shows. + load(app, ctx, &f, &shown); + } else if grew { + set_hidden(app, BASE, Value::Object(base)); + } +} + +/// Loads the named setup into the controls (but the [`KEPT`] ones) and makes it the one they show. +/// "Monitor Color" takes the monitor profile the dialog shows as its working RGB. +fn load(app: &mut PhotocraftApp, ctx: &egui::Context, f: &Map, name: &str) { + let monitor = f.get("monitorProfile").and_then(Value::as_str).unwrap_or("auto"); + let monitor_rgb = app.session.color().monitor_rgb_for(monitor); + let id = dialog_id(COMMAND); + if let Some(Value::Object(setup)) = preset_setup(&ColorSettings::default(), name, &monitor_rgb).and_then(|c| serde_json::to_value(c).ok()) { + for (k, v) in setup { + if is_tracked(&k) && !KEPT.contains(&k.as_str()) && f.contains_key(&k) { + // A value a row refuses keeps what the row shows; the setups' values all fit the rows. + let _ = app.framework.dialogs.set_json_field(ctx, id, &k, v); + } + } + } + let Some(dialog) = app.framework.dialogs.get_by_id::(id) else { return }; + let base = tracked(&fields_map(dialog.fields())); + set_hidden(app, APPLIED, json!(name)); + set_hidden(app, BASE, Value::Object(base)); +} + +/// A tracked control no longer shows the stored Color Settings' value (for Reset, which the +/// settings don't hold, its opening value: off). +fn differs_from_stored(app: &PhotocraftApp, f: &Map) -> bool { + let Ok(Value::Object(stored)) = serde_json::to_value(&app.session.color().settings) else { return false }; + let opening = |k: &str| stored.get(k).cloned().or_else(|| (k == "reset").then_some(Value::Bool(false))); + tracked(f).iter().any(|(k, v)| opening(k).is_some_and(|s| !same(&s, v))) +} + +/// The working RGB Monitor Color gave (in `base`) is no longer the one the shown monitor profile gives. +fn monitor_rgb_moved(app: &PhotocraftApp, f: &Map, base: &Map) -> bool { + let monitor = f.get("monitorProfile").and_then(Value::as_str).unwrap_or("auto"); + base.get("workingRgb").and_then(Value::as_str) != Some(app.session.color().monitor_rgb_for(monitor).as_str()) +} + +/// Writes `value` under `key` of the open dialog: the menu's entry as text, the bookkeeping as JSON. +fn set_hidden(app: &mut PhotocraftApp, key: &str, value: Value) { + let Some(dialog) = app.framework.dialogs.get_mut_by_id::(dialog_id(COMMAND)) else { return }; + match value { + Value::String(text) => dialog.set_field(key, FieldValue::Text(text)), + value => dialog.set_field(key, FieldValue::Json(value)), + } +} + +fn fields_map(fields: &DialogFields) -> Map { + match serde_json::to_value(fields) { + Ok(Value::Object(map)) => map, + _ => Map::new(), + } +} + +/// Keys whose change makes the values Custom: the params but the menu and the monitor profile. +fn is_tracked(k: &str) -> bool { + !k.starts_with("__") && k != KEY && k != "monitorProfile" +} + +fn tracked(f: &Map) -> Map { + f.iter().filter(|(k, _)| is_tracked(k)).map(|(k, v)| (k.clone(), v.clone())).collect() +} + +/// Equal values; numbers within the controls' rounding (a stored f32 gamma reads back as +/// 1.4500000476837158, the field shows 1.45). +fn same(a: &Value, b: &Value) -> bool { + match (a.as_f64(), b.as_f64()) { + (Some(x), Some(y)) => (x - y).abs() <= 1e-4, + _ => a == b, + } +} + +#[cfg(test)] +#[path = "../color_settings_presets_tests.rs"] +mod tests; diff --git a/crates/ui-egui/src/dialogs/image_processor_settings_tests.rs b/crates/ui-egui/src/dialogs/image_processor_settings_tests.rs new file mode 100644 index 0000000000..a925c45b69 --- /dev/null +++ b/crates/ui-egui/src/dialogs/image_processor_settings_tests.rs @@ -0,0 +1,268 @@ +use std::cell::RefCell; +use std::path::PathBuf; +use std::rc::Rc; +use std::sync::Arc; + +use craft::host::{FileFilter, PickKind, Picked, ScriptedFiles}; +use craft::ui::dialog::DialogId; +use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog}; +use egui_kittest::{Harness, kittest::Queryable}; +use serde_json::{Value, json}; + +use super::{COMMAND, settings}; +use crate::{PhotocraftApp, Services}; + +#[test] +fn settings_xml_follows_the_reference_order_and_formats() { + let mut fields = DialogFields::from_pairs([("source", "folder"), ("input", "C:\\é & \r\n"), ("output", "C:\\résultats")]); + fields.set("jpeg/quality", 5.25); + fields.set("jpeg/resize", true); + fields.set("jpeg/width", 100_i64); + fields.set("jpeg/height", 80_i64); + let xml = settings::encode(&fields).unwrap(); + let text = std::str::from_utf8(&xml).unwrap(); + assert_eq!( + text, + concat!( + "\u{feff}\n", + "\t1\n", + "\tfalse\n", + "\tfalse\n", + "\tC:\\é & <source> \n", + "\tfalse\n", + "\tfalse\n", + "\tC:\\résultats\n", + "\ttrue\n", + "\tfalse\n", + "\tfalse\n", + "\tfalse\n", + "\tfalse\n", + "\t5.25\n", + "\ttrue\n", + "\ttrue\n", + "\t100\n", + "\t80\n", + "\tfalse\n", + "\t1\n", + "\t1\n", + "\tfalse\n", + "\t1\n", + "\t1\n", + "\tfalse\n", + "\t\n", + "\t\n", + "\t\n", + "\ttrue\n", + "\ttrue\n", + "\n", + ) + ); + let decoded = settings::decode(&xml).unwrap(); + assert_eq!(decoded.text("input"), fields.text("input")); + assert_eq!(decoded.text("output"), fields.text("output")); + assert_eq!(decoded.number("jpeg/quality"), Some(5.25)); +} + +#[test] +fn partial_xml_keeps_missing_fields_and_ignores_unknown_elements() { + let fields = settings::decode( + br#"trueinvalidMissing set "#, + ) + .unwrap(); + assert_eq!(fields, DialogFields::from_pairs([("source", "open"), ("input", "")])); + for source in ["current", "open", "folder"] { + let current = DialogFields::from_pairs([("source", source)]); + let encoded = settings::encode(¤t).unwrap(); + assert_eq!(settings::decode(&encoded).unwrap().text("source"), Some(source)); + } +} + +#[test] +fn invalid_settings_are_rejected() { + for invalid in [ + "", + "", + "", + "", + "", + "abc", + "NaN", + "12.01", + "30001", + "0", + "maybe", + "true", + "falsetrue", + "&bad;", + "A & B", + "A &", + "", + "", + ] { + assert!(settings::decode(invalid.as_bytes()).is_err(), "{invalid}"); + } + assert!(settings::decode(&[0xff]).is_err()); + assert!(settings::decode(&vec![b' '; settings::MAX_BYTES + 1]).is_err()); + assert!(settings::encode(&DialogFields::from_pairs([("input", "bad\0path")])).is_err()); +} + +#[test] +fn escaped_ampersands_and_literal_cdata_remain_valid() { + let xml = concat!( + "\u{feff}", + "", + "A & B & C &amp;", + "", + ); + let fields = settings::decode(xml.as_bytes()).unwrap(); + assert_eq!(fields.text("output"), Some("A & B & C &")); + assert_eq!(fields.text("input"), Some("A & B")); +} + +type AppHarness = Harness<'static, Box>; +type Written = Rc)>>>; + +fn open(app: &mut PhotocraftApp) -> DialogId { + let ctx = app.ctx().clone(); + crate::menus::invoke(app, &ctx, COMMAND, json!({})).unwrap(); + app.framework.dialogs.stack().top().unwrap() +} + +fn harness() -> (AppHarness, DialogId, Arc, Written) { + let files = Arc::new(ScriptedFiles::held()); + let written: Written = Default::default(); + let log = written.clone(); + let services = Services { + files: Some(files.clone()), + write: Some(Box::new(move |path, bytes| { + log.borrow_mut().push((path.to_owned(), bytes.to_vec())); + Ok(()) + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + app.run("file.new", json!({"width": 40, "height": 20})).unwrap(); + let id = open(&mut app); + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 1000.0)).with_context(app.ctx().clone()).build_ui_state( + |ui, app: &mut Box| { + app.poll_file_dialog(); + crate::dialogs::run(app, ui); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + (h, id, files, written) +} + +fn fields(h: &AppHarness, id: DialogId) -> &DialogFields { + h.state().framework.dialogs.get_by_id::(id).unwrap().fields() +} + +fn set(h: &mut AppHarness, id: DialogId, key: &str, value: Value) { + let ctx = h.ctx.clone(); + h.state_mut().framework.dialogs.set_json_field(&ctx, id, key, value).unwrap_or_else(|error| panic!("{key}: {error}")); +} + +fn click(h: &mut AppHarness, label: &str) { + h.get_by_role_and_label(egui::accesskit::Role::Button, label).click(); + h.run_steps(4); +} + +#[test] +fn the_footer_saves_and_loads_pending_values_without_running_image_processor() { + let (mut h, id, files, written) = harness(); + for (key, value) in [ + ("source", json!("folder")), + ("input", json!("pictures & sketches")), + ("output", json!("exports")), + ("includeSubfolders", json!(true)), + ("jpeg/quality", json!(9.75)), + ("jpeg/convertToSrgb", json!(true)), + ("jpeg/resize", json!(true)), + ("jpeg/width", json!(2048)), + ("jpeg/height", json!(1536)), + ("psd/enabled", json!(true)), + ("psd/maximizeCompatibility", json!(false)), + ("psd/resize", json!(true)), + ("psd/width", json!(1024)), + ("psd/height", json!(768)), + ("tiff/enabled", json!(true)), + ("tiff/lzw", json!(true)), + ("tiff/resize", json!(true)), + ("tiff/width", json!(4096)), + ("tiff/height", json!(3072)), + ] { + set(&mut h, id, key, value); + } + h.run_steps(3); + let buttons = ["Load…", "Save…", "Cancel", "Run"].map(|label| h.get_by_role_and_label(egui::accesskit::Role::Button, label).rect()); + for (index, button) in buttons.iter().enumerate() { + assert!(button.is_positive(), "button {index} is visible"); + assert!(buttons.iter().skip(index + 1).all(|other| !button.intersects(*other)), "footer buttons must not overlap"); + } + let original = fields(&h, id).clone(); + click(&mut h, "Save…"); + let request = files.requests().pop().unwrap(); + assert_eq!(request.kind, PickKind::Save); + assert_eq!(request.title.as_deref(), Some("Pick an XML file to save")); + assert_eq!(request.filters, [FileFilter::new("XML Files (*.xml)", &["xml"])]); + files.answer(Picked::Paths(vec![PathBuf::from("preset.xml")])).unwrap(); + h.run_steps(3); + assert_eq!(fields(&h, id), &original); + let (path, saved) = written.borrow_mut().pop().unwrap(); + assert_eq!(path, "preset.xml"); + + set(&mut h, id, "source", json!("open")); + set(&mut h, id, "jpeg/quality", json!(2.0)); + set(&mut h, id, "psd/enabled", json!(false)); + set(&mut h, id, "tiff/width", json!(16)); + h.run_steps(3); + click(&mut h, "Load…"); + let request = files.requests().pop().unwrap(); + assert_eq!(request.kind, PickKind::Open); + assert_eq!(request.title.as_deref(), Some("Pick an XML file to load")); + assert_eq!(request.filters, [FileFilter::new("XML Files (*.xml)", &["xml"])]); + files.answer(Picked::Contents(vec![(path, saved)])).unwrap(); + h.run_steps(3); + assert_eq!(fields(&h, id), &original); + assert!(written.borrow().is_empty(), "Load does not write output or close the dialog"); +} + +#[test] +fn malformed_and_cancelled_picks_leave_the_form_unchanged() { + let (mut h, id, files, written) = harness(); + let original = fields(&h, id).clone(); + + click(&mut h, "Save…"); + files.answer(Picked::Cancelled).unwrap(); + h.run_steps(3); + assert!(written.borrow().is_empty()); + click(&mut h, "Load…"); + files.answer(Picked::Cancelled).unwrap(); + h.run_steps(3); + assert_eq!(h.state().framework.dialogs.stack().top(), Some(id)); + + let path = tempfile::NamedTempFile::new().unwrap(); + std::fs::write(path.path(), b"trueA & B").unwrap(); + click(&mut h, "Load…"); + files.answer(Picked::Paths(vec![path.path().to_path_buf()])).unwrap(); + h.run_steps(3); + assert_eq!(fields(&h, id), &original); + let alert = h.state().framework.dialogs.stack().top().unwrap(); + assert_ne!(alert, id, "an error is shown over the form"); + assert!(h.state().ui.status.contains("unescaped ampersand")); +} + +#[test] +fn a_load_answer_for_a_closed_dialog_does_not_edit_a_reopened_dialog() { + let (mut h, id, files, _) = harness(); + click(&mut h, "Load…"); + let ctx = h.ctx.clone(); + crate::dialogs::cancel(h.state_mut(), &ctx, id).unwrap(); + let reopened = open(h.state_mut()); + let original = fields(&h, reopened).clone(); + files.answer(Picked::Contents(vec![("preset.xml".into(), b"12".to_vec())])).unwrap(); + h.run_steps(4); + assert_eq!(fields(&h, reopened), &original); +} diff --git a/crates/ui-egui/src/dialogs/image_processor_ui.rs b/crates/ui-egui/src/dialogs/image_processor_ui.rs index 05bfc16396..f0853bad66 100644 --- a/crates/ui-egui/src/dialogs/image_processor_ui.rs +++ b/crates/ui-egui/src/dialogs/image_processor_ui.rs @@ -2,7 +2,12 @@ //! built with the rest of the form by `view_cmds::dialogs::params_for`; this module folds their values into the //! per-format objects the command takes and refuses an OK with no format ticked. -use craft::ui::patterns::form_dialogs::ParamResult; +use craft::host::{PickRequest, Picked}; +use craft::theme::Variant; +use craft::ui::buttons::Button; +use craft::ui::contract::{LeastWidth, Props as _, Show as _, TooltipSpec, clicked}; +use craft::ui::dialog::DialogId; +use craft::ui::patterns::form_dialogs::{HostedParamDialog, ParamDialog, ParamResult}; use craft::ui::runtime::env::Label; use serde_json::{Map, Value}; @@ -56,5 +61,120 @@ pub(crate) fn check(app: &mut PhotocraftApp, result: &ParamResult) -> Result<(), } } +#[derive(Clone, Copy)] +enum SettingsAction { + Load, + Save, +} + +fn settings_action_id() -> egui::Id { + egui::Id::unique("pc-image-processor-settings-action") +} + +fn generation_id() -> egui::Id { + egui::Id::unique("pc-image-processor-settings-generation") +} + +pub(crate) fn settings_footer(dialog: ParamDialog<'_>) -> ParamDialog<'_> { + dialog.ok_label(Label::from(tl!("Run"))).shaped(|dialog| { + dialog.footer(|ui, _| { + for (action, label, tip) in [ + (SettingsAction::Load, tl!("Load…"), tl!("Load a settings file from disk")), + (SettingsAction::Save, tl!("Save…"), tl!("Save the current dialog settings to disk")), + ] { + let button = Button::new(label).variant(Variant::SECONDARY).least_width(LeastWidth::DialogButton).tooltip(TooltipSpec::new(tip)); + if clicked(&button.show(ui)) { + ui.ctx().data_mut(|data| data.insert_temp(settings_action_id(), action)); + } + } + }) + }) +} + +/// The dialog's id is reused when it reopens. A picker left over from a previous opening must not touch the new form. +pub(crate) fn settings_opened(ctx: &egui::Context) { + ctx.data_mut(|data| { + let generation = data.get_temp_mut_or_default::(generation_id()); + *generation = generation.wrapping_add(1); + data.remove::(settings_action_id()); + }); +} + +pub(crate) fn take_settings_action(app: &mut PhotocraftApp, ctx: &egui::Context, id: DialogId) { + let action = ctx.data_mut(|data| { + let id = settings_action_id(); + let action = data.get_temp::(id)?; + data.remove::(id); + Some(action) + }); + let Some(action) = action else { return }; + let result = pick_settings(app, id, action); + if let Err(error) = result + && error != crate::file_dialog::CANCELLED + { + crate::dialogs::alerts::alert(app, error); + } +} + +fn pick_settings(app: &mut PhotocraftApp, id: DialogId, action: SettingsAction) -> Result { + const PURPOSE: &str = "imageProcessorSettings"; + let generation = app.ctx().data(|data| data.get_temp::(generation_id())); + let (request, bytes) = match action { + SettingsAction::Load => (PickRequest::open(PURPOSE).title(tl!("Pick an XML file to load")), None), + SettingsAction::Save => { + let Some(dialog) = app.framework.dialogs.get_by_id::(id) else { return Ok(Value::Null) }; + let request = PickRequest::save(PURPOSE).title(tl!("Pick an XML file to save")).file_name("Image Processor.xml").suggested_extension("xml"); + (request, Some(settings::encode(dialog.fields())?)) + } + }; + app.ask_file(request.filter(tl!("XML Files (*.xml)"), &["xml"]), move |app, picked| { + if app.ctx().data(|data| data.get_temp::(generation_id())) != generation || app.framework.dialogs.get_by_id::(id).is_none() { + return Ok(Value::Null); + } + let result = match bytes { + Some(bytes) => write_settings(app, picked, &bytes), + None => load_settings(app, id, picked), + }; + result.inspect_err(|error| { + if error != crate::file_dialog::CANCELLED { + crate::dialogs::alerts::alert(app, error.clone()); + } + }) + }) +} + +fn load_settings(app: &mut PhotocraftApp, id: DialogId, picked: Picked) -> Result { + let bytes = match picked { + Picked::Contents(files) => files.into_iter().next().map(|(_, bytes)| bytes).ok_or(crate::file_dialog::CANCELLED)?, + #[cfg(not(target_arch = "wasm32"))] + Picked::Paths(paths) => { + let path = paths.first().ok_or(crate::file_dialog::CANCELLED)?; + photocraft_format::read_file_limited(path, settings::MAX_BYTES as u64).map_err(|error| format!("{}: {error}", path.display()))? + } + _ => return Err(tl!("Could not open the Image Processor settings file.").into()), + }; + let fields = settings::decode(&bytes)?; + if let Some(dialog) = app.framework.dialogs.get_mut_by_id::(id) { + for (key, value) in fields.iter() { + dialog.set_field(key, value.clone()); + } + } + Ok(Value::Null) +} + +fn write_settings(app: &mut PhotocraftApp, picked: Picked, bytes: &[u8]) -> Result { + let path = picked.first_path().ok_or(crate::file_dialog::CANCELLED)?; + let path = path.to_str().ok_or(tl!("The settings file name is not valid text."))?; + let write = app.services.write.as_mut().ok_or(tl!("Saving Image Processor settings is unavailable."))?; + write(path, bytes)?; + Ok(Value::Null) +} + +mod settings; + #[cfg(test)] mod tests; + +#[cfg(test)] +#[path = "image_processor_settings_tests.rs"] +mod settings_tests; diff --git a/crates/ui-egui/src/dialogs/image_processor_ui/settings.rs b/crates/ui-egui/src/dialogs/image_processor_ui/settings.rs new file mode 100644 index 0000000000..267c863e1c --- /dev/null +++ b/crates/ui-egui/src/dialogs/image_processor_ui/settings.rs @@ -0,0 +1,202 @@ +//! XML presets for the Image Processor dialog. The element names and order follow the measured settings file. + +use std::borrow::Cow; +use std::fmt::Write; + +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue}; +use craft_xml::{Doctype, Event, Limits, Node, Options}; + +pub(super) const MAX_BYTES: usize = 256 * 1024; + +const ROOT: &str = "ImageProcessor"; +// XML has only an open-documents/folder switch. A processing instruction preserves PhotoCraft's +// third choice without adding an element to the reference format. +const CURRENT_SOURCE: &str = r#"source="current""#; + +#[derive(Clone, Copy)] +enum Kind { + OpenDocuments, + Bool(bool), + Text, + Int(i64), + Quality, +} + +use Kind::{Bool, Int, OpenDocuments, Quality, Text}; + +// Fields without a dialog key use the current processor behavior. Load validates those settings too. +const ELEMENTS: &[(&str, Option<&str>, Kind)] = &[ + ("version", None, Int(1)), + ("useopen", Some("source"), OpenDocuments), + ("includesub", Some("includeSubfolders"), Bool(false)), + ("source", Some("input"), Text), + ("open", None, Bool(false)), + ("saveinsame", None, Bool(false)), + ("dest", Some("output"), Text), + ("jpeg", Some("jpeg/enabled"), Bool(true)), + ("psd", Some("psd/enabled"), Bool(false)), + ("tiff", Some("tiff/enabled"), Bool(false)), + ("lzw", Some("tiff/lzw"), Bool(false)), + ("converticc", Some("jpeg/convertToSrgb"), Bool(false)), + ("q", Some("jpeg/quality"), Quality), + ("max", Some("psd/maximizeCompatibility"), Bool(true)), + ("jpegresize", Some("jpeg/resize"), Bool(false)), + ("jpegw", Some("jpeg/width"), Int(30_000)), + ("jpegh", Some("jpeg/height"), Int(30_000)), + ("psdresize", Some("psd/resize"), Bool(false)), + ("psdw", Some("psd/width"), Int(30_000)), + ("psdh", Some("psd/height"), Int(30_000)), + ("tiffresize", Some("tiff/resize"), Bool(false)), + ("tiffw", Some("tiff/width"), Int(30_000)), + ("tiffh", Some("tiff/height"), Int(30_000)), + ("runaction", None, Bool(false)), + ("actionset", None, Text), + ("action", None, Text), + ("info", None, Text), + ("icc", None, Bool(true)), + ("keepstructure", None, Bool(true)), +]; + +fn invalid(tag: &str) -> String { + crate::i18n::fmt(tl!("Invalid Image Processor setting: {setting}"), &[("setting", tag)]) +} + +fn too_large() -> String { + tl!("The Image Processor settings file is too large.").into() +} + +pub(super) fn encode(fields: &DialogFields) -> Result, String> { + let mut xml = String::from('\u{feff}'); + let _ = writeln!(xml, "<{ROOT}>"); + if fields.text("source") == Some("current") { + let _ = writeln!(xml, "\t"); + } + for &(tag, field, kind) in ELEMENTS { + let field = field.unwrap_or_default(); + let _ = write!(xml, "\t<{tag}>"); + match kind { + OpenDocuments => xml.push_str(if fields.text(field) == Some("open") { "true" } else { "false" }), + Bool(default) => { + let _ = write!(xml, "{}", fields.bool(field).unwrap_or(default)); + } + Int(max) => { + let value = fields.int(field).unwrap_or(1); + if !(1..=max).contains(&value) { + return Err(invalid(tag)); + } + let _ = write!(xml, "{value}"); + } + Quality => { + let value = fields.number(field).unwrap_or(5.0); + if !(1.0..=12.0).contains(&value) { + return Err(invalid(tag)); + } + let _ = write!(xml, "{value}"); + } + Text => { + let text = fields.text(field).unwrap_or_default(); + if text.len() > MAX_BYTES { + return Err(too_large()); + } + if !text.chars().all(craft_xml::is_xml_char) { + return Err(invalid(tag)); + } + // Keep the preset's one element per line even for paths containing line breaks. + xml.push_str(&craft_xml::esc(text).replace('\n', " ")); + } + } + let _ = writeln!(xml, ""); + } + let _ = writeln!(xml, ""); + if xml.len() > MAX_BYTES { + return Err(too_large()); + } + Ok(xml.into_bytes()) +} + +pub(super) fn decode(bytes: &[u8]) -> Result { + if bytes.len() > MAX_BYTES { + return Err(too_large()); + } + let text = std::str::from_utf8(bytes).map_err(|_| tl!("Image Processor settings must be UTF-8.").to_string())?; + let options = Options { doctype: Doctype::Reject, pis: true, ..Options::default() }.strict().with_limits(Limits { + max_input: MAX_BYTES, + max_depth: 32, + max_nodes: 4096, + ..Limits::default() + }); + if text.contains('&') { + validate_references(text.strip_prefix('\u{feff}').unwrap_or(text), &options)?; + } + let root = options.parse(bytes).map_err(xml_error)?; + if root.name != ROOT || root.attr("xmlns").is_some_and(|ns| !ns.is_empty()) { + return Err(tl!("This file does not contain Image Processor settings.").into()); + } + let current = root.children.iter().any(|node| matches!(node, Node::Pi { target, data } if target == "PhotoCraft" && data == CURRENT_SOURCE)); + let mut seen = std::collections::HashSet::new(); + let mut updates = DialogFields::new(); + for node in &root.children { + let child = match node { + Node::El(child) if child.attr("xmlns").is_none_or(str::is_empty) => child, + Node::Text(text) if !text.trim().is_empty() => return Err(invalid(ROOT)), + _ => continue, + }; + let tag = child.name.as_str(); + let Some(&(_, field, kind)) = ELEMENTS.iter().find(|(name, _, _)| *name == tag) else { continue }; + if !seen.insert(tag) || child.children.iter().any(|node| matches!(node, Node::El(_))) { + return Err(invalid(tag)); + } + let value = parse_value(kind, child.text(), current).ok_or_else(|| invalid(tag))?; + if let Some(field) = field { + updates.set(field, value); + } + } + Ok(updates) +} + +fn xml_error(error: craft_xml::Error) -> String { + crate::i18n::fmt(tl!("Could not read Image Processor settings: {error}"), &[("error", &error.to_string())]) +} + +/// The shared reader accepts bare ampersands even in strict mode. Its event spans let us +/// check the original text and attributes without treating CDATA, comments or instructions as XML text. +fn validate_references(text: &str, options: &Options<'_>) -> Result<(), String> { + let mut events = options.events(text.as_bytes()); + while let Some(event) = events.next().map_err(xml_error)? { + if !matches!(event, Event::Text(_) | Event::Start { .. }) { + continue; + } + let raw = text.get(events.span()).ok_or_else(|| invalid(ROOT))?; + if raw.split('&').skip(1).any(|tail| tail.split_once(';').and_then(|(name, _)| craft_xml::entity(name)).is_none()) { + return Err(tl!("Image Processor settings contain an unescaped ampersand.").into()); + } + } + Ok(()) +} + +fn parse_value(kind: Kind, text: Cow<'_, str>, current: bool) -> Option { + let trimmed = text.trim(); + Some(match kind { + OpenDocuments => { + let open = trimmed.parse::().ok()?; + if open { + "open" + } else if current { + "current" + } else { + "folder" + } + .into() + } + Bool(_) => trimmed.parse::().ok()?.into(), + Text => text.into_owned().into(), + Int(max) => { + let value = trimmed.parse::().ok()?; + (1..=max).contains(&value).then_some(value)?.into() + } + Quality => { + let value = trimmed.parse::().ok()?; + (1.0..=12.0).contains(&value).then_some(value)?.into() + } + }) +} diff --git a/crates/ui-egui/src/dialogs/layer_style/tests.rs b/crates/ui-egui/src/dialogs/layer_style/tests.rs index 0d50302f0d..dc12ab152a 100644 --- a/crates/ui-egui/src/dialogs/layer_style/tests.rs +++ b/crates/ui-egui/src/dialogs/layer_style/tests.rs @@ -718,6 +718,29 @@ fn style_click_does_not_mutate_document_until_confirm() { assert_eq!(layer_effects(&h.state().session).len(), 1); } +/// #14977: a Satin the dialog creates starts at the measured factory values. The page's rows and +/// their default table now live in the UI framework, whose Satin defaults are still 19 / 11 / 14; +/// `specs` lays the app's engine defaults OVER that table, so the instance the page adds starts at +/// the engine's 90 / 50 / 80. +#[test] +fn a_new_satin_in_the_dialog_starts_at_the_factory_values() { + let mut app = app_with_layer(32); + let id = open(&mut app, Some(EffectKind::Satin.key())).unwrap(); + let satin = first_of(&app, id, EffectKind::Satin); + let style = &draft(&app, id).style; + assert_eq!( + (num(style, satin, "angle"), num(style, satin, "distance"), num(style, satin, "size")), + (Some(90.0), Some(50.0), Some(80.0)), + "the new Satin page starts at the measured values" + ); + assert_eq!(text(style, satin, "blend").as_deref(), Some("Multiply"), "blend mode"); + assert_eq!(num(style, satin, "opacity"), Some(50.0), "opacity"); + assert_eq!(param(style, satin, "invert"), Some(StyleValue::Bool(true)), "invert"); + assert_eq!(param(style, satin, "antiAlias"), Some(StyleValue::Bool(true)), "anti-aliased"); + cancel(&mut app, id); + assert!(layer_effects(&app.session).is_empty(), "Cancel added no effect"); +} + /// #14944: the Outer Glow page is grouped Photoshop-style - Noise right under Opacity, the rows of /// the Structure, Elements and Quality blocks. The hosted page draws `specs()` rows in order, so /// the page order is pinned here; the group TITLES belong to the framework's page (craft-libs has diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 4094a2c242..7be1811eba 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -26,6 +26,7 @@ macro_rules! tl { } mod brush_mode_menu; pub mod canvas; +mod channel_titles; #[cfg(not(target_arch = "wasm32"))] pub mod control; pub mod dialogs; diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index ddb5005730..2d4b64db55 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -1,5 +1,6 @@ use super::dispatch::no_params; use super::{PhotocraftApp, Value, json}; +use crate::dialogs::image_processor_ui; use craft::ui::choice::Checkbox; use craft::ui::contract::{Bind, Outcome as _, Props as _, Show as _}; use craft::ui::dialog::DialogId; @@ -56,9 +57,14 @@ fn opened(id: DialogId) -> Value { fn open_form(app: &mut PhotocraftApp, id: &str, title: &str, params: Vec, fields: DialogFields, fixed: Value) -> DialogId { let title = crate::dialogs::filter_dialog::title_of(title); let key = id.to_owned(); + let image_processor = id == image_processor_ui::COMMAND; + if image_processor { + image_processor_ui::settings_opened(app.ctx()); + } crate::dialogs::params::open_param(app, id, fields, fixed, move |fields: &mut DialogFields| { derive(&key, fields); - ParamDialog::command(key.clone(), title.clone(), params.clone()).values(Bind::bound(fields)) + let dialog = ParamDialog::command(key.clone(), title.clone(), params.clone()).values(Bind::bound(fields)); + if image_processor { image_processor_ui::settings_footer(dialog) } else { dialog } }) } diff --git a/crates/ui-egui/src/os_window.rs b/crates/ui-egui/src/os_window.rs index 4f20c241d7..35261c73ff 100644 --- a/crates/ui-egui/src/os_window.rs +++ b/crates/ui-egui/src/os_window.rs @@ -6,9 +6,59 @@ /// Matches the `.desktop` file and hicolor icon name, so Wayland docks pick up the icon. pub const APP_ID: &str = "ai.storyteller.photocraft"; +/// Immutable startup identity. The desktop selects it before any UI/runtime service is created. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LaunchIdentity { + Stable, + NightlyV1, +} + +static IDENTITY: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); + +pub fn select_identity(identity: LaunchIdentity) -> Result<(), String> { + let value = match identity { + LaunchIdentity::Stable => 1, + LaunchIdentity::NightlyV1 => 2, + }; + IDENTITY + .compare_exchange(0, value, std::sync::atomic::Ordering::AcqRel, std::sync::atomic::Ordering::Acquire) + .map(|_| ()) + .map_err(|_| "the window launch identity was already selected".into()) +} + +pub fn identity() -> LaunchIdentity { + if IDENTITY.load(std::sync::atomic::Ordering::Acquire) == 2 { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable } +} + +pub const fn id_for(identity: LaunchIdentity) -> &'static str { + match identity { + LaunchIdentity::Stable => APP_ID, + LaunchIdentity::NightlyV1 => "ai.storyteller.photocraft.nightly-v1", + } +} + +pub fn app_id() -> &'static str { + id_for(identity()) +} + +pub const fn name_for(identity: LaunchIdentity) -> &'static str { + match identity { + LaunchIdentity::Stable => "PhotoCraft", + LaunchIdentity::NightlyV1 => "PhotoCraft Nightly", + } +} + +pub const fn stable_services_for(identity: LaunchIdentity) -> bool { + matches!(identity, LaunchIdentity::Stable) +} + +pub fn stable_services_allowed() -> bool { + stable_services_for(identity()) +} + /// A builder for an extra OS window, carrying [`APP_ID`]. pub fn builder() -> egui::ViewportBuilder { - egui::ViewportBuilder::default().with_app_id(APP_ID) + egui::ViewportBuilder::default().with_app_id(app_id()) } #[cfg(test)] @@ -18,3 +68,15 @@ mod tests { assert_eq!(super::builder().app_id.as_deref(), Some("ai.storyteller.photocraft")); } } + +#[cfg(test)] +mod profile_tests { + use super::*; + #[test] + fn nightly_identity_is_distinct_and_never_enables_stable_services() { + assert_eq!(id_for(LaunchIdentity::Stable), APP_ID); + assert_ne!(id_for(LaunchIdentity::NightlyV1), APP_ID); + assert!(stable_services_for(LaunchIdentity::Stable)); + assert!(!stable_services_for(LaunchIdentity::NightlyV1)); + } +} diff --git a/crates/ui-egui/src/panels/actions/runner.rs b/crates/ui-egui/src/panels/actions/runner.rs index 93fe979c21..c97cfd1d8b 100644 --- a/crates/ui-egui/src/panels/actions/runner.rs +++ b/crates/ui-egui/src/panels/actions/runner.rs @@ -191,10 +191,14 @@ pub(crate) fn open_recorded_editor(app: &mut PhotocraftApp, id: &str, params: &V // Private keys belong to the dialog, not the recorded Action step. object.retain(|key, _| !key.starts_with("__")); } - if let Some(dialog) = crate::adjust_dialog::open_with_params(app, id, &values) { + match crate::adjust_dialog::open_with_params_checked(app, id, &values) { // Adjustment dialogs normalized their effective target already. Raw parameters here // would restore discarded Lab/CMYK records or override the normalized tone controls. - return Ok(dialog); + Ok(dialog) => return Ok(dialog), + // The editor refuses these parameters (a CMYK Channel Mixer, #8047): say why instead of + // opening the generic step editor over them. + Err(Some(reason)) => return Err(reason), + Err(None) => {} } let dialog = open_step_editor(app, id, &values)?; if !crate::sizing::is_sizing(id) { diff --git a/crates/ui-egui/src/panels/actions/runner_tests.rs b/crates/ui-egui/src/panels/actions/runner_tests.rs index 4e86978d24..1f7a6fa720 100644 --- a/crates/ui-egui/src/panels/actions/runner_tests.rs +++ b/crates/ui-egui/src/panels/actions/runner_tests.rs @@ -2157,3 +2157,15 @@ fn save_hook_closing_the_target_stops_an_imported_close_with_save() { assert!(app.session.recording.playback_stack.is_empty()); } } + +/// #8047: a recorded Channel Mixer step with ink outputs reopened in an RGB document is refused by +/// the RGB-only editor. Playback must say why, not fall back to the generic step editor over it. +#[test] +fn a_recorded_cmyk_channel_mixer_step_reports_the_editors_refusal() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 4, "height": 4})).unwrap(); + let open = app.framework.dialogs.open_dialogs().len(); + let result = open_recorded_editor(&mut app, "image.adjustments.channelMixer", &json!({"cyan": [80, 0, 0, 0, 0]})); + assert_eq!(result, Err(crate::adjust_editors::values::CMYK_MIXER_UNAVAILABLE.to_string())); + assert_eq!(app.framework.dialogs.open_dialogs().len(), open, "no editor opened"); +} diff --git a/crates/ui-egui/src/panels/smart_ui.rs b/crates/ui-egui/src/panels/smart_ui.rs index 44ffadb2ef..93a6132de2 100644 --- a/crates/ui-egui/src/panels/smart_ui.rs +++ b/crates/ui-egui/src/panels/smart_ui.rs @@ -165,8 +165,15 @@ pub fn open_editor(app: &mut PhotocraftApp, ctx: &egui::Context, layer: u64, sm: return; } }; - if crate::adjust_dialog::open_smart_filter(app, &f.command, &f.params, target.clone()).is_some() || !crate::filter_dialog::has_dialog(&f.command) { - return; + match crate::adjust_dialog::open_smart_filter_checked(app, &f.command, &f.params, target.clone()) { + Ok(_) => return, + // The editor refuses these parameters (a CMYK Channel Mixer, #8047): say why instead of opening nothing. + Err(Some(reason)) => { + crate::notices::error(app, reason); + return; + } + Err(None) if !crate::filter_dialog::has_dialog(&f.command) => return, + Err(None) => {} } // The hosted filter dialog carries the target as its captured value; the recorded parameters // overlay the schema defaults, not the user's last-used values. diff --git a/crates/ui-egui/src/panels/smart_ui/editor_tests.rs b/crates/ui-egui/src/panels/smart_ui/editor_tests.rs index 4c2821be11..c7489d90bb 100644 --- a/crates/ui-egui/src/panels/smart_ui/editor_tests.rs +++ b/crates/ui-egui/src/panels/smart_ui/editor_tests.rs @@ -587,11 +587,27 @@ fn a_channel_mixer_smart_filter_turned_off_monochrome_keeps_its_red_row() { let sm = recorded(h.state(), id); assert_eq!(sm.smart_filters.len(), 1, "no filter was stacked"); let adjustment = photocraft_engine::adjust_params::from_params("channelMixer", &sm.smart_filters[0].params, None, photocraft_doc::ColorMode::Rgb).unwrap(); - let photocraft_doc::Adjustment::ChannelMixer { matrix, monochrome } = adjustment else { panic!("Channel Mixer params") }; + let photocraft_doc::Adjustment::ChannelMixer { matrix, monochrome, .. } = adjustment else { panic!("Channel Mixer params") }; assert!(!monochrome); assert!(matrix[0].iter().zip([0.7, 0.3, 0.0, 0.0]).all(|(a, b)| (a - b).abs() < 1e-5), "the edited Red row renders: {:?}", matrix[0]); } +/// #8047: the framework Channel Mixer editor has red, green and blue outputs only. A Channel Mixer +/// smart filter with ink outputs (`cyan`..`black` keys, accepted in any document mode) reopened in +/// an RGB document must not open it over RGB defaults, whose edits the engine would drop beside the +/// ink keys: nothing opens, the reason is shown, and the filter keeps its params. +#[test] +fn a_cmyk_channel_mixer_smart_filter_is_not_opened_in_the_rgb_editor() { + let (app, id) = adjustment_filter("rgb", "image.adjustments.channelMixer", json!({"cyan": [80, 0, 0, 0, 0]})); + let before = recorded(&app, id).smart_filters[0].params.clone(); + assert!(photocraft_engine::adjust_params::MIXER_INKS.iter().any(|k| before.get(*k).is_some()), "an ink-output filter: {before}"); + let h = edit_first_filter(app, id); + assert!(h.state().adjust_open.is_none(), "no Channel Mixer editor opened"); + assert_eq!(h.state().ui.status, crate::adjust_editors::values::CMYK_MIXER_UNAVAILABLE, "the reason is shown"); + assert!(h.state().ui.status_error); + assert_eq!(recorded(h.state(), id).smart_filters[0].params, before, "the filter is kept as it is"); +} + /// In Lab, top-level `points` aliases Lightness and the editor writes both on an edit. A stored /// one must not override the edit: the Lightness the editor sends is what the filter renders. #[test] diff --git a/crates/ui-egui/src/panels/title_bar.rs b/crates/ui-egui/src/panels/title_bar.rs index 5d99100419..020b4ec578 100644 --- a/crates/ui-egui/src/panels/title_bar.rs +++ b/crates/ui-egui/src/panels/title_bar.rs @@ -34,22 +34,28 @@ pub fn title_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { /// no document open. With Preferences › Interface › Show File Name In Title off, the file name drops out and the app /// name (and the dot) remains, since the tabs already name the file (#5037). pub(crate) fn title_text(app: &PhotocraftApp) -> String { - let show_name = app.session.prefs().interface.show_file_name_in_title; - app.session - .active() - .map(|d| format!("{}{}", if show_name { d.doc.name.as_str() } else { "PhotoCraft" }, if d.is_dirty() { " •" } else { "" })) - .unwrap_or_else(|| "PhotoCraft".into()) + title_text_for(app, crate::os_window::identity()) } -/// The OS window title: the active document's name suffixed with the app name (a `*` prefix -/// marks unsaved changes, like the `•` in the app-drawn title), or just the app name with no -/// document open. With Preferences › Interface › Show File Name In Title off, the file name -/// drops out and only the app name (and the `*`) remains (#5037). +fn title_text_for(app: &PhotocraftApp, identity: crate::os_window::LaunchIdentity) -> String { + let document = app.session.active().map(|d| (d.doc.name.as_str(), d.is_dirty())); + crate::channel_titles::drawn_title( + crate::os_window::name_for(identity), + document, + app.session.prefs().interface.show_file_name_in_title, + identity == crate::os_window::LaunchIdentity::NightlyV1, + ) +} + +/// The OS window title retains its channel through document/dirty/preference changes. +/// Stable formatting is unchanged; Nightly never falls back to the stable brand name. pub fn window_title(app: &PhotocraftApp) -> String { - if !app.session.prefs().interface.show_file_name_in_title { - return format!("{}PhotoCraft", if app.session.active().is_some_and(|d| d.is_dirty()) { "*" } else { "" }); - } - app.session.active().map(|d| format!("{}{} \u{2014} PhotoCraft", if d.is_dirty() { "*" } else { "" }, d.doc.name)).unwrap_or_else(|| "PhotoCraft".into()) + window_title_for(app, crate::os_window::identity()) +} + +fn window_title_for(app: &PhotocraftApp, identity: crate::os_window::LaunchIdentity) -> String { + let document = app.session.active().map(|d| (d.doc.name.as_str(), d.is_dirty())); + crate::channel_titles::os_title(crate::os_window::name_for(identity), document, app.session.prefs().interface.show_file_name_in_title) } #[cfg(test)] diff --git a/crates/ui-egui/src/prefs/prefs_ui/dialogs.rs b/crates/ui-egui/src/prefs/prefs_ui/dialogs.rs index 58fd1ea579..0f23b45c86 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/dialogs.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/dialogs.rs @@ -68,6 +68,14 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &V crate::monitor_status::read_now(app); dialog(crate::filter_dialog::open(app, "edit.colorSettings")) } + "edit.findAndReplaceText" + if app + .session + .active() + .is_some_and(|st| st.doc.walk().iter().all(|(_, _, layer)| !matches!(layer.content, photocraft_doc::LayerContent::Text(_)))) => + { + Some(Ok(Value::Null)) + } "edit.fade" | "edit.findAndReplaceText" | "edit.defineBrushPreset" | "edit.defineCustomShape" | "edit.autoAlignLayers" | "edit.autoBlendLayers" => { if !app.session.is_enabled(id) { return Some(Err(photocraft_engine::commands::find(id) @@ -354,3 +362,40 @@ pub(crate) fn set_draft(app: &mut PhotocraftApp, key: &str, value: PrefValue) -> None => false, } } + +#[cfg(test)] +mod find_replace_empty_tests { + use super::*; + use std::sync::Arc; + + #[test] + fn find_replace_empty_menu_invocation_is_silent() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = app.ctx().clone(); + let command = "edit.findAndReplaceText"; + assert!(!crate::menus::is_enabled(&app, command)); + assert!(crate::menus::invoke(&mut app, &ctx, command, json!({})).is_err()); + + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + assert!(crate::menus::is_enabled(&app, command)); + let before = app.session.active().unwrap().doc.clone(); + let history = app.session.active().unwrap().history.entries(); + let status = (app.ui.status.clone(), app.ui.status_error); + assert_eq!(crate::menus::invoke(&mut app, &ctx, command, json!({})).unwrap(), Value::Null); + assert!(!app.dialog_open()); + assert_eq!((app.ui.status.clone(), app.ui.status_error), status); + assert!(Arc::ptr_eq(&before, &app.session.active().unwrap().doc)); + assert_eq!(app.session.active().unwrap().history.entries(), history); + + app.run("type.create", json!({"text": "word", "size": 8})).unwrap(); + app.run("layer.setProps", json!({"locked": true})).unwrap(); + assert!(!crate::menus::is_enabled(&app, command)); + assert!(crate::menus::invoke(&mut app, &ctx, command, json!({})).is_err()); + assert!(!app.dialog_open()); + app.run("layer.setProps", json!({"locked": false})).unwrap(); + assert!(crate::menus::is_enabled(&app, command)); + let result = crate::menus::invoke(&mut app, &ctx, command, json!({})).unwrap(); + assert!(result.get("dialog").is_some(), "{result}"); + assert!(app.dialog_open()); + } +} diff --git a/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_tests.rs b/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_tests.rs index e2e132747e..1cd4b0da3c 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_tests.rs @@ -146,3 +146,23 @@ fn an_edit_still_marks_the_set_modified_and_sets_save_no_action_keys() { h.state_mut().run("edit.keyboardShortcuts", json!({"set": {"edit.cut": "F7"}})).unwrap(); assert!(modified(h.state().session.prefs())); } + +#[test] +fn deleting_a_custom_set_waits_for_confirmation_and_dialog_ok() { + use egui_kittest::kittest::{NodeT, Queryable}; + let mut h = harness(); + h.state_mut().run("edit.keyboardShortcuts", json!({"set":{"edit.copy":"F9"},"saveSet":"Painting"})).unwrap(); + open(&mut h); + h.run_steps(4); + h.get_by_label("Delete").click(); + h.run_steps(3); + let question = h.get_by_label("Delete the set “Painting”?"); + assert!(h.state().prefs_rt.shortcuts.as_ref().unwrap().profiles.sets().contains_key("Painting")); + let cancel = std::iter::successors(question.parent(), |node| node.parent()) + .find_map(|scope| scope.query_by_label("Cancel")) + .expect("the confirmation offers Cancel"); + cancel.click(); + h.run_steps(3); + assert!(h.query_by_label("Delete the set “Painting”?").is_none(), "Cancel closes the confirmation"); + assert!(h.state().prefs_rt.shortcuts.as_ref().unwrap().profiles.sets().contains_key("Painting")); +} diff --git a/crates/ui-egui/src/text.rs b/crates/ui-egui/src/text.rs index 69445ecb2f..d17ed944e8 100644 --- a/crates/ui-egui/src/text.rs +++ b/crates/ui-egui/src/text.rs @@ -1,3 +1,5 @@ pub mod cjk_fonts; pub mod direction; +#[cfg(not(target_arch = "wasm32"))] +pub(crate) mod installed_fonts; pub mod served_fonts; diff --git a/crates/ui-egui/src/text/installed_fonts.rs b/crates/ui-egui/src/text/installed_fonts.rs new file mode 100644 index 0000000000..e7a3832a8e --- /dev/null +++ b/crates/ui-egui/src/text/installed_fonts.rs @@ -0,0 +1,78 @@ +//! Fonts installed while the app runs (a family the launcher puts in the suite's font store, or +//! one installed in the system's font folders): the catalog notices them (its store poll, and a +//! check on window activation), and each frame registers what is new for documents and re-renders +//! the type layers that use those families. + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock, PoisonError}; + +use photocraft_engine::TypeLayerRef; + +use crate::PhotocraftApp; + +/// The context the catalog's worker wakes; set by the first frame once [`start`] ran. +static WAKE: OnceLock = OnceLock::new(); +/// [`start`] ran: activations check the font folders. +static STARTED: OnceLock<()> = OnceLock::new(); +/// The catalog generation [`tick`] last compared the shared engine's fonts with. +static CHECKED: AtomicU64 = AtomicU64::new(u64::MAX); +/// Layers whose document was busy with a background job when their font arrived. +static PENDING: Mutex> = Mutex::new(Vec::new()); + +/// Starts the font catalog (desktop start-up, before the first window). Until then [`tick`] and +/// [`on_input`] do nothing, so tests and the web build keep a catalog nothing polls. +pub(crate) fn start() { + if STARTED.set(()).is_ok() { + photocraft_text::fonts::start_catalog(|| { + if let Some(ctx) = WAKE.get() { + ctx.request_repaint(); + } + }); + } +} + +/// For the frame's raw input: a window activation checks the font folders. +pub(crate) fn on_input(raw_input: &egui::RawInput) { + if STARTED.get().is_some() && raw_input.events.iter().any(|e| matches!(e, egui::Event::WindowFocused(true))) { + photocraft_text::fonts::catalog_activated(); + } +} + +/// Registers fonts the installed catalog gained since the last frame and re-renders the type layers that +/// use their families (a missing font that now resolves, a style just installed). Also retries +/// the layers of a document that was busy. +pub(crate) fn tick(app: &mut PhotocraftApp, ctx: &egui::Context) { + if STARTED.get().is_none() { + return; + } + WAKE.get_or_init(|| ctx.clone()); + follow_catalog(app); +} + +/// [`tick`]'s work once the catalog runs. +fn follow_catalog(app: &mut PhotocraftApp) { + let mut layers = std::mem::take(&mut *PENDING.lock().unwrap_or_else(PoisonError::into_inner)); + let generation = photocraft_text::fonts::installed_catalog().generation(); + if generation != CHECKED.load(Ordering::Relaxed) + && let Some(engine) = photocraft_text::try_shared() + { + CHECKED.store(generation, Ordering::Relaxed); + let update = engine.lock().unwrap_or_else(PoisonError::into_inner).fonts.installed_update(); + if let Some(update) = update { + // Picked before the fonts are in: whether a layer shows our own layout compares its + // pixels with what the engine draws without them, and that takes the engine's lock. + if !update.families.is_empty() { + super::served_fonts::pick(&app.session, &update.families, &mut layers); + } + engine.lock().unwrap_or_else(PoisonError::into_inner).fonts.apply_installed(update); + } + } + if !layers.is_empty() { + let busy = app.session.refresh_type_layers(&layers); + PENDING.lock().unwrap_or_else(PoisonError::into_inner).extend(busy); + } +} + +#[cfg(test)] +#[path = "installed_fonts_tests.rs"] +mod tests; diff --git a/crates/ui-egui/src/text/installed_fonts_tests.rs b/crates/ui-egui/src/text/installed_fonts_tests.rs new file mode 100644 index 0000000000..561c1c2db1 --- /dev/null +++ b/crates/ui-egui/src/text/installed_fonts_tests.rs @@ -0,0 +1,75 @@ +//! A family installed while the app runs, picked from the Type tool's font menu. + +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; + +use crate::{PhotocraftApp, Services}; + +/// JetBrains Mono renamed to `family` in its name table (ASCII and UTF-16BE records; `family` has the same length). +fn renamed_font(family: &str) -> Vec { + let mut bytes = photocraft_text::fonts::JETBRAINS_MONO_REGULAR.clone(); + let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::>(); + 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(); + } + } + bytes +} + +/// A pointer press and release at the centre of the row labelled `label`, as a mouse click. +fn click_row(h: &mut Harness<'static, Box>, label: &str) { + let at = h.get_by_role_and_label(Role::TreeItem, label).rect().center(); + h.hover_at(at); + h.run(); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + h.step(); + } + h.run(); +} + +fn layer_font(app: &PhotocraftApp) -> String { + let st = app.session.active().unwrap(); + match &st.doc.layer(st.active_layer.unwrap()).unwrap().content { + photocraft_doc::LayerContent::Text(t) => t.font_family.clone(), + _ => panic!("type layer"), + } +} + +#[test] +fn a_family_installed_while_the_menu_is_open_is_picked_on_the_first_click() { + let family = "Zetbrains Pick"; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("type.create", json!({"text": "Sample", "font": "Inter", "size": 18})).unwrap(); + app.ui.tool = crate::state::Tool::Type; + app.sync_views(); + let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).with_max_steps(64).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::AppTheme::pro()); + app + }); + h.run_steps(4); + h.query_all_by_label("Font family").next().expect("the family field").click(); + h.run(); + h.query_all_by_label("Font family").next().expect("the family field").type_text("Zetbrains"); + h.run(); + + // The launcher installs the family into the store while the list is open. + let dir = std::env::temp_dir().join(format!("photocraft-pick-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("ZetbrainsPick-Regular.ttf"); + std::fs::write(&path, renamed_font(family)).unwrap(); + photocraft_text::fonts::catalog().add_file(&path, craft::font_catalog::Source::Store, &craft::font_catalog::Limits::default()).unwrap(); + super::follow_catalog(h.state_mut()); + h.run(); + + click_row(&mut h, family); + assert_eq!(layer_font(h.state()), family); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/src/text/served_fonts.rs b/crates/ui-egui/src/text/served_fonts.rs index 44a1b6ecb5..0f85380064 100644 --- a/crates/ui-egui/src/text/served_fonts.rs +++ b/crates/ui-egui/src/text/served_fonts.rs @@ -99,10 +99,11 @@ pub fn install(app: &mut PhotocraftApp, ctx: &egui::Context, delivered: Vec<(Str } } -/// Adds to `layers` the type layers to redraw once `families` arrive, in every open document and -/// in its first History snapshot (the document as opened), which is checked on its own: since -/// then its layers may have been edited (a PSD layer re-rendered) or deleted (#6087). -fn pick(session: &photocraft_engine::Session, families: &[String], layers: &mut Vec) { +/// Adds to `layers` the type layers to redraw once `families` arrive (served, or installed while +/// the app runs: `installed_fonts`), in every open document and in its first History snapshot +/// (the document as opened), which is checked on its own: since then its layers may have been +/// edited (a PSD layer re-rendered) or deleted (#6087). +pub(super) fn pick(session: &photocraft_engine::Session, families: &[String], layers: &mut Vec) { for st in session.documents() { let first = st.snapshots().iter().find(|s| s.id == 0).map(|s| &s.doc); // While it still is the open document, a layer picked there is picked in the snapshot too diff --git a/crates/ui-egui/src/tools/analysis/canvas.rs b/crates/ui-egui/src/tools/analysis/canvas.rs index edf05fdbbb..2f29a221d1 100644 --- a/crates/ui-egui/src/tools/analysis/canvas.rs +++ b/crates/ui-egui/src/tools/analysis/canvas.rs @@ -113,15 +113,25 @@ pub(crate) fn drain(app: &mut PhotocraftApp, state: &mut AnalysisTools, _respons } for event in state.sampler.take_events() { let result = match event { - SamplerEvent::Add { at, .. } => app.run("view.colorSamplers.add", json!({"x": at[0], "y": at[1]})), + SamplerEvent::Add { at, .. } => { + if app.session.active().is_some_and(|st| st.color_samplers.len() >= photocraft_engine::sampler_cmds::MAX_SAMPLERS) { + open_max_samplers_alert(app); + continue; + } + let r = app.run("view.colorSamplers.add", json!({"x": at[0], "y": at[1]})); + if r.is_ok() { + reveal_info_panel(app); + } + r + } SamplerEvent::Move { index, to, .. } => app.run("view.colorSamplers.move", json!({"index": index, "x": to[0], "y": to[1]})), SamplerEvent::Remove { index, .. } => app.run("view.colorSamplers.delete", json!({"index": index})), _ => continue, }; status_on_err(app, result); } - if let Some(toast) = state.sampler.take_error() { - crate::notices::post(app, toast.message.as_str().to_owned(), Vec::new(), toast.tone, None); + if let Some(_toast) = state.sampler.take_error() { + open_max_samplers_alert(app); } for event in std::mem::take(&mut state.count.events) { match event { @@ -162,6 +172,28 @@ pub(crate) fn drain(app: &mut PhotocraftApp, state: &mut AnalysisTools, _respons } } +/// The alert when the 11th Color Sampler is clicked (#11743). +#[cfg(test)] +pub const MAX_SAMPLERS_ALERT: &str = "Could not create a new sampler because the maximum number of samplers is 10."; + +/// Open the alert dialog when the Color Sampler limit is reached (#11743). +fn open_max_samplers_alert(app: &mut PhotocraftApp) { + app.ui.status.clear(); + app.ui.status_error = false; + let message = crate::i18n::fmt( + tl!("Could not create a new sampler because the maximum number of samplers is {max}."), + &[("max", &photocraft_engine::sampler_cmds::MAX_SAMPLERS.to_string())], + ); + let _ = crate::dialogs::alerts::alert(app, message); +} + +/// Open the closed Info panel when a Color Sampler point is placed (#11745). +pub(crate) fn reveal_info_panel(app: &mut PhotocraftApp) { + if !crate::panel_docking::is_checked(app, "info") { + let _ = crate::panel_docking::show_panel(app, "info", Some(true)); + } +} + /// Stores the Ruler line in the document: `None` clears it. fn set_ruler(app: &mut PhotocraftApp, line: Option) { let params = match line { diff --git a/crates/ui-egui/src/tools/analysis/tests.rs b/crates/ui-egui/src/tools/analysis/tests.rs index 91aa9c4e1f..d96462aee6 100644 --- a/crates/ui-egui/src/tools/analysis/tests.rs +++ b/crates/ui-egui/src/tools/analysis/tests.rs @@ -295,6 +295,143 @@ fn a_hidden_layer_keeps_the_button_and_the_click_shows_the_alert() { assert!(ruler(st).is_some(), "the ruler line is still there"); } +/// The messages of the alerts open on the host. +fn alerts(app: &PhotocraftApp) -> Vec { + app.framework + .dialogs + .open_dialogs() + .into_iter() + .filter(|d| d.key.as_deref() == Some("alert")) + .filter_map(|d| Some(d.fields.as_ref()?["message"].as_str()?.to_string())) + .collect() +} + +/// Closes every alert the host has open. +fn close_alerts(app: &mut PhotocraftApp, ctx: &egui::Context) { + let ids: Vec<_> = app.framework.dialogs.open_dialogs().into_iter().filter(|d| d.key.as_deref() == Some("alert")).map(|d| d.id).collect(); + for id in ids { + app.framework.dialogs.cancel_by_id(ctx, id); + } +} + +#[test] +fn placing_color_sampler_reveals_closed_info_panel() { + let (mut app, _) = app(); + app.ui.tool = Tool::ColorSampler; + // Close the Info panel. + let _ = crate::panel_docking::show_panel(&mut app, "info", Some(false)); + assert!(!crate::panel_docking::is_checked(&app, "info")); + + // Placing a sampler inside the canvas opens the Info panel (#11745). + down(&mut app, 25.0, 30.0, egui::Modifiers::NONE); + up(&mut app, 25.0, 30.0); + assert!(crate::panel_docking::is_checked(&app, "info")); + + // Placing a second sampler while the panel is already open leaves it open without error. + down(&mut app, 45.0, 50.0, egui::Modifiers::NONE); + up(&mut app, 45.0, 50.0); + assert!(crate::panel_docking::is_checked(&app, "info")); + + // A click on an existing sampler (starting a move or selection) does not reopen a closed panel. + let _ = crate::panel_docking::show_panel(&mut app, "info", Some(false)); + assert!(!crate::panel_docking::is_checked(&app, "info")); + down(&mut app, 25.0, 30.0, egui::Modifiers::NONE); + up(&mut app, 25.0, 30.0); + assert!(!crate::panel_docking::is_checked(&app, "info")); +} + +#[test] +fn placing_color_sampler_in_docked_workspace_leaves_info_panel_open() { + let (mut app, _) = app(); + app.ui.tool = Tool::ColorSampler; + // Dock the Info panel in an expanded column and close it. + app.run("window.panel.move", json!({"panel": "info", "anchor": "layers", "zone": "top"})).unwrap(); + let _ = crate::panel_docking::show_panel(&mut app, "info", Some(false)); + assert!(!crate::panel_docking::is_checked(&app, "info")); + + // Placing a sampler inside the canvas reveals the Info panel (#11745). + down(&mut app, 25.0, 30.0, egui::Modifiers::NONE); + up(&mut app, 25.0, 30.0); + assert!(crate::panel_docking::is_checked(&app, "info")); +} + +#[test] +fn color_sampler_limit_opens_alert_dialog_instead_of_status_note() { + let (mut app, _) = app(); + app.ui.tool = Tool::ColorSampler; + for i in 0..10 { + let x = 10.0 + (i as f64) * 10.0; + down(&mut app, x, 20.0, egui::Modifiers::NONE); + up(&mut app, x, 20.0); + } + assert_eq!(app.session.active().unwrap().color_samplers.len(), 10); + assert!(alerts(&app).is_empty()); + + // Prepare non-empty status and closed Info panel to verify state is cleared and panel is untouched. + app.ui.status = "Previous status".into(); + app.ui.status_error = true; + let _ = crate::panel_docking::show_panel(&mut app, "info", Some(false)); + assert!(!crate::panel_docking::is_checked(&app, "info")); + + // The 11th click opens the limit alert dialog instead of a status-bar note (#11743). + down(&mut app, 150.0, 20.0, egui::Modifiers::NONE); + up(&mut app, 150.0, 20.0); + assert_eq!(app.session.active().unwrap().color_samplers.len(), 10); + assert_eq!(app.ui.status, ""); + assert!(!app.ui.status_error); + // Limit rejection does not reveal or change the Info panel. + assert!(!crate::panel_docking::is_checked(&app, "info")); + + let dialogs = alerts(&app); + assert_eq!(dialogs, ["Could not create a new sampler because the maximum number of samplers is 10."]); + assert_eq!(dialogs, [super::canvas::MAX_SAMPLERS_ALERT]); +} + +#[test] +fn color_sampler_limit_alert_also_for_alt_click_off_a_point() { + // Measured in the reference application: Alt+click off a point adds a point like a plain + // click, so at 10 points it opens the same alert; Alt+click on a point deletes it, no alert. + let (mut app, ctx) = app(); + app.ui.tool = Tool::ColorSampler; + for i in 0..10 { + let x = 10.0 + (i as f64) * 10.0; + down(&mut app, x, 20.0, egui::Modifiers::NONE); + up(&mut app, x, 20.0); + } + down(&mut app, 150.0, 20.0, egui::Modifiers::ALT); + up(&mut app, 150.0, 20.0); + assert_eq!(app.session.active().unwrap().color_samplers.len(), 10); + let dialogs = alerts(&app); + assert_eq!(dialogs, ["Could not create a new sampler because the maximum number of samplers is 10."]); + assert_eq!(dialogs, [super::canvas::MAX_SAMPLERS_ALERT]); + + close_alerts(&mut app, &ctx); + down(&mut app, 10.0, 20.0, egui::Modifiers::ALT); + up(&mut app, 10.0, 20.0); + assert_eq!(app.session.active().unwrap().color_samplers.len(), 9); + assert!(alerts(&app).is_empty()); +} + +#[test] +fn color_sampler_drag_error_reports_to_status_bar_without_dialog() { + let (mut app, _) = app(); + app.ui.tool = Tool::ColorSampler; + // Place a sampler + down(&mut app, 25.0, 30.0, egui::Modifiers::NONE); + up(&mut app, 25.0, 30.0); + assert_eq!(app.session.active().unwrap().color_samplers.len(), 1); + + // Start dragging the sampler point + down(&mut app, 25.0, 30.0, egui::Modifiers::NONE); + // Clear samplers while drag is in flight + app.run("view.colorSamplers.clear", json!({})).unwrap(); + + // Release the drag inside canvas: move fails because point no longer exists + up(&mut app, 50.0, 50.0); + assert!(app.ui.status.contains("no sample point"), "status was: {}", app.ui.status); + assert!(alerts(&app).is_empty()); +} + /// The height of the number painted beside the first Count marker of a document whose group has `label_size`, read /// from the frame's text shapes. fn count_number_height(label_size: u32) -> f32 { diff --git a/crates/ui-egui/src/tools/type_tool/defaults.rs b/crates/ui-egui/src/tools/type_tool/defaults.rs index 3f8717dc3b..9477b2e60b 100644 --- a/crates/ui-egui/src/tools/type_tool/defaults.rs +++ b/crates/ui-egui/src/tools/type_tool/defaults.rs @@ -92,6 +92,45 @@ pub(super) fn default_style_params(app: &PhotocraftApp) -> serde_json::Value { p } +/// The `type.create` keys a new Type Mask takes from the document's active text layer (#12077): +/// the font, style and size the options bar shows for that layer, so the mask starts in the same +/// type settings instead of the tool's fresh defaults. Measured is only a click (not a paragraph +/// box) with the Horizontal Type Mask over a horizontal text layer, so any other active layer +/// gives `None` and today's tool options apply. The colour stays the foreground colour, as the +/// rest of the create parameters do. +pub(super) fn mask_style_from_active_layer(app: &PhotocraftApp) -> Option { + let st = app.session.active()?; + let t = text_layer(&st.doc, st.active_layer?)?; + if t.orientation != photocraft_doc::text::Orientation::Horizontal { + return None; + } + // The same first run the options bar names the layer by (`bar_character_values`), at the same + // shown size: a 12 pt layer scaled 200 % shows 24 pt. Only reached with no type session open, + // where `shown_scale` reads this very layer. + let c = t.char_runs().into_iter().next()?.style; + let mut p = json!({}); + // An empty name is the layer's placeholder for the default family, not a name to hand to + // `type.create`: the key is only taken when the layer names one. + if !c.font_family.is_empty() { + p["font"] = json!(c.font_family); + } + if !c.font_style.is_empty() { + p["fontStyle"] = json!(c.font_style); + } + let size = c.size_pt * shown_scale(app); + // Only inherit a size `type.create` would itself accept, asked through the engine's own + // `check_size_tracking` so the range stays single-sourced (0.1-1296 pt today). `json!` turns + // a non-finite product into `null`, which the check refuses; a FINITE shown size can leave + // the range too: an 800 pt layer under a 2x transform shows 1600 pt, and a corrupt document + // can carry a 0 pt run. A refused parameter fails the whole create, and the click would make + // no mask at all - so such a size stays out of the parameters and the tool's own applies, as + // it does for a family or style the layer does not name. + if photocraft_engine::type_cmds::check_size_tracking(&json!({ "size": size })).is_ok() { + p["size"] = json!(size); + } + Some(p) +} + /// Style numbers become f32 in the engine. JSON itself permits finite f64 values too large /// for that conversion; a hand-edited setting must not inject infinity into a new layer. /// Style collections (features, axes, colour) contain only scalar values, so no recursion. diff --git a/crates/ui-egui/src/tools/type_tool/fonts.rs b/crates/ui-egui/src/tools/type_tool/fonts.rs index ea0993a8ca..002b00fc4c 100644 --- a/crates/ui-egui/src/tools/type_tool/fonts.rs +++ b/crates/ui-egui/src/tools/type_tool/fonts.rs @@ -64,8 +64,11 @@ pub fn style_label(style: &str) -> String { } /// Starts scanning the installed fonts on a background thread (desktop start-up), so choosing -/// the Type tool doesn't stall the UI while they are read (#3021). Does nothing on the web. +/// the Type tool doesn't stall the UI while they are read (#3021), and follows fonts installed +/// while the app runs (`installed_fonts`). Does nothing on the web. pub fn warm_fonts() { + #[cfg(not(target_arch = "wasm32"))] + crate::text::installed_fonts::start(); photocraft_text::warm_shared(); } diff --git a/crates/ui-egui/src/tools/type_tool/mask_active_layer_style_tests.rs b/crates/ui-egui/src/tools/type_tool/mask_active_layer_style_tests.rs new file mode 100644 index 0000000000..1d946637b0 --- /dev/null +++ b/crates/ui-egui/src/tools/type_tool/mask_active_layer_style_tests.rs @@ -0,0 +1,336 @@ +//! #12077: with a text layer active, the Horizontal Type Mask starts a new mask in that layer's +//! type settings - the font, style and size the options bar shows for the layer - and not in the +//! tool's fresh defaults. The measured document (800x600 RGB/8, an 80 pt "TXT" active) gives the +//! same selection size as the same text typed with the tool itself set to 80 pt and a pixel layer +//! active; the text layer is not changed and stays active after the commit. +//! +//! The issue's *not measured* rows keep today's behaviour, pinned here: the Vertical Type Mask, a +//! paragraph (box) drag, a mixed orientation (a vertical text layer active), a non-text active +//! layer, and the tool options after the mask. Clicks and the box drag go through the canvas's +//! tool events. + +use egui::Modifiers; +use photocraft_doc::LayerId; +use serde_json::json; + +use super::super::commit; +use super::super::mask_replace_selection_tests::{bounds, click, new_app, selection}; +use super::super::{current_text, text_layer}; +use crate::PhotocraftApp; +use crate::canvas::testing::{ToolEvent, tool_event}; +use crate::state::Tool; + +/// The layer's first character run, which is what `bar_character_values` names the layer by. +fn char_style(app: &PhotocraftApp, id: LayerId) -> photocraft_doc::text::CharStyle { + let t = text_layer(&app.session.active().unwrap().doc, id).expect("a type layer"); + t.char_runs().into_iter().next().expect("a first character run").style +} + +/// What the options bar shows for the layer: its first character run's family, style name and size. +fn style(app: &PhotocraftApp, id: LayerId) -> (String, String, f32) { + let c = char_style(app, id); + (c.font_family, c.font_style, c.size_pt) +} + +/// The working layer the open mask session is typing into. +fn mask_style(app: &PhotocraftApp) -> (String, String, f32) { + let ed = app.ui.text_edit.as_ref().expect("an open mask session"); + style(app, LayerId(ed.layer)) +} + +fn active_layer(app: &PhotocraftApp) -> Option { + app.session.active().and_then(|st| st.active_layer) +} + +fn layers(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().doc.layers.len() +} + +/// [`new_app`]'s document, whose active layer is a type layer named `TXT` with the family +/// `"Inter"`, the style `"Bold"` and `pt` points - the issue's 80 pt text layer. +fn txt_active(pt: f32) -> (Box, LayerId) { + let mut app = new_app(); + let id = + app.run("type.create", json!({"text": "TXT", "x": 60, "y": 120, "font": "Inter", "fontStyle": "Bold", "size": pt})).unwrap()["layer"].as_u64().unwrap(); + let id = LayerId(id); + // The tool's own options, deliberately different from the layer's. + app.ui.tool_options.type_font = "Tool Font".into(); + app.ui.tool_options.type_style = "Regular".into(); + app.ui.tool_options.type_size = 48.0; + (app, id) +} + +/// Start a mask with a click at `at` and type `s`. +fn mask(app: &mut PhotocraftApp, at: (f64, f64), s: &str) { + click(app, at.0, at.1, Modifiers::NONE); + assert!(app.ui.text_edit.as_ref().is_some_and(|ed| ed.mask && ed.created), "a new mask session at {at:?}"); + super::super::host::type_text(app, s); +} + +/// A paragraph mask dragged from `from` to `to` (both ways over 4 screen pixels). +fn box_mask(app: &mut PhotocraftApp, from: (f64, f64), to: (f64, f64), s: &str) { + tool_event(app, ToolEvent::Down { x: from.0, y: from.1, pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Up { x: to.0, y: to.1 }, Modifiers::NONE); + assert!(app.ui.text_edit.as_ref().is_some_and(|ed| ed.mask && ed.created), "a new mask box {from:?} to {to:?}"); + super::super::host::type_text(app, s); +} + +/// The size of the committed mask's selection, in whole pixels. +fn selection_size(app: &PhotocraftApp) -> (u32, u32) { + let r = bounds(&selection(app)).expect("a Type Mask selection"); + (r.width(), r.height()) +} + +/// The measured row: an 80 pt text layer active and a click on empty canvas starts the mask at +/// 80 pt, not at the tool's 48 pt. +#[test] +fn a_mask_click_with_an_active_text_layer_starts_at_that_layers_size() { + let (mut app, _) = txt_active(80.0); + mask(&mut app, (60.0, 300.0), "MASK"); + assert_eq!(mask_style(&app).2, 80.0, "the active layer's size, not the tool's 48"); +} + +/// The measured acceptance "font, size and style as the options bar shows them for that layer". +#[test] +fn a_mask_click_takes_the_active_layers_font_and_style() { + let (mut app, _) = txt_active(80.0); + mask(&mut app, (60.0, 300.0), "MASK"); + assert_eq!(mask_style(&app), ("Inter".into(), "Bold".into(), 80.0), "the layer's font, style and size"); +} + +/// A 12 pt layer scaled 200 % shows 24 pt in the options bar and the Character panel, so that is +/// the size the mask takes. +#[test] +fn a_mask_click_takes_the_size_the_options_bar_shows_for_the_layer() { + let (mut app, id) = txt_active(12.0); + app.run("type.edit", json!({"layer": id.0, "transform": [2.0, 0.0, 0.0, 2.0, 60.0, 120.0]})).unwrap(); + mask(&mut app, (60.0, 300.0), "MASK"); + assert_eq!(mask_style(&app).2, 24.0, "12 pt at 200 % reads 24 pt, as the bar shows it"); +} + +/// The issue's comparison rows: the mask started by an active 80 pt text layer and the mask the +/// same text makes with a pixel layer active and the tool set to what the bar shows for that layer +/// (font, style and size) have the same selection size, and both differ from today's 48 pt result +/// made at the same point. +#[test] +fn the_active_layer_mask_selects_the_same_glyphs_as_the_tool_at_the_same_size() { + let (mut from_layer, _) = txt_active(80.0); + mask(&mut from_layer, (60.0, 300.0), "MASK"); + commit(&mut from_layer); + let from_layer = selection_size(&from_layer); + + let (mut from_tool, _) = txt_active(80.0); + from_tool.run("layer.new.layer", json!({})).unwrap(); + // The bar shows "Inter" "Bold" 80 pt for the layer, so the comparison tool is set to all three. + from_tool.ui.tool_options.type_font = "Inter".into(); + from_tool.ui.tool_options.type_style = "Bold".into(); + from_tool.ui.tool_options.type_size = 80.0; + mask(&mut from_tool, (60.0, 300.0), "MASK"); + commit(&mut from_tool); + let from_tool = selection_size(&from_tool); + + let (mut at_48, _) = txt_active(80.0); + at_48.run("layer.new.layer", json!({})).unwrap(); + mask(&mut at_48, (60.0, 300.0), "MASK"); + commit(&mut at_48); + let at_48 = selection_size(&at_48); + + assert_eq!(from_layer, from_tool, "the same size as the tool set to the layer's size"); + assert_ne!(from_layer, at_48, "and not today's 48 pt outline {at_48:?}"); +} + +/// The second measured row: the text layer is not changed and stays active after the commit, and +/// the session still leaves only the selection behind. +#[test] +fn the_text_layer_is_unchanged_and_stays_active_after_the_commit() { + let (mut app, id) = txt_active(80.0); + let (before_style, before_text, count) = (style(&app, id), current_text(&app, id), layers(&app)); + mask(&mut app, (60.0, 300.0), "MASK"); + commit(&mut app); + assert!(app.ui.text_edit.is_none(), "the session ended"); + assert_eq!(current_text(&app, id), before_text, "\"TXT\" is not changed"); + assert_eq!(style(&app, id), before_style, "nor its font, style or size"); + assert_eq!(active_layer(&app), Some(id), "and it is the active layer again after the commit"); + assert_eq!(layers(&app), count, "no layer is left behind"); + assert!(selection(&app).is_some(), "the selection is what the commit made"); +} + +/// The third measured row, and the case with no active layer at all: today's tool options still +/// apply. Guard test: passes before and after the change. +#[test] +fn a_non_text_active_layer_keeps_todays_tool_options() { + // A document whose only layer is the Background pixel layer. + let mut background = new_app(); + background.ui.tool_options.type_font = "Tool Font".into(); + background.ui.tool_options.type_style = "Regular".into(); + background.ui.tool_options.type_size = 48.0; + // The empty pixel layer above "TXT" is active. + let (mut pixel, _) = txt_active(80.0); + pixel.run("layer.new.layer", json!({})).unwrap(); + // "TXT" is present but nothing is the active layer. + let (mut none_active, _) = txt_active(80.0); + none_active.run("select.deselectLayers", json!({})).unwrap(); + assert_eq!(active_layer(&none_active), None, "no active layer"); + let cases: Vec<(&str, Box)> = vec![("Background", background), ("pixel layer", pixel), ("no active layer", none_active)]; + for (what, mut app) in cases { + mask(&mut app, (60.0, 300.0), "MASK"); + assert_eq!(mask_style(&app), ("Tool Font".into(), "Regular".into(), 48.0), "{what}: the tool options as today"); + } +} + +/// Not measured and keeping today's behaviour, as a whole: the Vertical Type Mask, and a click +/// whose active text layer is vertical; a paragraph drag with a horizontal text layer active. +#[test] +fn the_vertical_mask_and_a_paragraph_drag_keep_todays_tool_options() { + // The Vertical Type Mask with a horizontal text layer active. + let (mut vertical, _) = txt_active(80.0); + vertical.ui.tool = Tool::VerticalTypeMask; + mask(&mut vertical, (600.0, 100.0), "MASK"); + assert_eq!(mask_style(&vertical), ("Tool Font".into(), "Regular".into(), 48.0), "the vertical mask keeps today's defaults"); + // The Horizontal Type Mask with a vertical text layer active. + let (mut mixed, _) = new_vertical(); + mixed.ui.tool = Tool::HorizontalTypeMask; + mask(&mut mixed, (600.0, 300.0), "MASK"); + assert_eq!(mask_style(&mixed), ("Tool Font".into(), "Regular".into(), 48.0), "a mixed orientation keeps today's defaults"); + // A paragraph (box) drag with a horizontal text layer active. + let (mut dragged, _) = txt_active(80.0); + box_mask(&mut dragged, (60.0, 250.0), (400.0, 340.0), "MASK"); + assert_eq!(mask_style(&dragged), ("Tool Font".into(), "Regular".into(), 48.0), "a box drag keeps today's defaults"); +} + +/// [`txt_active`] with a vertical type layer active instead. +fn new_vertical() -> (Box, LayerId) { + let mut app = new_app(); + let id = app + .run("type.create", json!({"text": "TXT", "x": 60, "y": 120, "font": "Inter", "fontStyle": "Bold", "size": 80.0, "orientation": "vertical"})) + .unwrap()["layer"] + .as_u64() + .unwrap(); + app.ui.tool_options.type_font = "Tool Font".into(); + app.ui.tool_options.type_style = "Regular".into(); + app.ui.tool_options.type_size = 48.0; + (app, LayerId(id)) +} + +/// The plain Type tool is not a Type Mask: with the same 80 pt layer active its click still uses +/// the tool options (#10824 covers the settings of a type target, not this). Guard test: passes +/// before and after the change. +#[test] +fn the_plain_type_tool_still_starts_at_the_tool_options() { + let (mut app, _) = txt_active(80.0); + app.ui.tool = Tool::Type; + click(&mut app, 60.0, 300.0, Modifiers::NONE); + let ed = app.ui.text_edit.clone().expect("a new type session"); + assert!(!ed.mask, "a type layer, not a mask"); + assert_eq!(mask_style(&app), ("Tool Font".into(), "Regular".into(), 48.0), "the Type tool's own defaults"); +} + +/// The zero case: a text layer with no characters still shows its font, style and size in the bar +/// (its one run), so the mask starts at them - the takeover only moves create parameters, it +/// cannot knock anything out. +#[test] +fn an_empty_active_text_layer_gives_its_style_too() { + let mut app = new_app(); + app.run("type.create", json!({"text": "", "x": 60, "y": 120, "font": "Inter", "fontStyle": "Bold", "size": 80})).unwrap(); + app.ui.tool_options.type_font = "Tool Font".into(); + app.ui.tool_options.type_style = "Regular".into(); + app.ui.tool_options.type_size = 48.0; + mask(&mut app, (60.0, 300.0), "MASK"); + assert_eq!(mask_style(&app), ("Inter".into(), "Bold".into(), 80.0), "the empty layer's run, as the bar shows it"); +} + +/// Not measured: which settings besides the size are taken over. Only the bar's font, style and +/// size move to the mask - the active layer's leading, tracking, baseline shift and underline do +/// not. Red before the change like the takeover itself: its last line names the three keys that +/// move over. +#[test] +fn a_mask_takes_no_other_character_settings_from_the_layer() { + let mut app = new_app(); + app.run("type.create", json!({"text": "TXT", "x": 60, "y": 120, "font": "Inter", "fontStyle": "Bold", "size": 80, "leading": 100, "tracking": 200, "baselineShift": 5, "underline": true})) + .unwrap(); + app.ui.tool_options.type_font = "Tool Font".into(); + app.ui.tool_options.type_style = "Regular".into(); + app.ui.tool_options.type_size = 48.0; + mask(&mut app, (60.0, 300.0), "MASK"); + let id = LayerId(app.ui.text_edit.as_ref().expect("an open mask session").layer); + let c = char_style(&app, id); + assert_eq!((c.leading_pt, c.tracking, c.baseline_shift_pt, c.underline), (None, 0.0, 0.0, false), "only font, style and size move over"); + assert_eq!((c.font_family.as_str(), c.font_style.as_str(), c.size_pt), ("Inter", "Bold", 80.0), "those three do"); +} + +/// A layer that names no family or style (their placeholder for "the default"): the mask takes its +/// size but keeps the tool's own font and style, so no empty name reaches `type.create`. +#[test] +fn a_layer_that_names_no_family_or_style_gives_only_its_size() { + let mut app = new_app(); + app.run("type.create", json!({"text": "TXT", "x": 60, "y": 120, "font": "", "fontStyle": "", "size": 80})).unwrap(); + app.ui.tool_options.type_font = "Tool Font".into(); + app.ui.tool_options.type_style = "Regular".into(); + app.ui.tool_options.type_size = 48.0; + mask(&mut app, (60.0, 300.0), "MASK"); + assert_eq!(mask_style(&app), ("Tool Font".into(), "Regular".into(), 80.0), "the size is taken, the empty names are not"); +} + +/// A document as a corrupt file can leave it: the active layer's runs carry `bad` as their size, a +/// value no `type` command writes (the commands keep the size within 0.1-1296 pt). +fn corrupt_layer_size(app: &mut PhotocraftApp, id: LayerId, bad: f32) { + let st = app.session.active_mut().unwrap(); + let mut doc = (*st.doc).clone(); + if let Some(photocraft_doc::LayerContent::Text(t)) = doc.layer_mut(id).map(|l| &mut l.content) { + t.size_pt = bad; + for r in &mut t.runs { + r.style.size_pt = bad; + } + } + *st.doc_mut() = std::sync::Arc::new(doc); + st.revision += 1; +} + +/// The corrupt-document case: a layer size that is not a finite number. It stays out of the create +/// parameters, so the mask still starts - at the tool's own size, with the layer's font and style +/// taken as measured. Red without the gate on the finite product: the size becomes JSON `null`, +/// `type.create` refuses it, and the click does nothing at all. +#[test] +fn a_non_finite_layer_size_keeps_the_tool_size() { + for bad in [f32::NAN, f32::INFINITY] { + let (mut app, id) = txt_active(80.0); + corrupt_layer_size(&mut app, id, bad); + mask(&mut app, (60.0, 300.0), "MASK"); + assert_eq!(mask_style(&app), ("Inter".into(), "Bold".into(), 48.0), "the tool's size, not a null the engine rejects ({bad})"); + } +} + +/// A shown size can also leave the range `type.create` accepts while staying finite: an 800 pt +/// layer under a 4x/0.7x transform shows sqrt(2.8) * 800 = 1338 pt, above the engine's 1296 pt +/// maximum, and a corrupt document can carry a 0 pt run, below its 0.1 pt minimum. Inheriting a +/// refused size fails the whole create, so the click would make no mask at all. The size stays +/// out of the parameters there too, and the mask still starts - at the tool's own size, the +/// layer's font and style taken. Red before the range gate: no mask session opens. +#[test] +fn a_shown_layer_size_outside_the_create_range_keeps_the_tool_size() { + // A plain document reaches the too-large case: 800 pt is a size the commands write, only the + // transform pushes the shown product past the maximum. The transformed glyph band then sits + // entirely right of x = 189 and above y = 120, so the same click this file's other cases use + // does not land on the layer's glyphs (which would edit the layer, #12075) but starts a + // fresh mask. + let (mut app, id) = txt_active(800.0); + app.run("type.edit", json!({"layer": id.0, "transform": [4.0, 0.0, 0.0, 0.7, 60.0, 120.0]})).unwrap(); + mask(&mut app, (60.0, 300.0), "MASK"); + assert_eq!(mask_style(&app), ("Inter".into(), "Bold".into(), 48.0), "the tool's size, not the 1338 pt the create refuses"); + // And the corrupt-document case below the accepted minimum. + let (mut app, id) = txt_active(80.0); + corrupt_layer_size(&mut app, id, 0.0); + mask(&mut app, (60.0, 300.0), "MASK"); + assert_eq!(mask_style(&app), ("Inter".into(), "Bold".into(), 48.0), "the tool's size, not the 0 pt the create refuses"); +} + +/// Not measured: whether the tool options themselves change afterwards. Today they do not, and +/// they still do not. Guard test: passes before and after the change. +#[test] +fn taking_the_active_layers_style_leaves_the_tool_options_as_they_are() { + let (mut app, _) = txt_active(80.0); + mask(&mut app, (60.0, 300.0), "MASK"); + commit(&mut app); + let o = &app.ui.tool_options; + assert_eq!((o.type_font.as_str(), o.type_style.as_str(), o.type_size), ("Tool Font", "Regular", 48.0), "the tool options are untouched"); +} diff --git a/crates/ui-egui/src/tools/type_tool/pointer.rs b/crates/ui-egui/src/tools/type_tool/pointer.rs index f9239c1ce7..ff6f7a3ca3 100644 --- a/crates/ui-egui/src/tools/type_tool/pointer.rs +++ b/crates/ui-egui/src/tools/type_tool/pointer.rs @@ -13,7 +13,7 @@ use craft::ui::canvas::{CanvasTool, ToolAction, ToolContext, ToolHostResponse, T use craft::ui::primitives::{Draw, PaintShape, StrokeColor, StrokeWidth}; use craft::ui::style::DataColor; -use super::defaults::default_style_params; +use super::defaults::{default_style_params, mask_style_from_active_layer}; use super::editing::begin_edit; use super::layout::{hit_layer, offset_at}; @@ -227,6 +227,18 @@ fn create_text(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2]) { let placeholder = app.ui.tool != crate::state::Tool::VerticalTypeMask && app.session.prefs().type_.fill_new_type_layers_with_placeholder; let text = if placeholder { PLACEHOLDER } else { "" }; let mut p = default_style_params(app); + // #12077: the measured case - a click, not a paragraph box, with the Horizontal Type Mask over + // a horizontal text layer - starts the mask in that layer's font, style and size, as the + // options bar shows them for the layer. The vertical mask and a box drag are not measured in + // the issue, so they keep today's tool options. + if mask + && !is_box + && app.ui.tool == crate::state::Tool::HorizontalTypeMask + && let Some(style) = mask_style_from_active_layer(app) + && let (Some(params), Some(style)) = (p.as_object_mut(), style.as_object()) + { + params.extend(style.clone()); + } p["text"] = json!(text); p["orientation"] = json!(if app.ui.tool.is_vertical_type() { "vertical" } else { "horizontal" }); if is_box { @@ -362,3 +374,7 @@ mod mask_placeholder_tests; #[cfg(test)] #[path = "mask_click_text_layer_tests.rs"] mod mask_click_text_layer_tests; + +#[cfg(test)] +#[path = "mask_active_layer_style_tests.rs"] +mod mask_active_layer_style_tests; diff --git a/crates/ui-egui/src/tools/vector_ui/tests.rs b/crates/ui-egui/src/tools/vector_ui/tests.rs index fff3e07a26..2e5013b4dd 100644 --- a/crates/ui-egui/src/tools/vector_ui/tests.rs +++ b/crates/ui-egui/src/tools/vector_ui/tests.rs @@ -31,6 +31,28 @@ fn shape_drag(app: &mut PhotocraftApp, tool: Tool, from: [f64; 2], to: [f64; 2]) tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, none); } +#[test] +fn line_drag_with_a_path_operation_records_one_line_tool_step() { + let mut app = app(); + app.ui.tool_options.shape_mode = VectorMode::Shape; + shape_drag(&mut app, Tool::Line, [20.0, 20.0], [120.0, 100.0]); + let initial = app.run("shape.info", json!({})).unwrap(); + let steps = app.session.active().unwrap().history.past_len(); + + for op in ["combine", "subtract", "intersect"] { + app.ui.tool_options.shape_path_op = op.into(); + shape_drag(&mut app, Tool::Line, [30.0, 30.0], [120.0, 85.0]); + let result = app.run("shape.info", json!({})).unwrap(); + assert_eq!(result["layer"], initial["layer"], "{op}"); + assert_eq!(result["path"]["subpaths"][1]["op"], op); + let history = &app.session.active().unwrap().history; + assert_eq!(history.past_len(), steps + 1, "{op}"); + assert_eq!(history.undo_label(), Some("Line Tool"), "{op}"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.run("shape.info", json!({})).unwrap(), initial, "{op}"); + } +} + /// A plain click at each point, with the current tool. fn clicks(app: &mut PhotocraftApp, points: &[[f64; 2]]) { for at in points { diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index e004f9e2dd..29c3f08b32 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -8,7 +8,7 @@ use crate::PhotocraftApp; pub(crate) struct Runtime { /// The one checker: the startup prompt, the manual check, the installation and the last update's outcome. #[cfg(not(target_arch = "wasm32"))] - updater: craft::update::updater::Updater, + updater: Option, /// The check-result dialog on the dialog host, while one is open. #[cfg(not(target_arch = "wasm32"))] result_dialog: Option, @@ -17,11 +17,18 @@ pub(crate) struct Runtime { outcome_announced: bool, } +#[cfg(not(target_arch = "wasm32"))] +fn stable_updater(identity: crate::os_window::LaunchIdentity, make: impl FnOnce() -> T) -> Option { + crate::os_window::stable_services_for(identity).then(make) +} + impl Default for Runtime { fn default() -> Self { Self { #[cfg(not(target_arch = "wasm32"))] - updater: craft::update::updater::Updater::new(&crate::UPDATE_APP, photocraft_engine::build_info::VERSION), + updater: stable_updater(crate::os_window::identity(), || { + craft::update::updater::Updater::new(&crate::UPDATE_APP, photocraft_engine::build_info::VERSION) + }), #[cfg(not(target_arch = "wasm32"))] result_dialog: None, #[cfg(not(target_arch = "wasm32"))] @@ -33,7 +40,8 @@ impl Default for Runtime { /// Help ▸ Check for Updates: starts a check whose outcome the result window shows. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn check(app: &mut PhotocraftApp, _ctx: &egui::Context, _params: Value) -> Result { - app.updates_rt.updater.check_now(); + let updater = app.updates_rt.updater.as_mut().ok_or("Nightly updates are managed by ArtCraft Launcher")?; + updater.check_now(); app.ui.updates_open = true; Ok(serde_json::json!({"status": "checking"})) } @@ -49,12 +57,13 @@ pub(crate) fn check(_app: &mut PhotocraftApp, _ctx: &egui::Context, _params: Val #[cfg(not(target_arch = "wasm32"))] pub(crate) fn tick(app: &mut PhotocraftApp) { use craft::update::updater::Status; + let Some(updater) = app.updates_rt.updater.as_mut() else { return }; if app.session.prefs().general.automatically_check_updates { - app.updates_rt.updater.check_at_start(); + updater.check_at_start(); } else { - app.updates_rt.updater.read_last_update(); + updater.read_last_update(); } - if !app.updates_rt.outcome_announced && matches!(app.updates_rt.updater.status(), Status::Updated(_) | Status::InstallFailed(_)) { + if !app.updates_rt.outcome_announced && matches!(updater.status(), Status::Updated(_) | Status::InstallFailed(_)) { app.updates_rt.outcome_announced = true; app.ui.updates_open = true; } @@ -77,8 +86,14 @@ pub(crate) fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { // An update starts, and a ready one asks the app to close, only while no work is unsaved. let clean = !app.has_unsaved_work(); - app.updates_rt.updater.tick(ctx); - match app.updates_rt.updater.run(&mut app.framework.dialogs, clean) { + let action = match app.updates_rt.updater.as_mut() { + Some(updater) => { + updater.tick(ctx); + updater.run(&mut app.framework.dialogs, clean) + } + None => return, + }; + match action { Action::None => {} Action::OpenUrl(url) => { let _ = crate::links::open(app, ctx, &url); @@ -92,7 +107,7 @@ pub(crate) fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { // A cancelled result (the dialog withdrawn below) answers nothing. if let Some(choice) = app.framework.dialogs.take::().and_then(|result| result.ok()) { app.updates_rt.result_dialog = None; - let updater = &mut app.updates_rt.updater; + let Some(updater) = app.updates_rt.updater.as_mut() else { return }; match choice { CheckChoice::CheckNow | CheckChoice::CheckAgain => updater.check_now(), CheckChoice::RestartToUpdate => updater.restart_to_update(), @@ -105,7 +120,7 @@ pub(crate) fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { } // An available release shows in the updater's prompt instead of the result window. - let updater = &app.updates_rt.updater; + let Some(updater) = app.updates_rt.updater.as_ref() else { return }; let wanted = app.ui.updates_open && *updater.status() != Status::Idle && !updater.prompt_open(); let status = updater.status().clone(); let dialogs = &mut app.framework.dialogs; @@ -124,7 +139,7 @@ pub(crate) fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { /// The updater's installation progress or error line, for `ui.inspect`. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn status_message(app: &PhotocraftApp) -> Option { - app.updates_rt.updater.status_message() + app.updates_rt.updater.as_ref()?.status_message() } /// The web build has no updater, so no message. @@ -136,7 +151,8 @@ pub(crate) fn status_message(_app: &PhotocraftApp) -> Option { /// Offers `version` as an available release, as a check at start would, for the snapshot example. #[cfg(not(target_arch = "wasm32"))] pub fn preview_release(app: &mut PhotocraftApp, version: &str, url: &str) { - app.updates_rt.updater.offer(craft::update::Release { + let Some(updater) = app.updates_rt.updater.as_mut() else { return }; + updater.offer(craft::update::Release { tag: format!("v{version}"), version: craft::update::parse_version(version), name: format!("PhotoCraft {version}"), @@ -168,17 +184,17 @@ mod tests { Err("offline".into()) }); let mut app = app(); - app.updates_rt.updater = craft::update::updater::Updater::new(&crate::UPDATE_APP, photocraft_engine::build_info::VERSION).with_source(source); + app.updates_rt.updater = Some(craft::update::updater::Updater::new(&crate::UPDATE_APP, photocraft_engine::build_info::VERSION).with_source(source)); app.session.edit_prefs(|p| p.general.automatically_check_updates = false); tick(&mut app); assert!(checks.recv_timeout(Duration::from_millis(100)).is_err(), "no automatic check while the preference is off"); - assert_eq!(*app.updates_rt.updater.status(), craft::update::updater::Status::Idle); + assert_eq!(*app.updates_rt.updater.as_ref().unwrap().status(), craft::update::updater::Status::Idle); let ctx = app.ctx().clone(); menus::invoke(&mut app, &ctx, "help.checkForUpdates", serde_json::json!({})).unwrap(); assert!(app.ui.updates_open); - assert_ne!(*app.updates_rt.updater.status(), craft::update::updater::Status::Idle); + assert_ne!(*app.updates_rt.updater.as_ref().unwrap().status(), craft::update::updater::Status::Idle); assert!(checks.recv_timeout(Duration::from_secs(5)).is_ok(), "the manual check ran"); } @@ -203,3 +219,27 @@ mod tests { assert!(!app.ui.updates_open); } } + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod profile_tests { + use super::*; + use crate::os_window::LaunchIdentity; + #[test] + fn a_nightly_never_even_constructs_the_stable_updater() { + let calls = std::cell::Cell::new(0); + let nightly = stable_updater(LaunchIdentity::NightlyV1, || { + calls.set(calls.get() + 1); + 42 + }); + assert_eq!(nightly, None); + assert_eq!(calls.get(), 0, "Updater::new reads stable installed-version state"); + assert_eq!( + stable_updater(LaunchIdentity::Stable, || { + calls.set(calls.get() + 1); + 42 + }), + Some(42) + ); + assert_eq!(calls.get(), 1); + } +} diff --git a/packaging/linux/nightly.sh b/packaging/linux/nightly.sh new file mode 100644 index 0000000000..7b40025eda --- /dev/null +++ b/packaging/linux/nightly.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +# App-owned GUI-only nightly tar: no FUSE/AppImage, CLI, association or install hooks. +set -euo pipefail +ARCH= +while [[ $# -gt 0 ]]; do + case "$1" in + --arch) [[ $# -ge 2 ]] || { echo 'missing --arch value' >&2; exit 2; }; ARCH="$2"; shift 2 ;; + -h|--help) echo 'Usage: nightly.sh --arch x86_64'; exit 0 ;; + *) echo "unsupported nightly argument: $1" >&2; exit 2 ;; + esac +done +[[ "$ARCH" == x86_64 && "$(uname -s)" == Linux ]] || { echo 'only native Linux x86_64 nightly packaging is supported' >&2; exit 2; } +. "$(dirname "${BASH_SOURCE[0]}")/../nightly-common.sh" +nightly_init linux "$ARCH" x86_64-unknown-linux-gnu +OUTPUT="$DIST/photocraft-$VERSION-linux-x86_64-nightly.tar.gz" +[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || nightly_die 'refusing to replace an existing nightly archive' +nightly_build_gui +STAGE="$NIGHTLY_WORK/stage" +mkdir -p "$STAGE" +cp "$NIGHTLY_GUI" "$STAGE/photocraft" +chmod 755 "$STAGE/photocraft" +cp "$ROOT/assets/app-icon/photocraft-nightly.png" "$STAGE/photocraft-nightly.png" +nightly_copy_notices "$STAGE" +# The private mktemp cwd is the helper authority root, not a CLI path parent. +(cd "$NIGHTLY_WORK" && python3 "$ROOT/packaging/nightly-archive.py" linux stage archive.tar.gz) +nightly_publish_archive "$NIGHTLY_WORK/archive.tar.gz" "$OUTPUT" diff --git a/packaging/macos/nightly_plist.py b/packaging/macos/nightly_plist.py new file mode 100644 index 0000000000..bb2a101e8e --- /dev/null +++ b/packaging/macos/nightly_plist.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +"""Nightly metadata: run from a private owned build cwd with a staged template. + +All file arguments must stay beneath that cwd; this is not native/signing acceptance. +""" +import argparse +import datetime +import os +from pathlib import Path +import plistlib +import re +import sys + +# The shared helper location is fixed by this script, not by CLI file arguments. +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +from nightly_paths import OwnedBuildRoot + +MAX_TEMPLATE_BYTES = 256 * 1024 + +IDENTIFIER = "ai.storyteller.photocraft.nightly" +ASSOCIATIONS = ("CFBundleDocumentTypes", "CFBundleURLTypes", "UTExportedTypeDeclarations", "UTImportedTypeDeclarations") +VERSION = re.compile(r"([0-9]+\.[0-9]+\.[0-9]+)-nightly\.([0-9]{8})\.[0-9]+\.[0-9]+\.g([0-9a-f]{12})\Z") + + +def render(template: bytes, version: str, commit: str) -> bytes: + match = VERSION.fullmatch(version) + if not match or not re.fullmatch(r"[0-9a-f]{40}", commit) or match[3] != commit[:12]: + raise ValueError("exact prepared Nightly version and matching source commit are required") + datetime.datetime.strptime(match[2], "%Y%m%d") + data = plistlib.loads(template) + if not isinstance(data, dict) or data.get("CFBundlePackageType") != "APPL": + raise ValueError("expected the app-owned application plist template") + for key in ASSOCIATIONS: + data.pop(key, None) + data.update( + CFBundleDisplayName="PhotoCraft Nightly", + CFBundleName="PhotoCraft Nightly", + CFBundleIdentifier=IDENTIFIER, + CFBundleExecutable="PhotoCraft", + CFBundleIconFile="photocraft-nightly", + CFBundleShortVersionString=match[1], + CFBundleVersion=match[1], + PhotoCraftVersion=version, + PhotoCraftBuildCommit=commit, + ) + return plistlib.dumps(data, fmt=plistlib.FMT_XML, sort_keys=False) + + +def write_plist(template: Path, destination: Path, version: str, commit: str) -> None: + with OwnedBuildRoot() as root: + content = render(root.read_bytes(template, MAX_TEMPLATE_BYTES), version, commit) + with root.create(destination) as stream: + stream.write(content) + stream.flush() + os.fsync(stream.fileno()) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--template", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--version", required=True) + parser.add_argument("--source-commit", required=True) + args = parser.parse_args() + write_plist(args.template, args.output, args.version, args.source_commit) + + +if __name__ == "__main__": + main() diff --git a/packaging/macos/nightly_plist_tests.py b/packaging/macos/nightly_plist_tests.py new file mode 100644 index 0000000000..32f8e6d5ba --- /dev/null +++ b/packaging/macos/nightly_plist_tests.py @@ -0,0 +1,202 @@ +#!/usr/bin/env python3 +"""Generated metadata/sentinel fixtures; no native binary, signature, archive or network.""" +import importlib.util +import os +from pathlib import Path +import plistlib +import runpy +import sys +from unittest import mock +import tempfile +import unittest + +HERE = Path(__file__).resolve().parent +SPEC = importlib.util.spec_from_file_location("photo_nightly_plist", HERE / "nightly_plist.py") +POLICY = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(POLICY) +COMMIT = "a" * 40 +VERSION = "0.23.1-nightly.20261121.12345.1.g" + COMMIT[:12] + + +class NightlyMetadata(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.root = Path(self.directory.name).resolve() + previous = Path.cwd() + os.chdir(self.root) + self.addCleanup(os.chdir, previous) + self.template = self.root / "Info.plist.in" + self.original = (HERE / "Info.plist.in").read_bytes() + self.template.write_bytes(self.original) + self.output = self.root / "Info.plist" + + def test_nightly_transform_removes_associations_without_changing_stable_or_platform_metadata(self): + stable = plistlib.loads(self.original) + stable["CFBundleURLTypes"] = [{"CFBundleURLSchemes": ["generated-test-scheme"]}] + prepared = plistlib.dumps(stable) + self.template.write_bytes(prepared) + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + rendered = plistlib.loads(self.output.read_bytes()) + for key in POLICY.ASSOCIATIONS: + self.assertNotIn(key, rendered) + self.assertNotEqual(rendered["CFBundleIdentifier"], stable["CFBundleIdentifier"]) + self.assertEqual(rendered["CFBundleIdentifier"], "ai.storyteller.photocraft.nightly") + self.assertEqual(rendered["CFBundleExecutable"], "PhotoCraft") + self.assertEqual(rendered["PhotoCraftVersion"], VERSION) + self.assertEqual(rendered["PhotoCraftBuildCommit"], COMMIT) + self.assertTrue(VERSION.startswith(rendered["CFBundleVersion"] + "-nightly.")) + for key in ("LSMinimumSystemVersion", "CFBundleLocalizations", "NSHighResolutionCapable", "NSHumanReadableCopyright"): + self.assertEqual(rendered[key], stable[key]) + self.assertEqual(self.template.read_bytes(), prepared) + self.assertEqual((HERE / "Info.plist.in").read_bytes(), self.original) + + def test_bad_identity_or_template_refuses_before_creating_output(self): + for version, commit in (("0.23.1", COMMIT), (VERSION, "b" * 40), (VERSION, "not-a-commit"), (VERSION.replace("20261121", "20261399"), COMMIT)): + with self.subTest(version=version, commit=commit): + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, self.output, version, commit) + self.assertFalse(self.output.exists()) + self.assertEqual(self.template.read_bytes(), self.original) + self.template.write_bytes(plistlib.dumps({"CFBundlePackageType": "generated-not-an-app"})) + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + + def test_cli_writes_the_requested_identity_without_replacing_the_template(self): + helper = HERE / "nightly_plist.py" + argv = [str(helper), "--template", str(self.template), "--output", str(self.output), "--version", VERSION, "--source-commit", COMMIT] + with mock.patch.object(sys, "argv", argv): + runpy.run_path(str(helper), run_name="__main__") + result = plistlib.loads(self.output.read_bytes()) + self.assertEqual(result["PhotoCraftVersion"], VERSION) + self.assertEqual(result["PhotoCraftBuildCommit"], COMMIT) + self.assertEqual(self.template.read_bytes(), self.original) + + def test_template_alias_or_nonfile_refuses_before_output(self): + alias = self.root / "template-alias" + alias.symlink_to(self.template) + for template in (alias, self.root, self.root / "missing-template"): + with self.subTest(template=template), self.assertRaises(ValueError): + POLICY.write_plist(template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + self.assertEqual(self.template.read_bytes(), self.original) + + def test_failed_write_cleans_owned_output_but_preserves_a_replacement(self): + sentinel = b"generated replacement artifact" + for disposition in ("owned", "missing", "replacement"): + with self.subTest(disposition=disposition): + if self.output.exists(): + self.output.unlink() + + def fail_sync(_descriptor): + # macOS/Linux allow unlink of an open file: exercise the real + # cleanup ownership check, not a mocked inode comparison. + if disposition != "owned": + self.output.unlink() + if disposition == "replacement": + self.output.write_bytes(sentinel) + raise OSError("generated fsync failure") + + with mock.patch.object(POLICY.os, "fsync", side_effect=fail_sync), self.assertRaises(OSError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + if disposition == "replacement": + self.assertEqual(self.output.read_bytes(), sentinel) + else: + self.assertFalse(self.output.exists()) + self.assertEqual(self.template.read_bytes(), self.original) + + def test_exclusive_output_preserves_existing_bytes_and_symlink_targets(self): + sentinel = b"generated owned sentinel, not an existing app or user file" + self.output.write_bytes(sentinel) + with self.assertRaises(FileExistsError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertEqual(self.output.read_bytes(), sentinel) + self.output.unlink() + external = self.root / "sentinel" + external.write_bytes(sentinel) + self.output.symlink_to(external) + with self.assertRaisesRegex(ValueError, "symlinks or aliases"): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertEqual(external.read_bytes(), sentinel) + self.assertTrue(self.output.is_symlink()) + + + def test_template_outside_build_root_refuses_before_output(self): + with tempfile.TemporaryDirectory() as external: + template = Path(external) / "Info.plist.in" + template.write_bytes(self.original) + with self.assertRaises(ValueError): + POLICY.write_plist(template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + self.assertEqual(template.read_bytes(), self.original) + + def test_output_outside_build_root_refuses_before_write(self): + with tempfile.TemporaryDirectory() as external: + output = Path(external) / "Info.plist" + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, output, VERSION, COMMIT) + self.assertFalse(output.exists()) + + def test_parent_traversal_refuses_even_to_an_owned_sibling(self): + with tempfile.TemporaryDirectory(dir=self.root.parent) as external: + output = Path("..") / Path(external).name / "Info.plist" + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, output, VERSION, COMMIT) + self.assertFalse((Path(external) / "Info.plist").exists()) + + def test_symlinked_output_parent_refuses(self): + with tempfile.TemporaryDirectory() as external: + alias = self.root / "alias" + alias.symlink_to(external, target_is_directory=True) + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, alias / "Info.plist", VERSION, COMMIT) + self.assertFalse((Path(external) / "Info.plist").exists()) + + def test_template_read_is_bounded_before_output(self): + self.template.write_bytes(plistlib.dumps({"CFBundlePackageType": "APPL", "fixture": "x" * 300000})) + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + + def test_nonprivate_build_root_refuses(self): + self.root.chmod(0o755) + try: + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + finally: + self.root.chmod(0o700) + + + def test_output_keeps_normal_new_file_permissions_inside_private_root(self): + previous = os.umask(0o022) + try: + reference = self.root / "reference" + reference.write_bytes(b"generated ordinary output") + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + finally: + os.umask(previous) + self.assertEqual(self.output.stat().st_mode & 0o777, reference.stat().st_mode & 0o777) + + def test_open_parent_anchor_prevents_a_later_alias_redirect(self): + parent = self.root / "stage" + parent.mkdir() + retained = self.root / "retained-stage" + destination = parent / "Info.plist" + original = POLICY.OwnedBuildRoot._parent + with tempfile.TemporaryDirectory() as external: + def swap_after_parent_open(root, path): + descriptor, name = original(root, path) + if Path(path) == destination: + parent.rename(retained) + parent.symlink_to(external, target_is_directory=True) + return descriptor, name + with mock.patch.object(POLICY.OwnedBuildRoot, "_parent", swap_after_parent_open): + POLICY.write_plist(self.template, destination, VERSION, COMMIT) + self.assertFalse((Path(external) / "Info.plist").exists()) + self.assertEqual(plistlib.loads((retained / "Info.plist").read_bytes())["PhotoCraftVersion"], VERSION) + + +if __name__ == "__main__": + unittest.main() diff --git a/packaging/nightly-archive-tests.py b/packaging/nightly-archive-tests.py new file mode 100644 index 0000000000..c324516083 --- /dev/null +++ b/packaging/nightly-archive-tests.py @@ -0,0 +1,229 @@ +#!/usr/bin/env python3 +"""Synthetic app-owned archive/output tests; no native build or executable launch.""" +import gzip +import importlib.util +import os +import runpy +import sys +from unittest import mock +from pathlib import Path +import subprocess +import tarfile +import tempfile +import unittest + +HERE = Path(__file__).resolve().parent +SPEC = importlib.util.spec_from_file_location("photo_nightly_archive", HERE / "nightly-archive.py") +ARCHIVE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(ARCHIVE) + + +class ArchivePolicy(unittest.TestCase): + def setUp(self): + self.scratch = tempfile.TemporaryDirectory() + self.addCleanup(self.scratch.cleanup) + self.root = Path(self.scratch.name).resolve() + previous = Path.cwd() + os.chdir(self.root) + self.addCleanup(os.chdir, previous) + self.stage = self.root / "stage" + self.stage.mkdir() + self.output = self.root / "nightly.tar.gz" + self.required = {"photocraft", "photocraft-nightly.png", "README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md"} + for name in self.required: + (self.stage / name).write_bytes(b"generated fixture: " + name.encode()) + (self.stage / "photocraft").chmod(0o755) + + def test_flat_regular_ustar_with_all_notices(self): + (self.stage / "OFL-Font.txt").write_text("generated fixture license", encoding="utf-8") + ARCHIVE.linux_archive(self.stage, self.output) + with tarfile.open(self.output) as archive: + self.assertEqual({m.name for m in archive}, self.required | {"OFL-Font.txt"}) + self.assertTrue(all(m.isfile() and not m.pax_headers for m in archive)) + self.assertEqual(archive.extractfile("photocraft").read(), (self.stage / "photocraft").read_bytes()) + with gzip.open(self.output, "rb") as stream: + while (header := stream.read(512)) != bytes(512): + self.assertEqual(len(header), 512) + self.assertIn(header[156:157], {b"0", b"\0"}) + self.assertEqual(header[257:263], b"ustar\0") + size = int(header[124:136].rstrip(b"\0 ").lstrip(b" ") or b"0", 8) + stream.read(((size + 511) // 512) * 512) + + def test_each_required_member_is_required_before_output(self): + for name in self.required: + with self.subTest(name=name): + content = (self.stage / name).read_bytes() + (self.stage / name).unlink() + with self.assertRaisesRegex(ValueError, "required"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + (self.stage / name).write_bytes(content) + + def test_unexpected_cli_portable_or_installer_member_refuses(self): + for name in ["photocraft-cli", "portable.txt", "photocraft.desktop"]: + with self.subTest(name=name): + bad = self.stage / name + bad.write_bytes(b"generated fixture") + with self.assertRaisesRegex(ValueError, "unexpected"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + bad.unlink() + + def test_symlink_refuses_before_output(self): + icon = self.stage / "photocraft-nightly.png" + icon.unlink() + icon.symlink_to(self.stage / "README.md") + with self.assertRaisesRegex(ValueError, "regular file|symlinks or aliases"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_directory_refuses_before_output(self): + icon = self.stage / "photocraft-nightly.png" + icon.unlink() + icon.mkdir() + with self.assertRaisesRegex(ValueError, "regular file"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_long_notice_refuses_before_output(self): + (self.stage / ("OFL-" + "x" * 100 + ".txt")).write_bytes(b"fixture") + with self.assertRaisesRegex(ValueError, "short regular"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_case_colliding_notices_refuse_before_output(self): + for name in ["OFL-Font.txt", "OFL-font.txt"]: + (self.stage / name).write_bytes(b"fixture") + with self.assertRaisesRegex(ValueError, "case-colliding"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_cli_dispatches_only_the_supported_archive_kind(self): + helper = HERE / "nightly-archive.py" + with mock.patch.object(sys, "argv", [str(helper), "linux", str(self.stage), str(self.output)]): + runpy.run_path(str(helper), run_name="__main__") + with tarfile.open(self.output) as archive: + self.assertEqual({member.name for member in archive}, self.required) + refused = self.root / "refused.tar.gz" + for args in ([str(helper)], [str(helper), "unknown", str(self.stage), str(refused)]): + with self.subTest(args=args), mock.patch.object(sys, "argv", args): + with self.assertRaises(SystemExit): + runpy.run_path(str(helper), run_name="__main__") + self.assertFalse(refused.exists()) + + def test_existing_archive_is_unchanged(self): + self.output.write_bytes(b"owned earlier artifact") + with self.assertRaises(FileExistsError): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertEqual(self.output.read_bytes(), b"owned earlier artifact") + + + def test_archive_output_outside_build_root_refuses(self): + with tempfile.TemporaryDirectory() as external: + output = Path(external) / "nightly.tar.gz" + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, output) + self.assertFalse(output.exists()) + + def test_archive_stage_outside_build_root_refuses(self): + with tempfile.TemporaryDirectory() as external: + stage = Path(external) + for name in self.required: + (stage / name).write_bytes(b"generated external fixture") + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(stage, self.output) + self.assertFalse(self.output.exists()) + + def test_archive_stage_alias_refuses(self): + alias = self.root / "stage-alias" + alias.symlink_to(self.stage, target_is_directory=True) + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(alias, self.output) + self.assertFalse(self.output.exists()) + + def test_archive_output_parent_alias_refuses(self): + with tempfile.TemporaryDirectory() as external: + alias = self.root / "output-alias" + alias.symlink_to(external, target_is_directory=True) + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, alias / "nightly.tar.gz") + self.assertFalse((Path(external) / "nightly.tar.gz").exists()) + + def test_archive_parent_traversal_refuses(self): + with tempfile.TemporaryDirectory(dir=self.root.parent) as external: + output = Path("..") / Path(external).name / "nightly.tar.gz" + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, output) + self.assertFalse((Path(external) / "nightly.tar.gz").exists()) + + def test_nonflat_member_name_refuses(self): + stage_root = os.path.realpath(self.stage) + with open(self.stage / "README.md", "rb") as incoming: + for bad in ("../escape", "/absolute", "nested/name", "x/../README.md", "", ".", ".."): + with self.subTest(name=bad), self.assertRaises(ValueError): + ARCHIVE.member_info(stage_root, bad, incoming) + + def test_member_header_matches_what_gettarinfo_records(self): + stage_root = os.path.realpath(self.stage) + for name in sorted(self.required): + with self.subTest(name=name), open(self.stage / name, "rb") as incoming: + ours = ARCHIVE.member_info(stage_root, name, incoming) + with tarfile.open(fileobj=__import__("io").BytesIO(), mode="w") as reference: + theirs = reference.gettarinfo(fileobj=incoming, arcname=name) + self.assertEqual(ours.get_info(), theirs.get_info()) + + def test_member_read_budget_refuses_before_output(self): + (self.stage / "OFL-Large.txt").write_bytes(b"x" * 65) + with mock.patch.object(ARCHIVE, "MAX_MEMBER_BYTES", 64, create=True): + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + + def test_member_growth_is_rechecked_before_copy_and_output_is_cleaned(self): + growing = self.stage / "OFL-Growing.txt" + growing.write_bytes(b"x" * 32) + original = ARCHIVE.member_info + + def grow_before_stat(stage_root, name, incoming): + if name == growing.name: + growing.write_bytes(b"x" * 65) + return original(stage_root, name, incoming) + + with mock.patch.object(ARCHIVE, "MAX_MEMBER_BYTES", 64), \ + mock.patch.object(ARCHIVE, "member_info", grow_before_stat): + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + +class ExclusiveOutput(unittest.TestCase): + def setUp(self): + self.scratch = tempfile.TemporaryDirectory() + self.addCleanup(self.scratch.cleanup) + self.root = Path(self.scratch.name) + self.source = self.root / "input archive" + self.output = self.root / "final archive" + self.source.write_bytes(b"generated archive fixture" * 1024) + + def publish(self): + return subprocess.run(["bash", "-c", 'set -euo pipefail; source "$1"; nightly_publish_archive "$2" "$3"', "test", str(HERE / "nightly-common.sh"), str(self.source), str(self.output)], capture_output=True, text=True, timeout=15) + + def test_success_copies_exact_bytes(self): + result = self.publish() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.output.read_bytes(), self.source.read_bytes()) + + def test_existing_output_is_never_replaced(self): + self.output.write_bytes(b"existing artifact") + self.assertNotEqual(self.publish().returncode, 0) + self.assertEqual(self.output.read_bytes(), b"existing artifact") + + def test_missing_source_does_not_leave_a_fake_empty_artifact(self): + self.source.unlink() + self.assertNotEqual(self.publish().returncode, 0) + self.assertFalse(self.output.exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/packaging/nightly-archive.py b/packaging/nightly-archive.py new file mode 100644 index 0000000000..8a58119462 --- /dev/null +++ b/packaging/nightly-archive.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +"""Flat Linux archive policy, invoked from its private owned build cwd. + +The stage and archive must both remain under that independently chosen root. +No native build, platform signing, or malicious-same-UID sandbox is implied. +""" +import grp +import gzip +import os +import pathlib +import pwd +import re +import stat +import sys +import tarfile + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +from nightly_paths import OwnedBuildRoot + +APP_DOCS = {"README.md", "LICENSE", "LICENSE-MIT", "LICENSE-APACHE", "COPYRIGHT", "NOTICE", "ATTRIBUTION.md"} +MAX_MEMBER_BYTES = 512 * 1024 * 1024 +MAX_TOTAL_BYTES = 1024 * 1024 * 1024 +MAX_MEMBERS = 128 + + +def notice(name): + return name in APP_DOCS or re.fullmatch(r"OFL-[A-Za-z0-9_.-]+\.txt", name) is not None + + +def checked_entries(root, stage): + entries = sorted(root.children(stage, MAX_MEMBERS), key=lambda item: item.name) + folded = set() + total = 0 + for entry in entries: + name = entry.name + if name not in {"photocraft", "photocraft-nightly.png"} and not notice(name): + raise ValueError(f"unexpected nightly member: {name}") + if len(name.encode("utf-8")) > 100: + raise ValueError(f"nightly member must be a short regular file: {name}") + with root.reader(entry, MAX_MEMBER_BYTES) as stream: + total += os.fstat(stream.fileno()).st_size + if total > MAX_TOTAL_BYTES: + raise ValueError("nightly stage exceeds its read bound") + if name.casefold() in folded: + raise ValueError(f"case-colliding nightly member: {name}") + folded.add(name.casefold()) + required = {"photocraft", "photocraft-nightly.png", "README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md"} + if not required.issubset({item.name for item in entries}): + raise ValueError("required GUI/icon/notices missing") + return entries + + +def member_info(stage_root, name, incoming): + """Header for one stage file, built from the file this run opened rather than from the archive. + + Members are flat names that resolve directly inside the stage they came from. + """ + if os.path.isabs(name) or os.path.basename(name) != name or name in ("", ".", ".."): + raise ValueError(f"nightly member name must be a flat file name: {name}") + destination = os.path.realpath(os.path.join(stage_root, name)) + if not destination.startswith(stage_root + os.sep) or os.path.dirname(destination) != stage_root: + raise ValueError(f"nightly member resolves outside its stage: {name}") + status = os.fstat(incoming.fileno()) + if not stat.S_ISREG(status.st_mode): + raise ValueError(f"nightly member must be a regular file: {name}") + # The same fields TarFile.gettarinfo records for a regular file. + info = tarfile.TarInfo(os.path.basename(destination)) + info.type = tarfile.REGTYPE + info.mode = stat.S_IMODE(status.st_mode) + info.uid, info.gid = status.st_uid, status.st_gid + info.size = status.st_size + info.mtime = status.st_mtime + try: + info.uname = pwd.getpwuid(status.st_uid).pw_name + except KeyError: + pass + try: + info.gname = grp.getgrgid(status.st_gid).gr_name + except KeyError: + pass + return info + + +def verify_headers(root, output): + # Bounded ordinary headers, not a transparent PAX/GNU-normalizing reader. + total = 0 + count = 0 + with root.reader(output, MAX_TOTAL_BYTES) as incoming, gzip.GzipFile(fileobj=incoming) as stream: + while True: + header = stream.read(512) + if header == b"\0" * 512: + break + if len(header) != 512 or header[156:157] not in {b"0", b"\0"}: + raise ValueError("non-ordinary TAR record was emitted") + size = int(header[124:136].rstrip(b"\0 ").lstrip(b" ") or b"0", 8) + count += 1 + total += size + if count > MAX_MEMBERS or size > MAX_MEMBER_BYTES or total > MAX_TOTAL_BYTES: + raise ValueError("archive exceeds its bounded member budget") + remaining = ((size + 511) // 512) * 512 + while remaining: + chunk = stream.read(min(remaining, 1024 * 1024)) + if not chunk: + raise ValueError("truncated TAR member") + remaining -= len(chunk) + + +def linux_archive(stage, output): + with OwnedBuildRoot() as root: + entries = checked_entries(root, stage) + stage_root = os.path.realpath(os.path.join(root.directory, stage)) + total = 0 + with root.create(output) as outgoing: + with tarfile.open(fileobj=outgoing, mode="w:gz", format=tarfile.USTAR_FORMAT) as archive: + for entry in entries: + with root.reader(entry, MAX_MEMBER_BYTES) as incoming: + info = member_info(stage_root, entry.name, incoming) + total += info.size + if info.size > MAX_MEMBER_BYTES or total > MAX_TOTAL_BYTES: + raise ValueError("nightly stage grew beyond its read bound") + archive.addfile(info, incoming) + outgoing.flush() + os.fsync(outgoing.fileno()) + verify_headers(root, output) + + +if __name__ == "__main__": + if len(sys.argv) != 4 or sys.argv[1] != "linux": + raise SystemExit("usage: nightly-archive.py linux STAGE OUTPUT (from owned private build cwd)") + linux_archive(pathlib.Path(sys.argv[2]), pathlib.Path(sys.argv[3])) diff --git a/packaging/nightly-common.sh b/packaging/nightly-common.sh new file mode 100644 index 0000000000..8f9514169f --- /dev/null +++ b/packaging/nightly-common.sh @@ -0,0 +1,72 @@ +# shellcheck shell=bash +# Shared setup for app-owned native nightly archives; stable packaging does not source this file. + +nightly_die() { printf 'error: %s\n' "$*" >&2; exit 2; } + +nightly_init() { + local os="$1" arch="$2" target="$3" date_digits + [[ "${PHOTOCRAFT_BUILD_CHANNEL:-}" == nightly-v1 ]] || nightly_die 'PHOTOCRAFT_BUILD_CHANNEL must be nightly-v1' + [[ "${PHOTOCRAFT_VERSION:-}" =~ ^[0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[0-9]+\.[0-9]+\.g[0-9a-f]{12}$ ]] || nightly_die 'an exact prepared nightly version is required' + [[ "${PHOTOCRAFT_BUILD_SHA:-}" =~ ^[0-9a-f]{40}$ ]] || nightly_die 'an exact source commit is required' + [[ "${PHOTOCRAFT_VERSION##*.g}" == "${PHOTOCRAFT_BUILD_SHA:0:12}" ]] || nightly_die 'version/source commit mismatch' + [[ "${PHOTOCRAFT_BUILD_DATE:-}" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] || nightly_die 'the original run-created UTC date is required' + date_digits="${PHOTOCRAFT_VERSION#*-nightly.}" + date_digits="${date_digits%%.*}" + [[ "${PHOTOCRAFT_BUILD_DATE//-/}" == "$date_digits" ]] || nightly_die 'version/original-run date mismatch' + [[ "${CARGO_TARGET_DIR:-}" == /* && "$CARGO_TARGET_DIR" != / ]] || nightly_die 'an absolute owned CARGO_TARGET_DIR base is required' + [[ "${DIST:-}" == /* && "$DIST" != / ]] || nightly_die 'an absolute DIST output directory is required' + [[ "/$CARGO_TARGET_DIR/" != *'/../'* && "/$DIST/" != *'/../'* ]] || nightly_die 'output paths must not contain parent traversal' + ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + [[ "$(git -C "$ROOT" rev-parse HEAD)" == "$PHOTOCRAFT_BUILD_SHA" ]] || nightly_die 'prepared source is not the checked-out commit' + [[ -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'nightly packaging requires the frozen clean source' + if [[ -n "${CRAFT_FONTS_DIR:-}" && ! -d "$CRAFT_FONTS_DIR/fonts" ]]; then + nightly_die 'declared CRAFT_FONTS_DIR has no fonts directory' + fi + # env.sh retains the established notice copier. Required values above prohibit its stable fallbacks. + . "$ROOT/packaging/env.sh" + export CARGO_TARGET_DIR="$CARGO_TARGET_DIR/nightly-v1/$os-$arch" + NIGHTLY_RUST_TARGET="$target" + mkdir -p "$CARGO_TARGET_DIR" + NIGHTLY_WORK="$(mktemp -d "$CARGO_TARGET_DIR/nightly-package.XXXXXX")" + trap 'rm -rf -- "$NIGHTLY_WORK"' EXIT +} + +nightly_build_gui() { + (cd "$ROOT" && PHOTOCRAFT_OVERRIDE_VERSION="$VERSION" cargo build --release --locked -p photocraft --features heif --target "$NIGHTLY_RUST_TARGET") + NIGHTLY_GUI="$CARGO_TARGET_DIR/$NIGHTLY_RUST_TARGET/release/photocraft" + [[ -f "$NIGHTLY_GUI" && ! -L "$NIGHTLY_GUI" ]] || nightly_die 'the owned GUI build did not produce a regular executable' + local actual + actual="$("$NIGHTLY_GUI" --version)" || nightly_die 'side-effect-free nightly version verification failed' + [[ "$actual" == "PhotoCraft $VERSION (nightly-v1)" ]] || nightly_die 'the built version/flavor is not the prepared identity' + [[ "$(git -C "$ROOT" rev-parse HEAD)" == "$PHOTOCRAFT_BUILD_SHA" && -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'source changed during the build' +} + +nightly_copy_notices() { + local destination="$1" required + for required in README.md LICENSE-MIT LICENSE-APACHE NOTICE ATTRIBUTION.md; do + [[ -f "$ROOT/$required" && ! -L "$ROOT/$required" ]] || nightly_die "missing regular app notice: $required" + done + copy_docs "$destination" +} + +nightly_publish_archive() { + # Exclusive creation: never replace an existing artifact, even if another writer raced the preflight. + python3 - "$1" "$2" <<'PY' +import os, shutil, sys +source, destination = sys.argv[1:] +created = False +try: + # Open the input first: a missing source must not leave an empty final artifact. + with open(source, 'rb') as incoming: + with open(destination, 'xb') as output: + created = True + shutil.copyfileobj(incoming, output, length=1024 * 1024) + output.flush() + os.fsync(output.fileno()) +except BaseException: + if created: + os.unlink(destination) + raise +PY + printf 'Nightly artifact: %s\n' "$2" +} diff --git a/packaging/nightly-tests.py b/packaging/nightly-tests.py new file mode 100644 index 0000000000..5d410795af --- /dev/null +++ b/packaging/nightly-tests.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python3 +"""Run the existing synthetic packaging suites together; no app build or signing.""" +import importlib.util +from pathlib import Path +import unittest + + +def main() -> int: + here = Path(__file__).resolve().parent + suite = unittest.TestSuite() + for name, relative in ( + ("photo_archive_suite", "nightly-archive-tests.py"), + ("photo_plist_suite", "macos/nightly_plist_tests.py"), + ): + spec = importlib.util.spec_from_file_location(name, here / relative) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + suite.addTests(unittest.defaultTestLoader.loadTestsFromModule(module)) + return 0 if unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful() else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packaging/nightly_paths.py b/packaging/nightly_paths.py new file mode 100644 index 0000000000..792198589e --- /dev/null +++ b/packaging/nightly_paths.py @@ -0,0 +1,139 @@ +"""POSIX packaging I/O rooted at a caller-owned private working directory. + +The build launcher chooses cwd independently of file arguments (Linux uses its +mktemp directory). This is not a sandbox against root or a malicious same-UID +caller, and inode-check/unlink cleanup is not an atomic replacement-race primitive. +""" +import contextlib +import os +from pathlib import Path +import stat + + +def _component(name): + # A descriptor-relative open must name exactly one entry in its directory. + if not name or name in (".", "..") or os.path.basename(name) != name: + raise ValueError("build path components must be single names") + return os.path.basename(name) + + +class OwnedBuildRoot: + def __enter__(self): + self.directory = Path.cwd() + self.fd = os.open(".", os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + info = os.fstat(self.fd) + if info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) & 0o077: + os.close(self.fd) + raise ValueError("packaging cwd must be an owned private build directory") + return self + + def __exit__(self, *_error): + os.close(self.fd) + + def _relative(self, path): + path = Path(path) + try: + relative = path.relative_to(self.directory) if path.is_absolute() else path + except ValueError as error: + raise ValueError("path is outside the owned build directory") from error + if not relative.parts or ".." in relative.parts: + raise ValueError("empty or parent-traversing build path") + # Check an independently selected root, never the supplied filename's parent. + try: + parent = (self.directory / relative).parent.resolve(strict=True) + except OSError as error: + raise ValueError("build path parent must exist") from error + if not parent.is_relative_to(self.directory): + raise ValueError("resolved path escapes the owned build directory") + return relative + + def _checked_parts(self, path): + relative = self._relative(path) + root = os.path.realpath(self.directory) + lexical = os.path.join(root, *relative.parts) + target = os.path.realpath(lexical) + if target == root or os.path.commonpath([root, target]) != root: + raise ValueError("resolved path escapes the owned build directory") + if target != lexical: + raise ValueError("build path must not pass through symlinks or aliases") + return [_component(part) for part in os.path.relpath(target, root).split(os.sep)] + + def _parent(self, path): + parts = self._checked_parts(path) + current = os.dup(self.fd) + try: + for part in parts[:-1]: + next_fd = os.open(_component(part), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=current) + os.close(current) + current = next_fd + return current, parts[-1] + except OSError as error: + os.close(current) + raise ValueError("build path parents must be non-symlink directories") from error + + @contextlib.contextmanager + def reader(self, path, limit): + parent, name = self._parent(path) + try: + try: + descriptor = os.open(_component(name), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent) + except OSError as error: + raise ValueError("build input must be a regular file without aliases") from error + finally: + os.close(parent) + info = os.fstat(descriptor) + if not stat.S_ISREG(info.st_mode) or info.st_size > limit: + os.close(descriptor) + raise ValueError("build input must be a regular file within its read bound") + with os.fdopen(descriptor, "rb") as stream: + yield stream + + def read_bytes(self, path, limit): + with self.reader(path, limit) as stream: + data = stream.read(limit + 1) + if len(data) > limit: + raise ValueError("build input grew beyond its read bound") + return data + + def children(self, path, limit): + relative = self._relative(path) + parent, name = self._parent(path) + try: + try: + descriptor = os.open(_component(name), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent) + except OSError as error: + raise ValueError("build stage must be a non-symlink directory") from error + finally: + os.close(parent) + try: + entries = [] + with os.scandir(descriptor) as iterator: + for entry in iterator: + if len(entries) >= limit: + raise ValueError("too many build stage members") + entries.append(self.directory / relative / entry.name) + return entries + finally: + os.close(descriptor) + + @contextlib.contextmanager + def create(self, path): + parent, name = self._parent(path) + name = _component(name) + try: + descriptor = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o666, dir_fd=parent) + info = os.fstat(descriptor) + identity = (info.st_dev, info.st_ino) + try: + with os.fdopen(descriptor, "wb") as stream: + yield stream + except BaseException: + try: + current = os.stat(name, dir_fd=parent, follow_symlinks=False) + if (current.st_dev, current.st_ino) == identity: + os.unlink(_component(name), dir_fd=parent) + except FileNotFoundError: + pass + raise + finally: + os.close(parent) diff --git a/packaging/windows/README.md b/packaging/windows/README.md index 63025f400c..19fefe307b 100644 --- a/packaging/windows/README.md +++ b/packaging/windows/README.md @@ -1,3 +1,30 @@ # Windows packaging See [installation policy checks](INSTALLATION.md) for the installer scope and path gates. + +## Nightly build and signing boundary + +`package.ps1 -Arch x64 -Nightly -BuildOnly` is for the secret-free compilation job. +It refuses signing credential variables and builds the GUI only, without CLI, +portable marker, installer or associations. Its `*-nightly.unsigned.zip` is an +internal intermediate, not the final feed artifact. There is no unsigned +publication switch. + +The separate trusted producer signing job safely unpacks that new intermediate, +checks its exact identity/inventory, then invokes the existing backend: + +```powershell +pwsh packaging/windows/sign.ps1 -Required -CheckOnly +pwsh packaging/windows/sign.ps1 -Required -Files /photocraft.exe +``` + +Missing or partial configuration fails. `-Required` verifies Authenticode and +a signer certificate after the existing signtool verification. Stable local +packaging keeps its existing optional-signing policy. The producer independently +verifies the final signature, PE identity and inventory before archiving under +the normal feed filename, and refuses to overwrite prepared outputs. It never +executes the payload in the signing step. Real keys belong only to that step, +not compilation. These interfaces do not configure or grant access to keys. + +The signing-policy fixtures use generated dummy values and a mocked compiler +boundary; they do not prove real certificate signing or release readiness. diff --git a/packaging/windows/nightly-package-tests.ps1 b/packaging/windows/nightly-package-tests.ps1 new file mode 100644 index 0000000000..f5768849ec --- /dev/null +++ b/packaging/windows/nightly-package-tests.ps1 @@ -0,0 +1,95 @@ +param([Parameter(Mandatory=$true)][string] $FixtureRoot) +. (Join-Path $PSScriptRoot 'nightly.ps1') -FunctionsOnly +function Assert([bool] $Value, [string] $Message) { if (-not $Value) { throw $Message } } +$spec = Get-NightlyArchiveSpec '0.23.1-nightly.20261120.17.1.gabcdef012345' 'x64' +Assert ($spec.Archive -eq 'photocraft-0.23.1-nightly.20261120.17.1.gabcdef012345-windows-x86_64-nightly.zip') 'wrong nightly artifact name' +Assert ($spec.Executables.Count -eq 1 -and $spec.Executables[0] -eq 'photocraft.exe') 'nightly must not ship the unqualified CLI' +Assert ($spec.AppId -eq 'ai.storyteller.photocraft.nightly-v1') 'nightly identity is not distinct' +foreach ($arch in @('x86', 'arm64')) { + $refused = $false + try { Get-NightlyArchiveSpec '0.23.1' $arch | Out-Null } catch { $refused = $true } + Assert $refused 'unsupported target was accepted' +} +foreach ($bad in @('', '0.23.1', '../other', '0.23.1/elsewhere')) { + $refused = $false + try { Get-NightlyArchiveSpec $bad 'x64' | Out-Null } catch { $refused = $true } + Assert $refused 'unsafe artifact version was accepted' +} +Assert-NightlyFlavor 'PhotoCraft Nightly' 'PhotoCraft 0.23.1-nightly.20261120.17.1.gabcdef012345 (nightly-v1)' '0.23.1-nightly.20261120.17.1.gabcdef012345' +foreach ($pair in @(@('PhotoCraft', 'PhotoCraft 0.23.1 (nightly-v1)'), @('PhotoCraft Nightly', 'PhotoCraft 0.23.1'))) { + $refused = $false + try { Assert-NightlyFlavor $pair[0] $pair[1] '0.23.1-nightly.20261120.17.1.gabcdef012345' } catch { $refused = $true } + Assert $refused 'stable or mismatched build flavor was accepted' +} +$sha = 'abcdef0123456789abcdef0123456789abcdef01' +$good = '0.23.1-nightly.20261120.17.1.gabcdef012345' +Assert-NightlySource $good $sha '2026-11-20' $sha '' +$cases = @( + @('missing commit', $good, '', '2026-11-20', $sha, ''), + @('short commit', $good, 'abcdef012345', '2026-11-20', $sha, ''), + @('uppercase commit', $good, $sha.ToUpper(), '2026-11-20', $sha.ToUpper(), ''), + @('version names another commit', '0.23.1-nightly.20261120.17.1.g000000000000', $sha, '2026-11-20', $sha, ''), + @('missing date', $good, $sha, '', $sha, ''), + @('date differs from version', $good, $sha, '2026-11-21', $sha, ''), + @('other commit checked out', $good, $sha, '2026-11-20', ('0' * 40), ''), + @('dirty tree', $good, $sha, '2026-11-20', $sha, ' M apps/photocraft/src/main.rs') +) +foreach ($case in $cases) { + $refused = $false + try { Assert-NightlySource $case[1] $case[2] $case[3] $case[4] $case[5] } catch { $refused = $true } + Assert $refused "source identity accepted: $($case[0])" +} +Write-Output 'nightly packaging spec, target/version refusal, source identity and flavor-binding tests passed' + +# Exercise the SAME production notice copier with the real repository layout, then inspect a ZIP. +if (-not $FixtureRoot -or -not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'supply an owned absolute -FixtureRoot for the notices/ZIP regression' } +$testRoot = Join-Path $FixtureRoot ("nightly-notices-" + [Guid]::NewGuid().ToString('N')) +try { + $repo = Join-Path $testRoot 'app' + $fontRepo = Join-Path $testRoot 'craft-fonts' + $family = Join-Path $fontRepo 'fonts\ExampleFamily' + $stage = Join-Path $testRoot 'stage' + New-Item -ItemType Directory -Force -Path $repo, $family, $stage | Out-Null + $rootNames = @('README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') + foreach ($name in $rootNames) { Set-Content -LiteralPath (Join-Path $repo $name) -Value "root-notice-$name" } + Set-Content -LiteralPath (Join-Path $family 'OFL.txt') -Value 'font-notice-example' + Copy-NightlyNotices $repo $fontRepo $stage + foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) { + Assert (Test-Path -LiteralPath (Join-Path $stage $name)) "missing staged notice $name" + } + $zip = Join-Path $testRoot 'notices.zip' + Compress-Archive -Path (Join-Path $stage '*') -DestinationPath $zip + $archive = [IO.Compression.ZipFile]::OpenRead($zip) + try { + $names = @($archive.Entries | ForEach-Object { $_.FullName }) + foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) { Assert ($name -in $names) "missing archived notice $name" } + foreach ($forbidden in @('portable.txt', 'photocraft-cli.exe')) { Assert ($forbidden -notin $names) "unexpected payload $forbidden" } + $entry = $archive.GetEntry('OFL-ExampleFamily.txt') + $reader = [IO.StreamReader]::new($entry.Open()) + try { Assert ($reader.ReadToEnd().Contains('font-notice-example')) 'wrong font license bytes in ZIP' } finally { $reader.Dispose() } + } finally { $archive.Dispose() } +} finally { + if (Test-Path -LiteralPath $testRoot) { Remove-Item -LiteralPath $testRoot -Recurse -Force } +} +Write-Output 'nightly mock-repository root and font notices are present in stage and ZIP' + +# The source state comes from git itself: the checked-out commit, then a dirty tree. +$gitRoot = Join-Path $FixtureRoot ("nightly-source-" + [Guid]::NewGuid().ToString('N')) +try { + New-Item -ItemType Directory -Force -Path $gitRoot | Out-Null + git -C $gitRoot init -q; git -C $gitRoot -c user.name=fixture -c user.email=fixture@invalid commit -q --allow-empty -m fixture + if ($LASTEXITCODE -ne 0) { throw 'cannot create the git fixture' } + $head = (git -C $gitRoot rev-parse HEAD).Trim() + $state = Get-NightlySourceState $gitRoot + Assert ($state.Head -ceq $head -and -not $state.Status) 'clean checkout not reported as clean at HEAD' + $version = '0.23.1-nightly.20261120.17.1.g' + $head.Substring(0, 12) + Assert-NightlySource $version $head '2026-11-20' $state.Head $state.Status + Set-Content -LiteralPath (Join-Path $gitRoot 'untracked.txt') -Value 'dirty' + $state = Get-NightlySourceState $gitRoot + $refused = $false + try { Assert-NightlySource $version $head '2026-11-20' $state.Head $state.Status } catch { $refused = $true } + Assert $refused 'a dirty checkout was accepted' +} finally { + if (Test-Path -LiteralPath $gitRoot) { Remove-Item -LiteralPath $gitRoot -Recurse -Force } +} +Write-Output 'nightly source state is read from git and a dirty checkout is refused' diff --git a/packaging/windows/nightly-signing-tests.ps1 b/packaging/windows/nightly-signing-tests.ps1 new file mode 100644 index 0000000000..f826728e44 --- /dev/null +++ b/packaging/windows/nightly-signing-tests.ps1 @@ -0,0 +1,83 @@ +param( + [Parameter(Mandatory=$true)][string] $FixtureRoot, + [string] $PackagingRoot = $PSScriptRoot, + [switch] $PhaseGuardOnly +) +$ErrorActionPreference = 'Stop' +. (Join-Path $PackagingRoot 'nightly.ps1') -FunctionsOnly +$sign = Join-Path $PackagingRoot 'sign.ps1' +$names = @('WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_TENANT_ID','AZURE_CLIENT_ID','AZURE_CLIENT_SECRET','AZURE_SIGNING_ENDPOINT','AZURE_SIGNING_ACCOUNT','AZURE_CERT_PROFILE') +function Clear-SigningFixtures { foreach ($name in $names) { [Environment]::SetEnvironmentVariable($name, $null) } } +function Assert-Policy([bool] $Value, [string] $Message) { if (-not $Value) { throw $Message } } +function Invoke-Refusal([scriptblock] $Operation, [string] $Message) { + $errorText = '' + try { & $Operation | Out-Null } catch { $errorText = $_.Exception.Message } + Assert-Policy ($errorText.Contains($Message)) "expected refusal: $Message; got: $errorText" +} +function global:cargo { $global:SigningFixtureCargoCalls++; throw 'FIXTURE_COMPILER_BOUNDARY' } +function global:Invoke-WebRequest { throw 'fixture must not perform signing downloads' } +$global:SigningFixtureCargoCalls = 0 +if (-not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'use an owned absolute FixtureRoot' } +$root = Join-Path $FixtureRoot ('signing-policy-' + [Guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Path $root | Out-Null +$version = '0.23.1-nightly.20261121.12345.1.gaaaaaaaaaaaa' +$env:PHOTOCRAFT_VERSION = $version +function Invoke-Build([switch] $BuildOnly) { + $arguments = @{Arch='x64';Version=$version;Target='x86_64-pc-windows-msvc';TargetDir=$root;Dist=(Join-Path $root 'dist')} + if ($BuildOnly) { $arguments.BuildOnly = $true } + & (Join-Path $PackagingRoot 'nightly.ps1') @arguments +} +try { + Clear-SigningFixtures + Invoke-Refusal { Invoke-Build } 'requires -BuildOnly' + Assert-Policy ($global:SigningFixtureCargoCalls -eq 0) 'default mode invoked Cargo' + Write-Output 'PASS: explicit-build-phase-required' + if ($PhaseGuardOnly) { return } + + foreach ($name in @('WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_CLIENT_SECRET')) { + Clear-SigningFixtures + [Environment]::SetEnvironmentVariable($name, 'generated-fixture-not-a-secret') + Invoke-Refusal { Invoke-Build -BuildOnly } 'Compilation must not receive signing credentials' + Assert-Policy ($global:SigningFixtureCargoCalls -eq 0) 'key-bearing compilation reached Cargo' + } + Write-Output 'PASS: credentials-rejected-before-compilation' + + Clear-SigningFixtures + Invoke-Refusal { Invoke-Build -BuildOnly } 'FIXTURE_COMPILER_BOUNDARY' + Assert-Policy ($global:SigningFixtureCargoCalls -eq 1) 'clean compilation did not reach the mocked compiler boundary' + Assert-Policy (-not (Test-Path (Join-Path $root 'dist'))) 'mocked compilation produced an artifact' + Write-Output 'PASS: secret-free-build-reaches-only-mocked-boundary' + + Clear-SigningFixtures + Invoke-Refusal { & $sign -Required -CheckOnly } 'Nightly signing is required' + $env:AZURE_CLIENT_SECRET = 'generated-partial-fixture' + Invoke-Refusal { & $sign -Required -CheckOnly } 'Nightly signing is required' + Write-Output 'PASS: required-signer-refuses-missing-and-partial-configuration' + + Clear-SigningFixtures + $env:WINDOWS_CERTIFICATE = 'generated-presence-fixture-not-a-certificate' + & $sign -Required -CheckOnly + Clear-SigningFixtures + foreach ($name in $names | Where-Object { $_.StartsWith('AZURE_') }) { [Environment]::SetEnvironmentVariable($name, 'generated-presence-fixture') } + & $sign -Required -CheckOnly + Clear-SigningFixtures + Write-Output 'PASS: supported-configuration-presence-without-signing' + + # Load the policy function without signing. These objects are not crypto evidence. + . $sign -CheckOnly + foreach ($value in @($null, [pscustomobject]@{Status='NotSigned';SignerCertificate='fixture'}, [pscustomobject]@{Status='HashMismatch';SignerCertificate='fixture'}, [pscustomobject]@{Status='Valid';SignerCertificate=$null})) { + Invoke-Refusal { Assert-AuthenticodeSignature $value } 'valid Authenticode signature' + } + Assert-AuthenticodeSignature ([pscustomobject]@{Status='Valid';SignerCertificate='generated-public-certificate-placeholder'}) + Write-Output 'PASS: required-signature-policy-rejects-invalid-or-missing-signer' + + $file = Join-Path $root 'owned-sentinel.exe' + [IO.File]::WriteAllText($file, 'generated sentinel, not a real executable') + $before = (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash + & $sign -Files $file + Assert-Policy ((Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash -ceq $before) 'optional stable policy changed unsigned bytes' + Write-Output 'PASS: stable-optional-policy-preserves-owned-bytes' +} finally { + Clear-SigningFixtures + Remove-Item -LiteralPath $root -Recurse -Force +} diff --git a/packaging/windows/nightly.ps1 b/packaging/windows/nightly.ps1 new file mode 100644 index 0000000000..5eaa20263d --- /dev/null +++ b/packaging/windows/nightly.ps1 @@ -0,0 +1,133 @@ +<# First nightly target only: Windows x86_64 GUI ZIP. No MSI, CLI, portable marker or association registration. #> +param( + [string] $Arch = 'x64', + [string] $Version, + [string] $Target, + [string] $TargetDir, + [string] $Dist, + [switch] $SkipBuild, + [switch] $BuildOnly, + [switch] $FunctionsOnly +) +$ErrorActionPreference = 'Stop' + +function Get-NightlyArchiveSpec([string] $Version, [string] $Arch) { + if ($Arch -ne 'x64') { throw 'nightly-v1 supports only Windows x86_64' } + if (-not $Version -or $Version -cnotmatch '^\d+\.\d+\.\d+-nightly\.\d{8}\.\d+\.\d+\.g[0-9a-f]{12}\z') { throw 'invalid nightly artifact version' } + return @{ + Archive = "photocraft-$Version-windows-x86_64-nightly.zip" + UnsignedArchive = "photocraft-$Version-windows-x86_64-nightly.unsigned.zip" + Executables = @('photocraft.exe') + Channel = 'nightly-v1' + AppId = 'ai.storyteller.photocraft.nightly-v1' + } +} + +# The same source identity the Linux helper enforces (nightly-common.sh): the version names the +# commit being built, the date is the original run's, and the tree is clean. +function Assert-NightlySource([string] $Version, [string] $Sha, [string] $BuildDate, [string] $Head, [string] $Status) { + if ($Sha -cnotmatch '^[0-9a-f]{40}\z') { throw 'an exact source commit is required (PHOTOCRAFT_BUILD_SHA)' } + if ($Version -cnotmatch '^\d+\.\d+\.\d+-nightly\.\d{8}\.\d+\.\d+\.g[0-9a-f]{12}\z') { throw 'invalid nightly artifact version' } + if ($Version.Substring($Version.Length - 12) -cne $Sha.Substring(0, 12)) { throw 'version/source commit mismatch' } + if ($BuildDate -cnotmatch '^\d{4}-\d{2}-\d{2}\z') { throw 'the original run-created UTC date is required (PHOTOCRAFT_BUILD_DATE)' } + $versionDate = ($Version -split '-nightly\.', 2)[1].Substring(0, 8) + if ($BuildDate.Replace('-', '') -cne $versionDate) { throw 'version/original-run date mismatch' } + if ($Head -cne $Sha) { throw 'prepared source is not the checked-out commit' } + if ($Status) { throw 'nightly packaging requires the frozen clean source' } +} + +function Get-NightlySourceState([string] $RepositoryRoot) { + $head = git -C $RepositoryRoot rev-parse HEAD + if ($LASTEXITCODE -ne 0) { throw 'cannot read the checked-out commit' } + $status = git -C $RepositoryRoot status --porcelain + if ($LASTEXITCODE -ne 0) { throw 'cannot read the source tree status' } + return @{ Head = "$head".Trim(); Status = ($status | Out-String).Trim() } +} + +function Assert-NightlyFlavor([string] $ProductName, [string] $VersionOutput, [string] $ExpectedVersion) { + if ($ProductName -ne 'PhotoCraft Nightly' -or $VersionOutput -cne "PhotoCraft $ExpectedVersion (nightly-v1)") { + throw 'the executable is not the compiled nightly-v1 flavor' + } +} + + +function Copy-NightlyNotices([string] $RepositoryRoot, [string] $FontRepository, [string] $Destination) { + foreach ($name in 'README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') { + $source = Join-Path $RepositoryRoot $name + if (Test-Path -LiteralPath $source) { Copy-Item -LiteralPath $source -Destination $Destination } + } + if ($FontRepository) { + $fonts = Join-Path $FontRepository 'fonts' + if (-not (Test-Path -LiteralPath $fonts -PathType Container)) { throw 'CRAFT_FONTS_DIR has no fonts directory for the bundled notices' } + foreach ($family in Get-ChildItem -LiteralPath $fonts -Directory) { + $license = Join-Path $family.FullName 'OFL.txt' + if (Test-Path -LiteralPath $license) { Copy-Item -LiteralPath $license -Destination (Join-Path $Destination "OFL-$($family.Name).txt") } + } + } +} + +if ($FunctionsOnly) { return } +if (-not $env:PHOTOCRAFT_VERSION -or $Version -cne $env:PHOTOCRAFT_VERSION) { throw 'nightly-v1 requires explicit PHOTOCRAFT_VERSION, not the Cargo version fallback' } +$Spec = Get-NightlyArchiveSpec $Version $Arch +if ($SkipBuild) { throw 'nightly-v1 forbids -SkipBuild; the executable flavor must be built in this operation' } +if ($Target -ne 'x86_64-pc-windows-msvc') { throw 'nightly-v1 target must be x86_64-pc-windows-msvc' } +if (-not $BuildOnly) { throw 'Nightly compilation requires -BuildOnly; final archives are produced in the separate trusted signing job' } +# No key values may enter compilation. This produces an internal intermediate, not a feed artifact. +& (Join-Path $PSScriptRoot 'sign.ps1') -CheckBuildEnvironment +$Root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path +$Source = Get-NightlySourceState $Root +Assert-NightlySource $Version $env:PHOTOCRAFT_BUILD_SHA $env:PHOTOCRAFT_BUILD_DATE $Source.Head $Source.Status +$oldChannel = $env:PHOTOCRAFT_BUILD_CHANNEL +$oldVersionOverride = $env:PHOTOCRAFT_OVERRIDE_VERSION +try { + $env:PHOTOCRAFT_BUILD_CHANNEL = 'nightly-v1' + $env:PHOTOCRAFT_OVERRIDE_VERSION = $Version + $env:PHOTOCRAFT_REQUIRE_WINRES = '1' + $env:CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS = '-C target-feature=+crt-static' + cargo build --release --locked -p photocraft --features heif --target $Target + if ($LASTEXITCODE -ne 0) { throw "nightly cargo build failed: $LASTEXITCODE" } +} finally { + $env:PHOTOCRAFT_BUILD_CHANNEL = $oldChannel + $env:PHOTOCRAFT_OVERRIDE_VERSION = $oldVersionOverride +} +$Source = Get-NightlySourceState $Root +try { Assert-NightlySource $Version $env:PHOTOCRAFT_BUILD_SHA $env:PHOTOCRAFT_BUILD_DATE $Source.Head $Source.Status } +catch { throw "source changed during the build: $_" } +$Exe = Join-Path $TargetDir "$Target\release\photocraft.exe" +$pe = [System.IO.File]::ReadAllBytes($Exe) +if ($pe.Length -lt 64) { throw 'truncated nightly PE executable' } +$offset = [BitConverter]::ToInt32($pe, 0x3C) +if ($offset -lt 0 -or $offset -gt $pe.Length - 0x5E) { throw 'invalid nightly PE header offset' } +if ([BitConverter]::ToUInt16($pe, $offset + 4) -ne 0x8664 -or [BitConverter]::ToUInt16($pe, $offset + 0x5C) -ne 2) { + throw 'nightly executable must be x86_64 Windows GUI' +} +$VersionInfo = (Get-Item -LiteralPath $Exe).VersionInfo +$ProductName = $VersionInfo.ProductName +if ($VersionInfo.ProductVersion -cne $Version) { throw 'nightly PE ProductVersion differs from the feed identity' } +# Check the embedded build flavor before invoking even the side-effect-free version query. +if ($ProductName -ne 'PhotoCraft Nightly') { throw 'nightly executable is missing the embedded build flavor' } +$VersionOutput = (& $Exe --version | Out-String).Trim() +if ($LASTEXITCODE -ne 0) { throw 'nightly --version query failed' } +Assert-NightlyFlavor $ProductName $VersionOutput $Version +$Stage = Join-Path $TargetDir 'windows-package\nightly-v1-x86_64' +if (Test-Path -LiteralPath $Stage) { Remove-Item -LiteralPath $Stage -Recurse -Force } +New-Item -ItemType Directory -Force -Path $Stage | Out-Null +Copy-Item -LiteralPath $Exe -Destination (Join-Path $Stage 'photocraft.exe') +# Signing happens only in the separate trusted step, using sign.ps1 -Required. +# The intermediate's filename cannot satisfy the feed-ready archive contract. +Copy-NightlyNotices $Root $env:CRAFT_FONTS_DIR $Stage +if ((Get-ChildItem -LiteralPath $Stage -Filter '*.exe').Count -ne 1 -or (Test-Path (Join-Path $Stage 'portable.txt'))) { + throw 'nightly stage contains an unexpected executable or portable fallback marker' +} +New-Item -ItemType Directory -Force -Path $Dist | Out-Null +$Zip = Join-Path $Dist $Spec.UnsignedArchive +if (Test-Path -LiteralPath $Zip) { throw 'Nightly output already exists; refusing to replace prepared artifact bytes' } +Compress-Archive -Path (Join-Path $Stage '*') -DestinationPath $Zip +$Archive = [System.IO.Compression.ZipFile]::OpenRead($Zip) +try { + $Names = @($Archive.Entries | ForEach-Object { $_.FullName }) + if ('photocraft.exe' -notin $Names -or 'photocraft-cli.exe' -in $Names -or 'portable.txt' -in $Names) { + throw 'nightly ZIP payload violates the GUI-only profile contract' + } +} finally { $Archive.Dispose() } +Write-Output "Nightly build intermediate (not publishable): $Zip ($VersionOutput)" diff --git a/packaging/windows/package.ps1 b/packaging/windows/package.ps1 index d984e3930a..5d4279a005 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -23,9 +23,12 @@ #> param( [ValidateSet('x64', 'x86', 'arm64')] [string] $Arch = 'x64', - [switch] $SkipBuild + [switch] $SkipBuild, + [switch] $Nightly, + [switch] $BuildOnly ) $ErrorActionPreference = 'Stop' +if ($BuildOnly -and -not $Nightly) { throw '-BuildOnly is only for secret-free nightly compilation' } $Root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path function Invoke-Native([string] $What, [scriptblock] $Block) { @@ -52,12 +55,22 @@ $Dist = if ($env:DIST) { $env:DIST } else { Join-Path $Root 'dist\release' } $TargetDir = if ($env:CARGO_TARGET_DIR) { $env:CARGO_TARGET_DIR } else { Join-Path $Root 'target' } New-Item -ItemType Directory -Force -Path $Dist | Out-Null -if (-not $env:PHOTOCRAFT_BUILD_SHA) { $env:PHOTOCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) } -if (-not $env:PHOTOCRAFT_BUILD_DATE) { $env:PHOTOCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') } +# Nightly requires the prepared commit and original run date explicitly; nightly.ps1 checks both. +if (-not $Nightly) { + if (-not $env:PHOTOCRAFT_BUILD_SHA) { $env:PHOTOCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) } + if (-not $env:PHOTOCRAFT_BUILD_DATE) { $env:PHOTOCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') } +} Write-Output "PhotoCraft $Version for Windows $Arch ($Target)" +if ($Nightly) { + & (Join-Path $PSScriptRoot 'nightly.ps1') -Arch $Arch -Version $Version -Target $Target -TargetDir $TargetDir -Dist $Dist -SkipBuild:$SkipBuild -BuildOnly:$BuildOnly + return +} + if (-not $SkipBuild) { + $env:PHOTOCRAFT_BUILD_CHANNEL = 'stable' + # Static CRT: no VC++ redistributable needed. Scoped to the target so host build scripts and # proc-macros are unaffected. $flagVar = 'CARGO_TARGET_' + ($Target.ToUpper() -replace '-', '_') + '_RUSTFLAGS' @@ -85,6 +98,9 @@ foreach ($check in @(@('photocraft.exe', 2), @('photocraft-cli.exe', 3))) { if ($h.Subsystem -ne $check[1]) { throw "$($check[0]) has PE subsystem $($h.Subsystem), expected $($check[1])" } Write-Output "ok $($check[0]): $Arch, PE subsystem $($h.Subsystem)" } +if ((Get-Item -LiteralPath (Join-Path $Bin 'photocraft.exe')).VersionInfo.ProductName -eq 'PhotoCraft Nightly') { + throw 'a nightly executable cannot be packaged as stable' +} $Stage = Join-Path $TargetDir "windows-package\$Arch" Remove-Item -Recurse -Force $Stage -ErrorAction SilentlyContinue New-Item -ItemType Directory -Force -Path $Stage | Out-Null diff --git a/packaging/windows/sign.ps1 b/packaging/windows/sign.ps1 index 6064a9409b..7fc248995c 100644 --- a/packaging/windows/sign.ps1 +++ b/packaging/windows/sign.ps1 @@ -9,7 +9,9 @@ AZURE_SIGNING_ENDPOINT (e.g. https://eus.codesigning.azure.net), AZURE_SIGNING_ACCOUNT, AZURE_CERT_PROFILE With neither, it prints a warning and leaves the files unsigned (exit code 0), so test builds - still produce installers. + still produce installers. Nightly callers require signing with -Required and can + check signing configuration with -Required -CheckOnly. Compilation uses the + separate -CheckBuildEnvironment mode, without importing signing keys. This is the one place to adapt when the signing setup changes (an HSM/cloud key, a different timestamp server, ...). Optional overrides: WINDOWS_TIMESTAMP_URL, SIGNTOOL (path to signtool.exe). @@ -18,8 +20,11 @@ pwsh packaging/windows/sign.ps1 dist/photocraft.exe dist/Photocraft.msi #> param( - [Parameter(Mandatory = $true, ValueFromRemainingArguments = $true)] - [string[]] $Files + [Parameter(Position = 0, ValueFromRemainingArguments = $true)] + [string[]] $Files, + [switch] $Required, + [switch] $CheckOnly, + [switch] $CheckBuildEnvironment ) $ErrorActionPreference = 'Stop' @@ -37,6 +42,12 @@ function Write-Warn([string] $Message) { if ($env:GITHUB_ACTIONS) { Write-Output "::warning::$Message" } else { Write-Warning $Message } } +function Assert-AuthenticodeSignature($Signature) { + if (-not $Signature -or [string]$Signature.Status -cne 'Valid' -or -not $Signature.SignerCertificate) { + throw 'Required signing must produce a valid Authenticode signature and signer certificate' + } +} + function Find-SignTool { if ($env:SIGNTOOL) { return $env:SIGNTOOL } $onPath = Get-Command signtool.exe -ErrorAction SilentlyContinue @@ -54,11 +65,28 @@ function Invoke-SignTool([string[]] $Arguments) { if ($LASTEXITCODE -ne 0) { throw "signtool $($Arguments[0]) failed with exit code $LASTEXITCODE" } } -$Files = $Files | ForEach-Object { (Resolve-Path $_).Path } -$haveCert = [bool]$env:WINDOWS_CERTIFICATE $azureVars = 'AZURE_TENANT_ID', 'AZURE_CLIENT_ID', 'AZURE_CLIENT_SECRET', 'AZURE_SIGNING_ENDPOINT', 'AZURE_SIGNING_ACCOUNT', 'AZURE_CERT_PROFILE' +if ($CheckBuildEnvironment) { + if ($Required -or $CheckOnly -or $Files) { throw '-CheckBuildEnvironment is separate from signing' } + $names = @('WINDOWS_CERTIFICATE', 'WINDOWS_CERTIFICATE_PASSWORD') + $azureVars + if ($names | Where-Object { [Environment]::GetEnvironmentVariable($_) }) { + throw 'Compilation must not receive signing credentials; use a separate trusted signing step' + } + return +} +$haveCert = [bool]$env:WINDOWS_CERTIFICATE $haveAzure = -not ($azureVars | Where-Object { -not [Environment]::GetEnvironmentVariable($_) }) +if ($Required -and -not $haveCert -and -not $haveAzure) { + throw 'Nightly signing is required: configure WINDOWS_CERTIFICATE or the complete existing Azure signing configuration' +} +if ($CheckOnly) { + if ($Files) { throw '-CheckOnly does not sign files' } + return +} +if (-not $Files) { throw 'At least one file is required for signing' } +$Files = $Files | ForEach-Object { (Resolve-Path $_).Path } + if (-not $haveCert -and -not $haveAzure) { Write-Warn "Windows signing secrets not set (WINDOWS_CERTIFICATE or AZURE_*): leaving unsigned: $($Files -join ', ')" exit 0 @@ -104,6 +132,9 @@ try { Invoke-SignTool ($common + @('/tr', $ts, '/dlib', $dlib.FullName, '/dmdf', $metadata) + $Files) } Invoke-SignTool (@('verify', '/pa', '/v') + $Files) + if ($Required) { + foreach ($file in $Files) { Assert-AuthenticodeSignature (Get-AuthenticodeSignature -LiteralPath $file) } + } } finally { Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue diff --git a/sonar-project.properties b/sonar-project.properties index 73d114e6bc..64622ff8d0 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -1,2 +1,8 @@ sonar.projectKey=storytold_photocraft sonar.organization=storytold +# Setting test roots disables the CLI default; keep all production sources analyzed. +sonar.sources=. +# These exact fixture runners are tests, not production code. Do not exclude helpers. +sonar.tests=packaging +sonar.test.inclusions=packaging/nightly-tests.py,packaging/nightly-archive-tests.py,packaging/macos/nightly_plist_tests.py,packaging/windows/nightly-package-tests.ps1,packaging/windows/nightly-signing-tests.ps1 +sonar.python.coverage.reportPaths=python-coverage.xml