diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index c0cef67a5e3..7981035a5d8 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -20,6 +20,7 @@ next to them. | `assets/icons/gradient-tool.svg` | Gradient tool glyph with a horizontal opacity ramp | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/spirit-level.svg` | Straighten tool glyph: a spirit level with its vial and bubble under a dotted arc | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/type-vertical.svg` | Vertical Type tool glyph: Lucide `type`'s T, drawn narrower to make room for a downward arrow of our own at its left | Lucide Icons and Contributors; arrow by PhotoCraft contributors | Derived from `icons/type.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | +| `assets/icons/quick-mask-{off,masked-areas,selected-areas}.svg` | Quick Mask toolbar glyphs showing the inactive mode and the two overlay meanings | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/path-op-{new-layer,combine,subtract,intersect,exclude,merge}.svg` | Path Operations glyphs (Pen options bar): a single square for New Layer, and two overlapping squares showing the area each operation keeps (union, back minus front, overlap, everything but the overlap, the merged outline), drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/arrange-{tile-all-vertically,tile-all-horizontally,two-up-horizontal,two-up-vertical,three-up-horizontal,three-up-vertical,three-up-stacked,four-up,six-up,consolidate-all-to-tabs}.svg` | Window › Arrange layout glyphs: a window outline split into the panes each entry lays out (columns, rows, the n-up splits, and one window with a tab row for Consolidate All to Tabs), drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `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) | diff --git a/Cargo.lock b/Cargo.lock index 3f47ef1ed5a..467b509d340 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1376,7 +1376,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-automation", "craft-behavior", @@ -1417,7 +1417,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "crc32fast", "flate2", @@ -1438,7 +1438,7 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -1450,7 +1450,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "rustix 1.1.6", ] @@ -1458,7 +1458,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1483,7 +1483,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1501,7 +1501,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-behavior", "craft-docpath", @@ -1519,7 +1519,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "egui", ] @@ -1527,7 +1527,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "md-5", "rayon", @@ -1536,12 +1536,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" [[package]] name = "craft-color" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "serde", ] @@ -1549,7 +1549,7 @@ dependencies = [ [[package]] name = "craft-color-transform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-cms", "craft-color", @@ -1559,7 +1559,7 @@ dependencies = [ [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-behavior", "craft-cms", @@ -1580,7 +1580,7 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-ai-agents", "craft-atomic", @@ -1596,7 +1596,7 @@ dependencies = [ [[package]] name = "craft-control-protocol" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "getrandom 0.3.4", "serde_json", @@ -1606,7 +1606,7 @@ dependencies = [ [[package]] name = "craft-crs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-metadata", "craft-xml", @@ -1616,7 +1616,7 @@ dependencies = [ [[package]] name = "craft-crw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "thiserror 2.0.21", ] @@ -1624,7 +1624,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "rayon", ] @@ -1632,7 +1632,7 @@ dependencies = [ [[package]] name = "craft-develop" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-color", "craft-color-transform", @@ -1647,7 +1647,7 @@ dependencies = [ [[package]] name = "craft-develop-model" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-geom", "craft-metadata", @@ -1659,7 +1659,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "block2 0.6.2", "craft-appkit", @@ -1685,7 +1685,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "serde", ] @@ -1693,7 +1693,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1712,7 +1712,7 @@ dependencies = [ [[package]] name = "craft-drawingml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "chrono", "craft-xml", @@ -1724,12 +1724,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" [[package]] name = "craft-file-formats" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-eps", "craft-idml", @@ -1747,7 +1747,7 @@ dependencies = [ [[package]] name = "craft-flags" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-atomic", "dirs", @@ -1757,7 +1757,7 @@ dependencies = [ [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1772,7 +1772,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1792,7 +1792,7 @@ dependencies = [ [[package]] name = "craft-font-os-windows" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "windows-registry", "windows-sys 0.61.2", @@ -1801,7 +1801,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "cap-primitives", "craft-atomic", @@ -1824,12 +1824,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" [[package]] name = "craft-geom" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "serde", ] @@ -1837,7 +1837,7 @@ dependencies = [ [[package]] name = "craft-heif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "heic-rs", "rayon", @@ -1846,7 +1846,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1859,7 +1859,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "brotli 9.1.3", "brotli-decompressor 6.3.2", @@ -1889,7 +1889,7 @@ dependencies = [ [[package]] name = "craft-idml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-xml", "craft-zip", @@ -1899,7 +1899,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-dds", "craft-heif", @@ -1927,7 +1927,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1945,12 +1945,12 @@ dependencies = [ [[package]] name = "craft-ipp" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "thiserror 2.0.21", ] @@ -1958,7 +1958,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-host", "craft-i18n", @@ -1973,7 +1973,7 @@ dependencies = [ [[package]] name = "craft-kra" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-xml", "craft-zip", @@ -1983,7 +1983,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-behavior", "craft-i18n", @@ -1997,7 +1997,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-behavior", "craft-host", @@ -2015,7 +2015,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -2027,7 +2027,7 @@ dependencies = [ [[package]] name = "craft-nightly" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "uds_windows", "winsafe", @@ -2036,7 +2036,7 @@ dependencies = [ [[package]] name = "craft-ora" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-xml", "craft-zip", @@ -2046,7 +2046,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-behavior", "craft-keymap", @@ -2062,7 +2062,7 @@ dependencies = [ [[package]] name = "craft-pcraft-bundle" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "blake3", "craft-atomic", @@ -2075,7 +2075,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "flate2", "serde", @@ -2086,7 +2086,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "bytemuck", "flate2", @@ -2101,7 +2101,7 @@ dependencies = [ [[package]] name = "craft-pdn" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2110,7 +2110,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "async-channel", "async-io", @@ -2143,7 +2143,7 @@ dependencies = [ [[package]] name = "craft-plist" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "thiserror 2.0.21", ] @@ -2151,7 +2151,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-behavior", "craft-host", @@ -2175,7 +2175,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "encoding_rs", "flate2", @@ -2186,7 +2186,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "dispatch2", "egui", @@ -2199,7 +2199,7 @@ dependencies = [ [[package]] name = "craft-raw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "chrono", "craft-crw", @@ -2217,7 +2217,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -2236,7 +2236,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-atomic", "craft-host", @@ -2253,7 +2253,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2274,7 +2274,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-behavior", "craft-keymap", @@ -2286,7 +2286,7 @@ dependencies = [ [[package]] name = "craft-testkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "rustix 1.1.6", "tempfile", @@ -2296,7 +2296,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2319,7 +2319,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2334,7 +2334,7 @@ dependencies = [ [[package]] name = "craft-theme-editor" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-behavior", "craft-theme", @@ -2345,7 +2345,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-atomic", "craft-behavior", @@ -2360,7 +2360,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "serde", "thiserror 2.0.21", @@ -2370,7 +2370,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "serde", "thiserror 2.0.21", @@ -2379,7 +2379,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-behavior", "craft-keymap", @@ -2394,7 +2394,7 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "serde", ] @@ -2402,7 +2402,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2416,7 +2416,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -2433,7 +2433,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "accesskit", "craft-behavior", @@ -2475,7 +2475,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2486,7 +2486,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-behavior", "craft-host", @@ -2504,7 +2504,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-behavior", "craft-host", @@ -2525,7 +2525,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-behavior", "craft-host", @@ -2545,7 +2545,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-behavior", "craft-host", @@ -2564,7 +2564,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "base64 0.22.1", "chrono", @@ -2596,7 +2596,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "winsafe", ] @@ -2604,7 +2604,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "craft-appkit", "craft-atomic", @@ -2636,7 +2636,7 @@ dependencies = [ [[package]] name = "craft-xcf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2645,7 +2645,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "quick-xml 0.41.0", "serde", @@ -2655,7 +2655,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "flate2", "thiserror 2.0.21", @@ -4179,7 +4179,7 @@ dependencies = [ [[package]] name = "hayro" version = "0.7.1" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "bytemuck", "hayro-interpret", @@ -4209,7 +4209,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -4227,7 +4227,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -4251,7 +4251,7 @@ checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "flate2", "hayro-ccitt", @@ -5344,7 +5344,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -9857,7 +9857,7 @@ dependencies = [ [[package]] name = "vello_common" version = "0.0.8" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "bytemuck", "fearless_simd", @@ -9905,7 +9905,7 @@ dependencies = [ [[package]] name = "vello_cpu" version = "0.0.8" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" dependencies = [ "bytemuck", "glifo 0.1.1", @@ -11551,14 +11551,14 @@ source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387 [[patch.unused]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" [[patch.unused]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" [[patch.unused]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=475f6feb712bd2db2f235d9999be61c68477ae39#475f6feb712bd2db2f235d9999be61c68477ae39" +source = "git+https://github.com/storytold/craft-libs?rev=fc3262f68babdb19a98a89c415c84c6b327073d3#fc3262f68babdb19a98a89c415c84c6b327073d3" diff --git a/Cargo.toml b/Cargo.toml index 61da67d493e..c941befcf2b 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 = "475f6feb712bd2db2f235d9999be61c68477ae39", default-features = false } -craft-tracked = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } -craft-ui-macros = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3", default-features = false } +craft-tracked = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } +craft-ui-macros = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } # 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 = "475f6feb712bd2db2f235d9999be61c68477ae39" } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } -photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } -photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] } +craft-plist = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } +photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } +photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3", 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 = "475f6feb712bd2db2f235d9999be61c68477ae39" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } photocraft-compose = { path = "crates/compose" } photocraft-gpu = { path = "crates/gpu" } photocraft-paint = { path = "crates/paint" } @@ -48,38 +48,38 @@ 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 = "475f6feb712bd2db2f235d9999be61c68477ae39" } -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } # HEIC/HEIF: the shared decoder (replaces crates/heif; craft-libs#784). -craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39", features = ["raster", "write-raster"] } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } -craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } -craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } -craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } -craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } -craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } -craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } -craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } +craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3", features = ["raster", "write-raster"] } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } +craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } +craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } +craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } +craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } +craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } +craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } +craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } # Keep the shared embedded-image validation API until the framework revision includes it. -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39", features = ["tree-render", "tree-render-system-fonts"] } -craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3", features = ["tree-render", "tree-render-system-fonts"] } +craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } # Camera-field EXIF reader/writer, shared prerequisite craft-libs#1563. -craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } -craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } -craft-develop = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } -craft-develop-model = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } +craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } +craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } +craft-develop = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } +craft-develop-model = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } # 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 = "475f6feb712bd2db2f235d9999be61c68477ae39" } +craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } # 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 = "475f6feb712bd2db2f235d9999be61c68477ae39", features = ["ui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3", features = ["ui"] } # Self-contained nightly profile isolation, launch protocol, and security fence. -craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } thiserror = "2" serde = { version = "1", features = ["derive", "rc"] } serde_json = "1" @@ -352,16 +352,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 = "475f6feb712bd2db2f235d9999be61c68477ae39" } -hayro = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } -vello_common = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } -vello_cpu = { git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } +hayro = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } +vello_common = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } +vello_cpu = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } emath = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } epaint = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index 34abab284a1..cd5d580945b 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -258,6 +258,8 @@ fn claim_single_instance( // 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()); + // The CPU-compatibility relaunch's `--safe-gpu` is not a person's: it takes part. + let launch_options = single_instance::without_relaunch_safe_gpu(launch_options, std::env::var_os("PHOTOCRAFT_GPU_STARTUP_FAILURE").as_deref()); let context = single_instance::LaunchContext { per_user_settings: launch_profile::current().is_nightly() || app_dirs::current().mode == app_dirs::Mode::Platform, new_instance_flag: new_instance && !nightly, diff --git a/apps/photocraft/src/single_instance.rs b/apps/photocraft/src/single_instance.rs index 4d836adc907..782b234e2b3 100644 --- a/apps/photocraft/src/single_instance.rs +++ b/apps/photocraft/src/single_instance.rs @@ -29,9 +29,7 @@ use std::io::{BufReader, Read, Write}; use std::net::{Ipv4Addr, SocketAddr, TcpListener, TcpStream}; #[cfg(unix)] use std::os::unix::net::{UnixListener, UnixStream}; -use std::path::Path; -#[cfg(unix)] -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::mpsc::{SyncSender, sync_channel}; use std::sync::{Arc, Mutex, PoisonError}; @@ -181,6 +179,22 @@ fn env_launch_options_from(get: impl Fn(&str) -> Option) -> ENV_LAUNCH_OPTIONS.iter().filter(|(name, _, is_on)| get(name).is_some_and(|v| is_on(&v.to_string_lossy()))).map(|(_, option, _)| *option).collect() } +/// Whether `--safe-gpu` keeps a launch out of single-instance. It does when a person passes it, but +/// not for the CPU-compatibility relaunch (which sets `PHOTOCRAFT_GPU_STARTUP_FAILURE`): that one +/// takes the place of a launch that has already shut its instance down. +pub fn safe_gpu_is_launch_option(gpu_startup_failure: Option<&std::ffi::OsStr>) -> bool { + gpu_startup_failure.is_none() +} + +/// `options` without the `--safe-gpu` the CPU-compatibility relaunch adds; a person's stays +/// ([`safe_gpu_is_launch_option`]). Every other option is kept. +pub fn without_relaunch_safe_gpu(mut options: Vec, gpu_startup_failure: Option<&std::ffi::OsStr>) -> Vec { + if !safe_gpu_is_launch_option(gpu_startup_failure) { + options.retain(|option| *option != PerProcess::SafeGpu); + } + options +} + /// Why this launch runs as its own instance, or `None` to take part in single-instance. pub fn skip_reason(c: &LaunchContext) -> Option { if !c.per_user_settings { @@ -210,6 +224,8 @@ pub struct Primary { /// then, so the second call (`Drop`) can't remove the socket the next primary has bound. #[cfg(unix)] socket: Mutex>, + /// Where `instance.json` is, removed on [`Primary::shutdown`]. + dir: PathBuf, } struct Shared { @@ -255,7 +271,13 @@ impl Primary { if let Some(path) = self.socket.lock().unwrap_or_else(PoisonError::into_inner).take() { let _ = std::fs::remove_file(path); } - drop(self.lock.lock().unwrap_or_else(PoisonError::into_inner).take()); + let mut lock = self.lock.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(file) = lock.take() { + // Before the lock goes, so the file can only be ours: a later launch never reads an + // endpoint that has since been freed (or taken by another program). + remove_info(&self.dir); + drop(file); + } } } @@ -324,11 +346,11 @@ pub fn claim_with(dir: &Path, paths: &[String], timing: Timing) -> Launch { /// once a quitting or crashed primary is gone) and then the running primary, wherever /// `instance.json` says it listens. pub fn claim_in(dir: &Path, paths: &[String], timing: Timing, transport: &Transport) -> Launch { - if let Err(e) = std::fs::create_dir_all(dir) { + if let Err(e) = create_private_dir(dir) { return Launch::Standalone(format!("{}: {e}", dir.display())); } let lock_path = dir.join(LOCK_FILE); - let lock = match OpenOptions::new().read(true).write(true).create(true).truncate(false).open(&lock_path) { + let lock = match open_lock(&lock_path) { Ok(lock) => lock, Err(e) => return Launch::Standalone(format!("{}: {e}", lock_path.display())), }; @@ -407,9 +429,39 @@ fn serve(dir: &Path, lock: File, timing: Timing, transport: &Transport) -> Resul shared, #[cfg(unix)] socket: Mutex::new(socket), + dir: dir.to_path_buf(), }) } +/// The settings folder, the user's alone (0700) on Unix when this is the first to create it. +fn create_private_dir(dir: &Path) -> std::io::Result<()> { + let mut builder = std::fs::DirBuilder::new(); + builder.recursive(true); + #[cfg(unix)] + std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700); + builder.create(dir) +} + +/// `instance.lock`, the user's alone (0600) on Unix: another local user who could open it could +/// hold the lock, and every launch would then wait out its hand-off time and start on its own. +fn open_lock(path: &Path) -> std::io::Result { + let mut options = OpenOptions::new(); + options.read(true).write(true).create(true).truncate(false); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + let lock = options.open(path)?; + // The mode applies only on create: narrow a lock file an earlier version left readable. + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let wide = lock.metadata().is_ok_and(|m| m.permissions().mode() & 0o077 != 0); + if wide && let Err(e) = lock.set_permissions(std::fs::Permissions::from_mode(0o600)) { + log::warn!("{}: couldn't make it private: {e}", path.display()); + } + } + Ok(lock) +} + /// The primary's listener on either transport. enum Listener { Tcp(TcpListener), @@ -574,6 +626,15 @@ fn write_info(dir: &Path, endpoint: &Endpoint, token: &str) -> Result<(), String }) } +/// Remove `instance.json` if this process wrote it. +fn remove_info(dir: &Path) { + let path = dir.join(INFO_FILE); + let pid = std::fs::read(&path).ok().and_then(|b| serde_json::from_slice::(&b).ok()).and_then(|v| v.get("pid")?.as_u64()); + if pid == Some(u64::from(std::process::id())) { + let _ = std::fs::remove_file(&path); + } +} + fn read_info(dir: &Path) -> Option<(Endpoint, String)> { let v: Value = serde_json::from_slice(&std::fs::read(dir.join(INFO_FILE)).ok()?).ok()?; let token = v.get("token")?.as_str()?.to_string(); diff --git a/apps/photocraft/src/single_instance/tests.rs b/apps/photocraft/src/single_instance/tests.rs index e450758865b..309d55873f5 100644 --- a/apps/photocraft/src/single_instance/tests.rs +++ b/apps/photocraft/src/single_instance/tests.rs @@ -133,9 +133,10 @@ fn a_launch_waiting_on_a_closing_instance_takes_over() { std::thread::sleep(Duration::from_millis(1)); } primary.shutdown(); - assert!(matches!(waiting.join().unwrap(), Launch::Primary(_)), "the waiting launch becomes the primary"); - // After shutdown new connections are refused too. + let Launch::Primary(next) = waiting.join().unwrap() else { panic!("the waiting launch becomes the primary") }; + // After shutdown new connections are refused too. (Read before the drop, which removes the file.) let (endpoint, token) = read_info(&dir).unwrap(); + drop(next); drop(primary); let short = Instant::now() + Duration::from_millis(300); assert!(send(&endpoint, &token, &["b.psd".into()], short).is_err()); @@ -227,6 +228,82 @@ fn the_token_file_is_private_to_the_user() { let _ = std::fs::remove_dir_all(&dir); } +/// Follow-up to #3755, point 1: another local user can't open the lock, so can't hold it. +#[cfg(unix)] +#[test] +fn the_lock_file_and_a_new_settings_folder_are_private_to_the_user() { + use std::os::unix::fs::PermissionsExt; + let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777; + let dir = temp_dir("lock-mode").join("photocraft"); + let first = primary(&dir); + assert_eq!((mode(&dir), mode(&dir.join(LOCK_FILE))), (0o700, 0o600)); + drop(first); + // A lock file an earlier version created 0644 is narrowed on the next start. + std::fs::set_permissions(dir.join(LOCK_FILE), std::fs::Permissions::from_mode(0o644)).unwrap(); + let second = primary(&dir); + assert_eq!(mode(&dir.join(LOCK_FILE)), 0o600); + drop(second); + let _ = std::fs::remove_dir_all(dir.parent().unwrap()); +} + +/// Follow-up to #3755, point 3: a primary that shuts down takes its `instance.json` with it, +/// and a second `shutdown` (the drop) leaves the next primary's alone. +#[test] +fn shutdown_removes_the_instance_file_but_not_the_next_ones() { + let dir = temp_dir("info-cleanup"); + let first = primary(&dir); + assert!(read_info(&dir).is_some()); + first.shutdown(); + assert!(read_info(&dir).is_none(), "no endpoint left behind for a later launch"); + let second = primary(&dir); + let port = port_of(&dir); + drop(first); + assert_eq!(port_of(&dir), port, "the running primary's file stays"); + drop(second); + assert!(read_info(&dir).is_none()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Follow-up to #3755, point 2: the CPU-compatibility relaunch takes part in single-instance; +/// `--safe-gpu` given by a person still gets its own process. +#[test] +fn the_cpu_relaunch_takes_part_in_single_instance() { + assert!(safe_gpu_is_launch_option(None)); + assert!(!safe_gpu_is_launch_option(Some(std::ffi::OsStr::new("wgpu: no adapter")))); + // The relaunch sets the reason even when it is empty. + assert!(!safe_gpu_is_launch_option(Some(std::ffi::OsStr::new("")))); +} + +/// The filtering `claim_single_instance` applies, through to `skip_reason`: the relaunch's own +/// `--safe-gpu` takes part, a person's stays separate, and the relaunch keeps any other option. +#[test] +fn the_cpu_relaunch_filter_decides_who_takes_part() { + let check = |options: &[PerProcess], failure: Option<&str>| { + let launch_options = without_relaunch_safe_gpu(options.to_vec(), failure.map(std::ffi::OsStr::new)); + let context = LaunchContext { + per_user_settings: true, + new_instance_flag: false, + new_instance_env: None, + control: false, + unreadable_paths: false, + launch_options: &launch_options, + }; + (launch_options.clone(), skip_reason(&context)) + }; + // The CPU relaunch with no other options takes part, whatever its reason says. + for failure in ["wgpu: no adapter", ""] { + assert_eq!(check(&[PerProcess::SafeGpu], Some(failure)), (vec![], None)); + } + // A person's `--safe-gpu` keeps its own process. + let (kept, reason) = check(&[PerProcess::SafeGpu], None); + assert_eq!(kept, [PerProcess::SafeGpu]); + assert!(reason.is_some()); + // The relaunch drops only its own `--safe-gpu`: another option still keeps it separate. + let (kept, reason) = check(&[PerProcess::SafeGpu, PerProcess::GpuAdapterEnv], Some("wgpu: no adapter")); + assert_eq!(kept, [PerProcess::GpuAdapterEnv]); + assert!(reason.is_some()); +} + #[test] fn an_unreachable_instance_falls_back_to_a_standalone_launch() { let dir = temp_dir("unreachable"); diff --git a/assets/icons/quick-mask-masked-areas.svg b/assets/icons/quick-mask-masked-areas.svg new file mode 100644 index 00000000000..5890c17a665 --- /dev/null +++ b/assets/icons/quick-mask-masked-areas.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/icons/quick-mask-off.svg b/assets/icons/quick-mask-off.svg new file mode 100644 index 00000000000..b65c0038596 --- /dev/null +++ b/assets/icons/quick-mask-off.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/icons/quick-mask-selected-areas.svg b/assets/icons/quick-mask-selected-areas.svg new file mode 100644 index 00000000000..bc28117be10 --- /dev/null +++ b/assets/icons/quick-mask-selected-areas.svg @@ -0,0 +1,4 @@ + + + + diff --git a/contributors/people.toml b/contributors/people.toml index eaf0ac8139f..984365460cc 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -306,6 +306,9 @@ sync_github_name = false real_name = "Jason DeBoever" sync_github_name = true +[people.yadser] +real_name = "Sergey Yadryshnikov" + [people.dylanmtaylor] sync_github_name = true @@ -361,3 +364,6 @@ sync_github_name = true [people.MMexicann] display_name = "mexicann" + +[people.webglobepl] +real_name = "Maciej Malinowski" diff --git a/crates/algo/src/retouch.rs b/crates/algo/src/retouch.rs index ba496d0e482..caf0d33609e 100644 --- a/crates/algo/src/retouch.rs +++ b/crates/algo/src/retouch.rs @@ -315,7 +315,12 @@ const PROTECT_DETAIL_LIMIT: f32 = 6.0 / 255.0; /// low halo a few pixels wide, and each difference is soft-limited to `L` = 6 levels: /// `v + amount·d·L/(L + |d|)`. Fine detail is sharpened about as much as without it, while a /// strong edge or a lone bright pixel moves by less than `L` per pass instead of overshooting. -/// Uniform areas stay exactly as they are. Alpha is left unchanged. +/// Uniform areas stay exactly as they are. +/// +/// Without `protect_detail`, alpha is sharpened by the same rule as colour and clamped to 0..1 +/// (#12940): a semi-transparent edge gets crisper while the colour stays, since the colour is +/// blurred premultiplied. An opaque pixel next to a transparent one stays as it is, because the +/// clamp holds both at their limits. With `protect_detail`, alpha is left unchanged (not measured). #[allow(clippy::too_many_arguments)] pub fn local_sharpen( data: &[f32], @@ -346,7 +351,7 @@ pub fn local_sharpen( for c in 0..ch { let v = data[i + c]; if Some(c) == alpha { - dst[o + c] = v; + dst[o + c] = if protect_detail { v } else { (v + amount * (v - blur_row[o + c])).clamp(0.0, 1.0) }; continue; } let d = v - blur_row[o + c]; diff --git a/crates/algo/src/selection.rs b/crates/algo/src/selection.rs index 742ca5085a3..22ec6441ca6 100644 --- a/crates/algo/src/selection.rs +++ b/crates/algo/src/selection.rs @@ -170,6 +170,36 @@ pub fn combine(old: Option<&Surface>, new: &[f32], area: Rect, mode: SelectionMo (s.tile_count() > 0).then_some(s) } +/// [`combine`] for a channel loaded as a selection, with Photoshop's channel arithmetic: where +/// coverage is partial, Add screens (`a + b − a·b`), Subtract keeps what `new` leaves +/// (`a·(1 − b)`) and Intersect multiplies (`a·b`). Intersecting a luminosity selection with the +/// luminosity again so narrows it to brighter tones at every step (a 50% grey goes 50%, 25%, +/// 12.5%, … while white stays selected), and Select All minus the lights minus the darks leaves +/// the midtones; [`combine`]'s min and max would leave the first unchanged and the second empty. +/// Fully selected and unselected pixels combine as in [`combine`]. Source: Greg Benz, "Photoshop +/// channel math: add, subtract, intersect" (gregbenzphotography.com, luminosity-masking). +pub fn combine_scaled(old: Option<&Surface>, new: &[f32], area: Rect, mode: SelectionMode) -> Option { + if area.is_empty() { + return None; + } + if mode == SelectionMode::Replace || (old.is_none() && mode == SelectionMode::Add) { + return combine(old, new, area, mode); + } + let old = old?; + if old.format() == PixelFormat::GRAY8 { + return combine_mask::gray8_with(Some(old), new, area, mode, false, combine_mask::Arithmetic::Scaled); + } + // Quantized to the 8-bit grid first, as in `combine`, so the float path agrees with the GRAY8 one. + let q = |v: f32| f32::from(coverage8(v)) / 255.0; + let prev = mask_from_surface(Some(old), area); + let s = match mode { + SelectionMode::Add => surface_from_masks(area, new, Some(&prev), |p, v| p + q(v) - p * q(v)), + SelectionMode::Subtract => surface_from_masks(area, new, Some(&prev), |p, v| p * (1.0 - q(v))), + _ => surface_from_masks(area, new, Some(&prev), |p, v| p * q(v)), + }; + (s.tile_count() > 0).then_some(s) +} + fn close(a: [f32; 4], b: [f32; 4], tol: f32) -> bool { (a[3] == 0.0 && b[3] == 0.0) || (0..4).all(|c| (a[c] - b[c]).abs() * 255.0 <= tol + 1e-3) } diff --git a/crates/algo/src/selection/combine_mask.rs b/crates/algo/src/selection/combine_mask.rs index 5c45ed8ff00..62b640551be 100644 --- a/crates/algo/src/selection/combine_mask.rs +++ b/crates/algo/src/selection/combine_mask.rs @@ -39,8 +39,45 @@ pub fn combine_band(old: Option<&Surface>, mask: &[f32], band: Rect, mode: Selec (out.tile_count() > 0).then_some(out) } +/// How two 8-bit coverages meet where both are partial. Fully selected and unselected pixels +/// combine the same way under both. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Arithmetic { + /// The selection tools': Add keeps the larger coverage, Subtract takes the clipped + /// difference and Intersect keeps the smaller. + Extremes, + /// A channel loaded as a selection (Photoshop's channel arithmetic): Add screens + /// (`a + b − a·b`), Subtract keeps what the new coverage leaves (`a·(1 − b)`) and Intersect + /// multiplies (`a·b`). Intersecting a partial selection with itself narrows it. + Scaled, +} + +impl Arithmetic { + pub(super) fn apply(self, mode: SelectionMode, prev: u8, new: u8) -> u8 { + match (self, mode) { + (_, SelectionMode::Replace) => new, + (Arithmetic::Extremes, SelectionMode::Add) => prev.max(new), + (Arithmetic::Extremes, SelectionMode::Subtract) => prev.saturating_sub(new), + (Arithmetic::Extremes, SelectionMode::Intersect) => prev.min(new), + (Arithmetic::Scaled, SelectionMode::Add) => u8::MAX - mul8(u8::MAX - prev, u8::MAX - new), + (Arithmetic::Scaled, SelectionMode::Subtract) => mul8(prev, u8::MAX - new), + (Arithmetic::Scaled, SelectionMode::Intersect) => mul8(prev, new), + } + } +} + +/// `a·b / 255` rounded to the nearest byte, exactly, for every pair of bytes. +pub(super) fn mul8(a: u8, b: u8) -> u8 { + let t = u32::from(a) * u32::from(b) + 128; + u8::try_from((t + (t >> 8)) >> 8).unwrap_or(u8::MAX) +} + pub(super) fn gray8(old: Option<&Surface>, mask: &[f32], area: Rect, mode: SelectionMode, keep_outside: bool) -> Option { - build(old, area, mode, keep_outside, |i| coverage8(mask.get(i).copied().unwrap_or(0.0))) + gray8_with(old, mask, area, mode, keep_outside, Arithmetic::Extremes) +} + +pub(super) fn gray8_with(old: Option<&Surface>, mask: &[f32], area: Rect, mode: SelectionMode, keep_outside: bool, arithmetic: Arithmetic) -> Option { + build(old, area, mode, keep_outside, arithmetic, |i| coverage8(mask.get(i).copied().unwrap_or(0.0))) } pub(super) fn gray8_bytes(old: Option<&Surface>, mask: &[u8], area: Rect, mode: SelectionMode) -> Option { @@ -48,10 +85,17 @@ pub(super) fn gray8_bytes(old: Option<&Surface>, mask: &[u8], area: Rect, mode: if area.is_empty() { return if keep { old.cloned().filter(|s| !s.content_bounds().is_empty()) } else { None }; } - build(old, area, mode, keep, |i| mask.get(i).copied().unwrap_or(0)) + build(old, area, mode, keep, Arithmetic::Extremes, |i| mask.get(i).copied().unwrap_or(0)) } -fn build(old: Option<&Surface>, area: Rect, mode: SelectionMode, keep_outside: bool, sample: impl Fn(usize) -> u8 + Sync) -> Option { +fn build( + old: Option<&Surface>, + area: Rect, + mode: SelectionMode, + keep_outside: bool, + arithmetic: Arithmetic, + sample: impl Fn(usize) -> u8 + Sync, +) -> Option { let mut out = if keep_outside { old.cloned().unwrap_or_else(|| Surface::new(PixelFormat::GRAY8)) } else { Surface::new(PixelFormat::GRAY8) }; let default = old.and_then(|s| s.default_bytes().first()).copied().unwrap_or(0); let out_default = out.default_bytes().first().copied().unwrap_or(0); @@ -77,12 +121,7 @@ fn build(old: Option<&Surface>, area: Rect, mode: SelectionMode, keep_outside: b for (i, d) in dst.iter_mut().enumerate() { let new = start.and_then(|j| j.checked_add(i)).map(&sample).unwrap_or(0); let prev = src.and_then(|s| s.get(i)).copied().unwrap_or(default); - *d = match mode { - SelectionMode::Replace => new, - SelectionMode::Add => prev.max(new), - SelectionMode::Subtract => prev.saturating_sub(new), - SelectionMode::Intersect => prev.min(new), - }; + *d = arithmetic.apply(mode, prev, new); } } let (lo, hi) = tile.bytes().iter().fold((u8::MAX, 0u8), |(lo, hi), b| (lo.min(*b), hi.max(*b))); diff --git a/crates/algo/src/selection/combine_mask/tests.rs b/crates/algo/src/selection/combine_mask/tests.rs index 5c55d9d90ab..1766965d890 100644 --- a/crates/algo/src/selection/combine_mask/tests.rs +++ b/crates/algo/src/selection/combine_mask/tests.rs @@ -76,6 +76,37 @@ fn cropped_bands_match_dense_writeback_with_defaults_and_short_masks() { } } +#[test] +fn scaled_combining_narrows_partial_coverage_and_keeps_hard_edges() { + use crate::selection::combine_scaled; + let area = Rect::new(0, 0, 256, 256); + let prev: Vec = (0..65536).map(|i| (i / 256) as f32 / 255.0).collect(); + let mask: Vec = (0..65536).map(|i| (i % 256) as f32 / 255.0).collect(); + let gray8 = crate::selection::mask_to_surface(&prev, area); + // An unusual (float) selection surface takes the float path; it must agree with the byte path everywhere. + let mut float = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false)); + float.write_region(area, &prev); + for mode in MODES { + let scaled = combine_scaled(Some(&gray8), &mask, area, mode); + assert_eq!(scaled, combine_scaled(Some(&float), &mask, area, mode), "{mode:?}: float and byte paths"); + let scaled = mask_from_surface(scaled.as_ref(), area); + let tools = mask_from_surface(combine(Some(&gray8), &mask, area, mode).as_ref(), area); + for (i, ((&p, &m), (&s, &t))) in prev.iter().zip(&mask).zip(scaled.iter().zip(&tools)).enumerate() { + if m == 0.0 || m == 1.0 { + assert_eq!(s, t, "{mode:?} {i}: a fully selected or unselected pixel combines as the tools do"); + continue; + } + match mode { + SelectionMode::Add => assert!(s >= t, "{mode:?} {i}: adding partial coverage keeps at least the larger one"), + SelectionMode::Subtract => assert!(s >= t, "{mode:?} {i}: subtracting scales the selection, never below the difference"), + SelectionMode::Intersect if p == m && p > 0.0 => assert!(s < p, "{mode:?} {i}: intersecting a partial selection with itself narrows it"), + SelectionMode::Intersect => assert!(s <= t, "{mode:?} {i}: intersecting keeps no more than the smaller one"), + SelectionMode::Replace => assert_eq!(s, t), + } + } + } +} + #[test] fn unusual_selection_formats_keep_their_float_behavior() { let area = Rect::new(-2, -1, 3, 2); diff --git a/crates/algo/tests/it/retouch_sharpen_exact.rs b/crates/algo/tests/it/retouch_sharpen_exact.rs index 499b60d6ac3..c5a3d8448b1 100644 --- a/crates/algo/tests/it/retouch_sharpen_exact.rs +++ b/crates/algo/tests/it/retouch_sharpen_exact.rs @@ -62,7 +62,7 @@ fn scalar_local_sharpen( for c in 0..ch { let v = data[i + c]; if Some(c) == alpha { - out[o + c] = v; + out[o + c] = if protect_detail { v } else { (v + amount * (v - blur[o + c])).clamp(0.0, 1.0) }; continue; } let d = v - blur[o + c]; diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 34455d56222..a7193312765 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -334,10 +334,24 @@ impl Headless { _ => return Err(AutomationError::BadRequest("automation filesystem access is not granted: write authority is absent".into())), }; let mut outputs = workspace.export_sequence(dir)?; - let written = photocraft_engine::export_data_sets_with(&this.session, params, |name, bytes| { + let report = photocraft_engine::export_data_sets_report_with(&this.session, params, |name, bytes| { outputs.write(name, bytes).map_err(|e| photocraft_engine::EngineError::Other(e.to_string())) }); - exported(dir, written, &mut outputs) + // The sets a missing replacement image left out or stopped at, as the command says (#13767). + let (written, report) = match report { + Ok(report) => (Ok(report.files.clone()), Some(report)), + Err(error) => (Err(error), None), + }; + let mut result = exported(dir, written, &mut outputs)?; + if let Some(report) = report { + let full = report.json(Vec::new()); + for key in ["skipped", "stopped"] { + if let Some(value) = full.get(key) { + result[key] = value.clone(); + } + } + } + Ok(result) }) } diff --git a/crates/engine-core/Cargo.toml b/crates/engine-core/Cargo.toml index ac24b32f634..be32b115541 100644 --- a/crates/engine-core/Cargo.toml +++ b/crates/engine-core/Cargo.toml @@ -19,7 +19,7 @@ photocraft-geom = { workspace = true } photocraft-color = { workspace = true } craft-cms = { workspace = true } # PCTIP codec from craft-libs#1564; kept at the same shared revision as the workspace. -craft-pcraft-tip = { package = "craft-pcraft-format", git = "https://github.com/storytold/craft-libs", rev = "475f6feb712bd2db2f235d9999be61c68477ae39" } +craft-pcraft-tip = { package = "craft-pcraft-format", git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } photocraft-raster = { workspace = true } photocraft-doc = { workspace = true } photocraft-ops = { workspace = true } diff --git a/crates/engine-core/src/cmd/adjust_cmds/replace_color_range.rs b/crates/engine-core/src/cmd/adjust_cmds/replace_color_range.rs index 7191078c796..65ed998121e 100644 --- a/crates/engine-core/src/cmd/adjust_cmds/replace_color_range.rs +++ b/crates/engine-core/src/cmd/adjust_cmds/replace_color_range.rs @@ -7,6 +7,7 @@ use photocraft_raster::Surface; use serde_json::Value; use super::{bad, num}; +use crate::color_cmds::ColorExt; use crate::{EngineError, Result, Session}; const CMD: &str = "image.adjustments.replaceColor"; @@ -107,8 +108,12 @@ pub(super) fn apply(s: &mut Session, p: &Value) -> Result> { if format.mode != st.doc.mode { return Err(bad(CMD, "pixel layout does not match the document profile")); } - let transform = craft_cms::cached(&crate::color_cmds::document_profile(&st.doc), Builtin::LabD50.profile(), TransformOptions::default()) - .map_err(|e| bad(CMD, format!("Lab colour transform: {e}")))?; + // The layer's samples live in the space the session shows the document in, so an untagged + // document is read in its working space here too (#14224): Lab bounds that Replace Color works + // in, and the Gamut Warning marks, agree. + let source = s.color().document_profile(&st.doc); + let transform = + craft_cms::cached(&source, Builtin::LabD50.profile(), TransformOptions::default()).map_err(|e| bad(CMD, format!("Lab colour transform: {e}")))?; if transform.inputs() != format.mode.color_channels() || transform.outputs() != 3 || format.channels() != transform.inputs() + usize::from(format.alpha) { return Err(bad(CMD, "unsupported Lab colour-transform layout")); } diff --git a/crates/engine-core/src/cmd/channel_cmds.rs b/crates/engine-core/src/cmd/channel_cmds.rs index 371a4e18866..a595d6712d9 100644 --- a/crates/engine-core/src/cmd/channel_cmds.rs +++ b/crates/engine-core/src/cmd/channel_cmds.rs @@ -175,7 +175,7 @@ pub fn specs() -> Vec { "Load Selection…", ["Select"], None, - r##"{"channel":index|name|"composite"|"red|green|blue|…"|"transparency"|"mask"|"vectorMask"|"quickMask"|"selection"|"targeted" (the Channels panel's target),"layer":id|name|{"name":str}|{"background":true}?,"document":index?,"invert":bool=false,"operation":"new|add|subtract|intersect"="new"}"##, + r##"{"channel":index|name|"composite"|"red|green|blue|…"|"transparency"|"mask"|"vectorMask"|"quickMask"|"selection"|"targeted" (the Channels panel's target),"layer":id|name|{"name":str}|{"background":true}?,"document":index?,"invert":bool=false,"operation":"new|add|subtract|intersect"="new"} (an RGB composite loads its luminosity converted into the working gray, edit.colorSettings workingGray; partial coverage combines as channels do: add screens, subtract keeps a·(1−b), intersect multiplies)"##, has_doc, load_selection ), diff --git a/crates/engine-core/src/cmd/channel_cmds/selection.rs b/crates/engine-core/src/cmd/channel_cmds/selection.rs index ee81444c11f..7ef9c643685 100644 --- a/crates/engine-core/src/cmd/channel_cmds/selection.rs +++ b/crates/engine-core/src/cmd/channel_cmds/selection.rs @@ -1,7 +1,11 @@ use super::planes::{channel_format, next_alpha_name, plane_surface, read_plane}; use super::refs::{ChanRef, bad, doc_index, parse_ref, source}; use super::view::{ChannelTarget, QuickMaskOptions}; -use super::{AlphaChannel, ColorIndicates, Document, EngineError, PixelFormat, Rect, Result, SelectionMode, Session, Surface, Value, json, operation, sel}; +use super::{ + AlphaChannel, ColorIndicates, ColorMode, Document, EngineError, PixelFormat, Rect, Result, SelectionMode, Session, Surface, Value, json, operation, sel, +}; +use crate::color_cmds::{ColorExt, cms_err, document_profile}; +use craft_cms::TransformOptions; pub(super) fn save_selection(s: &mut Session, p: &Value) -> Result { let cmd = "select.saveSelection"; @@ -77,6 +81,43 @@ fn load_label(doc: &Document, p: &Value) -> &'static str { } } +/// The composite of an RGB document as a luminosity selection, as Photoshop builds one: the composite converted +/// from the document's profile into the working gray (Edit › Color Settings › Gray) with the Color Settings +/// conversion options. The working gray decides how much each tone is selected: with Gray Gamma 2.2 (Adobe RGB's +/// tone curve) a middle grey loads about half selected, with a dot gain gray clearly less, and the 50 % ants move +/// with it. `None` for any other channel or document mode, which loads its values as before. Source: Greg Benz, +/// "How to optimize your gray working space for better luminosity masks" (gregbenzphotography.com). +fn composite_luminosity(s: &Session, p: &Value, cmd: &str) -> Result>> { + // Pixels converted per call, so the interleaved RGB copy stays small. + const BAND: usize = 1 << 16; + let di = doc_index(s, p, "document")?; + let Some(doc) = s.documents().get(di).map(|st| &st.doc) else { return Ok(None) }; + if doc.mode != ColorMode::Rgb || p.get("channel").and_then(|v| parse_ref(v, doc)) != Some(ChanRef::Composite) { + return Ok(None); + } + // Invert applies to the gray, after the conversion, not to each colour plane. + let mut plain = p.clone(); + if let Some(m) = plain.as_object_mut() { + m.remove("invert"); + } + let planes = source(s, &plain, cmd, false)?; + let [red, green, blue] = planes.as_slice() else { return Ok(None) }; + let color = s.color(); + let options = TransformOptions { intent: color.settings.intent(), bpc: color.settings.bpc, ..TransformOptions::default() }; + let transform = craft_cms::cached(&document_profile(doc), &color.working(ColorMode::Grayscale), options).map_err(cms_err)?; + let mut gray = vec![0.0f32; red.len()]; + let mut rgb = Vec::with_capacity(BAND * 3); + for (((out, r), g), b) in gray.chunks_mut(BAND).zip(red.chunks(BAND)).zip(green.chunks(BAND)).zip(blue.chunks(BAND)) { + rgb.clear(); + rgb.extend(r.iter().zip(g).zip(b).flat_map(|((&r, &g), &b)| [r, g, b])); + transform.convert_f32(&rgb, 3, out, 1, false).map_err(cms_err)?; + } + if p.get("invert").and_then(Value::as_bool).unwrap_or(false) { + gray.iter_mut().for_each(|v| *v = 1.0 - *v); + } + Ok(Some(gray)) +} + pub(super) fn load_selection(s: &mut Session, p: &Value) -> Result { let cmd = "select.loadSelection"; let mode = match operation(p, "operation") { @@ -103,12 +144,19 @@ pub(super) fn load_selection(s: &mut Session, p: &Value) -> Result { }; } let p = &targeted; - // Composite and colour channels load their luminosity / values, as ⌘-clicking them does. - let plane = source(s, p, cmd, true)?.into_iter().next().ok_or_else(|| bad(cmd, "the channel has no pixels"))?; + // An RGB composite loads its luminosity in the working gray; other channels (colour channels, alphas, masks) + // load their values, as ⌘-clicking them does. + let plane = match composite_luminosity(s, p, cmd)? { + Some(plane) => plane, + None => source(s, p, cmd, true)?.into_iter().next().ok_or_else(|| bad(cmd, "the channel has no pixels"))?, + }; let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; let label = load_label(doc, p); + // A loaded channel meets the selection with channel arithmetic (multiply, screen), as Photoshop combines one: + // ⌘⇧⌥-clicking the composite again narrows a luminosity selection to brighter tones each time (lights, + // brighter lights, … up to the pure whites), where min / max would leave it unchanged. let selected = s.edit(label, |doc, _| { - doc.selection = sel::combine(doc.selection.as_ref(), &plane, doc.bounds(), mode); + doc.selection = sel::combine_scaled(doc.selection.as_ref(), &plane, doc.bounds(), mode); Ok(doc.selection.is_some()) })?; Ok(json!({ "selected": selected })) diff --git a/crates/engine-core/src/cmd/channel_cmds/tests.rs b/crates/engine-core/src/cmd/channel_cmds/tests.rs index 19666516f78..fcf9dac2bae 100644 --- a/crates/engine-core/src/cmd/channel_cmds/tests.rs +++ b/crates/engine-core/src/cmd/channel_cmds/tests.rs @@ -101,6 +101,72 @@ fn load_selection_operations_and_invert() { assert_eq!(sel_at(&s, 25, 5), 1.0); } +/// Paints the 40 × 20 background with neutral greys, `grey(x)` in column `x` (`edit.fill` is +/// engine-paint's, not in this crate's session). +fn paint_greys(s: &mut Session, grey: impl Fn(usize) -> f32) { + let d = s.active_mut().unwrap(); + let id = d.active_layer.unwrap(); + let surf = std::sync::Arc::make_mut(d.doc_mut()).layer_mut(id).unwrap().surface_mut().unwrap(); + let n = surf.format().channels(); + let mut px = vec![1.0; 40 * 20 * n]; + for (i, p) in px.chunks_exact_mut(n).enumerate() { + p[..3].fill(grey(i % 40)); + } + surf.write_region(Rect::new(0, 0, 40, 20), &px); +} + +#[test] +fn intersecting_the_composite_luminosity_with_itself_narrows_it_toward_the_whites() { + // Luminosity masks: ⌘-click the composite, then ⌘⇧⌥-click it again and again. Each step multiplies the + // selection by the luminosity, so it narrows to brighter tones while white stays fully selected; Select All + // minus the lights minus the darks leaves the midtones. Min / max combining left the first unchanged and the + // second empty. + for depth in [8, 16] { + let mut s = session_depth(depth); + // Neutral greys from black (x 0) to white (x 39). + paint_greys(&mut s, |x| x as f32 / 39.0); + let load = |s: &mut Session, operation: &str, invert: bool| { + s.execute("select.loadSelection", json!({"channel": "composite", "operation": operation, "invert": invert})).unwrap(); + (0..40).map(|x| sel_at(s, x, 5)).collect::>() + }; + let lights = load(&mut s, "new", false); + let lights2 = load(&mut s, "intersect", false); + let lights3 = load(&mut s, "intersect", false); + let step = 1.0 / 255.0 + 1e-6; + for x in 1..39 { + assert!(lights2[x] < lights[x] && lights3[x] <= lights2[x], "depth {depth}, x {x}: each step selects every grey less"); + assert!((lights2[x] - lights[x] * lights[x]).abs() <= step, "depth {depth}, x {x}: the step multiplies by the luminosity"); + } + assert!(lights3[20] < lights2[20], "depth {depth}: a middle grey keeps narrowing"); + assert!([&lights, &lights2, &lights3].iter().all(|l| l[39] == 1.0 && l[0] == 0.0), "depth {depth}: white stays selected, black never is"); + s.execute("select.all", json!({})).unwrap(); + let darks = load(&mut s, "subtract", false); + assert!(darks[0] == 1.0 && darks[39] == 0.0 && darks[20] > 0.4, "depth {depth}: Select All minus the lights is the darks"); + let mids = load(&mut s, "subtract", true); + assert!(mids[0] == 0.0 && mids[39] == 0.0, "depth {depth}: the midtones hold neither black nor white"); + assert!(mids[20] > 0.2 && mids[20] > mids[5] && mids[20] > mids[34], "depth {depth}: they peak at the middle grey"); + } +} + +#[test] +fn the_composite_loads_its_luminosity_in_the_working_gray() { + // ⌘-click on the composite converts it into Color Settings › Gray, as Photoshop does: a dot gain gray selects a + // middle grey clearly less than Gray Gamma 2.2 (about half), so the 50 % ants move with the setting. Inverting + // inverts that gray, not each colour plane before the conversion. + let load = |gray: &str, invert: bool| { + let mut s = session(); + s.execute("edit.colorSettings", json!({"workingGray": gray})).unwrap(); + paint_greys(&mut s, |_| 128.0 / 255.0); + s.execute("select.loadSelection", json!({"channel": "composite", "invert": invert})).unwrap(); + sel_at(&s, 5, 5) + }; + let (gamma, dot_gain) = (load("gray-gamma-2.2", false), load("dot-gain-20-compat", false)); + assert!((gamma - 0.5).abs() < 0.03, "Gray Gamma 2.2: a middle grey is about half selected ({gamma})"); + assert!(dot_gain < gamma - 0.05, "a dot gain gray selects it less ({dot_gain} vs {gamma})"); + let inverted = load("dot-gain-20-compat", true); + assert!((inverted - (1.0 - dot_gain)).abs() <= 1.0 / 255.0 + 1e-6, "inverted: {inverted} vs 1 - {dot_gain}"); +} + #[test] fn channel_management_and_view_state() { let mut s = session(); diff --git a/crates/engine-core/src/cmd/color_cmds.rs b/crates/engine-core/src/cmd/color_cmds.rs index 95acb5e2039..6ae8e703be6 100644 --- a/crates/engine-core/src/cmd/color_cmds.rs +++ b/crates/engine-core/src/cmd/color_cmds.rs @@ -3,8 +3,10 @@ //! Colors / Gamut Warning) and the display transform the canvas applies. //! //! Document space: `Document::icc_profile` holds the document's ICC bytes (kept byte-exact -//! from PSD resource 1039 / PNG iCCP / JPEG APP2 / TIFF). `None` means untagged: the working -//! profile of the mode is assumed (sRGB, sGray, the built-in coated CMYK, Lab D50). +//! from PSD resource 1039 / PNG iCCP / JPEG APP2 / TIFF). `None` means untagged: RGB and gray +//! documents are then taken in the working space of Color Settings ([`ColorState::working`], +//! sRGB and the default working gray unless the settings say otherwise, #14224), the other modes +//! in the mode's built-in default (the built-in coated CMYK, Lab D50). //! //! Compositing stays in document space for RGB and gray documents. CMYK and Lab documents are //! composited in sRGB after a per-layer conversion with the built-in profiles (see @@ -111,7 +113,8 @@ impl Policy { /// Edit › Color Settings: working spaces, colour management policies and conversion options. /// Honoured when files are opened ([`ColorExt::open_document`](crate::color_cmds::ColorExt::open_document)), by Image › Mode conversions -/// and by "working" profile specs (Convert to Profile, Proof Setup). +/// and by "working" profile specs (Convert to Profile, Proof Setup). An untagged RGB or Grayscale +/// document is taken in the working space as well, on screen and in conversions (#14224). #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] #[serde(default, rename_all = "camelCase", remote = "Self")] pub struct ColorSettings { @@ -468,6 +471,52 @@ impl ColorState { } } + /// The profile an untagged document is taken in: Color Settings' working space for the two + /// modes #14224 measures, otherwise the mode's built-in default, as [`working_profile`] gives. + pub fn untagged_profile(&self, doc: &Document) -> Arc { + match doc.mode { + ColorMode::Rgb | ColorMode::Grayscale => self.working(doc.mode), + _ => working_profile(doc.mode), + } + } + + /// The document's profile as this session sees it: [`document_profile`], except that an + /// untagged RGB or Grayscale document falls back to Color Settings' working space instead of + /// the mode's built-in default (#14224). A tagged document, and every other mode, resolve + /// exactly as the free function does. + pub fn document_profile(&self, doc: &Document) -> Arc { + embedded_profile(doc).unwrap_or_else(|| self.untagged_profile(doc)) + } + + /// [`composite_profile`] as this session sees it: an untagged document's composite is + /// described by the working space it is shown in (#14224). + pub fn composite_profile(&self, doc: &Document) -> Arc { + match mode_space(doc.mode) { + ColorSpace::Rgb => self.document_profile(doc), + ColorSpace::Gray => { + let p = self.document_profile(doc); + // sGray is a TRC profile, so its RGB view always exists; sRGB is the last resort. + p.gray_as_rgb().or_else(|| Builtin::SGray.profile().gray_as_rgb()).map(Arc::new).unwrap_or_else(|| Arc::new(Builtin::Srgb.profile().clone())) + } + _ => Arc::new(Builtin::Srgb.profile().clone()), + } + } + + /// The working-space spec Color Settings holds for `mode`, with the intent that spec is + /// validated against: the cheap stand-in for [`Self::working`] in the display cache key, + /// which runs on every frame and would otherwise clone the profile's tables (or read its + /// `.icc` file) each time (#14224). + pub fn working_space_spec(&self, mode: ColorMode) -> Option<&str> { + self.settings.working_spec(mode_space(mode)) + } + + /// [`gamut_mask`] as this session sees `doc`: the composite is judged in the profile the canvas + /// shows it in, so the Gamut Warning count and Color Range › Out of Gamut agree with the pixels + /// the canvas marks (#14224). + pub fn gamut_mask(&self, doc: &Document, setup: &ProofSetup, threshold: f32) -> Result<(Vec, usize)> { + gamut_mask_against(doc, &self.composite_profile(doc), setup, threshold) + } + /// Apply the colour management policy to a document being opened. Returns what happened /// (`action`: kept|converted|discarded|assigned|untagged) and whether to ask the user. /// @@ -549,7 +598,7 @@ impl ColorState { } let working = self.working(doc.mode); let policy = self.settings.policy(doc.mode); - let embedded = doc.icc_profile.as_ref().and_then(|b| profile_from_bytes(b).ok()).filter(|p| p.color_space == space); + let embedded = embedded_profile(doc); match embedded { Some(emb) => { let linear_hdr = @@ -579,7 +628,13 @@ impl ColorState { pub fn resolve_open(&self, doc: &mut Document, action: &str) -> Result<()> { match action { "preserve" | "useEmbedded" => Ok(()), - "convert" | "convertToWorking" => convert_document(doc, &self.working(doc.mode), self.settings.intent(), self.settings.bpc), + // An untagged document already lives in the working space, so converting it to that + // space keeps its samples and only tags it (#14224); a tagged one converts from its + // embedded profile as before. + "convert" | "convertToWorking" => { + let untagged = self.untagged_profile(doc); + convert_document_from(doc, &untagged, &self.working(doc.mode), self.settings.intent(), self.settings.bpc) + } "discard" | "off" => { doc.icc_profile = None; Ok(()) @@ -821,6 +876,11 @@ pub fn profile_from_bytes(bytes: &Arc>) -> std::result::Result Option> { + doc.icc_profile.as_ref().and_then(|b| profile_from_bytes(b).ok()).filter(|p| p.color_space == mode_space(doc.mode)) +} + /// The document's profile: its embedded profile when it parses and matches the mode, /// otherwise the mode's working profile. pub fn document_profile(doc: &Document) -> Arc { @@ -1155,13 +1215,23 @@ fn paint_colors(p: &mut FxPaint, cc: &mut dyn FnMut(&mut Color)) { /// converted. A Duotone document going to a colour space starts from its ink colours /// ([`ink_duotone`]). The document is tagged with `dst`. pub fn convert_document(doc: &mut Document, dst: &Profile, intent: Intent, bpc: bool) -> Result<()> { + let untagged = working_profile(doc.mode); + convert_document_from(doc, &untagged, dst, intent, bpc) +} + +/// [`convert_document`] with the profile an untagged document is taken in given explicitly: for a +/// session that is Color Settings' working space, which the free function cannot know (#14224). +/// Only that fallback changes: a document with a usable embedded profile converts from it, read +/// after [`ink_duotone`] has turned a Duotone one into sRGB, exactly as [`convert_document`] does. +pub fn convert_document_from(doc: &mut Document, untagged: &Profile, dst: &Profile, intent: Intent, bpc: bool) -> Result<()> { let to_mode = space_mode(dst.color_space).ok_or_else(|| EngineError::Other(format!("cannot convert to a {:?} profile", dst.color_space)))?; if to_mode != ColorMode::Grayscale { ink_duotone(doc); } - let src = document_profile(doc); + let embedded = embedded_profile(doc); + let src: &Profile = embedded.as_deref().unwrap_or(untagged); let from_mode = doc.pixel_format().mode; - let t = Transform::new(&src, dst, intent, bpc).map_err(cms_err)?; + let t = Transform::new(src, dst, intent, bpc).map_err(cms_err)?; let fmt = PixelFormat::new(to_mode, doc.depth, true); crate::image_cmds::for_each_surface(&mut doc.layers, false, &mut |surf, _| { let f = PixelFormat { alpha: surf.format().alpha, ..fmt }; @@ -1274,7 +1344,10 @@ pub fn convert_mode(s: &mut Session, mode: ColorMode, p: &Value) -> Result s.color().resolve(spec, Some(doc), Some(mode))?, - None if preserve_indexed_rgb => document_profile(doc), + // Indexed → RGB keeps its samples and its ICC bytes, so the space of the document that + // results is its embedded profile, or the working space of Color Settings when it carries + // none - the same space the canvas shows it in (#14224). + None if preserve_indexed_rgb => embedded_profile(doc).unwrap_or_else(|| s.color().working(ColorMode::Rgb)), None => s.color().working(mode), }; if space_mode(dst.color_space) @@ -1288,6 +1361,9 @@ pub fn convert_mode(s: &mut Session, mode: ColorMode, p: &Value) -> Result Result Result Result<(Vec, usize)> { - let check = GamutCheck::new(&composite_profile(doc), &setup.profile, threshold).map_err(cms_err)?; + gamut_mask_against(doc, &composite_profile(doc), setup, threshold) +} + +fn gamut_mask_against(doc: &Document, source: &Profile, setup: &ProofSetup, threshold: f32) -> Result<(Vec, usize)> { + let check = GamutCheck::new(source, &setup.profile, threshold).map_err(cms_err)?; let buf = photocraft_compose::flatten(doc); let mut mask = vec![0u8; buf.px.len()]; let count = check.mask_rgba(&buf.px, &mut mask).map_err(cms_err)?; @@ -1468,8 +1551,11 @@ fn convert_to_profile(s: &mut Session, p: &Value) -> Result { // or doesn't fit the mode is still replaced. let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; let measured = matches!(doc.mode, ColorMode::Rgb | ColorMode::Cmyk | ColorMode::Grayscale | ColorMode::Lab); - let embedded = doc.icc_profile.as_ref().and_then(|b| profile_from_bytes(b).ok()).filter(|p| p.color_space == mode_space(doc.mode)); + let embedded = embedded_profile(doc); let same = measured && embedded.is_some_and(|p| p.same_colors(&dst)); + // The fallback for an untagged document is Color Settings' working space, the space it is + // shown in (#14224); a tagged document keeps the embedded profile, as `document_profile` picks. + let untagged = s.color().untagged_profile(doc); if same && !flatten && !rasterize { return Ok(json!({ "profile": dst.description, "mode": format!("{:?}", doc.mode), "intent": intent.id(), "bpc": bpc, "converted": false })); } @@ -1487,9 +1573,9 @@ fn convert_to_profile(s: &mut Session, p: &Value) -> Result { doc.icc_profile = Some(dst.to_bytes()); Ok(()) } else if dither { - profile_dither::convert(doc, &dst, intent, bpc) + profile_dither::convert(doc, &untagged, &dst, intent, bpc) } else { - convert_document(doc, &dst, intent, bpc) + convert_document_from(doc, &untagged, &dst, intent, bpc) } })?; let d = &s.active().ok_or(EngineError::NoDocument)?.doc; @@ -1506,7 +1592,7 @@ fn profile_info(s: &mut Session, p: &Value) -> Result { Some(profile_json(&prof)) } None => doc.as_deref().map(|d| { - let mut j = profile_json(&document_profile(d)); + let mut j = profile_json(&s.color().document_profile(d)); j["embedded"] = json!(d.icc_profile.is_some()); j }), @@ -1555,7 +1641,7 @@ fn gamut_warning(s: &mut Session, p: &Value) -> Result { if let Some(spec) = p.get("profile").and_then(Value::as_str) { setup.profile = resolve_profile(spec, Some(&doc), Some(ColorMode::Cmyk))?; } - let (_, count) = gamut_mask(&doc, &setup, threshold)?; + let (_, count) = s.color().gamut_mask(&doc, &setup, threshold)?; let total = doc.size.width as usize * doc.size.height as usize; Ok(json!({ "on": on, "profile": setup.profile.description, "threshold": threshold, "outOfGamut": count, "fraction": count as f64 / total.max(1) as f64 })) } @@ -1699,7 +1785,10 @@ fn profile_mismatch(s: &mut Session, p: &Value) -> Result { "convert" | "convertToWorking" => { let dst = s.color().working(mode); let (intent, bpc) = (s.color().settings.intent(), s.color().settings.bpc); - s.edit("Convert to Working RGB", |doc, _| convert_document(doc, &dst, intent, bpc))?; + // An untagged document answers this dialog in its working space, not in the built-in + // default (#14224); a tagged one keeps its embedded profile. + let untagged = s.color().untagged_profile(&s.active().ok_or(EngineError::NoDocument)?.doc); + s.edit("Convert to Working RGB", |doc, _| convert_document_from(doc, &untagged, &dst, intent, bpc))?; Ok(json!({"action": "converted", "profile": dst.description})) } "discard" | "off" => { @@ -2092,6 +2181,10 @@ mod assign_profile_enabled_modes_tests; #[path = "../color_settings_presets_tests.rs"] mod color_settings_presets_tests; +#[cfg(test)] +#[path = "../color_settings_untagged_display_tests.rs"] +mod color_settings_untagged_display_tests; + #[cfg(test)] mod settings_tests { use super::*; diff --git a/crates/engine-core/src/cmd/color_cmds/profile_dither.rs b/crates/engine-core/src/cmd/color_cmds/profile_dither.rs index 6868532c55e..11ae970e648 100644 --- a/crates/engine-core/src/cmd/color_cmds/profile_dither.rs +++ b/crates/engine-core/src/cmd/color_cmds/profile_dither.rs @@ -7,8 +7,8 @@ use photocraft_raster::Tile; use rayon::prelude::*; use super::{ - ColorMode, Document, EngineError, Intent, PixelFormat, Profile, Result, SampleType, Surface, Transform, cms_err, convert_color, convert_document, - convert_layer_colors, convert_style_colors, convert_surface, document_profile, space_mode, + ColorMode, Document, EngineError, Intent, PixelFormat, Profile, Result, SampleType, Surface, Transform, cms_err, convert_color, convert_document_from, + convert_layer_colors, convert_style_colors, convert_surface, embedded_profile, space_mode, }; const TILE_PIXELS: u128 = (TILE_SIZE * TILE_SIZE) as u128; @@ -149,14 +149,17 @@ fn dither_tile(s: &Surface, out: &Surface, t: &Transform, bounds: Rect, c: TileC } /// Preserve ordinary conversion outside opt-in U8, admitting the whole dither edit first. -pub(super) fn convert(doc: &mut Document, dst: &Profile, intent: Intent, bpc: bool) -> Result<()> { - let src = document_profile(doc); +/// `untagged` is the profile an untagged document is taken in: Color Settings' working space, +/// which only the session knows (#14224); a tagged document still converts from its embedded one. +pub(super) fn convert(doc: &mut Document, untagged: &Profile, dst: &Profile, intent: Intent, bpc: bool) -> Result<()> { + let embedded = embedded_profile(doc); + let src: &Profile = embedded.as_deref().unwrap_or(untagged); if doc.depth != SampleType::U8 || src.to_bytes() == dst.to_bytes() || doc.mode == ColorMode::Duotone { - return convert_document(doc, dst, intent, bpc); + return convert_document_from(doc, untagged, dst, intent, bpc); } let to_mode = space_mode(dst.color_space).ok_or_else(|| EngineError::Other(format!("cannot convert to a {:?} profile", dst.color_space)))?; let from = doc.pixel_format().mode; - let t = Transform::new(&src, dst, intent, bpc).map_err(cms_err)?; + let t = Transform::new(src, dst, intent, bpc).map_err(cms_err)?; let format = PixelFormat::new(to_mode, doc.depth, true); let bounds = doc.bounds(); if doc.size.width > i32::MAX as u32 || doc.size.height > i32::MAX as u32 { diff --git a/crates/engine-core/src/cmd/file_cmds/raw_defaults_sharpen_tests.rs b/crates/engine-core/src/cmd/file_cmds/raw_defaults_sharpen_tests.rs new file mode 100644 index 00000000000..ec84e4e30b3 --- /dev/null +++ b/crates/engine-core/src/cmd/file_cmds/raw_defaults_sharpen_tests.rs @@ -0,0 +1,87 @@ +//! RAW Defaults output sharpening (#17776). + +use photocraft_algo::camera_raw::CameraRaw; +use photocraft_raw::testgen::{DngSpec, mosaic}; +use serde_json::json; + +use crate::prefs::{RawColorSpace, RawSharpen, RawSharpenAmount, SavedPrefsExt}; +use crate::{Session, file_cmds}; + +#[test] +fn saved_media_keep_their_existing_strength_without_an_amount() { + for (medium, expected) in [("none", None), ("screen", Some((25.0, 1.0))), ("glossy", Some((40.0, 1.0))), ("matte", Some((35.0, 1.2)))] { + let mut s = crate::session(); + let saved = json!({"rawDefaults": {"sharpenFor": medium}}); + assert!(s.load_prefs_json(&saved.to_string()).unwrap().is_empty()); + let defaults = &s.prefs().raw_defaults; + assert_eq!(defaults.sharpen_amount, RawSharpenAmount::Standard); + let mut settings = CameraRaw::default(); + assert_eq!(defaults.apply_output_sharpening(&mut settings), expected.is_some()); + if let Some(pair) = expected { + assert_eq!((settings.sharpen_amount, settings.sharpen_radius), pair); + } else { + assert_eq!(settings, CameraRaw::default()); + } + } +} + +#[test] +fn prefs_set_rejects_unknown_sharpening_amounts_and_keeps_the_previous_choice() { + let mut s = crate::session(); + let path = "rawDefaults.sharpenAmount"; + for valid in ["low", "standard", "high"] { + s.execute("prefs.set", json!({"path":path, "value":valid})).unwrap(); + assert_eq!(s.execute("prefs.get", json!({"path":path})).unwrap(), json!(valid)); + } + for invalid in [json!("medium"), json!(25)] { + let err = s.execute("prefs.set", json!({"path":path, "value":invalid})).unwrap_err(); + assert!(err.to_string().contains(path), "{err}"); + assert_eq!(s.prefs().raw_defaults.sharpen_amount, RawSharpenAmount::High); + } +} + +#[test] +fn raw_detail_sharpening_takes_precedence_over_output_sharpening() { + let mut s = crate::session(); + s.execute("prefs.set", json!({"values":{"rawDefaults.sharpenFor":"matte","rawDefaults.sharpenAmount":"high"}})).unwrap(); + let mut detail = CameraRaw::default(); + detail.sharpen_amount = 12.0; + detail.sharpen_radius = 2.0; + let mut settings = detail.clone(); + assert!(!s.prefs().raw_defaults.apply_output_sharpening(&mut settings)); + assert_eq!(settings, detail); +} + +#[test] +fn quiet_raw_sharpening_levels_order_the_pixel_change_from_unsharpened() { + let (w, h) = (24, 16); + // Keep the edge away from clipping so each change in strength can affect the pixels. + let scene: Vec<_> = (0..w * h).map(|i| if i % w < w / 2 { [0.20; 3] } else { [0.32; 3] }).collect(); + let raw = DngSpec::cfa(w, h, mosaic(&scene, w, [0, 1, 1, 2], 0, 65535)).build(); + let open = |medium, amount| { + let mut s = crate::session(); + s.execute("edit.colorSettings", json!({"askOnMismatch":false,"askOnMissing":false})).unwrap(); + let mut defaults = s.prefs().raw_defaults.clone(); + defaults.color_space = RawColorSpace::ProPhoto; + defaults.sharpen_for = medium; + defaults.sharpen_amount = amount; + s.batch_raw_open = Some(defaults); + file_cmds::open_bytes_as(&mut s, "IMG_0001.dng", &raw, None, None).unwrap(); + s + }; + let pixels = |s: &Session| { + let doc = &s.active().unwrap().doc; + photocraft_compose::render(doc, doc.bounds()) + }; + let off = open(RawSharpen::None, RawSharpenAmount::High); + let unsharpened = pixels(&off); + let distance = |developed: &[[f32; 4]]| developed.iter().flatten().zip(unsharpened.px.iter().flatten()).map(|(a, b)| f64::from((a - b).abs())).sum::(); + let [low, standard, high] = + [RawSharpenAmount::Low, RawSharpenAmount::Standard, RawSharpenAmount::High].map(|amount| pixels(&open(RawSharpen::Screen, amount))); + let (low_distance, standard_distance, high_distance) = (distance(&low.px), distance(&standard.px), distance(&high.px)); + assert!(0.0 < low_distance && low_distance < standard_distance && standard_distance < high_distance); + + let mut previous = off; + previous.execute("filter.cameraRaw", json!({"sharpenAmount":25.0,"sharpenRadius":1.0})).unwrap(); + assert_eq!(standard.px.as_slice(), pixels(&previous).px.as_slice()); +} diff --git a/crates/engine-core/src/cmd/file_cmds/raw_open.rs b/crates/engine-core/src/cmd/file_cmds/raw_open.rs index eb61322f353..908d8386e14 100644 --- a/crates/engine-core/src/cmd/file_cmds/raw_open.rs +++ b/crates/engine-core/src/cmd/file_cmds/raw_open.rs @@ -112,12 +112,7 @@ pub(super) fn prepare(s: &Session, name: &str, shown: &str, path: Option<&str>, settings.tint = 0.0; } } - if let Some((amount, radius)) = defaults.sharpen_for.preset() - && settings.sharpen_amount == 0.0 - { - settings.sharpen_amount = amount; - settings.sharpen_radius = radius; - } + defaults.apply_output_sharpening(&mut settings); Ok(Some((imported, settings))) } @@ -148,3 +143,7 @@ pub(super) fn finish(s: &mut Session, settings: CameraRaw) -> Result<()> { } Ok(()) } + +#[cfg(test)] +#[path = "raw_defaults_sharpen_tests.rs"] +mod raw_defaults_sharpen_tests; diff --git a/crates/engine-core/src/cmd/layer_copy_cmds.rs b/crates/engine-core/src/cmd/layer_copy_cmds.rs index 4671ed0ee8f..6526a175610 100644 --- a/crates/engine-core/src/cmd/layer_copy_cmds.rs +++ b/crates/engine-core/src/cmd/layer_copy_cmds.rs @@ -112,8 +112,12 @@ pub(crate) fn adapt_copies(s: &Session, copies: &mut Document, dest: &Document) } } if (copies.mode, &copies.icc_profile) != (dest.mode, &dest.icc_profile) { - let profile = crate::color_cmds::document_profile(dest); - crate::color_cmds::convert_document(copies, &profile, s.color().settings.intent(), s.color().settings.bpc)?; + // Both sides are read as the session reads them: an untagged document, source or + // destination, is taken in its working space (#14224), so the copies keep their look on + // the destination's canvas instead of landing as raw numbers. + let untagged = s.color().untagged_profile(copies); + let profile = s.color().document_profile(dest); + crate::color_cmds::convert_document_from(copies, &untagged, &profile, s.color().settings.intent(), s.color().settings.bpc)?; } if copies.depth != dest.depth { crate::image_cmds::for_each_surface(&mut copies.layers, true, &mut |surf, _| { diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/tests.rs b/crates/engine-core/src/cmd/layer_multi_cmds/tests.rs index 0f43ef63782..f8f519d0ff6 100644 --- a/crates/engine-core/src/cmd/layer_multi_cmds/tests.rs +++ b/crates/engine-core/src/cmd/layer_multi_cmds/tests.rs @@ -967,6 +967,182 @@ fn merging_keeps_layer_effects_outside_the_pixels() { } } +#[test] +fn merging_down_keeps_the_lower_layers_style_live_on_the_union() { + // Merge Down over a styled layer keeps its style live, as in Photoshop, where it + // re-composes over the merged pixels: the glow that only surrounded the lower layer now + // surrounds the union of both layers' content. + let probe = |s: &Session| { + let d = doc(s); + photocraft_compose::render(d, d.bounds()).get(75, 26) + }; + for depth in [8, 16, 32] { + let mut s = session(depth); + let lower = rect_layer(&mut s, Rect::new(10, 10, 30, 30)); + let upper = rect_layer(&mut s, Rect::new(60, 20, 72, 32)); + s.execute("layer.layerStyle.outerGlow", json!({"layer": lower.0, "blend": "normal", "size": 6, "color": "#000000", "add": true})).unwrap(); + let before = probe(&s); + assert!(before.iter().all(|v| *v > 0.9), "depth {depth}: the glow never reaches the probe before the merge: {before:?}"); + s.execute("layer.mergeDown", json!({"layer": upper.0})).unwrap(); + let merged = doc(&s).layer(lower).unwrap().clone(); + assert!(doc(&s).layer(upper).is_none()); + assert_eq!(merged.effects.items.len(), 1); + assert!(merged.effects.items.iter().all(photocraft_doc::Effect::enabled), "the style stays live on the merged layer"); + let after = probe(&s); + assert!( + after.iter().take(3).zip(&before).all(|(a, b)| *a < *b - 0.03), + "depth {depth}: the glow re-applies to the merged union: {before:?} -> {after:?}" + ); + } +} + +#[test] +fn merging_down_inherits_the_lower_layers_fill_opacity() { + // Photoshop inherits the fill onto the merged layer (fixtures in PR #8750): merging onto a + // Fill-0% lower layer keeps the union ink in the pixels but invisible, and only the live + // style — re-rendered around the union — shows. The property is not reset to opaque. + let ink = |s: &Session| { + let d = doc(s); + photocraft_compose::render(d, d.bounds()).get(66, 26) + }; + let glow = |s: &Session| { + let d = doc(s); + photocraft_compose::render(d, d.bounds()).get(75, 26) + }; + for depth in [8, 16, 32] { + let mut s = session(depth); + let lower = rect_layer(&mut s, Rect::new(10, 10, 30, 30)); + let upper = rect_layer(&mut s, Rect::new(60, 20, 72, 32)); + s.execute("layer.layerStyle.outerGlow", json!({"layer": lower.0, "blend": "normal", "size": 6, "color": "#000000", "add": true})).unwrap(); + s.edit("zero fill", |doc, _| { + doc.layer_mut(lower).unwrap().fill_opacity = 0.0; + Ok(()) + }) + .unwrap(); + let before_ink = ink(&s); + let before_glow = glow(&s); + s.execute("layer.mergeDown", json!({"layer": upper.0})).unwrap(); + let merged = doc(&s).layer(lower).unwrap().clone(); + assert_eq!(merged.fill_opacity, 0.0, "depth {depth}: the fill inherits onto the merged layer"); + assert_eq!(merged.effects.items.len(), 1, "depth {depth}: the style stays live"); + let after_ink = ink(&s); + assert!(after_ink.iter().take(3).all(|v| *v > 0.9), "depth {depth}: the inherited zero fill hides the union ink: {before_ink:?} -> {after_ink:?}"); + let after_glow = glow(&s); + assert!( + after_glow.iter().take(3).zip(&before_glow).all(|(a, b)| *a < *b - 0.03), + "depth {depth}: the glow re-renders around the invisible union: {before_glow:?} -> {after_glow:?}" + ); + } +} + +#[test] +fn merging_down_applies_the_inherited_fill_to_the_baked_ink() { + // Observed in Photoshop (fixtures in PR #8750: each layer holds one opaque circle and one + // painted at 50% brush opacity). Merge Down bakes the visible pixels — with the lower + // layer's Fill already applied — onto the merged layer, and the merged layer inherits that + // same Fill, so the lower content is attenuated twice: at Fill 50% the opaque circle lands + // on a quarter (0.5 × 0.5) and the half-transparent one on an eighth, while the upper + // circles stay at half and a quarter. At Fill 0% the lower ink is already empty when baked + // and the rest leaves the composite through the inherited fill — as in the fixtures, where + // the lower shape and its glow vanish; at Fill 100% the merge changes nothing visible. + let alpha_at = |s: &Session, x: i32, y: i32| { + let d = doc(s); + photocraft_compose::render(d, d.bounds()).get(x, y)[3] + }; + let alphas = |s: &Session| [alpha_at(s, 30, 30), alpha_at(s, 30, 80), alpha_at(s, 130, 30), alpha_at(s, 130, 80)]; + let close = |got: &[f32; 4], want: [f32; 4]| got.iter().zip(&want).all(|(g, w)| (g - w).abs() < 0.01); + let (all, top_only) = (Rect::new(10, 10, 150, 100), Rect::new(110, 10, 150, 100)); + // (Fill, alpha of [lower opaque, lower half, upper opaque, upper half] after the merge, + // the ink baked into the merged layer) + let cases = [(1.0f32, [1.0, 0.5, 1.0, 0.5], all), (0.5, [0.25, 0.125, 0.5, 0.25], all), (0.0, [0.0; 4], top_only)]; + for (fill, after, baked) in cases { + for depth in [8, 16, 32] { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 160, "height": 120, "depth": depth, "background": "transparent"})).unwrap(); + let lower = rect_layer(&mut s, Rect::new(10, 10, 50, 50)); + let upper = rect_layer(&mut s, Rect::new(110, 10, 150, 50)); + let half = |s: &mut Session, id: LayerId, r: Rect| { + s.edit("half", |doc, _| { + doc.layer_mut(id).unwrap().surface_mut().unwrap().fill_rect(r, &[0.0, 0.0, 1.0, 0.5]); + Ok(()) + }) + .unwrap(); + }; + half(&mut s, lower, Rect::new(10, 60, 50, 100)); + half(&mut s, upper, Rect::new(110, 60, 150, 100)); + s.edit("fill", |doc, _| { + doc.layer_mut(lower).unwrap().fill_opacity = fill; + Ok(()) + }) + .unwrap(); + let before = alphas(&s); + assert!( + close(&before, [fill, fill * 0.5, 1.0, 0.5]), + "depth {depth}, fill {fill}: the lower layer's own fill attenuates it once before the merge: {before:?}" + ); + let layers_before = doc(&s).layer_count(); + s.execute("layer.mergeDown", json!({"layer": upper.0})).unwrap(); + let merged = doc(&s).layer(lower).unwrap().clone(); + assert!(doc(&s).layer(upper).is_none(), "depth {depth}, fill {fill}: the upper layer merged down"); + assert_eq!(doc(&s).layer_count(), layers_before - 1, "depth {depth}, fill {fill}: the merge took one layer"); + assert_eq!(merged.fill_opacity, fill, "depth {depth}, fill {fill}: the fill inherits onto the merged layer"); + assert_eq!(layer_bounds(&merged).unwrap(), baked, "depth {depth}, fill {fill}: the merge bakes the visible pixels of both layers"); + let got = alphas(&s); + assert!(close(&got, after), "depth {depth}, fill {fill}: the inherited fill applies to the baked ink again: {got:?}, want {after:?}"); + s.undo(); + assert_eq!(doc(&s).layer_count(), layers_before, "depth {depth}, fill {fill}: undo brings both layers back"); + assert!(doc(&s).layer(upper).is_some(), "depth {depth}, fill {fill}: undo restores the upper layer"); + assert_eq!(doc(&s).layer(lower).unwrap().fill_opacity, fill, "depth {depth}, fill {fill}: undo restores the fill"); + assert!(close(&alphas(&s), before), "depth {depth}, fill {fill}: undo restores the composite"); + } + } +} + +#[test] +fn merging_selected_layers_bakes_the_bottom_layers_style_to_pixels() { + // Observed in Photoshop (fixtures in PR #8750): ⌘E over a selection merges the selected + // layers preserving the visible composite — the bottommost layer's style is baked into + // the merged pixels and no longer carried as a live effect, so it keeps drawing only + // around its own shape and never wraps the upper layers' content. + for depth in [8, 16, 32] { + let mut s = session(depth); + let lower = rect_layer(&mut s, Rect::new(10, 10, 30, 30)); + let upper = rect_layer(&mut s, Rect::new(60, 20, 72, 32)); + s.execute("layer.layerStyle.outerGlow", json!({"layer": lower.0, "blend": "normal", "size": 6, "color": "#000000", "add": true})).unwrap(); + let before = photocraft_compose::render(doc(&s), doc(&s).bounds()); + select_all(&mut s, &[lower, upper]); + let m = LayerId(s.execute("layer.mergeLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); + assert!(doc(&s).layer(m).unwrap().effects.items.is_empty(), "depth {depth}: Merge Layers drops the style"); + let after = photocraft_compose::render(doc(&s), doc(&s).bounds()); + let worst = before.px.iter().zip(&after.px).map(|(a, b)| a.iter().zip(b).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max)).fold(0.0f32, f32::max); + assert!(worst <= 1.5 / 255.0, "depth {depth}: Merge Layers preserves the visible composite (off by {worst})"); + } +} + +#[test] +fn merging_down_inside_the_shaped_layer_is_a_pixel_match() { + // With the upper layer fully inside the lower one's shape, the union is the same shape, so + // a correct merge is a pixel-for-pixel match: the style is neither lost, nor applied + // twice, and Global Light follows the document instead of `Document::new` defaults. + for depth in [8, 16, 32] { + let mut s = session(depth); + let lower = rect_layer(&mut s, Rect::new(10, 10, 60, 60)); + let upper = rect_layer(&mut s, Rect::new(25, 25, 45, 45)); + s.edit("light", |doc, _| { + doc.global_light = photocraft_doc::GlobalLight { angle: 20.0, altitude: 40.0 }; + Ok(()) + }) + .unwrap(); + s.execute("layer.layerStyle.dropShadow", json!({"layer": lower.0, "blend": "normal", "useGlobalLight": true, "angle": 120, "distance": 5, "spread": 0, "size": 0, "opacity": 100, "color": "#000000"})).unwrap(); + let before = photocraft_compose::render(doc(&s), doc(&s).bounds()); + s.execute("layer.mergeDown", json!({"layer": upper.0})).unwrap(); + assert!(!doc(&s).layer(lower).unwrap().effects.items.is_empty()); + let after = photocraft_compose::render(doc(&s), doc(&s).bounds()); + let worst = before.px.iter().zip(&after.px).map(|(a, b)| a.iter().zip(b).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max)).fold(0.0f32, f32::max); + assert!(worst <= 1.5 / 255.0, "depth {depth}: merge down changed the composite (off by {worst})"); + } +} + #[test] fn merging_a_group_down_preserves_the_composite() { for depth in [8, 16, 32] { diff --git a/crates/engine-core/src/cmd/mode_cmds.rs b/crates/engine-core/src/cmd/mode_cmds.rs index 64c074d1dd8..5dc7c71d06c 100644 --- a/crates/engine-core/src/cmd/mode_cmds.rs +++ b/crates/engine-core/src/cmd/mode_cmds.rs @@ -357,7 +357,9 @@ fn parse_dither(s: &str) -> Option { /// grayscale output is a scalar sample replicated into the flattened RGB view. fn working_matte_color(s: &Session, doc: &Document, color: [f32; 4]) -> Result<[f32; 3]> { let destination = match crate::color_cmds::mode_space(doc.mode) { - ColorSpace::Rgb | ColorSpace::Gray => crate::color_cmds::document_profile(doc), + // An untagged RGB or Grayscale document is taken in Color Settings' working space (#14224), + // which is where the tool colour above already lives. + ColorSpace::Rgb | ColorSpace::Gray => s.color().document_profile(doc), // CMYK and Lab flatten through the compositor's sRGB view on the pinned main path. _ => crate::color_cmds::composite_profile(doc), }; diff --git a/crates/engine-core/src/cmd/selection_cmds.rs b/crates/engine-core/src/cmd/selection_cmds.rs index 4af971c7f78..d721e187556 100644 --- a/crates/engine-core/src/cmd/selection_cmds.rs +++ b/crates/engine-core/src/cmd/selection_cmds.rs @@ -298,10 +298,12 @@ fn parse_color(p: &Value) -> [f32; 3] { } } -/// Composite RGB (the compositor's output profile for the document) → CIE Lab D50. +/// Composite RGB (the profile the session shows the document's composite in) → CIE Lab D50. fn lab_transform(s: &Session) -> Result> { let d = s.active().ok_or(EngineError::NoDocument)?; - let src = crate::color_cmds::composite_profile(&d.doc); + // An untagged document's composite is the working space (#14224), so the hue rows and the + // sampled colours select what the canvas actually shows. + let src = s.color().composite_profile(&d.doc); craft_cms::cached(&src, craft_cms::Builtin::LabD50.profile(), craft_cms::TransformOptions::default()) .map_err(|e| EngineError::Other(format!("colour management: {e}"))) } @@ -553,10 +555,11 @@ fn color_range(s: &mut Session, p: &Value) -> Result { } "outOfGamut" => { // Pixels the current proof setup (View › Proof Setup) can't reproduce, as the gamut - // warning shows them: judged on the composite. + // warning shows them: judged on the composite, in the space the canvas shows it in + // (#14224), so the selection marks the same pixels the warning marks. let d = s.active().ok_or(EngineError::NoDocument)?; let pv = s.color().proof(d.doc.id); - let (m, _) = crate::color_cmds::gamut_mask(&d.doc, &pv.setup, pv.gamut_threshold)?; + let (m, _) = s.color().gamut_mask(&d.doc, &pv.setup, pv.gamut_threshold)?; (d.doc.bounds(), m.iter().map(|v| f32::from(*v) / 255.0).collect()) } other => { diff --git a/crates/engine-core/src/cmd/smart_cmds/unpack.rs b/crates/engine-core/src/cmd/smart_cmds/unpack.rs index a2dfbc61f94..2bb946a0adc 100644 --- a/crates/engine-core/src/cmd/smart_cmds/unpack.rs +++ b/crates/engine-core/src/cmd/smart_cmds/unpack.rs @@ -25,7 +25,10 @@ fn contents(s: &Session, doc: &Document, sm: &SmartObject, intent: Intent, bpc: let mut src = decode_source(&name, &bytes)?; let mode = doc.pixel_format().mode; if src.pixel_format().mode != mode || src.icc_profile != doc.icc_profile { - crate::color_cmds::convert_document(&mut src, &crate::color_cmds::document_profile(doc), intent, bpc)?; + // An untagged document is taken in its working space (#14224): the contents are re-encoded + // into that space so they keep their look once they are layers on this canvas. + let destination = s.color().document_profile(doc); + crate::color_cmds::convert_document(&mut src, &destination, intent, bpc)?; if src.pixel_format().mode != mode { return Err(other(format!("can't convert the smart object's contents to the document's {:?} mode", doc.mode))); } diff --git a/crates/engine-core/src/cmd/variables_cmds.rs b/crates/engine-core/src/cmd/variables_cmds.rs index 4fe4c3fccc5..40f9019f1dd 100644 --- a/crates/engine-core/src/cmd/variables_cmds.rs +++ b/crates/engine-core/src/cmd/variables_cmds.rs @@ -465,22 +465,69 @@ fn split_csv(line: &str, delim: u8) -> Vec { } /// Apply each data set in turn and export the flattened document, restoring the original after. -/// `{dir, format?("png"), dataSets?[names]}` → `{files:[…],count}`. +/// `{dir, format?("png"), dataSets?[names], missingImage?, start?}` → `{files:[…],count,skipped?,stopped?}`. fn export_as_files(s: &mut Session, p: &Value) -> Result { let dir = p.get("dir").and_then(Value::as_str).ok_or_else(|| bad("file.export.dataSetsAsFiles", "need `dir`"))?.to_string(); // The directory appears only once the batch has been planned, as it always did, so a batch // rejected for colliding names still leaves no directory behind. let mut made_dir = false; - let names = export_data_sets_with(s, p, |name, bytes| { + let report = export_data_sets_report_with(s, p, |name, bytes| { if !made_dir { std::fs::create_dir_all(&dir).map_err(|e| EngineError::Other(format!("mkdir `{dir}`: {e}")))?; made_dir = true; } crate::file_cmds::write_file(&format!("{dir}/{name}"), bytes) })?; - let files: Vec = names.iter().map(|name| format!("{dir}/{name}")).collect(); - let count = files.len(); - Ok(json!({"files": files, "count": count})) + let files: Vec = report.files.iter().map(|name| format!("{dir}/{name}")).collect(); + Ok(report.json(files)) +} + +/// What a data-set export with a `missingImage` mode does when a set's Pixel Replacement image +/// does not exist (#13767). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum MissingImage { + /// The export ends with the missing-file error; the files written before it stay (the default). + Error, + /// The set is left out, listed in `skipped`, and the export goes on. + Skip, + /// The export ends without an error at that set; the result names it in `stopped`. + Stop, +} + +/// The data set a `missingImage: "stop"` export stopped at: its name, its 0-based position in the +/// batch (the `start` that resumes after it is `index + 1`), how many sets come after it and the +/// missing-file error it would have ended with. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StoppedDataSet { + pub name: String, + pub index: usize, + pub remaining: usize, + pub error: String, +} + +/// What a data-set export did: the filenames written, in order, the sets left out for a missing +/// replacement image (`missingImage: "skip"`) and the set a `"stop"` export stopped at. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct DataSetsExportReport { + pub files: Vec, + pub skipped: Vec, + pub stopped: Option, +} + +impl DataSetsExportReport { + /// The command's result, with `files` as the caller names them (joined to its folder). + pub fn json(&self, files: Vec) -> Value { + let count = files.len(); + let mut out = json!({"files": files, "count": count}); + // Listed only when a set was left out, so an export without a missing image reads as before. + if !self.skipped.is_empty() { + out["skipped"] = json!(self.skipped); + } + if let Some(stop) = &self.stopped { + out["stopped"] = json!({"name": stop.name, "index": stop.index, "remaining": stop.remaining, "error": stop.error}); + } + out + } } /// The bodies of `file.export.dataSetsAsFiles`, streamed to `write` as a single-component @@ -488,8 +535,30 @@ fn export_as_files(s: &mut Session, p: &Value) -> Result { /// so colliding names are rejected before any file is written, and automation writes exactly /// these bytes beneath its write root (#3216) — the two paths cannot drift. Returns the /// filenames written, in order. -pub fn export_data_sets_with(s: &Session, p: &Value, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result> { +pub fn export_data_sets_with(s: &Session, p: &Value, write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result> { + export_data_sets_report_with(s, p, write).map(|report| report.files) +} + +/// [`export_data_sets_with`] that also says which sets a missing replacement image left out or +/// stopped at (`missingImage`, #13767). `start` resumes a batch at that 0-based position: the +/// sets before it are not written, and `{index}` keeps counting from the first set. +pub fn export_data_sets_report_with(s: &Session, p: &Value, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result { let format = p.get("format").and_then(Value::as_str).unwrap_or("png"); + let missing = match p.get("missingImage") { + None | Some(Value::Null) => MissingImage::Error, + Some(v) => match v.as_str() { + Some("error") => MissingImage::Error, + Some("skip") => MissingImage::Skip, + Some("stop") => MissingImage::Stop, + _ => return Err(bad("file.export.dataSetsAsFiles", "`missingImage` must be \"error\", \"skip\" or \"stop\"")), + }, + }; + let start = match p.get("start") { + None | Some(Value::Null) => 0, + Some(v) => { + v.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| bad("file.export.dataSetsAsFiles", "`start` must be a whole number from 0"))? + } + }; let st = s.active().ok_or(EngineError::NoDocument)?; let original = st.doc.clone(); let vars = original.variables.clone(); @@ -498,6 +567,9 @@ pub fn export_data_sets_with(s: &Session, p: &Value, mut write: impl FnMut(&str, if sets.is_empty() { return Err(bad("file.export.dataSetsAsFiles", "no data sets to export")); } + if start >= sets.len() { + return Err(bad("file.export.dataSetsAsFiles", format!("`start` {start} is past the last of {} data sets", sets.len()))); + } // Judge every image path before anything is written, as Apply Data Set does. for set in &sets { authorize_pixel_paths(s, set)?; @@ -538,17 +610,30 @@ pub fn export_data_sets_with(s: &Session, p: &Value, mut write: impl FnMut(&str, } names.push(name); } - let mut written = Vec::new(); - for (set, name) in sets.iter().zip(&names) { + let mut report = DataSetsExportReport::default(); + for (n, (set, name)) in sets.iter().zip(&names).enumerate().skip(start) { let mut doc = (*original).clone(); - apply_to_doc(&mut doc, &vars, set)?; + match apply_to_doc(&mut doc, &vars, set) { + Ok(()) => {} + // Only a replacement file that does not exist: one that can't be read or decoded is + // still an error in every mode. + Err(EngineError::Other(m)) if missing != MissingImage::Error && m.starts_with(DATA_SET_FILE_MISSING) => { + if missing == MissingImage::Skip { + report.skipped.push(set.name.clone()); + continue; + } + report.stopped = Some(StoppedDataSet { name: set.name.clone(), index: n, remaining: sets.len() - n - 1, error: m }); + break; + } + Err(e) => return Err(e), + } // An untrusted session's PSD export embeds no file a linked smart object names. let opts = photocraft_io::ExportOptions { read_linked_files: s.authorize.is_none(), ..Default::default() }; let bytes = photocraft_io::export(&doc, format, &opts).map(|r| r.bytes).map_err(|e| EngineError::Other(format!("export `{}`: {e}", set.name)))?; write(name, &bytes)?; - written.push(name.clone()); + report.files.push(name.clone()); } - Ok(written) + Ok(report) } fn list(s: &mut Session) -> Result { @@ -612,7 +697,7 @@ pub fn specs() -> Vec { "file.export.dataSetsAsFiles", "Data Sets as Files…", &["File", "Export"], - "{dir, format?:png, dataSets?[names], naming?:\"{name}|{index}|{document}\"} → {files,count}: apply each data set and export the flattened document; colliding filenames are rejected before writing (include {index} to disambiguate)", + "{dir, format?:png, dataSets?[names], naming?:\"{name}|{index}|{document}\", missingImage?:error|skip|stop, start?:n} → {files,count,skipped?,stopped?:{name,index,remaining,error}}: apply each data set and export the flattened document; colliding filenames are rejected before writing (include {index} to disambiguate). A set whose Pixel Replacement image does not exist ends the export with an error (missingImage error, the default), is left out and listed in `skipped` (skip), or ends the export without an error, named in `stopped` (stop); `start` resumes at that 0-based set, keeping {index}", has_data_sets, |s, p| export_as_files(s, p) ), diff --git a/crates/engine-core/src/color_settings_untagged_display_tests.rs b/crates/engine-core/src/color_settings_untagged_display_tests.rs new file mode 100644 index 00000000000..2a619aaa7f0 --- /dev/null +++ b/crates/engine-core/src/color_settings_untagged_display_tests.rs @@ -0,0 +1,480 @@ +//! #14224: an untagged document is displayed in the working space of Edit > Color Settings, not +//! always in the mode's built-in default, and a change of that space refreshes an open document. +//! +//! The checks are relative: what the canvas must show is the transform our own engine builds for +//! the profile Color Settings names ([`ColorState::working`]) to the monitor the session resolves, +//! evaluated in this file. The reference application's absolute numbers for ProPhoto working RGB +//! are its profile's tables, so they are reported rather than asserted here. +//! +//! Untagged documents only: a tagged one keeps its embedded profile, and CMYK keeps today's +//! display (the issue leaves it unmeasured). + +use super::*; +use photocraft_doc::Size; +use photocraft_geom::Rect; + +use crate::display_color::{DISPLAY_BPC, DISPLAY_INTENT}; + +/// Tolerance of the CPU canvas path against the transform evaluated here (8-bit quantisation plus +/// table evaluation), as in `display_color/tests.rs`. +const TOL: f32 = 2.0; + +/// An untagged RGB document: one 4x4 block per entry of `values`, in columns. +fn untagged_rgb(values: &[[f32; 3]], depth: SampleType) -> Document { + let fmt = PixelFormat::new(ColorMode::Rgb, depth, true); + let mut d = Document::new("t", Size::new(values.len() as u32 * 4, 4), ColorMode::Rgb, depth); + let mut surf = Surface::new(fmt); + for (i, v) in values.iter().enumerate() { + let x = i as i32 * 4; + surf.fill_rect(Rect::new(x, 0, x + 4, 4), &[v[0], v[1], v[2], 1.0]); + } + d.layers.push(Layer::new("pixels", LayerContent::Raster(surf))); + d +} + +/// An RGB document tagged with `tag`. +fn tagged_rgb(tag: &Profile, v: [f32; 3]) -> Document { + let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::rgb(v[0], v[1], v[2])); + d.icc_profile = Some(tag.to_bytes()); + d +} + +/// An untagged Grayscale document. +fn untagged_gray(v: f32) -> Document { + Document::with_background("g", Size::new(8, 8), ColorMode::Grayscale, SampleType::U8, Color::gray(v)) +} + +/// A two-layer untagged CMYK document, so the composite goes through the compositor. +fn untagged_cmyk(ink: [f32; 4]) -> Document { + let fmt = PixelFormat::new(ColorMode::Cmyk, SampleType::U8, true); + let mut d = Document::new("c", Size::new(8, 8), ColorMode::Cmyk, SampleType::U8); + let mut surf = Surface::new(fmt); + surf.fill_rect(Rect::new(0, 0, 8, 8), &[ink[0], ink[1], ink[2], ink[3], 1.0]); + d.layers.push(Layer::new("ink", LayerContent::Raster(surf))); + d.layers.push(Layer::new("empty", LayerContent::Raster(Surface::new(fmt)))); + d +} + +/// What the CPU canvas shows in the middle of column `i` of `d`, in 8-bit codes. +fn shown(s: &Session, d: &Document, i: usize) -> [f32; 3] { + let buf = photocraft_compose::flatten(d); + let img = s.color().canvas_display(d).unwrap().to_rgba8(&buf); + let x = (i as u32 * 4 + 2).min(d.size.width - 1); + let y = d.size.height / 2; + let k = (y as usize * d.size.width as usize + x as usize) * 4; + [0, 1, 2].map(|c| img.pixels[k + c] as f32) +} + +/// The transform our engine builds from `src` to the session's monitor, evaluated at `v`: what the +/// canvas has to show. Returns 8-bit codes. +fn shown_want(s: &Session, src: &Profile, v: &[f32]) -> [f32; 3] { + let monitor = s.color().monitor(); + let t = Transform::new(src, &monitor, DISPLAY_INTENT, DISPLAY_BPC).unwrap(); + let mut out = [0.0f32; 16]; + t.eval(v, &mut out).unwrap(); + let n = t.outputs(); + [0, 1, 2].map(|c| out[if n == 1 { 0 } else { c }].clamp(0.0, 1.0) * 255.0) +} + +fn close(a: [f32; 3], b: [f32; 3], tol: f32) -> bool { + (0..3).all(|i| (a[i] - b[i]).abs() <= tol) +} + +fn far(a: [f32; 3], b: [f32; 3], d: f32) -> bool { + (0..3).any(|i| (a[i] - b[i]).abs() >= d) +} + +fn raw_codes(v: &[f32]) -> [f32; 3] { + [0, 1, 2].map(|c| v[c] * 255.0) +} + +/// The document's description as `edit.profileInfo` reports it. +fn reported(s: &mut Session) -> Value { + s.execute("edit.profileInfo", json!({})).unwrap()["profile"].clone() +} + +#[test] +fn an_untagged_rgb_document_is_displayed_in_the_working_space() { + let mut s = crate::session(); + // The ticket's fixture: 200,30,30 and 30,60,200, profile removed. + let values = [[200.0 / 255.0, 30.0 / 255.0, 30.0 / 255.0], [30.0 / 255.0, 60.0 / 255.0, 200.0 / 255.0]]; + let d = untagged_rgb(&values, SampleType::U8); + // Unchanged with the default settings: sRGB working RGB means the values go to the screen. + let first = s.color().canvas_display(&d).unwrap(); + assert_eq!(first.source.description, Builtin::Srgb.profile().description, "the default working space is sRGB"); + assert!(first.is_identity(), "sRGB on an sRGB monitor still costs nothing"); + s.execute("edit.colorSettings", json!({"workingRgb": "prophoto-compat"})).unwrap(); + let working = s.color().working(ColorMode::Rgb); + assert_eq!(working.description, Builtin::ProPhotoCompat.profile().description, "the setting resolved"); + // The monitor side of the comparison: with no platform profile the canvas is shown on sRGB. + assert_eq!(s.color().monitor().description, Builtin::Srgb.profile().description, "the test monitor"); + let cd = s.color().canvas_display(&d).unwrap(); + assert_eq!(cd.source.description, working.description, "an untagged document is shown in Color Settings' working RGB"); + for (i, v) in values.iter().enumerate() { + let got = shown(&s, &d, i); + let want = shown_want(&s, &working, v); + assert!(close(got, want, TOL), "column {i}: canvas {got:?} vs the working space's transform {want:?}"); + assert!(far(got, raw_codes(v), 8.0), "column {i} is still shown as its raw values: {got:?}"); + } +} + +#[test] +fn changing_the_working_space_refreshes_an_open_untagged_document() { + let mut s = crate::session(); + let v = [0.8, 0.12, 0.12]; + let d = untagged_rgb(&[v], SampleType::U8); + let before = s.color().canvas_display(&d).unwrap(); + let signature = s.color().display_signature(&d); + s.execute("edit.colorSettings", json!({"workingRgb": "adobe-rgb-compat"})).unwrap(); + let after = s.color().canvas_display(&d).unwrap(); + assert_eq!(after.source.description, s.color().working(ColorMode::Rgb).description); + assert!(!Arc::ptr_eq(&before, &after), "the display cache handed back the entry made for the old working space"); + assert_ne!(before.key, after.key, "the cache entry and its signature have to move with the working space"); + assert_ne!(signature, s.color().display_signature(&d), "the canvas reloads the document without reopening it"); + assert_eq!(before.monitor.content_hash(), after.monitor.content_hash(), "only the working space moved"); + assert!(close(shown(&s, &d, 0), shown_want(&s, &after.source, &v), TOL), "{:?}", shown(&s, &d, 0)); + // Back to the default: the same entry as before, so the key follows the setting and not a counter. + s.execute("edit.colorSettings", json!({"workingRgb": "srgb"})).unwrap(); + let back = s.color().canvas_display(&d).unwrap(); + assert!(back.is_identity()); + assert_eq!(back.key, before.key, "the same settings give the same display"); +} + +#[test] +fn an_untagged_document_stays_untagged_and_keeps_its_pixels() { + let mut s = crate::session(); + let v = [200.0 / 255.0, 30.0 / 255.0, 30.0 / 255.0]; + s.open_document(untagged_rgb(&[v], SampleType::U8), None); + let before = reported(&mut s); + assert_eq!(before["embedded"], json!(false)); + let sample = |s: &Session| s.active().unwrap().doc.layers[0].surface().unwrap().pixel(1, 1); + let pixels = sample(&s); + s.execute("edit.colorSettings", json!({"workingRgb": "prophoto-compat"})).unwrap(); + let after = reported(&mut s); + assert_eq!(after["embedded"], json!(false), "the working space is not written into the document"); + assert_eq!(after["description"], Builtin::ProPhotoCompat.profile().description, "the document is taken in the working space"); + assert_eq!(sample(&s), pixels, "only the interpretation changes, not the stored samples"); + let d = &s.active().unwrap().doc; + assert!(close(shown(&s, d, 0), shown_want(&s, &s.color().working(ColorMode::Rgb), &v), TOL), "{:?}", shown(&s, d, 0)); +} + +#[test] +fn a_tagged_document_keeps_its_embedded_profile() { + let mut s = crate::session(); + let v = [0.4, 0.6, 0.2]; + for tag in [Builtin::Srgb, Builtin::AdobeRgbCompat, Builtin::DisplayP3] { + let d = tagged_rgb(tag.profile(), v); + let before = s.color().canvas_display(&d).unwrap(); + s.execute("edit.colorSettings", json!({"workingRgb": "prophoto-compat"})).unwrap(); + let cd = s.color().canvas_display(&d).unwrap(); + assert_eq!(cd.source.content_hash(), tag.profile().content_hash(), "{} was replaced by the working space", tag.description()); + assert_eq!(cd.key, before.key, "a tagged document's display does not move with the setting"); + assert!(close(shown(&s, &d, 0), shown_want(&s, tag.profile(), &v), TOL), "{}: {:?}", tag.description(), shown(&s, &d, 0)); + s.execute("edit.colorSettings", json!({"workingRgb": "srgb"})).unwrap(); + } + // The command read-back of a tagged document is its own profile. + s.open_document(tagged_rgb(Builtin::AdobeRgbCompat.profile(), v), None); + s.execute("edit.colorSettings", json!({"workingRgb": "prophoto-compat"})).unwrap(); + let info = reported(&mut s); + assert_eq!(info["embedded"], json!(true)); + assert_eq!(info["description"], Builtin::AdobeRgbCompat.profile().description); +} + +#[test] +fn an_untagged_grayscale_document_follows_the_working_gray() { + let mut s = crate::session(); + let d = untagged_gray(0.3); + let first = s.color().canvas_display(&d).unwrap(); + // The default working Gray is the built-in default, so nothing moves without a setting. + assert_eq!(first.source.content_hash(), working_profile(ColorMode::Grayscale).gray_as_rgb().unwrap().content_hash()); + s.execute("edit.colorSettings", json!({"workingGray": "gray-gamma-2.2"})).unwrap(); + let working = s.color().working(ColorMode::Grayscale); + assert_eq!(working.description, Builtin::GrayGamma22.profile().description, "the setting resolved"); + let cd = s.color().canvas_display(&d).unwrap(); + assert_eq!(cd.source.content_hash(), working.gray_as_rgb().unwrap().content_hash(), "an untagged gray document is shown in the working Gray"); + assert_ne!(cd.key, first.key, "and its display cache entry re-keys"); + assert!(close(shown(&s, &d, 0), shown_want(&s, &cd.source, &[0.3, 0.3, 0.3]), TOL), "{:?}", shown(&s, &d, 0)); +} + +#[test] +fn an_untagged_cmyk_document_keeps_todays_display() { + let mut s = crate::session(); + let ink = [0.1, 0.6, 0.7, 0.05]; + let d = untagged_cmyk(ink); + let before = shown(&s, &d, 0); + let entry = s.color().canvas_display(&d).unwrap(); + s.execute("edit.colorSettings", json!({"workingCmyk": "coated-fogra39"})).unwrap(); + let cd = s.color().canvas_display(&d).unwrap(); + assert_eq!(cd.source.description, Builtin::Srgb.profile().description, "CMYK is not measured and keeps its sRGB composite"); + assert_eq!(cd.key, entry.key, "the working CMYK does not re-key an untagged CMYK document"); + assert!(close(shown(&s, &d, 0), before, 0.6), "its inks are still read through the built-in coated profile: {before:?} -> {:?}", shown(&s, &d, 0)); + // And the profile it is taken in stays the mode's built-in default even though the setting + // now names another one: only RGB and Grayscale follow Color Settings here. + assert_ne!(s.color().working(ColorMode::Cmyk).content_hash(), working_profile(ColorMode::Cmyk).content_hash(), "the setting really moved"); + assert_eq!( + s.color().document_profile(&d).content_hash(), + working_profile(ColorMode::Cmyk).content_hash(), + "an untagged CMYK document keeps the mode default" + ); +} + +#[test] +fn the_same_rule_holds_at_every_depth() { + let mut s = crate::session(); + let v = [0.8, 0.12, 0.12]; + s.execute("edit.colorSettings", json!({"workingRgb": "prophoto-compat"})).unwrap(); + let working = s.color().working(ColorMode::Rgb); + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + let d = untagged_rgb(&[v], depth); + let cd = s.color().canvas_display(&d).unwrap(); + assert_eq!(cd.source.description, working.description, "{depth:?}"); + let got = shown(&s, &d, 0); + let want = shown_want(&s, &working, &v); + let tol = if depth == SampleType::U8 { TOL } else { 1.0 }; + assert!(close(got, want, tol), "{depth:?}: {got:?} vs {want:?}"); + } +} + +#[test] +fn a_conversion_starts_from_the_working_space() { + let mut s = crate::session(); + let v = [200.0 / 255.0, 30.0 / 255.0, 30.0 / 255.0]; + let filled = [v[0], v[1], v[2], 1.0]; + s.open_document(untagged_rgb(&[v], SampleType::U8), None); + s.execute("edit.colorSettings", json!({"workingRgb": "prophoto-compat"})).unwrap(); + let working = s.color().working(ColorMode::Rgb); + let srgb = Builtin::Srgb.profile().clone(); + // What Convert to Profile has to write: the working space's own transform of the stored + // samples, clamped the way the sample write clamps them (this colour is outside sRGB). + let clamp3 = |o: &[f32; 16]| [o[0].clamp(0.0, 1.0), o[1].clamp(0.0, 1.0), o[2].clamp(0.0, 1.0)]; + let mut out = [0.0f32; 16]; + Transform::new(&working, &srgb, Intent::RelativeColorimetric, false).unwrap().eval(&v, &mut out).unwrap(); + let want = clamp3(&out); + let mut built_in = [0.0f32; 16]; + let default = working_profile(ColorMode::Rgb); + Transform::new(&default, &srgb, Intent::RelativeColorimetric, false).unwrap().eval(&v, &mut built_in).unwrap(); + assert!( + want.iter().zip(clamp3(&built_in).iter()).any(|(a, b)| (a - b).abs() > 8.0 / 255.0), + "the fixture must tell the working space apart from the built-in default: {want:?} vs {built_in:?}" + ); + for dither in [false, true] { + let r = s.execute("edit.convertToProfile", json!({"profile": "srgb", "intent": "relative", "bpc": false, "dither": dither})).unwrap(); + assert_eq!(r["converted"], json!(true), "dither {dither}"); + let px = s.active().unwrap().doc.layers[0].surface().unwrap().pixel(1, 1); + assert!((0..3).all(|c| (px[c] - want[c]).abs() <= 2.0 / 255.0), "dither {dither}: {px:?} vs the working space's own conversion {want:?}"); + assert_eq!(reported(&mut s)["description"], srgb.description, "tagged with the destination"); + // Back to the untagged start for the second round. + s.execute("edit.assignProfile", json!({"profile": "none"})).unwrap(); + s.edit("reset", |doc, _| { + doc.layers[0].surface_mut().unwrap().fill_rect(Rect::new(0, 0, 4, 4), &filled); + Ok(()) + }) + .unwrap(); + } +} + +#[test] +fn a_mode_change_starts_from_the_working_space() { + let mut s = crate::session(); + let v = [0.8, 0.12, 0.12]; + s.open_document(untagged_rgb(&[v], SampleType::U8), None); + s.execute("edit.colorSettings", json!({"workingRgb": "prophoto-compat", "workingGray": "gray-gamma-2.2"})).unwrap(); + let src = s.color().working(ColorMode::Rgb); + let dst = s.color().working(ColorMode::Grayscale); + let t = Transform::new(&src, &dst, Intent::RelativeColorimetric, false).unwrap(); + let from_built_in = { + let built_in = working_profile(ColorMode::Rgb); + Transform::new(&built_in, &dst, Intent::RelativeColorimetric, false).unwrap() + }; + let mut out = [0.0f32; 16]; + let mut other = [0.0f32; 16]; + t.eval(&v, &mut out).unwrap(); + from_built_in.eval(&v, &mut other).unwrap(); + assert!((out[0] - other[0]).abs() > 1.0 / 255.0, "the fixture must tell the two sources apart: {out:?} vs {other:?}"); + s.execute("image.mode.grayscale", json!({"intent": "relative", "bpc": false})).unwrap(); + let px = s.active().unwrap().doc.layers[0].surface().unwrap().pixel(1, 1); + assert!((px[0] - out[0]).abs() <= 2.0 / 255.0, "the mode change read the built-in default, not the working RGB: {px:?} vs {out:?}"); +} + +#[test] +fn a_layer_copied_into_an_untagged_document_lands_in_its_space() { + let mut s = crate::session(); + // A: untagged, opened under the default settings so nothing is assigned to it on the way in. + s.open_document(untagged_rgb(&[[0.5, 0.5, 0.5]], SampleType::U8), None); + // B: the same shape tagged sRGB, with a saturated block. + let v = [0.9f32, 0.2, 0.2]; + s.open_document(tagged_rgb(Builtin::Srgb.profile(), v), None); + s.execute("edit.colorSettings", json!({"workingRgb": "prophoto-compat"})).unwrap(); + let block = s.active().unwrap().active_layer.unwrap(); + let r = s.execute("layer.copyToDocument", json!({"document": 0, "source": 1, "layers": [block.0]})).unwrap(); + let id = photocraft_doc::LayerId(r["layers"][0].as_u64().unwrap()); + let a = &s.documents()[0].doc; + assert!(a.icc_profile.is_none(), "the destination is still untagged"); + let px = a.layer(id).unwrap().surface().unwrap().pixel(1, 1); + // It has to keep its look, so it is re-encoded into the space A is shown in. + let mut out = [0.0f32; 16]; + let working = s.color().working(ColorMode::Rgb); + Transform::new(Builtin::Srgb.profile(), &working, s.color().settings.intent(), s.color().settings.bpc).unwrap().eval(&v, &mut out).unwrap(); + let want = [out[0], out[1], out[2]]; + assert!((0..3).all(|c| (px[c] - want[c]).abs() <= 2.0 / 255.0), "the pasted block landed as {px:?}, not in the space A is shown in ({want:?})"); + assert!((0..3).any(|c| (px[c] - v[c]).abs() > 8.0 / 255.0), "the fixture must tell a raw copy apart from a re-encoded one: {px:?} vs {v:?}"); +} + +#[test] +fn the_gamut_count_is_judged_in_the_space_the_canvas_marks_in() { + let mut s = crate::session(); + // Six colours that straddle the coated-CMYK gamut: read as sRGB some of them are inside it, + // read as ProPhoto the same samples are far outside. + let colours = [[0.95f32, 0.05, 0.05], [0.8, 0.3, 0.3], [0.6, 0.1, 0.1], [0.3, 0.85, 0.3], [0.1, 0.4, 0.9], [0.45, 0.45, 0.95]]; + s.open_document(untagged_rgb(&colours, SampleType::U8), None); + s.execute("edit.colorSettings", json!({"workingRgb": "prophoto-compat"})).unwrap(); + s.execute("view.proofSetup", json!({"profile": "coated-cmyk", "intent": "perceptual"})).unwrap(); + let doc = s.active().unwrap().doc.clone(); + let setup = s.color().proof(doc.id).setup.clone(); + let buf = photocraft_compose::flatten(&doc); + let count_with = |src: &Profile| { + let check = GamutCheck::new(src, &setup.profile, 4.0).unwrap(); + let mut mask = vec![0u8; buf.px.len()]; + let count = check.mask_rgba(&buf.px, &mut mask).unwrap(); + (mask, count) + }; + // The canvas marks its out-of-gamut pixels through the display source; that is the count the + // Gamut Warning command and Color Range > Out of Gamut have to agree with. + let want = count_with(&s.color().composite_profile(&doc)); + let built_in = count_with(&composite_profile(&doc)); + assert_ne!(want.1, built_in.1, "the fixture must tell the two spaces apart: {want:?} vs {built_in:?}"); + let warning = s.execute("view.gamutWarning", json!({"on": true, "threshold": 4.0})).unwrap(); + assert_eq!(warning["outOfGamut"].as_u64().unwrap() as usize, want.1, "Gamut Warning judged another space than the canvas"); + // Color Range › Out of Gamut has to mark exactly those pixels. + s.execute("select.colorRange", json!({"select": "outOfGamut"})).unwrap(); + let with = s.active().unwrap().doc.clone(); + let selection = with.selection.clone().expect("the selection was set"); + let width = with.size.width as usize; + let marked = |surface: &photocraft_raster::Surface| -> Vec { + (0..with.size.width as usize / 4).map(|i| (surface.pixel(i as i32 * 4 + 2, 2)[0] > 0.5) as usize).collect() + }; + let marks = marked(&selection); + let columns: Vec = (0..width / 4).map(|i| usize::from(want.0[2 * width + i * 4 + 2] == 255)).collect(); + assert_eq!(marks, columns, "Color Range > Out of Gamut marks other pixels than the warning counts"); +} + +#[test] +fn converting_an_untagged_document_to_working_leaves_its_samples() { + let mut s = crate::session(); + let v = [0.9f32, 0.2, 0.2]; + s.execute("edit.colorSettings", json!({"workingRgb": "prophoto-compat"})).unwrap(); + // The answer to the "missing profile" prompt for a document that is not open yet. + let mut d = untagged_rgb(&[v], SampleType::U8); + s.color().resolve_open(&mut d, "convert").unwrap(); + let tagged = profile_from_bytes(d.icc_profile.as_ref().expect("tagged by the answer")).unwrap(); + assert_eq!(tagged.description, s.color().working(ColorMode::Rgb).description, "tagged with the working space"); + let px = d.layers[0].surface().unwrap().pixel(1, 1); + assert!((0..3).all(|c| (px[c] - v[c]).abs() <= 2.0 / 255.0), "the answer read the document in the built-in default and moved its pixels: {px:?} vs {v:?}"); + // The command path agrees: an untagged document answers the same way once it is open. + s.open_document(untagged_rgb(&[v], SampleType::U8), None); + let r = s.execute("color.profileMismatch", json!({"action": "convertToWorking"})).unwrap(); + assert_eq!(r["action"], json!("converted")); + let px = s.active().unwrap().doc.layers[0].surface().unwrap().pixel(1, 1); + assert!((0..3).all(|c| (px[c] - v[c]).abs() <= 2.0 / 255.0), "the open document's answer moved its pixels: {px:?}"); + let info = reported(&mut s); + assert_eq!(info["embedded"], json!(true)); + assert_eq!(info["description"], s.color().working(ColorMode::Rgb).description); +} + +#[test] +fn an_untagged_indexed_document_follows_the_mode_default_until_it_becomes_rgb() { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 8, "height": 8, "background": "#ff0000"})).unwrap(); + s.execute("edit.colorSettings", json!({"workingRgb": "prophoto-compat"})).unwrap(); + s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "colors": 8})).unwrap(); + // Indexed is not one of the two modes the item measures: it keeps the mode's built-in default. + let indexed = working_profile(ColorMode::Indexed); + assert_eq!(reported(&mut s)["description"], indexed.description, "an Indexed document is not switched"); + // Image > Mode > RGB without a profile keeps the stored samples; the document that results is + // untagged RGB, so the reply and Profile Info have to name the same space. + let r = s.execute("image.mode.rgb", json!({})).unwrap(); + assert_eq!(r["profile"], s.color().working(ColorMode::Rgb).description, "the reply names the space the result is taken in"); + assert_eq!(reported(&mut s)["description"], s.color().working(ColorMode::Rgb).description, "and Profile Info agrees"); +} + +#[test] +fn colour_range_judges_sampled_colours_in_the_space_the_canvas_shows() { + let mut s = crate::session(); + // A box spanned by two sampled colours and a ramp of columns across it. Membership is decided in + // Lab, through the profile the composite is read in, so once the working space moves the box has + // to move with the picture: with the ramp below one column drops out going from sRGB to + // ProPhoto, and none of this changes at the default setting. + let columns: Vec<[f32; 3]> = (0..8).map(|i| [0.55 + 0.03 * i as f32, 0.45 - 0.03 * i as f32, 0.45 - 0.02 * i as f32]).collect(); + s.open_document(untagged_rgb(&columns, SampleType::U8), None); + let marked = |s: &mut Session| -> Vec { + s.execute("select.colorRange", json!({"select": "sampledColors", "colors": ["#cc4d4d", "#996666"], "fuzziness": 40})).unwrap(); + let doc = s.active().unwrap().doc.clone(); + let selection = doc.selection.clone().expect("a selection was set"); + (0..columns.len()).filter(|i| selection.pixel(*i as i32 * 4 + 2, 2)[0] > 0.5).collect() + }; + let as_built_in = marked(&mut s); + s.execute("edit.colorSettings", json!({"workingRgb": "prophoto-compat"})).unwrap(); + let as_working = marked(&mut s); + assert_ne!(as_built_in, as_working, "the sampled colour box marked the same columns whatever the working space: {as_built_in:?} vs {as_working:?}"); +} + +#[test] +fn replace_color_judges_its_lab_bounds_in_the_space_the_canvas_shows() { + // A Lab cube drawn around one column of the gamut fixture through the profile this session reads + // the layer in. The same device numbers sit far away when they are read in the mode's built-in + // default, so the cube has to catch that column here and miss it in a session at the default. + let columns = [[0.95f32, 0.05, 0.05], [0.8f32, 0.3, 0.3], [0.6f32, 0.1, 0.1], [0.3, 0.85, 0.3], [0.1, 0.4, 0.9], [0.45, 0.45, 0.95]]; + let column = 1usize; + let lab_in = |profile: &Profile, v: [f32; 3]| -> [f32; 3] { + let t = craft_cms::cached(profile, Builtin::LabD50.profile(), craft_cms::TransformOptions::default()).unwrap(); + let mut out = [0.0f32; 16]; + t.eval(&v, &mut out).unwrap(); + [out[0] * 100.0, out[1] * 255.0 - 128.0, out[2] * 255.0 - 128.0] + }; + let mut s = crate::session(); + s.open_document(untagged_rgb(&columns, SampleType::U8), None); + s.execute("edit.colorSettings", json!({"workingRgb": "prophoto-compat"})).unwrap(); + let doc = s.active().unwrap().doc.clone(); + let centre = lab_in(&s.color().document_profile(&doc), columns[column]); + let elsewhere = lab_in(&document_profile(&doc), columns[column]); + assert!((0..3).any(|c| (centre[c] - elsewhere[c]).abs() > 10.0), "the fixture must tell the two readings apart: {centre:?} vs {elsewhere:?}"); + let cube = json!({ + "labMinimum": [centre[0] - 4.0, centre[1] - 4.0, centre[2] - 4.0], + "labMaximum": [centre[0] + 4.0, centre[1] + 4.0, centre[2] + 4.0], + "fuzziness": 0, + "saturation": -60, + }); + let shifted = |s: &Session| -> bool { + // The layer makes a Lab round trip whether it is inside the cube or not, which moves single + // codes here and there; only the desaturation is a real change. + let surf = s.active().unwrap().doc.layers[0].surface().unwrap(); + let got = raw_codes(&surf.pixel(column as i32 * 4 + 2, 2)); + let stored = raw_codes(&columns[column]); + (0..3).any(|c| (got[c] - stored[c]).abs() > 8.0) + }; + s.execute("image.adjustments.replaceColor", cube.clone()).unwrap(); + assert!(shifted(&s), "the cube drawn in this session's own space missed the column it was drawn around: {centre:?}"); + let mut plain = crate::session(); + plain.open_document(untagged_rgb(&columns, SampleType::U8), None); + plain.execute("image.adjustments.replaceColor", cube).unwrap(); + assert!(!shifted(&plain), "the same cube also caught the column read in the built-in default: {centre:?} vs {elsewhere:?}"); +} + +#[test] +fn the_profile_commands_answer_the_same_for_a_tagged_document() { + let mut replies = Vec::new(); + for working in ["srgb", "prophoto-compat"] { + let mut s = crate::session(); + s.open_document(tagged_rgb(Builtin::AdobeRgbCompat.profile(), [0.4, 0.6, 0.2]), None); + s.execute("edit.colorSettings", json!({"workingRgb": working})).unwrap(); + replies.push(json!({ + "info": reported(&mut s), + "assign": s.execute("edit.assignProfile", json!({"profile": "display-p3"})).unwrap(), + "info_after_assign": reported(&mut s), + "convert": s.execute("edit.convertToProfile", json!({"profile": "srgb", "intent": "relative", "bpc": false})).unwrap(), + "mode": s.execute("image.mode.grayscale", json!({"intent": "relative", "bpc": false})).unwrap(), + "info_after_mode": reported(&mut s), + })); + } + assert_eq!(replies[0], replies[1], "a tagged document's replies must not depend on the working space"); +} diff --git a/crates/engine-core/src/display_color.rs b/crates/engine-core/src/display_color.rs index b0d5b65b554..de10d463c13 100644 --- a/crates/engine-core/src/display_color.rs +++ b/crates/engine-core/src/display_color.rs @@ -2,9 +2,10 @@ //! monitor profile, on the GPU canvas (matrix/shaper or display 3D LUT) and the CPU canvas //! (an 8-bit transform of the composite). //! -//! * The composite is in [`composite_profile`] (the document profile for RGB, its gray curve as +//! * The composite is in `composite_profile` (the document profile for RGB, its gray curve as //! RGB for gray documents, sRGB for CMYK — read through the document's CMYK profile, see -//! `photocraft_color::convert::CmykSpace` — and Lab). +//! `photocraft_color::convert::CmykSpace` — and Lab). An untagged document has no profile of +//! its own, and an untagged RGB or gray one is taken in Color Settings' working space (#14224). //! * Linear composites (EXR/HDR, linear profiles) are stored in the 8-bit canvas texture //! sRGB-encoded ([`CanvasDisplay::encode_srgb`]) so shadows keep their precision; the display //! source profile is then the same primaries with the sRGB curve. @@ -14,19 +15,21 @@ //! * When the source and the monitor match (sRGB documents on an sRGB display, the common //! case) the transform is the identity and nothing is applied on either path. //! -//! Results are cached per (document profile, mode, monitor profile); the rendering intent is -//! relative colorimetric with black point compensation, as for Photoshop's monitor display. +//! Results are cached per (document profile, mode, monitor profile) — plus the working space while +//! the document is untagged, so a Color Settings change re-keys it (#14224); the rendering intent +//! is relative colorimetric with black point compensation, as for Photoshop's monitor display. use std::borrow::Cow; use std::collections::HashMap; use std::sync::{Arc, Mutex, OnceLock}; use craft_cms::{Builtin, ColorSpace, Curve, Intent, Profile, Transform}; +use photocraft_color::ColorMode; use photocraft_compose::Buffer; use photocraft_doc::Document; use photocraft_raster::Rgba8Image; -use crate::color_cmds::{ColorState, composite_profile, mode_space, profile_from_bytes, resolve_profile}; +use crate::color_cmds::{ColorState, mode_space, profile_from_bytes, resolve_profile}; use crate::{EngineError, Result}; /// Display intent and black point compensation of the monitor transform. @@ -261,11 +264,15 @@ struct MonitorEntry { status: MonitorStatus, } +/// The canvas display cache key: colour space, document profile, monitor profile, and while the +/// document is untagged the Color Settings working space it is shown in (#14224). +type CanvasKey = (ColorSpace, u64, u64, Option); + /// Caches of [`ColorState`] for the display (monitor profiles per display, per-document displays). #[derive(Default)] pub struct DisplayCaches { monitor: Mutex, MonitorEntry>>, - canvas: Mutex>>, + canvas: Mutex>>, } impl ColorState { @@ -407,16 +414,30 @@ impl ColorState { } /// How the canvas shows `doc` on `display` (cached per document profile, mode and monitor - /// profile). + /// profile; for an untagged document also per Color Settings' working space, which is the + /// profile it is shown in). pub fn canvas_display_for(&self, doc: &Document, display: Option) -> Result> { let space = mode_space(doc.mode); - let doc_hash = doc.icc_profile.as_ref().and_then(|b| profile_from_bytes(b).ok()).filter(|p| p.color_space == space).map_or(0, |p| p.content_hash()); + let embedded = crate::color_cmds::embedded_profile(doc); + // An untagged RGB or Grayscale document is displayed in Color Settings' working space + // (#14224), so the setting joins its key: the profile hash 0 that an untagged document + // used before did not move when the working space did, and an open document kept the + // display it was first shown with. The setting is hashed rather than the profile it + // resolves to, because this runs on every frame and `working` would clone the profile's + // tables (or read its `.icc` file) each time. Every other mode keeps the built-in default + // and stays keyed 0. + let working = if embedded.is_none() && matches!(doc.mode, ColorMode::Rgb | ColorMode::Grayscale) { + Some(hash_of((self.working_space_spec(doc.mode), self.settings.intent().id()))) + } else { + None + }; + let doc_hash = embedded.map_or(0, |p| p.content_hash()); let monitor = self.monitor_for(display); - let key = (space, doc_hash, monitor.content_hash()); + let key: CanvasKey = (space, doc_hash, monitor.content_hash(), working); if let Some(d) = self.display.canvas.lock().unwrap_or_else(|e| e.into_inner()).get(&key) { return Ok(d.clone()); } - let composite = composite_profile(doc); + let composite = self.composite_profile(doc); let encode_srgb = is_linear_rgb(&composite); let source = if encode_srgb { Arc::new(srgb_curve_twin(&composite)) } else { composite }; let transform = if source.content_hash() == monitor.content_hash() { diff --git a/crates/engine-core/src/hidden_target.rs b/crates/engine-core/src/hidden_target.rs index 5422f1e2e79..1df52ae9e79 100644 --- a/crates/engine-core/src/hidden_target.rs +++ b/crates/engine-core/src/hidden_target.rs @@ -14,6 +14,11 @@ pub const HIDDEN: &str = "Could not complete your request because the target lay /// The Art History Brush's own alert text (#12638). pub const ART_HISTORY_HIDDEN: &str = "Could not use the art history brush because the target layer is hidden."; +/// The gradient's alerts for a pixel layer's mask it can't draw into (#18637): the layer is hidden, or it has Lock All +/// (its own or a group's). Measured with the Gradient tool in Gradient mode. +pub const GRADIENT_MASK_HIDDEN: &str = "Could not use the gradient tool because the target layer mask is hidden."; +pub const GRADIENT_MASK_LOCKED: &str = "Could not use the gradient tool because the layer is locked."; + /// The Color Replacement tool's alerts for a target it can't recolour (#17782): a pixel layer's /// mask, an adjustment layer (its mask or its content), a group's mask, an alpha channel or the /// Quick Mask. @@ -71,6 +76,11 @@ pub fn refusal(s: &Session, id: &str, params: &Value) -> Option<&'static str> { { return Some(why); } + if id == "paint.gradient" + && let Some(why) = gradient_mask_refusal(s, ¶ms) + { + return Some(why); + } if crate::channel_cmds::is_channel_target(¶ms) { return None; } @@ -85,6 +95,26 @@ pub fn refusal(s: &Session, id: &str, params: &Value) -> Option<&'static str> { (st.doc.layer(layer).is_some() && !shown(&st.doc, layer)).then_some(why) } +/// Why `paint.gradient` with `params` (its `target` filled in) can't draw into a pixel layer's mask (#18637): the layer is +/// hidden, else it has Lock All. A hidden or locked adjustment, fill or group layer's mask was not measured and keeps the +/// generic refusals. These texts are Gradient mode's: a Classic call (`"classic": true`) or one without the flag keeps the +/// generic refusals too (#18902). +fn gradient_mask_refusal(s: &Session, params: &Value) -> Option<&'static str> { + if params.get("classic").and_then(Value::as_bool) != Some(false) || crate::channel_cmds::target_of(params) != crate::channel_cmds::Target::Mask { + return None; + } + let st = s.active()?; + let id = crate::commands::layer_param(s, params).ok()?; + let layer = st.doc.layer(id).filter(|l| matches!(l.content, photocraft_doc::LayerContent::Raster(_)) && l.mask.is_some())?; + if !shown(&st.doc, layer.id) { + Some(GRADIENT_MASK_HIDDEN) + } else if st.doc.effective_locks(layer.id).all { + Some(GRADIENT_MASK_LOCKED) + } else { + None + } +} + /// Why `paint.colorReplacement` with `params` (its `target` filled in) can't recolour its target /// (#17782): the tool works on a pixel layer's full colour composite only, not on some of its /// colour channels (#17783). The target decides diff --git a/crates/engine-core/src/lib.rs b/crates/engine-core/src/lib.rs index 2e4ee4c4139..5981e986a7f 100644 --- a/crates/engine-core/src/lib.rs +++ b/crates/engine-core/src/lib.rs @@ -55,7 +55,10 @@ pub mod shortcut_sets; mod slots; pub mod snap; mod state; -pub use variables_cmds::{DATA_SET_FILE_MISSING, DATA_SET_LAYER_LOCKED, data_set_preview, export_data_sets_with, import_data_sets_text}; +pub use variables_cmds::{ + DATA_SET_FILE_MISSING, DATA_SET_LAYER_LOCKED, DataSetsExportReport, StoppedDataSet, data_set_preview, export_data_sets_report_with, export_data_sets_with, + import_data_sets_text, +}; pub use video_cmds::render_video_with; use std::sync::Arc; diff --git a/crates/engine-core/src/new_layer.rs b/crates/engine-core/src/new_layer.rs index 1d5bb067210..96e46d89d4f 100644 --- a/crates/engine-core/src/new_layer.rs +++ b/crates/engine-core/src/new_layer.rs @@ -1,7 +1,8 @@ //! Layer › New › Layer: Photoshop's New Layer options (name, Use Previous Layer to Create Clipping //! Mask, color label, mode, opacity, and Fill with neutral color), applied in one history step. -use photocraft_doc::{BlendMode, LabelColor, Layer}; +use photocraft_color::{ColorMode, SampleType}; +use photocraft_doc::{BlendMode, Document, LabelColor, Layer}; use serde_json::{Value, json}; use crate::{EngineError, Result, Session}; @@ -12,6 +13,31 @@ fn bad(msg: impl Into) -> EngineError { EngineError::BadParams { cmd: CMD.into(), msg: msg.into() } } +/// The New Layer dialog only greys modes measured in RGB 32-bit and Lab 8-bit. +pub fn greyed_modes(doc: &Document) -> &'static [BlendMode] { + match (doc.mode, doc.depth) { + (ColorMode::Rgb, SampleType::F32) | (ColorMode::Lab, SampleType::U8) => crate::pixel_fill::greyed_modes(doc.mode, doc.depth), + _ => &[], + } +} + +fn check_mode_available(s: &Session, mode: BlendMode) -> Result<()> { + if let Some(st) = s.active() + && greyed_modes(&st.doc).contains(&mode) + { + crate::pixel_fill::check_mode_available(CMD, &st.doc, mode)?; + } + Ok(()) +} + +/// Refuse an unavailable mode before dispatch can settle a floating selection or the UI can commit a transform. +pub(crate) fn precheck_mode(s: &Session, p: &Value) -> Result<()> { + if let Some(mode) = p.get("mode").and_then(Value::as_str).and_then(crate::commands::parse_blend) { + check_mode_available(s, mode)?; + } + Ok(()) +} + /// The color that leaves everything below unchanged in `mode` (Photoshop's "Fill with /// Multiply-neutral color (white)"), as RGB, and its name. `None` for modes that have none. pub fn neutral_color(mode: BlendMode) -> Option<([f32; 3], &'static str)> { @@ -40,6 +66,7 @@ pub(crate) struct NewLayer { /// panel's ⌘/Ctrl-click), joining the clip group it lands in. pub fn run(s: &mut Session, p: &Value) -> Result { let NewLayer { clip, mode, opacity, label, neutral, below, name } = parse(p)?; + check_mode_available(s, mode)?; let place = if below { crate::layer_place::Place::Below } else { crate::layer_place::Place::Auto }; let id = s.edit("New Layer", |doc, active| { let name = name.clone().unwrap_or_else(|| doc.next_layer_suggestion()); diff --git a/crates/engine-core/src/pixels.rs b/crates/engine-core/src/pixels.rs index 0e5572d0d9d..878da574d22 100644 --- a/crates/engine-core/src/pixels.rs +++ b/crates/engine-core/src/pixels.rs @@ -557,17 +557,24 @@ pub fn remap_surface(s: &Surface, map: impl Fn(i32, i32) -> (i32, i32)) -> Surfa /// Merge `upper` onto `lower` producing a raster layer (Layer → Merge Down). pub fn merge_down(doc: &Document, lower: &Layer, upper: &Layer) -> Layer { let format = doc.pixel_format(); - let stack = vec![lower.clone(), upper.clone()]; - let mut tmp = Document::new("merge", doc.size, format.mode, format.sample); - // The pair is read (and a CMYK one separated again) through the document's own profile. - tmp.icc_profile = doc.icc_profile.clone(); - tmp.layers = stack.into(); + // Photoshop keeps the lower layer's layer style live on the merged layer, where it + // re-applies to the merged pixels: bake the pair without it so it is not applied twice. + let mut bare_lower = lower.clone(); + let style = std::mem::take(&mut bare_lower.effects); + // The pair is rendered with the document's own Global Light, patterns and colour profile, + // and read (and a CMYK one separated again) through that profile. + let mut tmp = doc.clone(); + tmp.layers = vec![bare_lower, upper.clone()].into(); // A Background stays canvas-sized; any other layer keeps the pixels outside the canvas (#5067). let s = if doc.is_background(lower.id) { composite_layers(&tmp, format, None) } else { composite_layers_uncropped(&tmp, format) }; let mut merged = Layer::new(lower.name.clone(), LayerContent::Raster(s)); merged.id = lower.id; merged.blend = lower.blend; merged.opacity = 1.0; + // And the fill: Photoshop inherits the lower layer's fill opacity onto the merged layer, + // so a zero-fill layer keeps its ink in the pixels but invisible, with only its style + // visible — instead of resetting the property (observed in the PR fixtures). + merged.fill_opacity = lower.fill_opacity; // Merge Down replaces the lower layer, so keep its editing restrictions. // In particular, a merged Background must remain opaque and position-locked. merged.locks = lower.locks; @@ -576,5 +583,8 @@ pub fn merge_down(doc: &Document, lower: &Layer, upper: &Layer) -> Layer { merged.clipped = lower.clipped && upper.clipped; merged.label = lower.label; merged.link_group = lower.link_group; + // The fill opacity and the masks are in the pixels now; the layer style is kept, live, and + // recomposes over the union of both layers' content. + merged.effects = style; merged } diff --git a/crates/engine-core/src/prefs.rs b/crates/engine-core/src/prefs.rs index 1f9c28c1584..a5336768de9 100644 --- a/crates/engine-core/src/prefs.rs +++ b/crates/engine-core/src/prefs.rs @@ -117,6 +117,7 @@ choice!(FontPreview { Off = "off", Small = "small", Medium = "medium", Large = " choice!(RawColorSpace { Srgb = "srgb", AdobeRgb = "adobeRgb", ProPhoto = "proPhoto", DisplayP3 = "displayP3" } default DisplayP3); choice!(RawDepth { Eight = "8", Sixteen = "16" } default Sixteen); choice!(RawSharpen { None = "none", Screen = "screen", Glossy = "glossy", Matte = "matte" } default None); +choice!(RawSharpenAmount { Low = "low", Standard = "standard", High = "high" } default Standard); choice!( /// How a raw file's colour filter array is filled in when it is developed: AHD /// (Hirakawa–Parks) keeps edges cleanest, Malvar–He–Cutler is sharp and fast, bilinear is the @@ -1177,6 +1178,7 @@ pub struct RawDefaults { #[serde(deserialize_with = "raw_resolution")] pub resolution: u32, pub sharpen_for: RawSharpen, + pub sharpen_amount: RawSharpenAmount, pub open_as_smart_object: bool, pub apply_auto_tone: bool, /// Opening a raw file interactively shows the Camera Raw dialog first (Open / Cancel), as @@ -1194,6 +1196,23 @@ pub struct RawDefaults { impl RawDefaults { /// What Resolution takes, as the reference application's field does. pub const RESOLUTION: std::ops::RangeInclusive = 1..=999; + + /// Apply output sharpening if a medium is selected and the raw has no Detail sharpening. + pub fn apply_output_sharpening(&self, settings: &mut photocraft_algo::camera_raw::CameraRaw) -> bool { + if settings.sharpen_amount != 0.0 { + return false; + } + let Some((amount, radius)) = self.sharpen_for.preset() else { return false }; + // Vary the strength around the existing Standard preset while keeping the medium's radius. + let amount = match self.sharpen_amount { + RawSharpenAmount::Low => amount * 0.5, + RawSharpenAmount::Standard => amount, + RawSharpenAmount::High => amount * 1.5, + }; + settings.sharpen_amount = amount; + settings.sharpen_radius = radius; + true + } } /// A saved Raw Defaults › Resolution as the field takes it: the nearest whole number within @@ -1251,6 +1270,7 @@ impl Default for RawDefaults { bit_depth: RawDepth::Sixteen, resolution: 300, sharpen_for: RawSharpen::None, + sharpen_amount: RawSharpenAmount::Standard, open_as_smart_object: false, apply_auto_tone: false, open_in_camera_raw: true, diff --git a/crates/engine-core/src/prefs/validate.rs b/crates/engine-core/src/prefs/validate.rs index 8e969114baf..6c2dac83b42 100644 --- a/crates/engine-core/src/prefs/validate.rs +++ b/crates/engine-core/src/prefs/validate.rs @@ -2,8 +2,8 @@ use super::shortcuts::normalize_shortcut; use super::{ AppearanceMode, Ask, CanvasBorder, CanvasColor, CheckerColors, CheckerSize, ColorPicker, ExportLocation, ExportMetadata, FontPreview, GpuBackend, Interpolation, LineStyle, LinuxDisplayServer, LogDestination, LogDetail, OtherCursor, PaintingCursor, PlaybackPerformance, PointSize, PressureCurve, - QuickExportFormat, RawColorSpace, RawDemosaic, RawDepth, RawSharpen, RenderingMode, RightClickPaint, TabletInput, TextEngine, TypeUnit, UiDensity, - UiFontSize, UiScale, Unit, Value, WhenAppClosed, + QuickExportFormat, RawColorSpace, RawDemosaic, RawDepth, RawSharpen, RawSharpenAmount, RenderingMode, RightClickPaint, TabletInput, TextEngine, TypeUnit, + UiDensity, UiFontSize, UiScale, Unit, Value, WhenAppClosed, }; /// Preferences dialog sections in Photoshop's order: (id, title). @@ -96,6 +96,7 @@ pub fn choices(path: &str) -> Option<&'static [&'static str]> { "rawDefaults.colorSpace" => RawColorSpace::NAMES, "rawDefaults.bitDepth" => RawDepth::NAMES, "rawDefaults.sharpenFor" => RawSharpen::NAMES, + "rawDefaults.sharpenAmount" => RawSharpenAmount::NAMES, "rawDefaults.demosaic" => RawDemosaic::NAMES, "performance.gpuBackend" => GpuBackend::NAMES, "performance.linuxDisplayServer" => LinuxDisplayServer::NAMES, diff --git a/crates/engine-core/src/session/execute.rs b/crates/engine-core/src/session/execute.rs index f22f31e193f..9b675b80ed5 100644 --- a/crates/engine-core/src/session/execute.rs +++ b/crates/engine-core/src/session/execute.rs @@ -33,7 +33,11 @@ impl Session { /// `check_params` hooks. pub(crate) fn validate_params(&self, id: &str, spec: &crate::registry::CommandSpec, params: &Value) -> Result<()> { crate::param_check::check(spec, params)?; - crate::registry::hooks().check_params.iter().try_for_each(|check| check(self, id, params)) + crate::registry::hooks().check_params.iter().try_for_each(|check| check(self, id, params))?; + if id == "layer.new.layer" { + crate::new_layer::precheck_mode(self, params)?; + } + Ok(()) } /// Check a call without running it: the command exists, its params have the shape diff --git a/crates/engine-paint/src/cmd/paint_cmds.rs b/crates/engine-paint/src/cmd/paint_cmds.rs index 53a8ca04183..ba95651d51d 100644 --- a/crates/engine-paint/src/cmd/paint_cmds.rs +++ b/crates/engine-paint/src/cmd/paint_cmds.rs @@ -350,7 +350,7 @@ pub fn specs() -> Vec { label: "Gradient", menu: &[], shortcut: None, - params: r##"{"from":[x,y],"to":[x,y],"style":"linear|radial|angle|reflected|diamond"="linear","colors":["#rrggbb",…]? (evenly spaced),"gradient":preset name?,"stops":[[t,"#rrggbb"|"foreground"|"background"],…]?,"transparency":[[t,0..100],…]? (default: the current gradient, see gradient.presets.select),"method":"classic|perceptual|linear|smooth"? (Photoshop's interpolation; omitted: straight stops),"smoothness":0..100=100,"reverse":bool=false,"dither":bool=true,"opacity":1..100=100,"mode":"normal|multiply|…|behind (paints only transparency)"="normal","layer":id? (default: the active layer; a layer name also works),"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target}"##, + params: r##"{"from":[x,y],"to":[x,y],"style":"linear|radial|angle|reflected|diamond"="linear","colors":["#rrggbb",…]? (evenly spaced),"gradient":preset name?,"stops":[[t,"#rrggbb"|"foreground"|"background"],…]?,"transparency":[[t,0..100],…]? (default: the current gradient, see gradient.presets.select),"method":"classic|perceptual|linear|smooth"? (Photoshop's interpolation; omitted: straight stops),"smoothness":0..100=100,"reverse":bool=false,"dither":bool=true,"opacity":1..100=100,"mode":"normal|multiply|…|behind (paints only transparency)"="normal","layer":id? (default: the active layer; a layer name also works),"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target,"classic":bool? (the Gradient tool's mode: false = Gradient mode, whose refusals on a hidden or Lock All layer's mask use that mode's texts; true or omitted = the generic refusals)}"##, enabled: crate::cmd::has_paintable, run: gradient, journal: true, diff --git a/crates/engine-paint/src/cmd/retouch_cmds.rs b/crates/engine-paint/src/cmd/retouch_cmds.rs index 767f0547db6..4d9ea4b56c3 100644 --- a/crates/engine-paint/src/cmd/retouch_cmds.rs +++ b/crates/engine-paint/src/cmd/retouch_cmds.rs @@ -458,6 +458,9 @@ mod tests; #[cfg(test)] mod clone_source_layer_tests; +#[cfg(test)] +mod untagged_working_space_tests; + #[cfg(test)] mod patch_history_names_tests; diff --git a/crates/engine-paint/src/cmd/retouch_cmds/clone_sampling.rs b/crates/engine-paint/src/cmd/retouch_cmds/clone_sampling.rs index a134d9f1901..83b7014b4ae 100644 --- a/crates/engine-paint/src/cmd/retouch_cmds/clone_sampling.rs +++ b/crates/engine-paint/src/cmd/retouch_cmds/clone_sampling.rs @@ -238,9 +238,11 @@ fn resolve_source(s: &Session, p: &Value, cmd: &str, source: Option Result>> { - let source = if which == SampleLayers::Current { crate::color_cmds::document_profile(doc) } else { crate::color_cmds::composite_profile(doc) }; + // Both documents are read as the session reads them: an untagged one is taken in its working + // space (#14224), so a stamp cloned across documents keeps the look it has on its own canvas. + let source = if which == SampleLayers::Current { s.color().document_profile(doc) } else { s.color().composite_profile(doc) }; let target = s.active().ok_or(EngineError::NoDocument)?; - let destination = crate::color_cmds::document_profile(&target.doc); + let destination = s.color().document_profile(&target.doc); let inputs = if which == SampleLayers::Current { doc.mode.color_channels() } else { 3 }; if source.channels() != inputs || destination.channels() != target.doc.mode.color_channels() { return Err(bad(cmd, "cross-document cloning does not support this color model")); diff --git a/crates/engine-paint/src/cmd/retouch_cmds/dab.rs b/crates/engine-paint/src/cmd/retouch_cmds/dab.rs index 36e2d13bd14..97d74ba89bb 100644 --- a/crates/engine-paint/src/cmd/retouch_cmds/dab.rs +++ b/crates/engine-paint/src/cmd/retouch_cmds/dab.rs @@ -385,6 +385,9 @@ impl DabTool { } Self::Focus { sharpen, strength, protect, sigma } => { let a = alpha_index(&fmt); + // Sharpen sharpens alpha too (#12940), measured at 8 bits only: 16- and 32-bit + // layers keep their alpha as before. + let keep_alpha = if sharpen && fmt.sample != SampleType::U8 { a } else { None }; let mut shares = ProtectDetailShares::default(); Box::new(move |work, fp| { let r = fp.rect.intersect(&work.rect); @@ -417,7 +420,9 @@ impl DabTool { let i = (x - wx0) as usize * n; let px = &mut line[i..i + n]; for c in 0..n { - px[c] += (out[o + c] - px[c]) * k; + if Some(c) != keep_alpha { + px[c] += (out[o + c] - px[c]) * k; + } } } }); @@ -917,6 +922,10 @@ mod smudge_refuses_indexed_tests; #[path = "smudge_mode_tests.rs"] mod smudge_mode_tests; +#[cfg(test)] +#[path = "sharpen_alpha_tests.rs"] +mod sharpen_alpha_tests; + #[cfg(test)] #[path = "burn_grayscale_tests.rs"] mod burn_grayscale_tests; diff --git a/crates/engine-paint/src/cmd/retouch_cmds/sharpen_alpha_tests.rs b/crates/engine-paint/src/cmd/retouch_cmds/sharpen_alpha_tests.rs new file mode 100644 index 00000000000..b8c06644106 --- /dev/null +++ b/crates/engine-paint/src/cmd/retouch_cmds/sharpen_alpha_tests.rs @@ -0,0 +1,157 @@ +//! #12940: with Protect Detail off, the Sharpen tool sharpens a layer's transparency by the same +//! rule as its colour, and keeps the colour. The reference test layer is (200,40,40) at alpha 64 +//! for x 300..399 and alpha 191 for x 400..499, y 300..349, clicked once at 400,320 with a 40 px +//! hard tip at Strength 100 %. +//! +//! The reference's exact alpha (40 at x 399, 215 at x 400, x 398 and 401 unchanged) comes from the +//! 8-neighbour kernel of #12939; until that lands, alpha follows today's colour kernel. + +use serde_json::json; + +use super::*; + +const RED: [f32; 3] = [200.0 / 255.0, 40.0 / 255.0, 40.0 / 255.0]; + +/// An 800 × 600 RGB document of `depth` whose active layer is `f(x, y)` (straight RGBA, 0..1). +fn doc(depth: u64, transparent: bool, f: impl Fn(i32, i32) -> [f32; 4]) -> Session { + let mut s = crate::session(); + let mut p = json!({"width": 800, "height": 600, "depth": depth, "mode": "rgb"}); + if transparent { + p["background"] = json!("transparent"); + } + s.execute("file.new", p).unwrap(); + s.edit("setup", |doc, active| { + let b = doc.bounds(); + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let fmt = surf.format(); + let mut data = Vec::new(); + for y in b.y0..b.y1 { + for x in b.x0..b.x1 { + data.extend(photocraft_raster::from_rgba(&fmt, f(x, y))); + } + } + surf.write_region(b, &data); + Ok(()) + }) + .unwrap(); + s +} + +/// The reference layer: red at alpha 64 | 191, transparent elsewhere. +fn steps(depth: u64) -> Session { + doc(depth, true, |x, y| { + let a = match (x, y) { + (300..=399, 300..=349) => 64.0, + (400..=499, 300..=349) => 191.0, + _ => 0.0, + }; + [RED[0], RED[1], RED[2], a / 255.0] + }) +} + +fn click(s: &mut Session, at: [i32; 2], extra: Value) { + let mut p = json!({"points": [at], "size": 40, "hardness": 100, "strength": 100, "protectDetail": false}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + s.execute("paint.sharpen", p).unwrap(); +} + +/// The active layer's pixel as 8-bit RGBA. +fn px(s: &Session, x: i32, y: i32) -> [i32; 4] { + let d = s.active().unwrap(); + d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y).map(|v| (v * 255.0).round() as i32) +} + +fn row(s: &Session, xs: std::ops::Range, y: i32) -> Vec<[i32; 4]> { + xs.map(|x| px(s, x, y)).collect() +} + +#[test] +fn a_click_sharpens_the_alpha_boundary_and_keeps_the_colour() { + let mut s = steps(8); + click(&mut s, [400, 320], json!({})); + let got = row(&s, 397..403, 320); + for p in &got { + assert!((p[0] - 200).abs() <= 1 && (p[1] - 40).abs() <= 1 && (p[2] - 40).abs() <= 1, "colour must stay 200,40,40: {got:?}"); + } + let alpha: Vec = got.iter().map(|p| p[3]).collect(); + // The low side goes down and the high side up, as with colour (the reference: 64 · 64 · 40 · + // 215 · 191 · 191 with #12939's kernel). Pinned from today's sigma-1 kernel. + assert!(alpha[2] < 64 && alpha[3] > 191, "alpha boundary not sharpened: {alpha:?}"); + assert_eq!(alpha, PINNED_ALPHA, "alpha x 397..402"); +} + +/// Alpha at x 397..402 after the reference click, with today's kernel. +const PINNED_ALPHA: [i32; 6] = [63, 57, 26, 229, 198, 192]; + +#[test] +fn opaque_next_to_transparent_stays_as_it_is() { + // A red square on an otherwise empty layer; a click on its left edge. + let mut s = doc(8, true, |x, y| { + let a = if (100..200).contains(&x) && (100..200).contains(&y) { 1.0 } else { 0.0 }; + [RED[0], RED[1], RED[2], a] + }); + let before = row(&s, 80..120, 150); + click(&mut s, [100, 150], json!({})); + let after = row(&s, 80..120, 150); + for (b, a) in before.iter().zip(&after) { + assert_eq!(b[3], a[3], "alpha changed: {before:?} -> {after:?}"); + if b[3] == 255 { + assert_eq!(b, a, "an opaque pixel changed: {before:?} -> {after:?}"); + } + } +} + +#[test] +fn an_opaque_layer_keeps_todays_result() { + // The epic's grey 96 | 160 step on the Background: pinned from main 038d035110. + let mut s = doc(8, false, |x, _| { + let g = if x < 400 { 96.0 } else { 160.0 } / 255.0; + [g, g, g, 1.0] + }); + click(&mut s, [400, 320], json!({})); + let grey: Vec = row(&s, 396..404, 320).iter().map(|p| p[0]).collect(); + assert_eq!(grey, [96, 96, 92, 77, 179, 164, 160, 160]); +} + +#[test] +fn lock_transparent_pixels_keeps_the_alpha() { + let mut s = steps(8); + s.execute("layer.setProps", json!({"locks": {"transparency": true}})).unwrap(); + let before = row(&s, 390..410, 320); + click(&mut s, [400, 320], json!({})); + let after = row(&s, 390..410, 320); + assert_eq!(before.iter().map(|p| p[3]).collect::>(), after.iter().map(|p| p[3]).collect::>()); +} + +#[test] +fn protect_detail_keeps_the_alpha() { + // Protect Detail on across a semi-transparent boundary was not measured: alpha stays. + let mut s = steps(8); + let before = row(&s, 390..410, 320); + click(&mut s, [400, 320], json!({"protectDetail": true})); + let after = row(&s, 390..410, 320); + assert_eq!(before.iter().map(|p| p[3]).collect::>(), after.iter().map(|p| p[3]).collect::>()); +} + +#[test] +fn sixteen_and_32_bit_keep_the_alpha() { + // Alpha at 16 and 32 bit was not measured: it stays as it was. + for depth in [16, 32] { + let mut s = steps(depth); + let before = row(&s, 390..410, 320); + click(&mut s, [400, 320], json!({})); + let after = row(&s, 390..410, 320); + assert_eq!(before.iter().map(|p| p[3]).collect::>(), after.iter().map(|p| p[3]).collect::>(), "{depth}-bit"); + } +} + +#[test] +fn blur_is_unchanged() { + // Blur already blurred alpha; this change is Sharpen's alone. + let mut s = steps(16); + s.execute("paint.blur", json!({"points": [[400, 320]], "size": 40, "hardness": 100, "strength": 100})).unwrap(); + let alpha: Vec = row(&s, 397..403, 320).iter().map(|p| p[3]).collect(); + assert!(alpha[2] > 64 && alpha[3] < 191, "16-bit Blur still blurs alpha: {alpha:?}"); +} diff --git a/crates/engine-paint/src/cmd/retouch_cmds/untagged_working_space_tests.rs b/crates/engine-paint/src/cmd/retouch_cmds/untagged_working_space_tests.rs new file mode 100644 index 00000000000..50770ed1a79 --- /dev/null +++ b/crates/engine-paint/src/cmd/retouch_cmds/untagged_working_space_tests.rs @@ -0,0 +1,43 @@ +//! #14224: cloning from another document into an untagged one lands in the space that document is +//! shown in, not in the mode's built-in default. + +use super::*; +use crate::color_cmds::ColorExt; +use craft_cms::{Builtin, Transform}; +use photocraft_color::ColorMode; + +/// Cross-document Clone Stamp over a flat sRGB block, into an untagged RGB document whose working +/// RGB is ProPhoto-compatible. The stamp keeps its look, so its samples are re-encoded into the +/// space the destination is displayed in. +#[test] +fn a_cloned_block_lands_in_the_working_space_of_the_untagged_destination() { + let mut s = crate::session(); + let filled = [0.9f32, 0.2, 0.2, 1.0]; + s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + s.execute("edit.assignProfile", json!({"profile": "srgb"})).unwrap(); + s.edit("block", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 64, 64), &filled); + Ok(()) + }) + .unwrap(); + s.execute("cloneSource.set", json!({"source": [16, 16]})).unwrap(); + // Opened under the default settings, so the document stays untagged. + s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("edit.colorSettings", json!({"workingRgb": "prophoto-compat"})).unwrap(); + let dst = s.active().unwrap().doc.clone(); + assert!(dst.icc_profile.is_none(), "the destination document is untagged"); + + s.execute("paint.cloneStamp", json!({"points": [[48, 48]], "size": 8, "hardness": 100})).unwrap(); + let st = s.active().unwrap(); + let got = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().read_region(Rect::new(48, 48, 49, 49)); + + let mut out = [0.0f32; 16]; + let working = s.color().working(ColorMode::Rgb); + Transform::new(Builtin::Srgb.profile(), &working, s.color().settings.intent(), s.color().settings.bpc).unwrap().eval(&filled[..3], &mut out).unwrap(); + let want = [out[0], out[1], out[2]]; + assert!((0..3).any(|c| (got[c] - filled[c]).abs() > 8.0 / 255.0), "the fixture must tell the two spaces apart: the stamp kept the source samples {got:?}"); + for c in 0..3 { + assert!((got[c] - want[c]).abs() < 0.01, "the stamp landed at {:?}, not in the destination's space {want:?}", &got[..3]); + } +} diff --git a/crates/engine/tests/it/paint_in_new_layer.rs b/crates/engine/tests/it/paint_in_new_layer.rs index eead47485be..4b5151d185b 100644 --- a/crates/engine/tests/it/paint_in_new_layer.rs +++ b/crates/engine/tests/it/paint_in_new_layer.rs @@ -1,12 +1,12 @@ //! Tests that run paint commands, moved from the engine-core `new_layer` tests: 1 test(s). -use photocraft_doc::BlendMode; +use photocraft_doc::{BlendMode, Layer}; use photocraft_geom::Rect; use serde_json::json; -use photocraft_engine::new_layer::neutral_color; +use photocraft_engine::new_layer::{greyed_modes, neutral_color}; use photocraft_engine::Session; @@ -41,9 +41,27 @@ fn neutral_fills_leave_the_image_unchanged() { let s0 = busy(mode, depth); let doc0 = s0.active().unwrap().doc.clone(); let shown = photocraft_compose::render(&doc0, doc0.bounds()); - for m in BlendMode::LAYER_MODES.into_iter().filter(|m| neutral_color(*m).is_some()) { + for (m, neutral) in BlendMode::LAYER_MODES.into_iter().filter_map(|m| neutral_color(m).map(|(rgb, _)| (m, rgb))) { let mut s = busy(mode, depth); - s.execute("layer.new.layer", json!({"mode": m.label(), "fillNeutral": true})).unwrap(); + let result = s.execute("layer.new.layer", json!({"mode": m.label(), "fillNeutral": true})); + if greyed_modes(&doc0).contains(&m) { + let error = result.unwrap_err().to_string(); + assert!(error.contains(m.label()) && error.contains("not available"), "{error}"); + assert_eq!(s.active().unwrap().doc.layers.len(), doc0.layers.len()); + // A file can still contain a layer in a mode that New Layer cannot create at this depth. + s.edit("Imported neutral layer", |doc, active| { + let fmt = doc.pixel_format(); + let bounds = doc.bounds(); + let mut layer = Layer::raster("Imported neutral layer", fmt); + layer.blend = m; + layer.surface_mut().unwrap().fill_rect(bounds, &photocraft_raster::from_rgba(&fmt, [neutral[0], neutral[1], neutral[2], 1.0])); + *active = Some(doc.insert_above(*active, layer)); + Ok(()) + }) + .unwrap(); + } else { + result.unwrap(); + } let doc = &s.active().unwrap().doc; let top = doc.layers.last().unwrap(); assert_eq!(top.blend, m); diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index b8791076908..a2716ddf8ee 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -1240,7 +1240,7 @@ fn export_stages_with_renderer( } if ext == "pdf" { let xmp = if opts.xmp == XmpEmbed::All { doc.metadata.xmp.as_deref() } else { None }; - let mut res = pdf::export_with(doc, opts.pdf_spot_plates, xmp, ctl)?; + let mut res = pdf::export_with_icc(doc, opts.pdf_spot_plates, xmp, opts.encode.embed_icc, ctl)?; if let Some(r) = renderer { res.warnings.push("PDF export uses CPU compositor; GPU rendering applies to flat formats".into()); res.warnings.extend(r.drain_diagnostics()); diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index a8dc29edc52..7813f5a6be5 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -176,6 +176,18 @@ pub fn export(doc: &Document, spot_plates: bool, ctl: &photocraft_raster::Interr /// PDF writer; /// without plates it is written as it is, and nothing when there is none. pub fn export_with(doc: &Document, spot_plates: bool, doc_xmp: Option<&str>, ctl: &photocraft_raster::Interrupt) -> std::result::Result { + export_with_icc(doc, spot_plates, doc_xmp, true, ctl) +} + +/// [`export_with`] with control over embedding the document profile in the page images. +/// The document's profile remains available to the compositor even when it is not embedded. +pub(crate) fn export_with_icc( + doc: &Document, + spot_plates: bool, + doc_xmp: Option<&str>, + embed_icc: bool, + ctl: &photocraft_raster::Interrupt, +) -> std::result::Result { ctl.check().map_err(|_| IoError::Cancelled)?; let (w, h) = (usize::try_from(doc.size.width).unwrap_or(0), usize::try_from(doc.size.height).unwrap_or(0)); if w == 0 || h == 0 { @@ -203,7 +215,7 @@ pub fn export_with(doc: &Document, spot_plates: bool, doc_xmp: Option<&str>, ctl let dpi = f64::from(doc.resolution_dpi.max(1.0)); let paper = if doc.mode == ColorMode::Cmyk { 0.0 } else { 1.0 }; let to8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; - let icc = doc.icc_profile.as_ref().map(|p| p.to_vec()); + let icc = doc.icc_profile.as_ref().filter(|_| embed_icc).map(|p| p.to_vec()); let plate_count = if spot_plates { plate_channels(doc).count() } else { 0 }; // Straight alpha, composited here over paper: white in RGB/Gray (1 = full light), zero ink // in CMYK (0 = paper). diff --git a/crates/io/src/pdf/tests.rs b/crates/io/src/pdf/tests.rs index b3844d993e9..412b05bd28b 100644 --- a/crates/io/src/pdf/tests.rs +++ b/crates/io/src/pdf/tests.rs @@ -202,6 +202,67 @@ fn an_embedded_profile_travels_as_iccbased() { assert_eq!(stream_after(&out.bytes, "/N 3 /Alternate"), vec![1, 2, 3, 4, 5, 6, 7, 8], "the profile bytes survive"); } +#[test] +fn the_export_profile_flag_changes_tagging_without_changing_samples_or_the_document() { + use craft_cms::Builtin; + + for (mode, profile, device) in [ + (ColorMode::Rgb, Builtin::DisplayP3, "DeviceRGB"), + (ColorMode::Grayscale, Builtin::SGray, "DeviceGray"), + (ColorMode::Cmyk, Builtin::CoatedCmyk, "DeviceCMYK"), + ] { + let mut d = doc(mode); + let profile = profile.profile().to_bytes(); + d.icc_profile = Some(profile.clone()); + let rect = Rect::new(0, 0, 4, 2); + let before = photocraft_compose::composite_to_surface(&d, rect, d.pixel_format(), None).read_region(rect); + let mut off = crate::ExportOptions::default(); + off.encode.embed_icc = false; + let tagged = crate::export(&d, "out.pdf", &crate::ExportOptions::default()).unwrap(); + let untagged = crate::export(&d, "out.pdf", &off).unwrap(); + + assert!(has(&tagged.bytes, "[/ICCBased "), "{mode:?} image uses its profile"); + let marker = format!("/N {} /Alternate", d.pixel_format().channels() - 1); + assert_eq!(stream_after(&tagged.bytes, &marker), *profile, "the document's exact profile"); + assert!(!has(&untagged.bytes, "/ICCBased"), "OFF writes no profile reference"); + assert!(!has(&untagged.bytes, "/Alternate"), "OFF writes no profile object"); + assert!(has(&untagged.bytes, &format!("/ColorSpace /{device}")), "OFF uses the matching device space"); + assert_eq!(stream_after(&tagged.bytes, "/Subtype /Image"), stream_after(&untagged.bytes, "/Subtype /Image"), "embedding must not convert the samples"); + assert_eq!(d.icc_profile.as_deref(), Some(profile.as_ref()), "the source profile remains"); + assert_eq!(photocraft_compose::composite_to_surface(&d, rect, d.pixel_format(), None).read_region(rect), before, "source samples remain"); + assert_eq!(d.layers.len(), 1); + assert_eq!(d.layers[0].name, "Paper"); + } +} + +#[test] +fn the_export_profile_flag_applies_to_every_artboard_without_changing_plates() { + let mut d = artboard_doc(&["Front", "Back"]); + let profile = craft_cms::Builtin::DisplayP3.profile().to_bytes(); + d.icc_profile = Some(profile.clone()); + d.channels.push(spot("Varnish", photocraft_color::Color::WHITE, &[0.0, 0.0, 1.0, 0.5, 0.0, 0.0, 1.0, 0.5])); + let mut off = crate::ExportOptions::default(); + off.encode.embed_icc = false; + let tagged = crate::export(&d, "out.pdf", &crate::ExportOptions::default()).unwrap(); + let untagged = crate::export(&d, "out.pdf", &off).unwrap(); + let on_pdf = lopdf::Document::load_mem(&tagged.bytes).unwrap(); + let off_pdf = lopdf::Document::load_mem(&untagged.bytes).unwrap(); + assert_eq!(on_pdf.get_pages().len(), 2); + assert_eq!(off_pdf.get_pages().len(), 2); + assert_eq!(tagged.bytes.windows(11).filter(|w| *w == b"[/ICCBased ").count(), 2, "every composite is tagged"); + assert!(!has(&untagged.bytes, "/ICCBased")); + assert!(!has(&untagged.bytes, "/Alternate")); + assert_eq!(untagged.bytes.windows(22).filter(|w| *w == b"/ColorSpace /DeviceRGB").count(), 2, "every composite uses device RGB"); + for (on, off) in on_pdf.get_pages().values().zip(off_pdf.get_pages().values()) { + assert_eq!(page_image(&on_pdf, *on), page_image(&off_pdf, *off), "the artboard samples remain"); + assert_eq!(page_xobject(&on_pdf, *on, b"Sp0"), page_xobject(&off_pdf, *off, b"Sp0"), "spot density remains"); + } + assert_eq!(xmp_of(&tagged.bytes), xmp_of(&untagged.bytes), "spot descriptions remain"); + assert_eq!(d.icc_profile.as_deref(), Some(profile.as_ref())); + assert_eq!(d.layers.len(), 2); + assert_eq!(d.channels[0].surface.read_region(Rect::new(0, 0, 4, 2)), vec![0.0, 0.0, 1.0, 0.5, 0.0, 0.0, 1.0, 0.5]); +} + #[test] fn other_modes_are_refused_with_an_actionable_error() { let d = doc(ColorMode::Lab); diff --git a/crates/ipp/Cargo.toml b/crates/ipp/Cargo.toml index b25a5ccd3f7..8c4df389b76 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 = "475f6feb712bd2db2f235d9999be61c68477ae39" } +craft-ipp = { git = "https://github.com/storytold/craft-libs", rev = "fc3262f68babdb19a98a89c415c84c6b327073d3" } [lints] workspace = true diff --git a/crates/paint/src/brush_tests.rs b/crates/paint/src/brush_tests.rs index dbb2e57790f..3e265d9869c 100644 --- a/crates/paint/src/brush_tests.rs +++ b/crates/paint/src/brush_tests.rs @@ -284,6 +284,43 @@ fn pencil_1px_freehand_line_never_breaks_where_it_turns() { assert_eq!(reached.len(), painted.len(), "the line breaks along {path:?}"); } } + +#[test] +fn pencil_1px_curve_has_no_holes() { + // #9003: a curve drawn with the 1 px Pencil broke where it bent. Each segment steps from its + // own column, so a pixel could be skipped between the end of one segment and the next. + let b = BrushSettings { aliased: true, hardness: 1.0, size: 1.0, ..brush() }; + let curves: [Vec; 3] = [ + (0..70).map(|i| StrokePoint::new(6.0 + 0.75 * f64::from(i), 24.0 + 13.0 * (f64::from(i) / 7.0).sin(), 1.0)).collect(), + (0..60).map(|i| StrokePoint::new(30.0 + 20.0 * (f64::from(i) / 9.5).cos(), 24.0 + 14.0 * (f64::from(i) / 9.5).sin(), 1.0)).collect(), + vec![ + StrokePoint::new(4.3, 30.6, 1.0), + StrokePoint::new(9.8, 8.2, 1.0), + StrokePoint::new(15.1, 30.9, 1.0), + StrokePoint::new(27.6, 12.4, 1.0), + StrokePoint::new(33.2, 31.7, 1.0), + ], + ]; + for (k, pts) in curves.iter().enumerate() { + let s = paint(&b, pts, 64, 48); + let painted: std::collections::BTreeSet<(i32, i32)> = + (0..48).flat_map(|y| (0..64).map(move |x| (x, y))).filter(|&(x, y)| s.rgba(x, y)[3] > 0.0).collect(); + let Some(&start) = painted.iter().next() else { panic!("curve {k}: nothing painted") }; + let mut seen = std::collections::BTreeSet::from([start]); + let mut todo = vec![start]; + while let Some((x, y)) = todo.pop() { + for (dx, dy) in [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)] { + let q = (x + dx, y + dy); + if painted.contains(&q) && seen.insert(q) { + todo.push(q); + } + } + } + let holes: Vec<_> = painted.difference(&seen).collect(); + assert!(holes.is_empty(), "curve {k}: the stroke breaks before {holes:?}"); + } +} + // ---------- spacing ---------- #[test] diff --git a/crates/paint/src/dynamics.rs b/crates/paint/src/dynamics.rs index 51962e59e32..9809e215ce3 100644 --- a/crates/paint/src/dynamics.rs +++ b/crates/paint/src/dynamics.rs @@ -283,8 +283,9 @@ pub struct PathWalker { /// Pixel-grid stepping for small aliased tips: the dab-centre offset inside a pixel (see /// [`PathWalker::pixel_grid`]). grid: Option, - /// The grid cell of the last pixel-grid step, so the next segment joins it (#8040). - cell: Option<(f64, f64)>, + /// The last pixel-grid step, on its grid cell, so the next segment joins it (#8040). Only pixel + /// steps set it: speed spacing and airbrush build-up leave their gaps on purpose. + cell: Option, } impl PathWalker { @@ -329,6 +330,7 @@ impl PathWalker { let (dm, dn) = (pm - am, pn - an); let n = (m1 - m0).abs(); if !(n.is_finite() && dn.is_finite()) || n > MAX_GRID_STEPS || dm == 0.0 { + self.cell = None; return false; } let dir = (m1 - m0).signum(); @@ -342,6 +344,7 @@ impl PathWalker { (q.x, q.y) = if steep { (cn, c) } else { (c, cn) }; self.bridge(&q, out); self.emit(q, out); + self.cell = Some(q); } true } @@ -350,11 +353,14 @@ impl PathWalker { /// samples its own line, so where a freehand stroke turns, the last pixel of one segment and /// the first of the next can sit two pixels apart, and the 1 px Pencil line breaks (#8040). fn bridge(&mut self, q: &StrokePoint, out: &mut impl FnMut(StepInput)) { - let Some((mut x, mut y)) = self.cell else { return }; + let Some(last) = self.cell else { return }; + let (mut x, mut y) = (last.x, last.y); + let n = (q.x - x).abs().max((q.y - y).abs()).round(); // Only a turn's small gap: a step cut off by the walker's budget is not filled in. - if (q.x - x).abs().max((q.y - y).abs()) > MAX_BRIDGE { + if n > MAX_BRIDGE { return; } + let mut i = 0.0; while (q.x - x).abs() > 1.5 || (q.y - y).abs() > 1.5 { if (q.x - x).abs() > 0.5 { x += (q.x - x).signum(); @@ -362,7 +368,9 @@ impl PathWalker { if (q.y - y).abs() > 0.5 { y += (q.y - y).signum(); } - self.emit(StrokePoint { x, y, ..*q }, out); + // Pressure, tilt and time run on across the filled-in cells too. + i += 1.0; + self.emit(StrokePoint { x, y, ..lerp_pt(&last, q, i / n) }, out); } } @@ -386,9 +394,6 @@ impl PathWalker { if self.step >= MAX_STEPS_PER_STROKE { return; } - if let Some(g) = self.grid { - self.cell = Some((grid_cell(point.x, g), grid_cell(point.y, g))); - } let s = StepInput { point, direction: self.dir, initial_direction: self.initial_dir.unwrap_or(self.dir), step: self.step }; self.step += 1; out(s); @@ -415,6 +420,9 @@ impl PathWalker { } } if let Some(f) = self.pending_first.take() { + if let Some(g) = self.grid { + self.cell = Some(StrokePoint { x: grid_cell(f.x, g), y: grid_cell(f.y, g), ..f }); + } self.emit_first(f, out); } if len > 1e-9 { @@ -438,6 +446,8 @@ impl PathWalker { } } Some(iv) => { + // The stroke moves on without pixel steps: a later pixel segment starts afresh. + self.cell = None; self.speed_acc += dt; let max_n = (len / MIN_SPEED_STEP).ceil().max(1.0) as usize; let mut n = 0; @@ -1168,6 +1178,56 @@ mod streaming_tests { } } +#[cfg(test)] +mod grid_bridge_tests { + use super::*; + + fn walk(mut walker: PathWalker, pts: &[StrokePoint]) -> Vec { + let mut steps = Vec::new(); + let mut out = |s: StepInput| steps.push(s.point); + for p in pts { + walker.push(*p, &|_: &StrokePoint| 1.0, &mut out); + } + walker.finish(&mut out); + steps + } + + fn at(x: f64, y: f64, time: f64) -> StrokePoint { + StrokePoint { time, ..StrokePoint::new(x, y, 1.0) } + } + + /// #9059 review: the bridge joins pixel steps only. Speed spacing leaves its gaps on purpose + /// (Spacing off: faster movement spreads the dabs out), so a pixel segment after one starts + /// afresh instead of filling the gap back in from the cell before it. + #[test] + fn a_pixel_segment_after_speed_spacing_leaves_its_gap() { + // A fast 8 px move in 60 ms: speed steps about every 1.07 px, the last (at 7.97) half a pixel + // short of the move's end. The segment after it has no timestamps, so it takes pixel steps. + let pts = [at(0.5, 0.5, 0.0), at(8.5, 0.5, 60.0), at(12.5, 0.5, 60.0)]; + let steps = walk(PathWalker::new(None).speed_spacing(SPEED_SPACING_MS).pixel_grid(0.5), &pts); + let xs: Vec = steps.iter().map(|p| p.x).collect(); + assert!(xs.iter().all(|x| !(8.0..9.4).contains(x)), "no cell filled in after the last speed step: {xs:?}"); + assert!(xs.windows(2).all(|w| w[1] > w[0]), "forward only: {xs:?}"); + assert!(steps.windows(2).all(|w| w[1].time >= w[0].time), "time runs on: {steps:?}"); + } + + /// #9059 review: a cell filled in at a bend takes the pressure and time between its two + /// neighbours, not the later one's, so pressure dynamics change across it. + #[test] + fn a_bridged_cell_blends_its_neighbours_dynamics() { + // Shallow, then steep: the steep segment's first step lands two cells from the last one. + let bend = [(0.3, 0.6), (10.6, 3.0), (13.0, 14.0)]; + let pts: Vec<_> = bend.iter().enumerate().map(|(i, &(x, y))| StrokePoint { pressure: 0.5 * i as f32, ..at(x, y, 100.0 * i as f64) }).collect(); + let steps = walk(PathWalker::new(None).pixel_grid(0.5), &pts); + let cell = |p: &StrokePoint| (grid_cell(p.x, 0.5), grid_cell(p.y, 0.5)); + for w in steps.windows(2) { + let ((ax, ay), (bx, by)) = (cell(&w[0]), cell(&w[1])); + assert!((bx - ax).abs() <= 1.0 && (by - ay).abs() <= 1.0, "8-connected: {:?} then {:?}", w[0], w[1]); + assert!(w[1].time > w[0].time && w[1].pressure > w[0].pressure, "dynamics run on: {:?} then {:?}", w[0], w[1]); + } + } +} + #[cfg(test)] #[path = "smoothing_lag_tests.rs"] mod smoothing_lag_tests; diff --git a/crates/ui-egui/src/artboard_top_level_background_tests.rs b/crates/ui-egui/src/artboard_top_level_background_tests.rs new file mode 100644 index 00000000000..55fb0b121ab --- /dev/null +++ b/crates/ui-egui/src/artboard_top_level_background_tests.rs @@ -0,0 +1,58 @@ +//! Canvas surround for an artboard document with a converted Background (#17309). + +use craft::behavior::CanvasView; +use craft::behavior::kurbo::{Point, Rect as DocRect}; +use craft::ui::canvas::{PageFrame, Pasteboard}; +use egui::{Rect, pos2}; +use photocraft_doc::Document; +use photocraft_engine::Session; +use photocraft_geom::Rect as PixelRect; +use serde_json::json; + +use super::{doc_rect, uncovered}; + +fn in_pasteboard(doc: &Document, point: Point) -> bool { + let screen = Rect::from_min_max(pos2(-40.0, -40.0), pos2(340.0, 240.0)); + let view = CanvasView::new(screen, Point::new(150.0, 100.0), 1.0); + let pages: Vec<_> = doc.artboards().into_iter().map(|(_, _, board)| PageFrame::new(doc_rect(board.rect))).collect(); + let point = view.to_screen(point); + Pasteboard::quads(&view, &pages, &uncovered(doc)).iter().any(|quad| Rect::from_points(quad).contains(point)) +} + +#[test] +fn a_converted_background_shows_around_the_board_but_stops_at_the_canvas() { + let mut session = Session::new(); + session.execute("file.new", json!({"width": 300, "height": 200, "background": "transparent"})).unwrap(); + let layer = session.active().unwrap().active_layer.unwrap(); + session.execute("select.rect", json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap(); + session.execute("edit.fill", json!({"color": "#c81e1e"})).unwrap(); + session.execute("select.deselect", json!({})).unwrap(); + let board = session.execute("layer.new.artboardFromLayers", json!({})).unwrap()["layer"].as_u64().unwrap(); + session.execute("layer.artboard.set", json!({"layer": board, "background": "white"})).unwrap(); + let around = Point::new(200.0, 150.0); + let on_board = Point::new(30.0, 30.0); + let outside = Point::new(320.0, 220.0); + let doc = &session.active().unwrap().doc; + assert!(doc.background().is_none()); + assert_eq!(doc.artboards()[0].2.rect, PixelRect::new(20, 20, 60, 60)); + assert!(in_pasteboard(doc, around)); + assert!(!in_pasteboard(doc, on_board)); + + session.tools.background = [0.0, 200.0 / 255.0, 0.0, 1.0]; + session.execute("layer.new.backgroundFromLayer", json!({"layer": layer.0})).unwrap(); + let doc = &session.active().unwrap().doc; + assert_eq!(doc.bounds(), PixelRect::new(0, 0, 300, 200)); + assert!(doc.is_background(layer)); + assert_eq!(uncovered(doc), [DocRect::new(0.0, 0.0, 300.0, 200.0)]); + assert!(!in_pasteboard(doc, around), "the actual pasteboard quads leave the Background open"); + assert!(!in_pasteboard(doc, on_board)); + assert!(in_pasteboard(doc, outside), "the real pasteboard beyond the canvas is still covered"); + + let green = photocraft_compose::render(doc, PixelRect::new(200, 150, 201, 151)).px[0]; + assert!(green[0] < 0.01 && green[1] > 0.5 && green[2] < 0.01 && green[3] > 0.99, "{green:?}"); + let white = photocraft_compose::render(doc, PixelRect::new(30, 30, 31, 31)).px[0]; + assert!(white.iter().all(|channel| *channel > 0.99), "the board remains white above it: {white:?}"); + + session.execute("layer.setProps", json!({"layer": layer.0, "visible": false})).unwrap(); + assert!(in_pasteboard(&session.active().unwrap().doc, around), "a hidden Background leaves the usual pasteboard"); +} diff --git a/crates/ui-egui/src/canvas/artboard_ui.rs b/crates/ui-egui/src/canvas/artboard_ui.rs index 1966f9c2b8b..68b076dd7d2 100644 --- a/crates/ui-egui/src/canvas/artboard_ui.rs +++ b/crates/ui-egui/src/canvas/artboard_ui.rs @@ -33,21 +33,32 @@ pub(crate) fn pages(app: &PhotocraftApp, idx: usize) -> Arc<[PageFrame]> { }) } -/// Where visible layers outside the boards draw: Photoshop shows those over the pasteboard, so a -/// board added next to earlier work must not paint over it (#5712). The Background and any layer -/// that covers the whole canvas (or may draw anywhere, such as a fill layer) are backdrop, not -/// loose work: they keep the pasteboard. The framework subtracts these rects and the pages from -/// the pasteboard in every view. +/// Where visible layers outside the boards draw. Loose work stays over the pasteboard (#5712), +/// and a visible Background opens the whole canvas (#17309) unless an ordinary canvas-wide +/// layer keeps the pasteboard. The framework subtracts these rects and the pages from it. pub(crate) fn uncovered(doc: &Document) -> Vec { let canvas = doc.bounds(); - let background = doc.background().map(|b| b.id); - doc.layers + let background = doc.background(); + let background_id = background.map(|layer| layer.id); + let mut regions = Vec::new(); + let mut has_canvas_wide_layer = false; + let layer_bounds = doc + .layers .iter() - .filter(|l| l.visible && !is_artboard(l) && Some(l.id) != background) - .filter_map(|l| photocraft_compose::composite_bounds(l, canvas)) - .filter(|b| !b.is_empty() && !b.contains_rect(&canvas)) - .map(doc_rect) - .collect() + .filter(|l| l.visible && !is_artboard(l) && Some(l.id) != background_id) + .map(|l| photocraft_compose::composite_bounds(l, canvas).unwrap_or(canvas)) + .filter(|b| !b.is_empty()); + for bounds in layer_bounds { + if bounds.contains_rect(&canvas) { + has_canvas_wide_layer = true; + } else { + regions.push(doc_rect(bounds)); + } + } + if background.is_some_and(|layer| layer.visible) && !canvas.is_empty() && !has_canvas_wide_layer { + regions.push(doc_rect(canvas)); + } + regions } fn is_artboard(l: &Layer) -> bool { @@ -149,16 +160,42 @@ mod tests { #[test] fn full_canvas_layers_keep_the_pasteboard() { - // The white Background (from `app()`) and a loose layer filling the whole canvas are - // backdrop: the pasteboard still shows outside the board. + // An ordinary layer filling the whole canvas keeps the pasteboard, with or without a Background. let (mut app, _) = app(); app.run("layer.new.artboard", json!({"rect": [0, 0, 40, 50]})).unwrap(); let mut doc = (*app.session.active().unwrap().doc).clone(); - assert!(doc.background().is_some()); + assert!(doc.background().unwrap().visible); let mut px = photocraft_doc::Layer::raster("Wash", doc.pixel_format()); px.surface_mut().unwrap().fill_rect(doc.bounds(), &[0.0, 0.0, 1.0, 1.0]); doc.layers.push(px); - assert!(uncovered(&doc).is_empty()); + assert!(uncovered(&doc).is_empty(), "a visible Background does not expose the full-canvas layer"); + doc.background_mut().unwrap().locks.position = false; + assert!(doc.background().is_none()); + assert!(uncovered(&doc).is_empty(), "the same rule applies without a Background"); + } + + #[test] + fn layers_with_an_opaque_default_keep_the_pasteboard() { + let (mut app, _) = app(); + app.run("layer.new.artboard", json!({"rect": [0, 0, 40, 50]})).unwrap(); + let mut doc = (*app.session.active().unwrap().doc).clone(); + let canvas = doc.bounds(); + assert!(doc.background().unwrap().visible); + + // An empty ordinary layer has bounded, empty content. It does not hide the Background. + let fmt = doc.pixel_format(); + doc.layers.push(Layer::raster("Empty", fmt)); + assert_eq!(uncovered(&doc), vec![doc_rect(canvas)]); + + // An opaque default can paint anywhere even without allocated raster tiles. + let mut wash = Layer::raster("Opaque wash", fmt); + *wash.surface_mut().unwrap() = photocraft_raster::Surface::with_default(fmt, &[0.0, 0.0, 1.0, 1.0]); + for layer in [wash.clone(), Layer::group("Wash group", vec![wash])] { + assert!(photocraft_compose::composite_bounds(&layer, canvas).is_none()); + let mut shown = doc.clone(); + shown.layers.push(layer); + assert!(uncovered(&shown).is_empty()); + } } #[test] @@ -186,3 +223,7 @@ mod tests { assert_eq!(crate::comps_ui::target(&app), Some(b)); } } + +#[cfg(test)] +#[path = "../artboard_top_level_background_tests.rs"] +mod top_level_background_tests; diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu.rs b/crates/ui-egui/src/canvas/canvas_tool_menu.rs index ba6cf181f71..38ef019fb0e 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu.rs @@ -2065,7 +2065,8 @@ pub(crate) fn run( let doc = view.to_doc(at); open_at(app, tool, mods, at, [doc.x, doc.y], None); } - if let Some(request) = host.context { + // A right press that ended a Gradient drag made the gradient instead (#18703). + if let Some(request) = host.context.filter(|_| !app.canvas_tools.gradient.ended_by_right_press()) { // A Space-held Hand opens the Hand's menu over the current tool. A momentary Zoom opens no menu of its own, but // with ⌘ held the right-click is still the one that lists the layers under the pointer (#307). let tool = match request.momentary { diff --git a/crates/ui-egui/src/canvas/document_area.rs b/crates/ui-egui/src/canvas/document_area.rs index 64d7572b281..256a1f3fc5a 100644 --- a/crates/ui-egui/src/canvas/document_area.rs +++ b/crates/ui-egui/src/canvas/document_area.rs @@ -320,7 +320,7 @@ fn arranged(app: &mut PhotocraftApp, ui: &mut egui::Ui, rect: Rect, active: usiz } // A clean document can leave the session immediately, so close only after the pane indices were used. for id in closing { - tabs::close_document(app, ui.ctx(), id); + tabs::close_tab(app, ui.ctx(), id); } true } diff --git a/crates/ui-egui/src/canvas/document_display.rs b/crates/ui-egui/src/canvas/document_display.rs index 08e063d974f..c332ddf098d 100644 --- a/crates/ui-egui/src/canvas/document_display.rs +++ b/crates/ui-egui/src/canvas/document_display.rs @@ -623,7 +623,7 @@ fn canvas_controls( crate::slice_ui::canvas_controls(ui, app, rect); crate::symmetry_ui::canvas_controls(ui, app, rect); crate::perspective_crop_ui::body(app, ui, rect); - crate::analysis::canvas::body(app, ui, rect); + crate::analysis::canvas::body(app, ui, rect, host); // The frame is the active document's: another document on screen shows none (#18368). if primary && app.session.active_index() == Some(host.idx) { reported.crop = super::tools::crop::show_frame(app, ui, rect); diff --git a/crates/ui-egui/src/canvas/tabs.rs b/crates/ui-egui/src/canvas/tabs.rs index 0466086965d..8c5bf98edd9 100644 --- a/crates/ui-egui/src/canvas/tabs.rs +++ b/crates/ui-egui/src/canvas/tabs.rs @@ -88,7 +88,7 @@ pub(super) fn apply(app: &mut PhotocraftApp, ctx: &egui::Context, out: DocumentT for event in out.events { match event { DocumentTabsEvent::Selected(tab) | DocumentTabsEvent::Picked(tab) | DocumentTabsEvent::Activated(tab) => show_tab(app, tab), - DocumentTabsEvent::CloseRequested(DocTab::Doc(id)) => close_document(app, ctx, id), + DocumentTabsEvent::CloseRequested(DocTab::Doc(id)) => close_tab(app, ctx, id), DocumentTabsEvent::CloseRequested(DocTab::Opening(job)) => { let _ = crate::jobs_ui::cancel(app, job); } @@ -120,7 +120,18 @@ pub(super) fn apply(app: &mut PhotocraftApp, ctx: &egui::Context, out: DocumentT menu } -/// The guarded close shared by the tab strip and a tiled document's title. +/// The close affordance shared by the tab strip and a tiled document's title. +pub(super) fn close_tab(app: &mut PhotocraftApp, ctx: &egui::Context, id: DocId) { + if app.ui.tool == crate::Tool::PerspectiveCrop + && app.session.active().is_some_and(|document| document.doc.id == id) + && crate::perspective_crop_ui::quad(app).is_some() + { + return; + } + close_document(app, ctx, id); +} + +/// Closes an open document, showing its unsaved-changes prompt when needed. pub(super) fn close_document(app: &mut PhotocraftApp, ctx: &egui::Context, id: DocId) { if let Some(index) = document_index(app, id) { let _ = crate::menus::invoke(app, ctx, "file.close", json!({"document": index})); @@ -307,6 +318,10 @@ mod file_info_copyright_title_tests; #[path = "tab_indexed_bitmap_label_tests.rs"] mod tab_indexed_bitmap_label_tests; +#[cfg(test)] +#[path = "tabs_perspective_crop_close_tests.rs"] +mod tabs_perspective_crop_close_tests; + #[cfg(test)] #[path = "../tab_title_channel_target_tests.rs"] mod tab_title_channel_target_tests; diff --git a/crates/ui-egui/src/canvas/tabs_perspective_crop_close_tests.rs b/crates/ui-egui/src/canvas/tabs_perspective_crop_close_tests.rs new file mode 100644 index 00000000000..1c881ed5ae0 --- /dev/null +++ b/crates/ui-egui/src/canvas/tabs_perspective_crop_close_tests.rs @@ -0,0 +1,122 @@ +use egui::accesskit::Role; +use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use crate::canvas::testing::to_screen; +use crate::perspective_crop_ui; +use crate::theme::AppTheme; +use crate::{PhotocraftApp, Tool}; + +type App = Harness<'static, Box>; + +fn two_documents(tiled: bool) -> Result { + let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, AppTheme::pro()); + PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), crate::Services::default()) + }); + let app = h.state_mut(); + for name in ["Reference.psd", "Edited.psd"] { + app.run("file.new", json!({"width": 400, "height": 300, "name": name}))?; + } + app.run("layer.new.layer", json!({"name": "Retouch"}))?; + h.run_steps(4); + let ctx = h.ctx.clone(); + if tiled { + crate::menus::invoke(h.state_mut(), &ctx, "window.arrange.tile", json!({}))?; + } + h.state_mut().ui.tool = Tool::PerspectiveCrop; + h.state_mut().ui.extras.snap = false; + h.run_steps(6); + assert!(h.state().session.active().is_some_and(|doc| doc.doc.name == "Edited.psd" && doc.is_dirty())); + Ok(h) +} + +fn point(h: &mut App, at: Pos2) { + h.event(Event::PointerMoved(at)); + h.run_steps(1); +} + +fn press(h: &mut App, pos: Pos2, pressed: bool) { + h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(1); +} + +fn click(h: &mut App, at: Pos2) { + point(h, at); + press(h, at, true); + press(h, at, false); + h.run_steps(3); +} + +fn draw_quad(h: &mut App) { + let from = to_screen(h.state(), [40.0, 30.0]); + let to = to_screen(h.state(), [360.0, 270.0]); + point(h, from); + press(h, from, true); + point(h, to); + press(h, to, false); + h.run_steps(2); + assert!(perspective_crop_ui::quad(h.state()).is_some()); +} + +fn click_close(h: &mut App, name: &str, tiled: bool) -> Result<(), String> { + let label = format!("Close {name}"); + let canvas = h.state().last_canvas_rect; + let at = h + .query_all_by_role(Role::Button) + .filter(|node| node.accesskit_node().label().is_some_and(|text| text.starts_with(label.as_str()))) + .map(|node| node.rect().center()) + .find(|at| canvas.contains(*at) == tiled) + .ok_or_else(|| format!("Missing {label} button for tiled={tiled}"))?; + click(h, at); + Ok(()) +} + +/// The active tab and active tiled title must leave the same quad editing session in place. +#[test] +fn a_complete_quad_protects_its_dirty_document_from_tab_and_tile_close() -> Result<(), String> { + for tiled in [false, true] { + let mut h = two_documents(tiled)?; + draw_quad(&mut h); + let quad = perspective_crop_ui::quad(h.state()); + let active = h.state().session.active().map(|doc| doc.doc.id); + click_close(&mut h, "Edited.psd", tiled)?; + assert!(h.state().discard.is_none(), "close opened a save prompt for tiled={tiled}"); + assert_eq!(h.state().session.documents().len(), 2); + assert_eq!(h.state().session.active().map(|doc| doc.doc.id), active); + assert_eq!(perspective_crop_ui::quad(h.state()), quad); + + // Reset through the tool before testing a partial session, independently of the tab's focus. + perspective_crop_ui::cancel(h.state_mut()); + h.run_steps(3); + assert!(perspective_crop_ui::quad(h.state()).is_none()); + let corner = to_screen(h.state(), [40.0, 30.0]); + click(&mut h, corner); + assert!(perspective_crop_ui::pending(h.state()), "one corner starts a partial session"); + assert!(perspective_crop_ui::quad(h.state()).is_none()); + click_close(&mut h, "Edited.psd", tiled)?; + assert!(h.state().discard.is_some(), "without a quad the existing dirty-document prompt is available for tiled={tiled}"); + assert_eq!(h.state().session.documents().len(), 2); + } + Ok(()) +} + +#[test] +fn a_complete_quad_leaves_other_tabs_and_the_file_close_command_available() -> Result<(), String> { + let mut h = two_documents(false)?; + draw_quad(&mut h); + let quad = perspective_crop_ui::quad(h.state()); + let active = h.state().session.active().map(|doc| doc.doc.id); + click_close(&mut h, "Reference.psd", false)?; + assert!(h.state().discard.is_none()); + assert_eq!(h.state().session.documents().len(), 1); + assert_eq!(h.state().session.active().map(|doc| doc.doc.id), active); + assert_eq!(perspective_crop_ui::quad(h.state()), quad); + + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "file.close", json!({}))?; + assert!(h.state().discard.is_some(), "File Close still asks before closing the dirty document"); + Ok(()) +} diff --git a/crates/ui-egui/src/canvas/tools/mod.rs b/crates/ui-egui/src/canvas/tools/mod.rs index 9090424e211..0f9031be618 100644 --- a/crates/ui-egui/src/canvas/tools/mod.rs +++ b/crates/ui-egui/src/canvas/tools/mod.rs @@ -514,6 +514,7 @@ fn with_rig( ) -> R { let tool = app.ui.tool; let fam = family(tool); + let scale_ruler = crate::analysis::canvas::scale_ruler_on(app, host); let in_gesture = ToolHost::in_gesture(ctx, host.canvas_id()); // Tools that own state the app lends nobody are built before the scope takes the app. The Crop tool edits the active // document's frame, so only that document's canvas runs it (#18368); a gesture keeps it to its cancel. @@ -528,7 +529,7 @@ fn with_rig( // gesture another pick began leaves it in the app, where that tool edits it: the Frame tool's press on an image // handle opens the session and its drag moves the box. let transform_open = app.ui.transform.is_some(); - let lends_transform = stand_ins && (!in_gesture || tools.gesture_pick == GesturePick::Transform); + let lends_transform = stand_ins && !scale_ruler && (!in_gesture || tools.gesture_pick == GesturePick::Transform); let free_transform = if lends_transform { app.ui.transform.take() } else { None }; let BodyShown { crop: crop_shown, transform_snapped, .. } = shown; let mut transform = free_transform.as_ref().map(|session| crate::transform_tool::canvas_tool(session, transform_snapped)); @@ -539,7 +540,7 @@ fn with_rig( (Some(tool), Some(run)) => Some(crop::pass(tool, run, ctx, crop_shown)), _ => None, }; - let command_wanted = stand_ins && !transform_open && takes_command_stand_in(tool); + let command_wanted = stand_ins && !scale_ruler && !transform_open && takes_command_stand_in(tool); let alt_wanted = stand_ins && !transform_open && super::cursor_policy::alt_eyedropper(tool); let source_wanted = stand_ins && matches!(tool, Tool::CloneStamp | Tool::Healing); @@ -653,7 +654,7 @@ fn with_rig( alt_t = Some(retouch::source_tool(&scope, state, host)); } let alt_stand_in = alt_t.is_some(); - let mut pre = Preflight { scope: &scope, inner: selected, tool, dialog: dialog_picked, outline_open, alt_stand_in }; + let mut pre = Preflight { scope: &scope, inner: selected, tool, dialog: dialog_picked || scale_ruler, outline_open, alt_stand_in }; let mut tool_host = ToolHost::new().momentary(momentary); if let Some(mover) = command_t.as_mut() { tool_host = tool_host.stand_in(StandInKey::Command, dynamic(mover)); @@ -806,6 +807,15 @@ pub(crate) fn tool_changed(app: &mut PhotocraftApp, ctx: &egui::Context, host: C app.canvas_tools = tools; } +/// Cancels the gesture that belongs to `doc`, using its original canvas even if the document has closed. +pub(crate) fn cancel_document_gesture(app: &mut PhotocraftApp, ctx: &egui::Context, doc: photocraft_doc::DocId) { + let Some((_, host)) = app.canvas_tools.gesture_on.filter(|(owner, _)| *owner == doc.0) else { return }; + app.canvas_tools.gesture_on = None; + if ToolHost::in_gesture(ctx, host.canvas_id()) { + tool_changed(app, ctx, host); + } +} + /// Whether the active document's own canvas has a gesture running, for the readers with no `Context` at hand. pub(crate) fn in_gesture(app: &PhotocraftApp) -> bool { let Some(idx) = app.session.active_index() else { return false }; diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 28ff520e7d1..20925809db7 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -132,7 +132,11 @@ pub(crate) mod params { check: Some(crate::canvas_tool_menu::pen_dialogs::check), ..ParamFamily::new(crate::canvas_tool_menu::pen_dialogs::owns, crate::canvas_tool_menu::pen_dialogs::run) }, - ParamFamily::new(crate::analysis::dialogs::owns, crate::analysis::dialogs::run), + ParamFamily { + cancel: Some(crate::analysis::dialogs::cancel), + document: Some(crate::analysis::dialogs::document), + ..ParamFamily::new(crate::analysis::dialogs::owns, crate::analysis::dialogs::run) + }, ParamFamily::new(crate::layers_panel_ui::owns, crate::layers_panel_ui::run), ParamFamily { check: Some(image_processor_ui::check), @@ -145,6 +149,10 @@ pub(crate) mod params { ..ParamFamily::new(|key| key == "file.automate.batch", filter_dialog::run) }, ParamFamily { document: Some(file_info_document), ..ParamFamily::new(|key| key == "file.fileInfo", run_file_info) }, + ParamFamily { + cancel: Some(filter_dialog::cancel), + ..ParamFamily::new(|key| key == crate::view_cmds::dialogs::DATA_SETS, crate::view_cmds::dialogs::data_sets_run) + }, ParamFamily { cancel: Some(filter_dialog::cancel), ..ParamFamily::new(crate::view_cmds::dialogs::is_form, filter_dialog::run) }, crate::prefs_ui::PRESETS_FAMILY, crate::swatches_ui::SWATCH_NAME_FAMILY, @@ -458,6 +466,7 @@ pub(crate) const PROMPTS: &[PromptRow] = &[ preset_group_prompt::answer, open_prompt::answer_prompt, alerts::answer, + crate::view_cmds::dialogs::data_sets_answer, contact_sheet_ui::answer, crate::jobs_ui::answer, crate::gpu_status::answer, diff --git a/crates/ui-egui/src/dialogs/alerts.rs b/crates/ui-egui/src/dialogs/alerts.rs index 670f8ef8d65..bbefe45c3dd 100644 --- a/crates/ui-egui/src/dialogs/alerts.rs +++ b/crates/ui-egui/src/dialogs/alerts.rs @@ -13,7 +13,7 @@ use serde_json::{Value, json}; use crate::PhotocraftApp; -/// The tag of an alert opened by [`alert_once`]: the dialog preference its "Don't show again" box sets. +/// The tag of an alert opened by [`alert_once`] or [`info_once`]: the dialog preference its "Don't show again" box sets. pub(crate) struct AlertOnce { pref: &'static str, } @@ -102,6 +102,21 @@ pub(crate) fn feed_restored_warning(app: &mut PhotocraftApp, ctx: &egui::Context } } +/// [`alert_once`] with the catalog's info icon beside the message, as the reference shows for the +/// Content-Aware Fill workspace's Custom sampling alert (#16693). The other alerts keep their look. +pub fn info_once(app: &mut PhotocraftApp, message: impl Into, pref: &'static str) -> Option { + if dismissed(app, pref) { + return None; + } + let prompt = StandardPrompt::custom(message.into()) + .title(TITLE) + .icon(IconId::new("info")) + .button(PromptChoice::Proceed, tl!("OK").to_owned()) + .dont_show_again() + .tag(AlertOnce { pref }); + open_prompt(app, prompt).ok().or_else(|| prompt_tagged::(app)) +} + /// Keeps "Don't show again" for the question remembered as `pref`, with the other dialog preferences. pub fn remember_skip(app: &mut PhotocraftApp, pref: &str) { remember_skip_or(app, pref, tl!("The preference could not be saved: {error}")); diff --git a/crates/ui-egui/src/dialogs/caf_ui/custom_alert_tests.rs b/crates/ui-egui/src/dialogs/caf_ui/custom_alert_tests.rs index d66740c1eb1..f49ca5010b9 100644 --- a/crates/ui-egui/src/dialogs/caf_ui/custom_alert_tests.rs +++ b/crates/ui-egui/src/dialogs/caf_ui/custom_alert_tests.rs @@ -2,7 +2,9 @@ //! reference's info alert, "Use the Sampling Brush Tool to add to the sampling area in order to //! fill the selected region.", with "Don't show again" and OK, once per choice. OK closes it and the //! Sampling Brush adds. With "Don't show again" ticked it stays closed. Other choices show nothing. +//! #16693: the alert shows an info icon beside its text. +use egui::accesskit::Role; use egui_kittest::kittest::Queryable; use serde_json::{Value, json}; @@ -94,6 +96,25 @@ fn choosing_custom_shows_the_alert_once_and_ok_leaves_the_brush_adding() { assert_eq!((d["settings"]["sampling"].as_str(), d["brushMode"].as_str()), (Some("custom"), Some("add"))); } +#[test] +fn the_alert_shows_an_icon_beside_its_text() { + let mut app = app(); + open(&mut app).unwrap(); + choose(&mut app, "custom"); + let mut h = egui_kittest::Harness::builder() + .with_size(egui::vec2(1440.0, 900.0)) + .with_max_steps(16) + .with_context(app.ctx().clone()) + .build_ui_state(|ui, app: &mut Box| crate::dialogs::run(app, ui), app); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + let title = h.get_by_role_and_label(Role::Heading, "PhotoCraft").rect(); + let message = h.get_by_label_contains(CUSTOM_SAMPLING_ALERT).rect(); + // The prompt draws the icon unnamed, so it shows in the layout: the title starts at the content's start, the + // message after the icon on its row. + assert!(message.left() > title.left() + 8.0, "the message starts after the icon: {message:?} vs title {title:?}"); +} + #[test] fn each_choice_of_custom_shows_it() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs b/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs index e2007c3d709..93f0ddc2530 100644 --- a/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs +++ b/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs @@ -316,7 +316,7 @@ pub(crate) fn take(app: &mut PhotocraftApp, ctx: &egui::Context) { } if custom_chosen { - let _ = crate::dialogs::alerts::alert_once(app, tl!(CUSTOM_SAMPLING_ALERT), CUSTOM_SAMPLING_PREF); + let _ = crate::dialogs::alerts::info_once(app, tl!(CUSTOM_SAMPLING_ALERT), CUSTOM_SAMPLING_PREF); } } diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/convert.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/convert.rs index 7817d007380..98c7a949d8f 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/convert.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/convert.rs @@ -12,14 +12,7 @@ use serde_json::json; /// Camera Raw Defaults › Sharpen For: output sharpening, folded into the Camera Raw step `rest` /// as the workflow's Sharpen For is. Returns what it applied. pub(super) fn output_sharpening(d: &photocraft_engine::prefs::RawDefaults, rest: &mut CameraRaw) -> Vec<&'static str> { - match d.sharpen_for.preset() { - Some((amount, radius)) if rest.sharpen_amount == 0.0 => { - rest.sharpen_amount = amount; - rest.sharpen_radius = radius; - vec!["sharpenFor"] - } - _ => Vec::new(), - } + if d.apply_output_sharpening(rest) { vec!["sharpenFor"] } else { Vec::new() } } /// The Camera Raw Defaults [`apply_raw_conversions`] applies. Resolution is not among them: the diff --git a/crates/ui-egui/src/dialogs/color_range_ui.rs b/crates/ui-egui/src/dialogs/color_range_ui.rs index 1611261f363..2e7e14487a5 100644 --- a/crates/ui-egui/src/dialogs/color_range_ui.rs +++ b/crates/ui-egui/src/dialogs/color_range_ui.rs @@ -212,6 +212,14 @@ fn query_key(app: &PhotocraftApp, params: &Value) -> u64 { (setup.profile.content_hash(), setup.intent, setup.bpc, setup.simulate_paper, setup.kind).hash(&mut key); (proof.enabled, proof.gamut_warning, proof.gamut_threshold.to_bits()).hash(&mut key); } + // Both fast paths judge colour in the space the session shows the document in (#14224): the + // sampled-colour box runs through the document's profile, and so does the gamut mask, which for + // an untagged RGB or Grayscale document is Color Settings' working space. Hash the setting + // rather than the resolved profile, for the same reason as the proof setup above. + let color = app.session.color(); + for mode in [photocraft_doc::ColorMode::Rgb, photocraft_doc::ColorMode::Grayscale] { + color.working_space_spec(mode).hash(&mut key); + } key.finish().max(1) } @@ -264,7 +272,7 @@ fn proxy_mask(app: &PhotocraftApp, proxy: &Document, k: u32, params: &Value) -> } if params.get("select").and_then(Value::as_str) == Some("outOfGamut") { let pv = app.session.color().proof(proxy.id); - let (m, _) = photocraft_engine::color_cmds::gamut_mask(proxy, &pv.setup, pv.gamut_threshold).map_err(|e| e.to_string())?; + let (m, _) = app.session.color().gamut_mask(proxy, &pv.setup, pv.gamut_threshold).map_err(|e| e.to_string())?; let invert = params.get("invert").and_then(Value::as_bool).unwrap_or(false); let mut mask: Vec = m.iter().map(|v| f32::from(*v) / 255.0).map(|v| if invert { 1.0 - v } else { v }).collect(); scope_preview(proxy, params, &mut mask); diff --git a/crates/ui-egui/src/dialogs/color_range_ui/tests.rs b/crates/ui-egui/src/dialogs/color_range_ui/tests.rs index 26ef41cf446..e94d26ef0c8 100644 --- a/crates/ui-egui/src/dialogs/color_range_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/color_range_ui/tests.rs @@ -130,6 +130,39 @@ fn preview_cache_refreshes_after_foreground_and_proof_changes() { assert_ne!(query_key(&app, &p), query_key(&app, &json!({"select": "outOfGamut", "invert": true}))); } +/// An untagged RGB strip whose colours straddle coated CMYK: read as sRGB some of them are inside +/// it, read as ProPhoto the same numbers are far outside. +fn untagged_strip_session() -> photocraft_engine::Session { + let colours = [[0.95f32, 0.05, 0.05], [0.8, 0.3, 0.3], [0.6, 0.1, 0.1], [0.3, 0.85, 0.3], [0.1, 0.4, 0.9], [0.45, 0.45, 0.95]]; + let mut doc = Document::with_background("strip", Size::new(24, 4), ColorMode::Rgb, SampleType::U8, Color::WHITE); + { + let bg = doc.layers[0].surface_mut().unwrap(); + for (i, c) in colours.iter().enumerate() { + bg.fill_rect(GRect::new(i as i32 * 4, 0, i as i32 * 4 + 4, 4), &[c[0], c[1], c[2], 1.0]); + } + } + let mut s = photocraft_engine::Session::new(); + s.add_document(doc, None); + s +} + +/// #14224: both fast preview paths judge colour in the space the session shows the document in, so +/// Color Settings' working space belongs in the key the cached picture is kept under - otherwise the +/// dialog keeps showing the old Out of Gamut mask after the setting moves. +#[test] +fn preview_cache_refreshes_after_a_working_space_change() { + let mut app = PhotocraftApp::new(untagged_strip_session(), crate::Services::default()); + app.run("view.proofSetup", json!({"profile": "coated-cmyk", "intent": "perceptual"})).unwrap(); + let p = json!({"select": "outOfGamut"}); + let doc = app.session.active().unwrap().doc.clone(); + let before = proxy_mask(&app, &doc, 1, &p).unwrap(); + let key_before = query_key(&app, &p); + app.run("edit.colorSettings", json!({"workingRgb": "prophoto-compat"})).unwrap(); + let after = proxy_mask(&app, &doc, 1, &p).unwrap(); + assert_ne!(before, after, "the preview marks the same pixels whatever the working space of an untagged document"); + assert_ne!(key_before, query_key(&app, &p), "and the cache key holds onto the picture the setting has made stale"); +} + #[test] fn eyedropper_hover_reuses_preview_textures_without_sampling() { let mut app = app_with_doc(); diff --git a/crates/ui-egui/src/dialogs/color_settings_presets_tests.rs b/crates/ui-egui/src/dialogs/color_settings_presets_tests.rs index b50df89570b..f8e4167e5f2 100644 --- a/crates/ui-egui/src/dialogs/color_settings_presets_tests.rs +++ b/crates/ui-egui/src/dialogs/color_settings_presets_tests.rs @@ -271,3 +271,10 @@ fn monitor_color_follows_a_monitor_profile_change() { 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")); } + +#[test] +fn every_setup_has_a_spelled_out_label_that_reads_its_name_in_english() { + for name in COLOR_SETTINGS_PRESETS { + assert_eq!(preset_label(name), Some(name), "a setup missing from `preset_label`, or a misspelled key, shows untranslated"); + } +} diff --git a/crates/ui-egui/src/dialogs/export_dialog/tests.rs b/crates/ui-egui/src/dialogs/export_dialog/tests.rs index 7adebfc1113..20efb9feb2e 100644 --- a/crates/ui-egui/src/dialogs/export_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/export_dialog/tests.rs @@ -1099,3 +1099,29 @@ fn profile_and_metadata_follow_the_existing_exporter() { assert!(kept.windows(b"secret".len()).any(|w| w == b"secret")); assert_eq!(doc, before); } + +/// A panorama's preview is the exported picture alone: the texture Export As shows has the export's +/// proportions, and an opaque image previews opaque. A preview padded to a square would read as +/// transparent bands above and below a wide image, as if the exported file had them. +#[test] +fn a_panorama_previews_at_its_own_proportions_with_no_transparent_bands() { + let mut h = harness(export_app(2172, 724)); + super::open(h.state_mut()).unwrap(); + settle_preview(&mut h); + let [w, h_px] = h.state().export_open.as_ref().expect("Export As is open").texture.as_ref().expect("the preview is shown").size(); + assert!(w > h_px, "the preview is wider than tall: {w} × {h_px}"); + let ratio = w as f64 / h_px as f64; + assert!((ratio - 3.0).abs() < 0.02, "the preview keeps 2172 × 724's proportions: {w} × {h_px}"); + + let doc = Document::with_background( + "panorama", + photocraft_doc::Size::new(2172, 724), + photocraft_doc::ColorMode::Rgb, + photocraft_doc::SampleType::U8, + photocraft_doc::Color::WHITE, + ); + let f = Map::from_iter([("format".into(), json!("jpg")), ("scale".into(), json!(100))]); + let pixels = super::preview_pixels(&default_preview_proxy(&doc, &f).unwrap(), None); + assert_eq!(pixels.rgba.len(), pixels.width * pixels.height * 4); + assert!(pixels.rgba.as_chunks::<4>().0.iter().all(|px| px[3] == 255), "every preview pixel of an opaque image is opaque"); +} diff --git a/crates/ui-egui/src/dialogs/file_ui/print.rs b/crates/ui-egui/src/dialogs/file_ui/print.rs index 613fdb9f9c0..bccd3245cf4 100644 --- a/crates/ui-egui/src/dialogs/file_ui/print.rs +++ b/crates/ui-egui/src/dialogs/file_ui/print.rs @@ -1,7 +1,9 @@ use craft::behavior::EditEvent; +use craft::ui::choice::Checkbox; +use craft::ui::contract::{Bind, Outcome as _, Props as _, Show as _}; use craft::ui::dialog::{DialogId, DialogResult, StackDialog as _}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, NumberUnit, Param, ParamKind}; -use craft::ui::runtime::env::UnitKind; +use craft::ui::runtime::env::{Label, UnitKind}; use craft::ui::runtime::requests::PathKind; use craft_print::ui::{Destination, Duplex, HostedPrint, PrintAnswer, PrintFinish, PrintMarks, PrintSection, PrintSheet, Printer, Settings, State}; use serde_json::{Map, Value, json}; @@ -146,7 +148,17 @@ pub fn open_print(app: &mut PhotocraftApp) -> DialogId { } } write_settings(&mut fields, &state.settings); - let sections = sections(&fields); + let document_profile = app.session.active().map(|state| { + let doc = &state.doc; + if doc.icc_profile.is_some() { + Label::from(crate::panels::chrome_ui::profile_name(doc)) + } else if doc.mode == photocraft_doc::ColorMode::Lab { + Label::from(tl!("Lab Color")) + } else { + Label::from(tl!(crate::canvas::mode_label(doc))) + } + }); + let sections = sections(&fields, document_profile); app.framework.dialogs.open(HostedPrint::new(state, fields, sections).json_form(|fields, listing| { if fields.text("paper") == Some("custom") { listing.insert("paper".into(), print_params(fields)["paper"].clone()); @@ -157,7 +169,7 @@ pub fn open_print(app: &mut PhotocraftApp) -> DialogId { /// The dialog's sections under the printer panel, as rows over today's `file.print` keys. /// Lengths are shown in the unit `file.print` keeps them in: positions in inches, the custom paper /// in points. -pub(super) fn sections(fields: &DialogFields) -> Vec { +fn sections(fields: &DialogFields, document_profile: Option