diff --git a/Cargo.lock b/Cargo.lock index 5df355ef90..4465866385 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1365,7 +1365,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-automation", "craft-behavior", @@ -1404,7 +1404,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "crc32fast", "flate2", @@ -1425,7 +1425,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "rustix 1.1.5", ] @@ -1433,7 +1433,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "base64 0.22.1", "craft-ai-agents", @@ -1459,7 +1459,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1475,7 +1475,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-docpath", @@ -1493,7 +1493,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "egui", ] @@ -1501,7 +1501,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "md-5", "rayon", @@ -1510,7 +1510,7 @@ dependencies = [ [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-cms", @@ -1530,17 +1530,17 @@ dependencies = [ [[package]] name = "craft-crs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "thiserror 2.0.21", ] [[package]] name = "craft-crw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "thiserror 2.0.21", ] @@ -1548,7 +1548,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "rayon", ] @@ -1564,7 +1564,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "block2 0.6.2", "craft-atomic", @@ -1587,7 +1587,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "serde", ] @@ -1595,7 +1595,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1614,21 +1614,21 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" [[package]] name = "craft-file-formats" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-eps", "craft-idml", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-kra", "craft-ora", "craft-pcraft-bundle", "craft-raw", - "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-zip", "serde", "serde_json", @@ -1637,7 +1637,7 @@ dependencies = [ [[package]] name = "craft-flags" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-atomic", "dirs", @@ -1647,7 +1647,7 @@ dependencies = [ [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1662,7 +1662,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1681,7 +1681,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "cap-primitives", "craft-atomic", @@ -1702,12 +1702,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" [[package]] name = "craft-heif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "heic-rs", "rayon", @@ -1716,7 +1716,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1729,7 +1729,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "chrono", "fixed_decimal", @@ -1757,9 +1757,9 @@ dependencies = [ [[package]] name = "craft-idml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-zip", "thiserror 2.0.21", ] @@ -1767,13 +1767,13 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ - "craft-dds 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-dds 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-heif", - "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "crc32fast", "exr", "flate2", @@ -1822,7 +1822,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1845,7 +1845,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=e7873217287876f76a0455 [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "thiserror 2.0.21", ] @@ -1861,11 +1861,11 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-host", "craft-i18n", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "egui", "serde", "serde_json", @@ -1874,9 +1874,9 @@ dependencies = [ [[package]] name = "craft-kra" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-zip", "thiserror 2.0.21", ] @@ -1884,7 +1884,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-i18n", @@ -1898,7 +1898,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-host", @@ -1916,11 +1916,11 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "brotli-decompressor 6.3.2", "chrono", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "quick-xml 0.41.0", "serde", ] @@ -1940,9 +1940,9 @@ dependencies = [ [[package]] name = "craft-ora" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-zip", "thiserror 2.0.21", ] @@ -1950,7 +1950,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-text", @@ -1964,7 +1964,7 @@ dependencies = [ [[package]] name = "craft-pcraft-bundle" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "blake3", "craft-atomic", @@ -1977,7 +1977,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "flate2", "serde", @@ -1988,7 +1988,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "bytemuck", "flate2", @@ -2003,7 +2003,7 @@ dependencies = [ [[package]] name = "craft-pdn" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2012,7 +2012,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "async-channel", "async-io", @@ -2038,7 +2038,7 @@ dependencies = [ [[package]] name = "craft-plist" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "thiserror 2.0.21", ] @@ -2046,7 +2046,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-ui", @@ -2064,7 +2064,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "encoding_rs", "flate2", @@ -2075,7 +2075,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "dispatch2", "egui", @@ -2086,12 +2086,12 @@ dependencies = [ [[package]] name = "craft-raw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "chrono", "craft-crw", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "jxl-oxide", "miniz_oxide 0.9.1", "rayon", @@ -2104,7 +2104,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-host", @@ -2121,7 +2121,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-atomic", "craft-host", @@ -2135,9 +2135,9 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "flate2", "kurbo 0.13.1", "quick-xml 0.41.0", @@ -2173,7 +2173,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-keymap", @@ -2185,7 +2185,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2208,7 +2208,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "bitflags 2.13.2", "ecolor", @@ -2221,7 +2221,7 @@ dependencies = [ [[package]] name = "craft-theme-editor" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-theme", @@ -2232,7 +2232,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-atomic", "craft-behavior", @@ -2247,7 +2247,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "serde", "thiserror 2.0.21", @@ -2265,7 +2265,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "serde", "thiserror 2.0.21", @@ -2274,7 +2274,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-keymap", @@ -2289,7 +2289,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2303,7 +2303,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-i18n", @@ -2319,7 +2319,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "accesskit", "craft-behavior", @@ -2331,7 +2331,7 @@ dependencies = [ "craft-platform", "craft-quit", "craft-settings", - "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-theme", "craft-ui-macros", "craft-window", @@ -2353,7 +2353,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2364,7 +2364,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-host", @@ -2382,7 +2382,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-host", @@ -2403,13 +2403,13 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-host", "craft-i18n", "craft-platform", - "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-theme", "craft-ui-macros", "craft-ui-panels", @@ -2422,7 +2422,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-host", @@ -2439,7 +2439,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "chrono", "craft-host", @@ -2468,7 +2468,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "winsafe", ] @@ -2476,7 +2476,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-atomic", "craft-behavior", @@ -2506,7 +2506,7 @@ dependencies = [ [[package]] name = "craft-xcf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2515,7 +2515,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "quick-xml 0.41.0", "serde", @@ -2535,7 +2535,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "flate2", "thiserror 2.0.21", @@ -3998,7 +3998,7 @@ dependencies = [ [[package]] name = "hayro" version = "0.7.1" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "bytemuck", "hayro-interpret", @@ -4028,7 +4028,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -4046,7 +4046,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -4070,7 +4070,7 @@ checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "flate2", "hayro-ccitt", @@ -5154,7 +5154,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -6371,10 +6371,10 @@ dependencies = [ "core-graphics2", "craft", "craft-cms", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be)", "craft-update", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "eframe", "egui", "egui_kittest", @@ -6418,7 +6418,7 @@ name = "photocraft-algo" version = "0.23.1" dependencies = [ "craft", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "criterion", "photocraft-color", "photocraft-geom", @@ -6438,7 +6438,7 @@ dependencies = [ "cap-std", "clap", "craft", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-psd", "getrandom 0.3.4", "photocraft-color", @@ -6471,7 +6471,7 @@ dependencies = [ "clap_mangen", "craft", "craft-cms", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-psd", "photocraft-automation", "photocraft-doc", @@ -6535,11 +6535,11 @@ dependencies = [ "craft-affinity", "craft-cms", "craft-file-formats", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-pcraft-format", "craft-print", "craft-psd", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "exr", "flate2", "photocraft-algo", @@ -6575,7 +6575,7 @@ name = "photocraft-format" version = "0.23.1" dependencies = [ "blake3", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-pcraft-bundle", "craft-pcraft-format", "craft-zip", @@ -6635,16 +6635,16 @@ dependencies = [ "craft-crs", "craft-docpath", "craft-file-formats", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-kra", "craft-ora", "craft-pdf", "craft-pdn", "craft-psd", "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be)", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-xcf", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "crc32fast", "flate2", "kurbo 0.13.1", @@ -6743,7 +6743,7 @@ dependencies = [ name = "photocraft-raw" version = "0.23.1" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-raw", "flate2", "image", @@ -6805,7 +6805,7 @@ dependencies = [ "craft", "craft-file-formats", "craft-i18n", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-print", "craft-psd", "eframe", @@ -6854,7 +6854,7 @@ dependencies = [ name = "photocraft-web" version = "0.23.1" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-psd", "eframe", "egui", @@ -11224,14 +11224,14 @@ source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1c [[patch.unused]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" [[patch.unused]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" [[patch.unused]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" diff --git a/Cargo.toml b/Cargo.toml index b0dce05db9..5d271814fe 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,19 +12,19 @@ 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 = "18ffc07519b15f5ef39e752aa0f405261fec8ebb", default-features = false } +craft = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee", default-features = false } # 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 = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] } +craft-plist = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee", 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 = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } photocraft-compose = { path = "crates/compose" } photocraft-gpu = { path = "crates/gpu" } photocraft-paint = { path = "crates/paint" } @@ -43,34 +43,34 @@ 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 = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } # HEIC/HEIF: the shared decoder (replaces crates/heif; craft-libs#784). -craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb", features = ["raster", "write-raster"] } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } +craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee", features = ["raster", "write-raster"] } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } # Keep the shared embedded-image validation API until the framework revision includes it. craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "7b8c1eccea0c695a495ab279c9523e6efcc9b8be", features = ["tree-render", "tree-render-system-fonts"] } -craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } +craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } # Camera-field EXIF reader/writer, shared prerequisite craft-libs#1563. -craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } +craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } # 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 = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } +craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } # 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 = "18ffc07519b15f5ef39e752aa0f405261fec8ebb", features = ["ui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee", features = ["ui"] } thiserror = "2" serde = { version = "1", features = ["derive", "rc"] } serde_json = "1" @@ -335,14 +335,14 @@ 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 = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -hayro = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +hayro = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" } emath = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" } epaint = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" } diff --git a/crates/algo/src/art_history.rs b/crates/algo/src/art_history.rs index 76a3402e7f..01dcbd306d 100644 --- a/crates/algo/src/art_history.rs +++ b/crates/algo/src/art_history.rs @@ -442,6 +442,7 @@ pub struct StampParams<'a> { pub hardness: f32, pub opacity: f32, pub flow: f32, + /// Tolerance as a fraction (Tolerance 50 % is `0.5`). pub tolerance: f32, /// Destination tile edge; `0` processes the whole buffer as one tile. pub tile: i32, @@ -581,26 +582,41 @@ fn dab_intersects(dab: &Dab, tile: (i32, i32, i32, i32)) -> bool { x0 < tile.2 && x1 > tile.0 && y0 < tile.3 && y1 > tile.1 } -/// Mean difference between `src` and `dest` over the dab's covered pixels (working-space peak is -/// 1, so a tolerance of 50% is `0.5`). Per pixel it is the larger of the mean colour change and the -/// alpha change: an opaque pixel's unchanged alpha must not water a colour change down, and the -/// Eraser keeps the colour and lowers only the alpha. Fully transparent source samples are left -/// out; a dab whose samples are all transparent has a mean of `0.0`. `None` if nothing is covered. -fn dab_mean_diff(p: &StampParams<'_>, dab: &Dab) -> Option { - let (x0, y0, x1, y1) = dab_bounds(dab)?; +/// Radius, in pixels, of the neighbourhood around a stroke's start that Tolerance measures. +const START_RADIUS: f32 = 2.5; + +/// Difference, in working-space units, that 100 % Tolerance asks for. The reference application +/// starts strokes on a 20-level change (about 8 %) at Tolerance 10 but not 20, and on red over grey +/// (about 50 %) at 80 but not 90, which a linear threshold of `0.6 × Tolerance` reproduces. +const TOLERANCE_SCALE: f32 = 0.6; + +/// Mean difference between `src` and `dest` around the dab's centre, where its stroke starts +/// (working-space peak is 1). Per pixel it is the larger of the mean colour change and the alpha +/// change: an opaque pixel's unchanged alpha must not water a colour change down, and the Eraser +/// keeps the colour and lowers only the alpha. Fully transparent source samples are left out; a +/// start whose samples are all transparent has a mean of `0.0`. `None` if nothing is there. +fn start_diff(p: &StampParams<'_>, dab: &Dab) -> Option { + if !(dab.x.is_finite() && dab.y.is_finite()) { + return None; + } + let x0 = floor_i32(dab.x - START_RADIUS); + let y0 = floor_i32(dab.y - START_RADIUS); + let x1 = floor_i32(dab.x + START_RADIUS).saturating_add(1); + let y1 = floor_i32(dab.y + START_RADIUS).saturating_add(1); let mut sampled = vec![0.0f32; p.ch]; let mut sum = 0.0f32; let mut count = 0u32; let mut transparent = 0u32; for y in y0..y1 { for x in x0..x1 { - if coverage_at(dab, x, y, p.hardness) <= 0.0 { + // The history state at the same position, not the dab's rotated read. + let (cx, cy) = (x as f32 + 0.5, y as f32 + 0.5); + if (cx - dab.x).hypot(cy - dab.y) > START_RADIUS { continue; } let Some(di) = origin_index(p.dest_origin, x, y, p.dest_w, p.dest_h, p.ch) else { continue }; let Some(dst) = p.dest.get(di..di.saturating_add(p.ch)) else { continue }; - let (sx, sy) = rotated_source(dab, x, y); - if !sample_bilinear(SrcView { data: p.src, w: p.src_w, h: p.src_h, origin: p.src_origin, ch: p.ch, alpha: p.alpha }, sx, sy, &mut sampled) { + if !sample_bilinear(SrcView { data: p.src, w: p.src_w, h: p.src_h, origin: p.src_origin, ch: p.ch, alpha: p.alpha }, cx, cy, &mut sampled) { continue; } let nch = p.ch.min(dst.len()).min(sampled.len()); @@ -636,8 +652,10 @@ fn dab_mean_diff(p: &StampParams<'_>, dab: &Dab) -> Option { /// Stamp posed dabs into `dest`, tile by tile, reading `src` at each dab's rotated positions. /// -/// Sequential dabs overlap: dab *n* sees dab *n − 1*. Returns how many destination pixels were -/// written (tolerance-skipped dabs count as zero). +/// Sequential dabs overlap: dab *n* sees dab *n − 1*. Tolerance is decided where a dab starts +/// (around its centre), so a dab that starts on a changed area also paints the unchanged pixels +/// it reaches. Returns how many destination pixels were written (tolerance-skipped dabs count as +/// zero). pub fn stamp(p: &mut StampParams<'_>) -> Result { dest_pixels(p)?; if p.src_w == 0 || p.src_h == 0 { @@ -653,9 +671,10 @@ pub fn stamp(p: &mut StampParams<'_>) -> Result { let tiles = tile_grid(p.dest_w, p.dest_h, p.dest_origin, p.tile); let mut written = 0u32; let dabs: Vec = p.dabs.to_vec(); + let threshold = p.tolerance * TOLERANCE_SCALE; for dab in &dabs { let Some(bounds) = dab_bounds(dab) else { continue }; - if p.tolerance > 0.0 && dab_mean_diff(p, dab).is_some_and(|m| m < p.tolerance) { + if p.tolerance > 0.0 && start_diff(p, dab).is_some_and(|m| m < threshold) { continue; } let overlapping: Vec<(i32, i32, i32, i32)> = tiles.iter().copied().filter(|t| dab_intersects(dab, *t)).collect(); @@ -676,3 +695,5 @@ pub fn stamp(p: &mut StampParams<'_>) -> Result { #[cfg(test)] mod tests; +#[cfg(test)] +mod tolerance_tests; diff --git a/crates/algo/src/art_history/tests.rs b/crates/algo/src/art_history/tests.rs index 61692cda74..a3567f98e9 100644 --- a/crates/algo/src/art_history/tests.rs +++ b/crates/algo/src/art_history/tests.rs @@ -23,7 +23,8 @@ fn tolerance_ignores_fully_transparent_samples() { } }); let dab = Dab { x: 1.0, y: 0.5, theta: 0.0, radius: 2.0, pressure: 1.0 }; - for tolerance in [0.6, 0.3] { + // Mean difference 0.4: under the 0.6 x Tolerance threshold at 1.0, over it at 0.3. + for tolerance in [1.0, 0.3] { let mut dest = before.clone(); let written = stamp(&mut StampParams { dest: &mut dest, @@ -46,7 +47,7 @@ fn tolerance_ignores_fully_transparent_samples() { alpha: Some(ch - 1), }) .unwrap(); - if tolerance == 0.6 { + if tolerance == 1.0 { assert_eq!(written, 0, "channels={ch}, hidden={hidden}"); assert_eq!(dest, before); } else { @@ -377,12 +378,13 @@ fn tolerance_zero_writes_where_history_differs() { #[test] fn tolerance_ignores_unchanged_alpha() { - // Colour moved by 0.3 and alpha did not: the 0.25 threshold must not see a 0.225 average. + // Colour moved by 0.3 and alpha did not: the 0.27 threshold (Tolerance 45 %) must not see a + // 0.225 average. let (w, h, ch) = (48usize, 48usize, 4); let src = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.6 }); let dest0 = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.3 }); let dab = Dab { x: 24.0, y: 24.0, theta: 0.0, radius: 8.0, pressure: 1.0 }; - for (tolerance, paints) in [(0.25, true), (0.35, false)] { + for (tolerance, paints) in [(0.45, true), (0.55, false)] { let mut dest = dest0.clone(); let mut p = StampParams { dest: &mut dest, diff --git a/crates/algo/src/art_history/tolerance_tests.rs b/crates/algo/src/art_history/tolerance_tests.rs new file mode 100644 index 0000000000..f68740c783 --- /dev/null +++ b/crates/algo/src/art_history/tolerance_tests.rs @@ -0,0 +1,159 @@ +//! Tolerance decides where a stroke may start, with the reference application's threshold (#12633). + +use super::*; + +const W: usize = 80; +const H: usize = 40; +const CH: usize = 4; + +fn level(v: u8) -> f32 { + f32::from(v) / 255.0 +} + +/// Source: grey on the left half, green on the right half (the measured Setup state). +fn setup_source() -> Vec { + image(|x| if x < W / 2 { [128, 128, 128] } else { [40, 160, 60] }) +} + +/// Current layer: red on the left half (far from grey), 20 levels off the green on the right. +fn current_layer() -> Vec { + image(|x| if x < W / 2 { [255, 0, 0] } else { [60, 180, 80] }) +} + +fn image(rgb: impl Fn(usize) -> [u8; 3]) -> Vec { + let mut v = Vec::with_capacity(W * H * CH); + for _ in 0..H { + for x in 0..W { + let [r, g, b] = rgb(x); + v.extend_from_slice(&[level(r), level(g), level(b), 1.0]); + } + } + v +} + +fn dab(x: f32, radius: f32) -> Dab { + Dab { x, y: H as f32 / 2.0, theta: 0.0, radius, pressure: 1.0 } +} + +/// Stamps `dabs` at `tolerance` (a fraction, Tolerance 50 % = 0.5) and returns the new layer. +fn paint(dest: &[f32], dabs: &[Dab], tolerance: f32) -> Vec { + let src = setup_source(); + let mut out = dest.to_vec(); + let mut p = StampParams { + dest: &mut out, + dest_w: W, + dest_h: H, + dest_origin: (0, 0), + src: &src, + src_w: W, + src_h: H, + src_origin: (0, 0), + ch: CH, + dabs, + hardness: 1.0, + opacity: 1.0, + flow: 1.0, + tolerance, + tile: 0, + selection: None, + lock_transparent: false, + alpha: Some(3), + }; + stamp(&mut p).unwrap(); + out +} + +/// Pixels changed in columns `x0..x1`. +fn changed(before: &[f32], after: &[f32], x0: usize, x1: usize) -> usize { + let mut n = 0; + for y in 0..H { + for x in x0..x1 { + let i = (y * W + x) * CH; + if (0..CH).any(|c| (before[i + c] - after[i + c]).abs() > 1.0e-4) { + n += 1; + } + } + } + n +} + +const LEFT: f32 = 12.0; +const RIGHT: f32 = 68.0; + +#[test] +fn a_small_difference_starts_strokes_at_10_but_not_at_20() { + let before = current_layer(); + let dabs = [dab(RIGHT, 6.0)]; + assert!(changed(&before, &paint(&before, &dabs, 0.10), 40, 80) > 0, "20 levels off paints at Tolerance 10"); + assert_eq!(changed(&before, &paint(&before, &dabs, 0.20), 0, 80), 0, "20 levels off paints nothing at Tolerance 20"); +} + +#[test] +fn red_over_grey_starts_strokes_up_to_80_and_nothing_from_90() { + let before = current_layer(); + let dabs = [dab(LEFT, 6.0)]; + for tolerance in [0.60, 0.80] { + assert!(changed(&before, &paint(&before, &dabs, tolerance), 0, 40) > 0, "red over grey paints at {tolerance}"); + } + let both = [dab(LEFT, 6.0), dab(RIGHT, 6.0)]; + for tolerance in [0.90, 0.95, 0.99, 1.0] { + assert_eq!(changed(&before, &paint(&before, &both, tolerance), 0, 80), 0, "nothing paints at {tolerance}"); + } +} + +#[test] +fn tolerance_zero_paints_everywhere() { + let before = current_layer(); + let after = paint(&before, &[dab(LEFT, 6.0), dab(RIGHT, 6.0)], 0.0); + assert!(changed(&before, &after, 0, 40) > 0); + assert!(changed(&before, &after, 40, 80) > 0); + // Even where the layer equals the source, the dab is stamped (nothing visible changes). + let src = setup_source(); + let mut out = src.clone(); + let d = [dab(LEFT, 6.0)]; + let mut p = StampParams { + dest: &mut out, + dest_w: W, + dest_h: H, + dest_origin: (0, 0), + src: &src, + src_w: W, + src_h: H, + src_origin: (0, 0), + ch: CH, + dabs: &d, + hardness: 1.0, + opacity: 1.0, + flow: 1.0, + tolerance: 0.0, + tile: 0, + selection: None, + lock_transparent: false, + alpha: Some(3), + }; + assert!(stamp(&mut p).unwrap() > 0); +} + +/// Several dabs across both halves at Tolerance 20: only those starting on the red half paint, and +/// the right half changes only where a red-half dab reaches into it. +#[test] +fn at_20_strokes_start_only_on_the_large_difference() { + let before = current_layer(); + let dabs: Vec = [8.0, 20.0, 36.0, 52.0, 64.0, 76.0].iter().map(|&x| dab(x, 6.0)).collect(); + let after = paint(&before, &dabs, 0.20); + assert!(changed(&before, &after, 0, 40) > 0); + assert_eq!(changed(&before, &after, 44, 80), 0, "no dab starts on the 20-level half"); + assert!(changed(&before, &after, 40, 44) > 0, "the dab at x 36 runs into the right half"); +} + +/// The rule is where a stroke starts, not the mean under the whole dab: a big dab that starts just +/// inside the red half paints over the right half too, and one that starts just inside the right +/// half paints nothing although a large part of it covers red. +#[test] +fn the_start_decides_not_the_whole_dab() { + let before = current_layer(); + let started_on_red = paint(&before, &[dab(37.0, 14.0)], 0.80); + assert!(changed(&before, &started_on_red, 40, 80) > 0, "a stroke started on red runs into the green half"); + let started_on_green = paint(&before, &[dab(43.0, 14.0)], 0.20); + assert_eq!(changed(&before, &started_on_green, 0, 80), 0, "a stroke started on the 20-level half stays unpainted"); +} diff --git a/crates/compose/src/effects/bevel.rs b/crates/compose/src/effects/bevel.rs index 266c3f7613..dab76a040a 100644 --- a/crates/compose/src/effects/bevel.rs +++ b/crates/compose/src/effects/bevel.rs @@ -193,11 +193,15 @@ pub(super) fn bevel_maps(shape: &Map, b: &Bevel, light: &GlobalLight, tex: &Text let on_bevel = |x: i64, y: i64| { hmap.get(x, y) > BEVEL_H_EPS || (reach_past && [(1, 0), (-1, 0), (0, 1), (0, -1)].iter().any(|(dx, dy)| hmap.get(x + dx, y + dy) > BEVEL_H_EPS)) }; - // The gloss contour remaps the shading `n · light` before it splits into highlight (above - // what it maps a flat face's `sin(altitude)` to) and shadow. Applied to the highlight and shadow amounts - // instead, a contour that starts high (Rolling Slope - Descending) lit every pixel the light - // missed, so a bevelled glyph's flat face took the full highlight (#7360) where Photoshop - // leaves it at the layer's colour. The Linear contour changes nothing either way. + // The gloss contour remaps the shading `n · light` before it splits into highlight (above a + // flat face's own, unmapped `sin(altitude)`) and shadow (below it). Applied to the highlight + // and shadow amounts instead, a contour that starts high (Rolling Slope - Descending) lit + // every pixel the light missed (#7360). With the mapped `lut(sin(altitude))` as the neutral, + // a high light washed out whole faces: at altitude 69 that contour maps the flat 0.93 to + // 0.16, so every slope above 0.16 took the full highlight where Photoshop only glints where + // the shading nears 0. A contour that moves the flat shading lights or darkens the flat face + // too, as Photoshop does (oracles bevel-inner-gloss-ramp-peak / -double-ring-aa: faces at + // the full highlight and a 0.69 shadow). The Linear contour changes nothing either way. let gloss = contour_lut(&b.gloss_contour); let shade_into = |depth: f32, region_kind: u8| -> (Map, Map) { let (mut hi, mut sh) = (Map::new(shape.w, shape.h, 0.0), Map::new(shape.w, shape.h, 0.0)); @@ -219,7 +223,7 @@ pub(super) fn bevel_maps(shape: &Map, b: &Bevel, light: &GlobalLight, tex: &Text let len = (n[0] * n[0] + n[1] * n[1] + 1.0).sqrt(); let shade = (n[0] * light_v[0] + n[1] * light_v[1] + n[2] * light_v[2]) / len; let region = if region_kind == 0 { shape.v[i] } else { f32::from(shape.v[i] < 1.0 - INSIDE_EPS && on_bevel(x, y)) }; - let k = gloss.as_ref().map_or(shade - se, |l| lut_at(l, shade) - lut_at(l, se)); + let k = gloss.as_ref().map_or(shade, |l| lut_at(l, shade)) - se; if k > 0.0 { hi_row[x as usize] = (k / (1.0 - se).max(1e-3)).clamp(0.0, 1.0) * region; } else { diff --git a/crates/compose/src/effects/tests.rs b/crates/compose/src/effects/tests.rs index d2552a9024..e546ece5bf 100644 --- a/crates/compose/src/effects/tests.rs +++ b/crates/compose/src/effects/tests.rs @@ -199,6 +199,64 @@ fn smooth_inner_bevel_lights_the_top_edge_inside_only() { assert!(at(&maps[0], 20, 15) < 0.05); } +/// A gloss contour from Photoshop's 0–255 contour editor points. +fn gloss_of(points: &[(f32, f32)]) -> Contour { + Contour::Custom { + name: "gloss".into(), + points: points.iter().map(|&(i, o)| photocraft_doc::adjust::CurvePoint { input: i / 255.0, output: o / 255.0 }).collect(), + corners: vec![], + } +} + +/// Smooth inner bevel highlight and shadow maps of `shape` with `gloss`, light from `angle` at +/// `altitude`. +fn gloss_maps(shape: &Map, gloss: Contour, angle: f32, altitude: f32, size: f32, depth: f32) -> Vec { + let mut b = bevel_of(BevelStyle::InnerBevel, BevelTechnique::Smooth); + (b.angle, b.altitude, b.size, b.depth, b.gloss_contour) = (angle, altitude, size, depth, gloss); + bevel_maps(shape, &b, &GlobalLight::default(), &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)).0 +} + +/// The gloss contour maps the shading, and the flat face's own unmapped shading `sin(altitude)` +/// stays the neutral. Photoshop's own composite of a purchased style pack's type (Rolling Slope - +/// Descending at altitude 69, 16 px smooth inner bevel at 358 %): the face stays at its colour, with white +/// glints only where the shading is within ~0.015 of zero (measured per pixel against this +/// bevel's shading). With the mapped `lut(sin 69°)` = 0.16 as the neutral, every slope pixel +/// whose mapped shading came out above it took the full highlight, and the type rendered white. +#[test] +fn high_altitude_descending_gloss_only_glints_where_the_light_misses() { + let n = 80; + let mut shape = Map::new(n, n, 0.0); + for y in 10..70 { + for x in 20..60 { + shape.v[y * n + x] = 1.0; + } + } + let rolling = gloss_of(&[(2.0, 255.0), (53.0, 100.0), (97.0, 107.0), (179.0, 153.0), (252.0, 0.0)]); + // Light from the left: the bar's right slope faces away from it. + let maps = gloss_maps(&shape, rolling, 180.0, 69.0, 16.0, 3.58); + let row: Vec = (20..60).map(|x| maps[0].v[40 * n + x]).collect(); + let lit = row.iter().filter(|v| **v > 0.05).count(); + assert!(lit <= 8, "only a few glint pixels, not the whole face: {row:?}"); + assert!(row[..20].iter().all(|v| *v < 0.05), "no highlight on the slope facing the light: {row:?}"); + assert!(row[20..].iter().any(|v| *v > 0.9), "a full glint where the slope faces away: {row:?}"); +} + +/// Photoshop 27.11 oracles (corpus `bevel-inner-gloss-ramp-peak` / `-double-ring-aa`: 12 px +/// smooth inner bevel at altitude 30, Screen white and Multiply black at 75 % over (90, 120, +/// 170)): a contour that maps the flat shading 0.5 above or below 0.5 lights or darkens the flat +/// face too. Ramp-peak (0,0)(128,255)(255,0) paints the face (214, 221, 234), the full +/// highlight; double-ring (…, (128, 40), …) paints it (44, 58, 83), a 0.69 shadow. +#[test] +fn a_gloss_contour_lights_or_darkens_the_flat_face_around_the_unmapped_neutral() { + let shape = square(40, 5, 35); + let face = |m: &Map| m.v[20 * 40 + 20]; + let peak = gloss_maps(&shape, gloss_of(&[(0.0, 0.0), (128.0, 255.0), (255.0, 0.0)]), 120.0, 30.0, 5.0, 1.0); + assert!(face(&peak[0]) > 0.99 && face(&peak[1]) == 0.0, "ramp-peak: full highlight, {} / {}", face(&peak[0]), face(&peak[1])); + let ring = gloss_maps(&shape, gloss_of(&[(0.0, 0.0), (64.0, 255.0), (128.0, 40.0), (192.0, 255.0), (255.0, 0.0)]), 120.0, 30.0, 5.0, 1.0); + // (0.5 − 40/255) / 0.5: 90 × (1 − 0.75 × 0.686) = 43.7. + assert!(face(&ring[0]) == 0.0 && (face(&ring[1]) - 0.686).abs() < 0.02, "double-ring: shadow {}", face(&ring[1])); +} + /// Photoshop 27.11, measured across a straight edge (size 10, depth 100 %, light from the top /// at 30°): a chisel facet has the slope `depth × size / (2 (size + 1))`, flat right up to the /// edge pixel for Inner Hard; Inner Soft's edge pixel is half as steep again; Outer Hard diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index b7375afa8e..a338e7317f 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -1988,10 +1988,12 @@ fn satin_and_bevel_stay_inside_shape() { /// #7360: a gloss contour that starts high (Rolling Slope - Descending, as the reporter's PSD /// uses) left a bevelled shape's flat face at the full Overlay highlight, (255, 40, 42) on a -/// (151, 22, 23) fill, where Photoshop leaves the face at the fill colour. The contour maps the -/// shading, so the flat face stays neutral and only the slopes are shaded. +/// (151, 22, 23) fill. The contour maps the shading, with the unmapped flat shading +/// `sin(altitude)` as the neutral, so the face only takes what the contour moves 0.5 by: +/// Rolling Slope maps it to 0.55, a 0.09 highlight, (161, 24, 25). Photoshop's own composite of +/// the reporter's repro has the glyph's face at 151–161 in red, not the exact fill. #[test] -fn a_gloss_contour_leaves_the_flat_face_of_a_bevel_unlit() { +fn a_gloss_contour_leaves_the_flat_face_of_a_bevel_near_its_fill() { let fill = [151.0 / 255.0, 22.0 / 255.0, 23.0 / 255.0, 1.0]; let rolling = photocraft_doc::Contour::Custom { name: "Rolling Slope - Descending".into(), @@ -2029,14 +2031,71 @@ fn a_gloss_contour_leaves_the_flat_face_of_a_bevel_unlit() { }; let d = render(rolling); for (x, y) in [(20, 20), (16, 22), (24, 16)] { - let p = px(&d, x, y); - assert!(close4(p, fill), "flat face ({x},{y}) keeps the fill: {:?}", p.map(|v| (v * 255.0).round())); + let p = px(&d, x, y).map(|v| (v * 255.0).round()); + assert!((158.0..=164.0).contains(&p[0]) && (22.0..=26.0).contains(&p[1]), "flat face ({x},{y}) near the fill: {p:?}"); } let linear = render(photocraft_doc::Contour::Linear); assert!(close4(px(&linear, 20, 20), fill), "Linear leaves the flat face too"); assert!(!close4(px(&d, 20, 11), fill), "the slopes are still shaded"); } +/// A deep bevel under a high light with a descending gloss contour (altitude 69, 358 %, Rolling +/// Slope - Descending, Screen white 78 %) keeps a red shape red at every depth: the slopes are +/// shaded around the unmapped `sin(altitude)`, so only the steepest pixels facing away glint. +/// Mapped through the contour, that neutral fell to 0.16 and the whole shape rendered white. +#[test] +fn a_high_light_descending_gloss_keeps_the_face_its_colour_at_every_depth() { + let red = [0.6, 0.0, 0.0, 1.0]; + let rolling = photocraft_doc::Contour::Custom { + name: "Rolling Slope - Descending".into(), + points: [(0.0078, 1.0), (0.2078, 0.3922), (0.3804, 0.4196), (0.7020, 0.6), (0.9882, 0.0)] + .iter() + .map(|&(input, output)| CurvePoint { input, output }) + .collect(), + corners: vec![], + }; + let mut first: Option> = None; + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + let mut d = Document::with_background("t", Size::new(80, 80), ColorMode::Rgb, depth, Color::BLACK); + let mut l = Layer::raster("bar", d.pixel_format()); + l.surface_mut().unwrap().fill_rect(Rect::new(20, 10, 60, 70), &red); + l.effects.items = vec![Effect::BevelEmboss(photocraft_doc::Bevel { + enabled: true, + style: photocraft_doc::BevelStyle::InnerBevel, + technique: photocraft_doc::BevelTechnique::Smooth, + depth: 3.58, + up: true, + size: 16.0, + soften: 0.0, + angle: 180.0, + altitude: 69.0, + use_global_light: false, + gloss_contour: rolling.clone(), + gloss_anti_alias: false, + highlight: FxCommon::new(photocraft_color::BlendMode::Screen, 0.78), + highlight_color: Color::WHITE, + shadow: FxCommon::new(photocraft_color::BlendMode::Multiply, 0.09), + shadow_color: Color::BLACK, + contour: None, + texture: None, + })]; + d.layers.push(l); + // The slope facing the light, the middle, and a slope pixel facing away short of its glint. + let got: Vec<[f32; 4]> = [(23, 40), (30, 40), (40, 40), (50, 40)].iter().map(|&(x, y)| px(&d, x, y)).collect(); + for (p, at) in got.iter().zip([23, 30, 40, 50]) { + assert!(p[0] > 0.5 && p[1] < 0.05 && p[2] < 0.05, "{depth:?} x={at}: still red, not washed white: {p:?}"); + } + match &first { + None => first = Some(got), + Some(f) => { + for (a, b) in f.iter().zip(&got) { + assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() <= 3.0 / 255.0), "{depth:?} agrees with 8-bit: {a:?} vs {b:?}"); + } + } + } + } +} + #[test] fn clipped_layer_effects_are_clipped_to_base() { let mut d = doc_white(40, 40); diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 65220283e8..b28eeb44cd 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -16,7 +16,7 @@ photocraft-geom = { workspace = true } photocraft-color = { workspace = true } craft-cms = { workspace = true } # PCTIP codec from craft-libs#1564; isolated pin until the shared revision is adopted workspace-wide. -craft-pcraft-tip = { package = "craft-pcraft-format", git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } +craft-pcraft-tip = { package = "craft-pcraft-format", git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } photocraft-raster = { workspace = true } photocraft-doc = { workspace = true } photocraft-ops = { workspace = true } diff --git a/crates/engine/examples/abr_memory.rs b/crates/engine/examples/abr_memory.rs index 9cec8ec1de..71c1460664 100644 --- a/crates/engine/examples/abr_memory.rs +++ b/crates/engine/examples/abr_memory.rs @@ -52,7 +52,7 @@ fn library_tip_bytes(s: &Session) -> (usize, u64, u64) { previews += g.data.len() as u64 * 2; } }; - for p in &s.tools.presets { + for p in s.tools.presets.iter() { let b = &p.brush; for t in [&b.tip, &b.dual_brush.tip] { match t { diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 478fc84eec..c66984f4c4 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -27,27 +27,6 @@ pub struct CommandSpec { pub journal: bool, } -/// Image › Adjustments › Desaturate: Hue/Saturation with saturation at -100. -pub(crate) fn desaturate_adjustment() -> Adjustment { - Adjustment::HueSaturation { hue: 0.0, saturation: -100.0, lightness: 0.0, colorize: false, ranges: photocraft_doc::adjust::HueRange::defaults() } -} - -/// Image › Image Rotation by a right angle or a flip (pixels, vectors, guides, … all move). -fn turn(s: &mut Session, label: &str, t: crate::canvas_geom::Turn) -> Result { - if let Some(d) = s.active() { - let a = t.affine(f64::from(d.doc.size.width), f64::from(d.doc.size.height)); - // Sampler points are pixel indices, not pixel edges: map the pixel's centre, so the point - // lands on the same pixel `Turn::pixel_map` moves the pixels to (`w - 1 - x`). - let half = photocraft_geom::Affine::translate(0.5, 0.5); - s.set_canvas_map(a, half.then(&a).then(&photocraft_geom::Affine::translate(-0.5, -0.5))); - } - s.edit(label, |doc, _| { - crate::canvas_geom::keeping_count_points(doc, |doc| crate::canvas_geom::turn_canvas(doc, t)); - Ok(()) - })?; - Ok(Value::Null) -} - macro_rules! cmd { ($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => { CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true } @@ -70,6 +49,8 @@ pub mod brush_preset_cmds; pub mod channel_cmds; pub mod color_cmds; pub mod color_to_alpha_cmds; +#[cfg(test)] +mod command_order_tests; pub mod comps_cmds; pub mod contour_lib_cmds; #[cfg(test)] @@ -139,6 +120,8 @@ pub(super) mod path_edit_cmds; pub mod pattern_cmds; pub mod pattern_fill_cmds; pub mod perspective_crop_cmds; +#[cfg(test)] +mod perspective_crop_refuse_tests; pub mod photo_cmds; pub mod pick_cmds; pub mod plugin_cmds; @@ -163,6 +146,7 @@ pub mod stamp_cmds; pub mod style_asl_cmds; pub mod swatch_cmds; pub mod symmetry_cmds; +mod table; pub(super) mod timeline_cmds; pub mod transform_cmds; pub(super) mod trap_cmds; @@ -270,1209 +254,148 @@ fn registry() -> &'static Registry { // ---------- the table ---------- -/// Every command this module owns, in menu order: the table the registry is built from once. -#[allow(clippy::too_many_lines)] -/// Register the core file, edit, layer and document commands. -fn build() -> Vec { - let mut v = vec![ - // File - cmd!( - "file.new", - "New…", - ["File"], - Some("Cmd+N"), - r##"{"width":1..300000=1920,"height":1..300000=1080 (pixel counts are rounded),"mode":"bitmap|rgb|gray|grayscale|cmyk|lab"="rgb","depth":8|16|32=8 (bitmap: 1, its only depth),"background":"white|black|backgroundColor|transparent|#rrggbb"="white" (bitmap: not transparent),"backgroundColor":[r,g,b]? (0..1; defaults to toolbox colour),"resolution":1..30000=72 (ppi),"name":str,"artboard":bool=false (one artboard over the canvas, its background the chosen one, holding an empty Layer 1; no Background layer),"profile":"working"|built-in id|path to an .icc file="working" (the colour profile it is tagged with; it must suit the mode)}"##, - always, - |s, p| { - use crate::document_preset_cmds::{MAX_DIMENSION, MAX_RESOLUTION, background_color, color_mode, sample_type}; - crate::document_preset_cmds::validate_new_params(s, p)?; - // A size given as a float (`512.0`, as JSON from a UI field) is still that size (#254). - let px = |k: &str, d: u32| match p.get(k) { - Some(v) => v - .as_u64() - .map(|n| n.clamp(1, MAX_DIMENSION as u64) as u32) - .or_else(|| v.as_f64().filter(|f| f.is_finite()).map(|f| f.round().clamp(1.0, MAX_DIMENSION as f64) as u32)) - .unwrap_or(d), - None => d, - }; - let (w, h) = (px("width", 1920), px("height", 1080)); - let mode = color_mode(p.get("mode").and_then(Value::as_str).unwrap_or("rgb")).unwrap_or(ColorMode::Rgb); - // A 1-bit Bitmap document is stored as 8-bit gray, like a converted Bitmap image. - let depth = sample_type(p.get("depth").and_then(Value::as_u64).unwrap_or(8)).filter(|_| mode != ColorMode::Bitmap).unwrap_or(SampleType::U8); - let name = p.get("name").and_then(Value::as_str).unwrap_or("Untitled").to_string(); - let res = p.get("resolution").and_then(Value::as_f64).unwrap_or(72.0).clamp(1.0, MAX_RESOLUTION) as f32; - // The background colour; `None` for Transparent. - let background = match p.get("background").and_then(Value::as_str).unwrap_or("white") { - "backgroundColor" => { - let bgc = background_color(p, s.tools.background, "file.new")?; - Some(Color::rgba(bgc[0], bgc[1], bgc[2], 1.0)) - } - "transparent" => None, - "black" => Some(Color::BLACK), - other => { - let c = parse_hex(other).unwrap_or([1.0; 4]); - Some(Color::rgba(c[0], c[1], c[2], c[3])) - } - }; - let mut doc = if p.get("artboard").and_then(Value::as_bool).unwrap_or(false) { - crate::artboard_cmds::new_artboard_document(name, Size::new(w, h), mode, depth, background) - } else if let Some(c) = background { - Document::with_background(name, Size::new(w, h), mode, depth, c) - } else { - let mut d = Document::new(name, Size::new(w, h), mode, depth); - d.layers.push(Layer::raster("Layer 1", d.pixel_format())); - d - }; - doc.resolution_dpi = res; - // Photoshop's New Document › Color Profile: tag the document with another profile - // than the working space (#321). Checked before the document opens. - if let Some(spec) = p.get("profile").and_then(Value::as_str).filter(|spec| !matches!(*spec, "working" | "none")) { - let prof = s.color.resolve(spec, Some(&doc), None)?; - if prof.color_space != crate::color_cmds::mode_space(doc.mode) { - return Err(EngineError::BadParams { - cmd: "file.new".into(), - msg: format!("profile `{}` is {:?}; the document is {:?}", prof.description, prof.color_space, doc.mode), - }); - } - doc.icc_profile = Some(prof.to_bytes()); - } - let i = s.add_document(doc, None); - // A new document's first History state is "New"; opened files keep "Open" (#14029). - if let Some(st) = s.active_mut() { - st.history.set_current_label("New"); - } - Ok(json!({ "document": i })) - } - ), - cmd!( - "file.close", - "Close", - ["File"], - Some("Cmd+W"), - r##"{"document":index?,"save":"discard|ask"|false="discard"} (false means discard; ask refuses to close a changed document in headless playback)"##, - has_doc, - |s, p| { - let i = p.get("document").and_then(Value::as_u64).map(|v| v as usize).or(s.active_index()).ok_or(EngineError::NoDocument)?; - match p.get("save").filter(|v| !v.is_null()) { - Some(v) if v == "ask" && s.documents().get(i).ok_or(EngineError::NoDocument)?.is_dirty() => { - return Err(bad("file.close", "the document has unsaved changes; save it or explicitly discard them")); - } - Some(v) if v == "ask" => {} - // `false` (don't save) is the older spelling of discard. - Some(Value::Bool(false)) => {} - Some(v) if v != "discard" => return Err(bad("file.close", "`save` must be ask, discard or false")), - _ => {} - } - s.close(i).ok_or(EngineError::NoDocument)?; - Ok(Value::Null) - } - ), - // Edit - cmd!("edit.undo", "Undo", ["Edit"], Some("Cmd+Z"), "{}", can_undo, |s, _| Ok(json!(s.undo()))), - cmd!("edit.redo", "Redo", ["Edit"], Some("Cmd+Shift+Z"), "{}", can_redo, |s, _| Ok(json!(s.redo()))), - cmd!( - "edit.fill", - "Fill…", - ["Edit"], - Some("Shift+F5"), - r##"{"contents":"foreground|background|color|contentAware|pattern|history|black|gray|white"="color","color":"#rrggbb|[r,g,b,a]"=foreground (contents=color),"pattern":id|name (contents=pattern),"scale":%=100,"angle":deg,"state":row?,"snapshot":id? (contents=history: a History panel row as history.setSource, redo rows last, or a snapshot; default the History Brush source),"colorAdaptation":bool=true,"scaleAdaptation":bool=false,"mirror":bool=false,"rotationAdaptation":bool=false (contents=contentAware: enable quarter-turn source candidates within the sampling budget),"mode":"normal|multiply|…"="normal","opacity":0..100=100,"preserveTransparency":bool=false,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}?}"##, - has_pixel_or_channel, - crate::fill_cmds::fill - ), - cmd!( - "edit.clear", - "Clear", - ["Edit"], - None, - r##"{"target":"mask"|{"color":i}|{"colors":[i,…]}?=Channels panel target,"layer":id|name?=active} (a targeted mask, channel or Quick Mask is cleared alone)"##, - has_pixel_or_channel, - |s, p| { - let bg = s.tools.background; - // A targeted alpha channel or Quick Mask is filled instead (#2734). - let channel = if crate::channel_cmds::is_channel_target(p) { - Some(p.clone()) - } else if p.get("target").is_none() { - crate::channel_cmds::targeted_channel(s) - } else { - None - }; - if let Some(t) = channel { - s.edit("Clear", |doc, _| crate::channel_cmds::clear_channel(doc, &t, bg))?; - return Ok(Value::Null); - } - let id = layer_param(s, p)?; - if is_mask_target(p) { - s.edit("Clear Mask", |doc, _| crate::edit_cmds::clear_mask(doc, id, bg, p))?; - return Ok(Value::Null); - } - // A targeted colour channel clears that channel only (#2720). - if let Some(colors) = crate::color_channels::target(s, p)? { - s.edit("Clear", |doc, _| { - for k in colors.indices() { - crate::channel_cmds::clear_color_channel(doc, id, k, bg)?; - } - Ok(()) - })?; - return Ok(Value::Null); - } - s.edit("Clear", |doc, _| { - let sel = doc.selection.clone(); - let area = sel.as_ref().map(|m| m.content_bounds()).unwrap_or(doc.bounds()); - crate::edit_cmds::clear_area(doc, id, area, sel.as_ref(), bg) - })?; - Ok(Value::Null) - } - ), - // Select - cmd!("select.all", "All", ["Select"], Some("Cmd+A"), "{}", has_doc, |s, _| { - // With the active layer on an artboard (the board itself or a layer inside it), Select - // All selects that board, as Photoshop does; otherwise the whole canvas (#10258). - let active = s.active().and_then(|d| d.active_layer); - s.edit("Select All", |doc, _| { - let board = active.and_then(|id| doc.artboard_of(id)).and_then(|id| doc.layer(id)).and_then(|l| l.artboard()).map(|a| a.rect); - // A board the canvas no longer reaches (cropped away) selects the canvas, never an - // empty selection that would block painting. - let area = board.map(|r| r.intersect(&doc.bounds())).filter(|r| !r.is_empty()).unwrap_or_else(|| doc.bounds()); - let mut m = Surface::new(photocraft_color::PixelFormat::GRAY8); - m.fill_rect(area, &[1.0]); - doc.selection = Some(m); - Ok(()) - })?; - Ok(Value::Null) - }), - cmd!("select.deselect", "Deselect", ["Select"], Some("Cmd+D"), "{}", has_selection, |s, _| { - // Nothing selected: nothing to do and no history step, as in Photoshop (#6744). - if s.active().is_none_or(|d| d.doc.selection.is_none()) { - return Ok(Value::Null); - } - s.edit("Deselect", |doc, _| { - doc.selection = None; - Ok(()) - })?; - Ok(Value::Null) - }), - cmd!("select.inverse", "Inverse", ["Select"], Some("Cmd+Shift+I"), "{}", has_selection, |s, _| { - s.edit("Inverse", |doc, _| { - let old = doc.selection.take().unwrap_or_else(|| Surface::new(photocraft_color::PixelFormat::GRAY8)); - doc.selection = Some(photocraft_algo::selection::inverse_surface(&old, doc.bounds())); - Ok(()) - })?; - Ok(Value::Null) - }), - cmd!( - "select.rect", - "Rectangular Selection", - [], - None, - r##"{"x":i32,"y":i32,"width":u32,"height":u32,"mode":"replace|add|subtract|intersect"="replace","ellipse":bool=false,"line":"row|column"?,"antiAlias":bool=true,"feather":px=0}"##, - has_doc, - |s, p| { - let get = |k: &str| int_i32("select.rect", p, k).and_then(|v| v.ok_or_else(|| bad("select.rect", format!("missing `{k}`")))); - let r = Rect::from_xywh(get("x")?, get("y")?, get("width")?.max(0) as u32, get("height")?.max(0) as u32); - let mode = p.get("mode").and_then(Value::as_str).unwrap_or("replace").to_string(); - let ellipse = p.get("ellipse").and_then(Value::as_bool).unwrap_or(false); - // The History step is named after the tool: the Single Row / Single Column - // Marquee send `line` (Photoshop). - let step = match p.get("line").and_then(Value::as_str) { - Some("row") => "Single Row Marquee", - Some("column") => "Single Column Marquee", - Some(other) => return Err(bad("select.rect", format!("unknown `line` {other:?} (row|column)"))), - None if ellipse => "Elliptical Marquee", - None => "Rectangular Marquee", - }; - // Options bar: anti-aliased ellipse edges (4x4 supersampled) and Feather (applied to the new shape only). - let aa = p.get("antiAlias").and_then(Value::as_bool).unwrap_or(true); - let feather = p.get("feather").and_then(Value::as_f64).unwrap_or(0.0).clamp(0.0, 1000.0) as f32; - s.edit(step, |doc, _| { - let area = doc.bounds(); - // A marquee dragged past the canvas stops at its edge (Photoshop); the ellipse - // keeps the dragged shape and is only cut there. - use photocraft_algo::selection as sel; - let shape = if ellipse { - sel::ellipse_surface(r, area, aa) - } else { - let mut s = Surface::new(photocraft_color::PixelFormat::GRAY8); - s.fill_rect(r.intersect(&area), &[1.0]); - s - }; - if feather > 0.0 { - let window = selection_cmds::feather_window(r, area, feather); - let m = sel::feather(&sel::mask_from_surface(Some(&shape), window), window.width() as usize, window.height() as usize, feather); - doc.selection = selection_cmds::combine_band(doc.selection.as_ref(), &m, window, sel::SelectionMode::parse(&mode)); - return Ok(()); - } - let old = doc.selection.take(); - let combined = match (mode.as_str(), old) { - ("add", Some(o)) => sel::combine_sparse(&o, &shape, area, |a, b| a.max(b)), - ("subtract", Some(o)) => sel::combine_sparse(&o, &shape, area, |a, b| a * (1.0 - b)), - ("intersect", Some(o)) => sel::combine_surfaces(&o, &shape, area, |a, b| a.min(b)), - // With no existing selection, neither operation can select new pixels. - ("subtract" | "intersect", None) => Surface::new(photocraft_color::PixelFormat::GRAY8), - _ => shape, - }; - // Sparse Add/Subtract keeps untouched pixels outside the canvas. Only pixels - // inside the document count when deciding whether a selection remains. - let has_on_canvas_pixels = (combined.default_bytes().first().copied().unwrap_or(0) != 0 && { - let canvas_tiles = u64::from(area.width().div_ceil(TILE_SIZE as u32)) * u64::from(area.height().div_ceil(TILE_SIZE as u32)); - let stored = combined.tiles().filter(|(coord, _)| !coord.rect().intersect(&area).is_empty()).count() as u64; - stored < canvas_tiles - }) || combined.tiles().any(|(coord, tile)| { - let tile_rect = coord.rect(); - let overlap = tile_rect.intersect(&area); - if overlap.is_empty() { - return false; - } - let x0 = (overlap.x0 - tile_rect.x0) as usize; - let x1 = (overlap.x1 - tile_rect.x0) as usize; - (overlap.y0 - tile_rect.y0..overlap.y1 - tile_rect.y0).any(|y| { - let row_start = y as usize * TILE_SIZE as usize; - let start = row_start + x0; - tile.bytes().get(start..row_start + x1).is_some_and(|row| row.iter().any(|&v| v != 0)) - }) - }); - doc.selection = has_on_canvas_pixels.then_some(combined); - Ok(()) - })?; - Ok(Value::Null) - } - ), - // Layer - cmd!( - "layer.new.layer", - "Layer…", - ["Layer", "New"], - Some("Cmd+Shift+N"), - r##"{"name":str?,"clipToPrevious":bool=false (Use Previous Layer to Create Clipping Mask; inside a clip group the layer joins it anyway),"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":"Normal|Multiply|…"="Normal","opacity":0..1=1,"fillNeutral":bool=false (fill with the mode's neutral color: modes without one are an error),"position":"above|below"="above" (below: the Layers panel's Cmd/Ctrl-click; never under the Background)} (above the active layer, or the top layer inside it when it is an open group)"##, - has_doc, - crate::new_layer::run - ), - cmd!( - "layer.new.group", - "Group…", - ["Layer", "New"], - None, - r##"{"name":text?,"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":str="passThrough" (blend mode),"opacity":0..100=100 (percent),"position":"above|below"="above" (below: the Layers panel's Cmd/Ctrl-click; never under the Background)} (above the active layer, or inside it when it is an open group; clipped when it lands inside a clipping mask)"##, - has_doc, - |s, p| { - let opts = crate::group_options::GroupOptions::parse("layer.new.group", p)?; - let below = crate::group_options::below("layer.new.group", p)?; - let place = if below { crate::layer_place::Place::Below } else { crate::layer_place::Place::Auto }; - let id = s.edit("New Group", |doc, active| { - let name = opts.name.clone().unwrap_or_else(|| doc.next_layer_name("Group")); - let mut group = Layer::group(name, vec![]); - opts.apply(&mut group); - let bg = crate::background_cmds::background_id(doc); - let id = crate::layer_place::insert_new(doc, *active, group, place); - crate::background_cmds::keep_background_at_bottom(bg, doc)?; - *active = Some(id); - Ok(id) - })?; - Ok(json!({ "layer": id.0 })) - } - ), - cmd!( - "layer.groupLayers", - "Group Layers", - ["Layer"], - Some("Cmd+G"), - r##"{"layer":id?,"name":text?,"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":str="passThrough" (blend mode),"opacity":0..100=100 (percent)} (no layer: every selected layer; the new group starts collapsed)"##, - has_layer, - crate::layer_multi_cmds::group_layers - ), - cmd!( - "layer.duplicate", - "Duplicate Layer…", - ["Layer"], - None, - r##"{"layer":id?,"inPlace":bool=false (artboards: keep the copy on the original instead of beside it),"name":str? (one layer: the copy's name),"document":index|"new"=same document (Photoshop's Destination: "new" makes a new document the size of this canvas holding just the copies),"documentName":str? (the new document's name)} (no layer: every selected layer)"##, - has_layer, - |s, p| { - if let Some(d) = p.get("document") { - if d.as_str() == Some("new") { - return crate::layer_copy_cmds::duplicate_to_new_document(s, p); - } - let same = d.as_u64().is_some_and(|i| s.active_index().is_some_and(|a| i == a as u64)); - if !same { - return Err(EngineError::BadParams { - cmd: "layer.duplicate".into(), - msg: if d.as_u64().is_some() { - "the destination is another open document (use layer.copyToDocument)".into() - } else { - "`document` must be a document index or \"new\"".into() - }, - }); - } - } - let in_place = p.get("inPlace").and_then(Value::as_bool).unwrap_or(false); - let name = p.get("name").and_then(Value::as_str).filter(|n| !n.is_empty()).map(str::to_string); - if crate::layer_multi_cmds::multi(s, p) { - return crate::layer_multi_cmds::duplicate_selected(s, in_place, "Duplicate Layers"); - } - let id = layer_param(s, p)?; - let add_copy = layer_panel_option(s, "addCopyToCopiedLayersAndGroups", true); - // The dialog offers Duplicate Layer's own name: only a different one was typed (#9023). - let mut typed = None; - let mut shift = (0, 0); - let nid = s.edit("Duplicate Layer", |doc, active| { - let mut dup = layer_copy(doc, id, add_copy)?; - if let Some(name) = name.as_ref().filter(|n| **n != dup.name) { - dup.name.clone_from(name); - typed = Some(name.clone()); - } - let nid = doc.insert_above(Some(id), dup); - // A lone copy joins its original's link group, as in the reference application (#11217). - crate::layer_multi_cmds::relink_copies(doc, &[nid])?; - if !in_place { - shift = crate::artboard_cmds::place_copy(doc, nid)?; - } - *active = Some(nid); - Ok(nid) - })?; - crate::artboard_cmds::follow_shift(s, shift); - if let Some(name) = typed { - crate::type_cmds::note_typed_name(s, nid, &name); - } - Ok(json!({ "layer": nid.0 })) - } - ), - cmd!("layer.delete", "Delete Layer", ["Layer", "Delete"], None, r##"{"layer":id?} (no layer: every selected layer)"##, has_layer, |s, p| { - if crate::layer_multi_cmds::multi(s, p) { - return crate::layer_multi_cmds::delete_selected(s); - } - let id = layer_param(s, p)?; - s.edit("Delete Layer", |doc, active| { - let neighbours = crate::layer_multi_cmds::deletion_neighbours(doc, id); - let before = crate::clip_group::Before::read(doc, &[id]); - doc.remove(id).ok_or(EngineError::NoLayer(id))?; - crate::clip_group::settle(doc, &[], &before, false); - if doc.layers.is_empty() { - return Err(EngineError::Other("a document must keep at least one layer".into())); - } - if active.is_some_and(|current| doc.layer(current).is_none()) { - *active = neighbours.into_iter().find(|candidate| doc.layer(*candidate).is_some()); - } - Ok(()) - })?; - Ok(Value::Null) - }), - cmd!( - "layer.select", - "Select Layer", - [], - None, - r##"{"layer":id|str|{"index":uint}|{"ordinal":"Trgt|Frwr|Bckw|Frnt|Back"} | "name":str,"occurrence":index?,"mode":"replace|toggle|range|add|remove"="replace"} | {"layers":[id,…]} (layers: exactly these selected, the last active; typed references use the recorded full layer stack; name occurrence: zero-based document walk order; required for duplicate names; toggle = ⌘-click, range = ⇧-click, remove = deselect it, keeping at least one)"##, - has_doc, - crate::layer_multi_cmds::select - ), - cmd!( - "layer.setProps", - "Layer Properties", - [], - None, - r##"{"layer":id?,"layers":[id,…]? (the same change to each, one step: the Layers panel's controls with several layers selected),"name":str? (one layer only),"visible":bool?,"opacity":0..1?,"fill":0..1?,"blend":"Multiply|…"?,"clipped":bool?,"locked":bool?,"locks":{"transparency","pixels","position","artboard","all":bool}?,"channels":[bool,…]? (Advanced Blending: which colour channels blend, R G B / C M Y K / L a b)}"##, - has_layer, - |s, p| { - // Several layers at once (the Layers panel with several selected, as in Photoshop), - // else the given or active one. - let ids: Vec = match p.get("layers") { - None | Some(Value::Null) => vec![layer_param(s, p)?], - Some(Value::Array(a)) if !a.is_empty() && a.len() <= 10_000 => { - let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; - let mut ids = Vec::with_capacity(a.len()); - for v in a { - let id = v.as_u64().map(LayerId).ok_or_else(|| bad("layer.setProps", format!("`layers` holds layer ids, got {v}")))?; - if doc.layer(id).is_none() { - return Err(EngineError::NoLayer(id)); - } - if !ids.contains(&id) { - ids.push(id); - } - } - ids - } - Some(v) => return Err(bad("layer.setProps", format!("`layers` is a non-empty list of layer ids, got {v}"))), - }; - if ids.len() > 1 && p.get("name").is_some() { - return Err(bad("layer.setProps", "`name` renames one layer, not several")); - } - // Opacity and Fill are fractions here, while the Layer Style commands take - // percentages: a value outside 0..1 is refused, never clamped to 100 % (#5242). - let unit = |key: &str| -> Result> { - let Some(v) = p.get(key) else { return Ok(None) }; - match v.as_f64() { - Some(x) if (0.0..=1.0).contains(&x) => Ok(Some(x as f32)), - _ => Err(bad("layer.setProps", format!("{key} must be a number in 0..1 (1 = 100 %), got {v}"))), - } - }; - let (opacity, fill) = (unit("opacity")?, unit("fill")?); - // Photoshop's History names for a single kind of change; a mix is "Layer Properties". - let changed: Vec<&str> = p - .as_object() - .map(|o| o.keys().map(String::as_str).filter(|k| !matches!(*k, "layer" | "layers" | "coalesce")).collect()) - .unwrap_or_default(); - let label = match changed.as_slice() { - ["visible"] => "Layer Visibility", - ["opacity"] => "Opacity Change", - ["fill"] => "Fill Opacity Change", - ["blend"] => "Blending Change", - ["name"] => "Rename Layer", - _ => "Layer Properties", - }; - // The eye: a history state only with History Options › Make Layer Visibility - // Changes Undoable. - let only_visibility = changed.as_slice() == ["visible"]; - let record = !only_visibility || s.visibility_undoable(); - s.edit_with(label, record, |doc, _| { - // The Background has no opacity, fill or blend mode: like Photoshop, setting - // one that changes its look turns it into a normal layer ("Layer 0") first. - let num = |k: &str| p.get(k).and_then(Value::as_f64).is_some_and(|v| v < 1.0); - let blends = p.get("blend").and_then(Value::as_str).and_then(parse_blend).is_some_and(|b| b != photocraft_color::BlendMode::Normal); - for &id in &ids { - if num("opacity") || num("fill") || blends { - crate::extra_cmds::background_to_layer(doc, id); - } - let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - if let Some(v) = p.get("name").and_then(Value::as_str) { - l.name = v.to_string(); - } - if let Some(v) = p.get("visible").and_then(Value::as_bool) { - l.visible = v; - } - if let Some(v) = opacity { - l.opacity = v; - } - if let Some(v) = fill { - l.fill_opacity = v; - } - if let Some(v) = p.get("blend").and_then(Value::as_str) { - let b = parse_blend(v).ok_or_else(|| bad("layer.setProps", format!("unknown blend mode `{v}`")))?; - // Pass Through is a group's mode only, as in Photoshop. - if b == photocraft_color::BlendMode::PassThrough && !l.is_group() { - return Err(bad("layer.setProps", format!("Pass Through applies to groups only; layer {} isn't one", l.id.0))); - } - l.blend = b; - } - if let Some(v) = p.get("clipped").and_then(Value::as_bool) { - l.clipped = v; - } - if let Some(v) = p.get("locked").and_then(Value::as_bool) { - l.locks.all = v; - } - if let Some(Value::Array(ch)) = p.get("channels") { - // Blending Options › Advanced Blending › Channels: unchecked = left out. - l.excluded_channels = ch.iter().take(32).enumerate().filter(|(_, v)| v.as_bool() == Some(false)).fold(0, |m, (i, _)| m | 1 << i); - } - if let Some(Value::Object(m)) = p.get("locks") { - for (k, v) in m { - let v = v.as_bool().unwrap_or(false); - if !l.locks.set(k, v) { - return Err(bad("layer.setProps", format!("unknown lock `{k}`"))); - } - } - } - } - Ok(()) - })?; - // The Layers panel's in-place rename: a name the user typed (#9023). - if let (Some(name), [id]) = (p.get("name").and_then(Value::as_str), ids.as_slice()) { - crate::type_cmds::note_typed_name(s, *id, name); - } - Ok(Value::Null) - } - ), - cmd!("layer.arrange.bringForward", "Bring Forward", ["Layer", "Arrange"], Some("Cmd+]"), r##"{"layer":id?}"##, has_layer, |s, p| arrange(s, p, 1)), - cmd!("layer.arrange.sendBackward", "Send Backward", ["Layer", "Arrange"], Some("Cmd+["), r##"{"layer":id?}"##, has_layer, |s, p| arrange(s, p, -1)), - cmd!("layer.arrange.bringToFront", "Bring to Front", ["Layer", "Arrange"], Some("Cmd+Shift+]"), r##"{"layer":id?}"##, has_layer, |s, p| arrange( - s, - p, - i32::MAX - )), - cmd!("layer.arrange.sendToBack", "Send to Back", ["Layer", "Arrange"], Some("Cmd+Shift+["), r##"{"layer":id?}"##, has_layer, |s, p| arrange( - s, - p, - i32::MIN - )), - cmd!( - "layer.createClippingMask", - "Create Clipping Mask", - ["Layer"], - Some("Cmd+Alt+G"), - r##"{"layer":id?} (no layer: every selected layer but the lowest clips to the layer below it)"##, - has_layer, - |s, p| set_clipped(s, p, true) - ), - cmd!( - "layer.releaseClippingMask", - "Release Clipping Mask", - ["Layer"], - None, - r##"{"layer":id?} (no layer: every selected layer)"##, - has_layer, - |s, p| set_clipped(s, p, false) - ), - cmd!( - "layer.layerMask.revealAll", - "Reveal All", - ["Layer", "Layer Mask"], - None, - r##"{"layer":id?} (no layer: every selected layer that can take a mask)"##, - has_layer, - |s, p| set_mask(s, p, "Add Layer Mask", Some(LayerMask::reveal_all())) - ), - cmd!( - "layer.layerMask.hideAll", - "Hide All", - ["Layer", "Layer Mask"], - None, - r##"{"layer":id?} (no layer: every selected layer that can take a mask)"##, - has_layer, - |s, p| set_mask(s, p, "Add Layer Mask", Some(LayerMask::hide_all())) - ), - cmd!( - "layer.layerMask.revealSelection", - "Reveal Selection", - ["Layer", "Layer Mask"], - None, - r##"{"layer":id?} (no layer: every selected layer that can take a mask)"##, - has_selection, - |s, p| { - let sel = s.active().and_then(|d| d.doc.selection.clone()).ok_or(EngineError::Other("no selection".into()))?; - let mask = LayerMask { surface: sel, ..LayerMask::reveal_all() }; - // The selection becomes the mask, so Photoshop drops it (as Hide Selection does): a - // following Invert (⌘I) on the targeted mask then inverts all of it, not just the - // part inside the old selection. Same undo step as the mask. - set_mask_and_deselect(s, p, "Add Layer Mask", mask) - } - ), - cmd!("layer.layerMask.delete", "Delete", ["Layer", "Layer Mask"], None, r##"{"layer":id?}"##, has_layer, |s, p| set_mask( - s, - p, - "Delete Layer Mask", - None - )), - cmd!( - "layer.layerMask.moveTo", - "Move Layer Mask", - [], - None, - r##"{"layer":id? (the mask's layer, default active),"to":id|name (the layer or group it goes to; a recorded step names it),"toOccurrence":n? (which of several layers named `to`, in document order),"copy":bool=false (⌥-drag: a copy goes and the original stays),"replace":bool=false (replace a mask already there; otherwise refused)} → {layer,to,copy}"##, - has_layer, - move_mask - ), - cmd!("layer.mergeDown", "Merge Down", ["Layer"], None, r##"{"layer":id?}"##, has_layer, |s, p| { - let id = layer_param(s, p)?; - s.edit("Merge Down", |doc, active| { - let path = doc.path_of(id).ok_or(EngineError::NoLayer(id))?; - let Some((&idx, parent)) = path.split_last() else { return Err(EngineError::NoLayer(id)) }; - if idx == 0 { - return Err(EngineError::Other("no layer below to merge into".into())); - } - let mut below = parent.to_vec(); - below.push(idx - 1); - let lower = doc.layer_at(&below).ok_or(EngineError::NoLayer(id))?.clone(); - let upper = doc.layer(id).ok_or(EngineError::NoLayer(id))?.clone(); - let merged = pixels::merge_down(doc, &lower, &upper); - doc.remove(id); - *doc.layer_at_mut(&below).ok_or(EngineError::NoLayer(lower.id))? = merged; - *active = Some(lower.id); - Ok(()) - })?; - Ok(Value::Null) - }), - cmd!("layer.mergeGroup", "Merge Group", ["Layer"], None, r##"{"layer":id?}"##, has_layer, |s, p| { - let id = layer_param(s, p)?; - if !s.active().and_then(|d| d.doc.layer(id)).is_some_and(|l| matches!(l.content, LayerContent::Group(_))) { - return Err(EngineError::Other("Merge Group needs a group".into())); - } - merge_group(s, id) - }), - cmd!("layer.flattenImage", "Flatten Image", ["Layer"], None, "{}", has_doc, |s, _| { - s.edit("Flatten Image", |doc, active| { - let fmt = doc.pixel_format(); - let mut bg = Layer::raster("Background", fmt); - bg.locks.transparency = true; - bg.locks.position = true; - *crate::pixels_mut(&mut bg)? = photocraft_compose::flatten_to_surface(doc, fmt, Some([1.0, 1.0, 1.0])); - *active = Some(bg.id); - doc.layers = vec![bg].into(); - Ok(()) - })?; - Ok(Value::Null) - }), - cmd!( - "layer.newFillLayer.solidColor", - "Solid Color…", - ["Layer", "New Fill Layer"], - None, - r##"{"color":"#rrggbb"=foreground,"cmyk":[c,m,y,k]? (inks 0..1 the colour was picked as: a CMYK document's fill holds exactly these; default the foreground's CMYK pick),"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask, making a shape; else the selection is the layer mask)}"##, - has_doc, - |s, p| { - let c = color_param("layer.newFillLayer.solidColor", p, "color", s.tools.foreground)?; - // The inks the colour was picked as, so CMYK 50/50/50/100 stays 50/50/50/100 instead - // of what its sRGB stand-in converts back to through the document profile (#8568). - let inks = match cmyk_param("layer.newFillLayer.solidColor", p, "cmyk")? { - Some(k) => Some(k), - None => s.tools.picked_cmyk([c[0], c[1], c[2]]), - }; - let default_mask = layer_panel_option(s, "useDefaultMasksOnFillLayers", true); - let id = s.edit("New Color Fill Layer", |doc, active| { - let fill = match inks { - Some(k) if doc.mode == ColorMode::Cmyk => Fill::Solid(Color { mode: ColorMode::Cmyk, c: k, alpha: c[3] }), - _ => Fill::Solid(Color::rgba(c[0], c[1], c[2], c[3])).in_mode(doc.mode), - }; - let mut l = Layer::new(doc.next_layer_name("Color Fill"), LayerContent::Fill(fill)); - mask_new_layer(doc, &mut l, p, "layer.newFillLayer.solidColor", default_mask)?; - let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); - *active = Some(id); - Ok(id) - })?; - Ok(json!({ "layer": id.0 })) - } - ), - cmd!( - "layer.newFillLayer.gradient", - "Gradient…", - ["Layer", "New Fill Layer"], - None, - r##"{"from":"#rrggbb","to":"#rrggbb","angle":deg=90,"style":"linear|radial|angle|reflected|diamond","reverse":bool,"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask; else the selection is the layer mask),"stops"?,"transparency"?,"midpoints"?,"scale"?,"offset"?,"dither"?,"align"? (as gradient.fill.set; stops replace from/to)}"##, - has_doc, - |s, p| { - let a = color_param("layer.newFillLayer.gradient", p, "from", s.tools.foreground)?; - let b = color_param("layer.newFillLayer.gradient", p, "to", s.tools.background)?; - let angle = crate::gradient_fill_cmds::angle_param("layer.newFillLayer.gradient", p, 90.0)?; - let style = crate::layer_style::gradient_style(p.get("style").and_then(Value::as_str).unwrap_or("linear")); - let reverse = p.get("reverse").and_then(Value::as_bool).unwrap_or(false); - let default_mask = layer_panel_option(s, "useDefaultMasksOnFillLayers", true); - // The rest of a recorded Gradient Fill (a loaded action's Make): applied as - // `gradient.fill.set` would, in the same step. - let rest: serde_json::Map = ["stops", "transparency", "midpoints", "scale", "offset", "dither", "align"] - .iter() - .filter_map(|k| p.get(*k).map(|v| ((*k).to_string(), v.clone()))) - .collect(); - let (fg, bg) = (s.tools.foreground, s.tools.background); - let id = s.edit("New Gradient Fill Layer", |doc, active| { - let mut fill = Fill::gradient( - vec![(0.0, Color::rgba(a[0], a[1], a[2], a[3])), (1.0, Color::rgba(b[0], b[1], b[2], b[3]))], - angle, - 1.0, - style, - reverse, - ); - if !rest.is_empty() { - let l = Layer::new(String::new(), LayerContent::Fill(fill.clone())); - fill = crate::gradient_fill_cmds::apply_set(&l, &fill, doc.bounds(), &Value::Object(rest.clone()), fg, bg)?; - } - let fill = fill.in_mode(doc.mode); - let mut l = Layer::new(doc.next_layer_name("Gradient Fill"), LayerContent::Fill(fill)); - mask_new_layer(doc, &mut l, p, "layer.newFillLayer.gradient", default_mask)?; - let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); - *active = Some(id); - Ok(id) - })?; - Ok(json!({ "layer": id.0 })) - } - ), - cmd!( - "layer.setAdjustment", - "Adjustment Properties", - [], - None, - r##"{"layer":id?, …params of that adjustment kind} (Levels, Curves: "eyedropper":{"point":"black|gray|white","at":[x,y],"size":1..101=1} or {"point",…,"color":[r,g,b] 0..1} = the Properties panel's Set Black/Neutral Gray/White Point, sampling the image below the layer, RGB and Grayscale (no gray) only)"##, - has_layer, - |s, p| { - let id = layer_param(s, p)?; - let eyedropped = crate::adjust_params::layer_eyedropper(s, id, p)?; - s.edit("Modify Adjustment", |doc, _| { - let mode = doc.mode; - let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - let LayerContent::Adjustment(adj) = &mut l.content else { return Err(EngineError::Other("not an adjustment layer".into())) }; - if matches!(adj, Adjustment::Unsupported { .. }) { - return Err(EngineError::Other("this adjustment can't be edited (kept as imported)".into())); - } - let kind = adjustment_kind(adj); - // No params resets to the defaults; otherwise params merge over the current values. - *adj = if let Some(eyedropped) = eyedropped { - eyedropped - } else if crate::adjust_params::user_keys(p).is_empty() { - crate::adjust_params::default_for(kind, mode)? - } else { - crate::adjust_params::from_params(kind, p, Some(adj), mode)? - }; - Ok(()) - })?; - Ok(Value::Null) - } - ), - cmd!( - "layer.moveTo", - "Reorder Layer", - [], - None, - r##"{"layer":id|{"index":uint}|{"ordinal":"Trgt|Frwr|Bckw|Frnt|Back"}?| "layers":[id,…]?, "target":id|name|{"index":uint},"targetOccurrence":n? (which of several layers named `target`, in document order),"position":"above|below|into"="above","copy":bool=false} (typed target: pre-move recorded stack boundary, omit position; layers: one undoable move, document order preserved; copy: place duplicates there and leave the layers, as ⌥-dragging a Layers panel row; recorded typed references retain their form)"##, - has_layer, - crate::layer_multi_cmds::move_to - ), - cmd!( - "layer.translate", - "Move Layer", - [], - None, - r##"{"layer":id?,"dx":i32,"dy":i32,"units":"px"|"pt"="px" (pt: points, whole pixels at the document's resolution),"target":"pixels"|"mask"="pixels","selection":bool=false,"wrap":bool=false,"nest":bool=false} → null | {nested:[id]} (no layer: every selected layer; linked layers follow; target mask: a layer whose mask is unlinked moves that mask alone, a linked mask moves with the layer; selection: the selection moves too, in the same step; wrap: View › Pattern Preview, pixels that leave the canvas come back on the opposite edge so the tile stays seamless; nest: auto-nesting as the Move tool does it, a layer whose bounds centre lands on another artboard joins it and one whose centre is off every artboard leaves for the top level; a clipping base takes the layers clipped to it along and a clipped layer goes only where its base goes; artboards, the Background, empty layers, layers whose board doesn't change, groups that would nest too deep and layers locked with Prevent Auto-Nesting (on the layer, a group around it or the destination board) stay put, with their whole clipping group; nested lists the layers that changed board)"##, - has_layer, - crate::layer_multi_cmds::translate - ), - // Image - cmd!("image.imageRotation.flipCanvasHorizontal", "Flip Canvas Horizontal", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| { - turn(s, "Flip Canvas Horizontal", crate::canvas_geom::Turn::FlipHorizontal) - }), - cmd!("image.imageRotation.flipCanvasVertical", "Flip Canvas Vertical", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| { - turn(s, "Flip Canvas Vertical", crate::canvas_geom::Turn::FlipVertical) - }), - cmd!("image.imageRotation.180", "180°", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| { - turn(s, "Rotate Canvas", crate::canvas_geom::Turn::Rotate180) - }), - cmd!("image.imageRotation.90cw", "90° Clockwise", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| { - turn(s, "Rotate Canvas", crate::canvas_geom::Turn::Cw90) - }), - cmd!("image.imageRotation.90ccw", "90° Counter Clockwise", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| { - turn(s, "Rotate Canvas", crate::canvas_geom::Turn::Ccw90) - }), - cmd!( - "image.adjustments.desaturate", - "Desaturate", - ["Image", "Adjustments"], - Some("Cmd+Shift+U"), - r##"{"target":"pixels"|"mask"|{"color":i}|{"colors":[i,…]}?=Channels panel target,"layer":id|name?=active}"##, - crate::adjust_cmds::has_adjustable, - |s, p| { - if crate::adjust_cmds::adjust_as_smart_filter(s, "desaturate", "Desaturate", p)? { - return Ok(Value::Null); - } - destructive_adjust(s, "Desaturate", desaturate_adjustment(), p) - } - ), - // Paint - cmd!( - "paint.stroke", - "Brush Stroke", - [], - None, - r##"{"points":[[x,y,pressure?,tiltX?,tiltY?,rotation?,timeMs?,wheel?],…],"brush":{…BrushSettings}?,"preset":name?,"size":0.5..5000 px?,"hardness":0..1?,"opacity":0..1?,"flow":0..1?,"fill":bool=false (fill the region the closed `points` enclose with the brush colour, its edge anti-aliased and softened by hardness, instead of stamping the outline; a closed gesture paints a filled dab, not a ring),"spacing":0..10?,"color":"#rrggbb"?=foreground,"mode":"normal|multiply|screen|…|clear (erases with this brush)"="normal","erase":bool?,"smoothing":0..1?,"zoom":number=1,"seed":u64?,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target}"##, - has_paintable, - crate::brush_cmds::paint_stroke - ), - cmd!( - "tools.setColors", - "Set Colors", - [], - None, - r##"{"foreground":"#rrggbb"|[r,g,b,a?]?,"background":same?,"foregroundCmyk":[c,m,y,k]? (inks 0..1 the foreground was picked as: a CMYK document is filled with exactly these),"backgroundCmyk":same?}"##, - always, - |s, p| { - let cmyk = |key: &str| cmyk_param("tools.setColors", p, key); - let (fg_cmyk, bg_cmyk) = (cmyk("foregroundCmyk")?, cmyk("backgroundCmyk")?); - let foreground = color_param("tools.setColors", p, "foreground", s.tools.foreground)?; - let background = color_param("tools.setColors", p, "background", s.tools.background)?; - s.tools.foreground = foreground; - s.tools.background = background; - if let Some(k) = fg_cmyk { - let [r, g, b, _] = s.tools.foreground; - s.tools.remember_cmyk([r, g, b], k); - } - if let Some(k) = bg_cmyk { - let [r, g, b, _] = s.tools.background; - s.tools.remember_cmyk([r, g, b], k); - } - Ok(Value::Null) - } - ), - cmd!("tools.swapColors", "Switch Foreground and Background Colors", [], Some("X"), "{}", always, |s, _| { - std::mem::swap(&mut s.tools.foreground, &mut s.tools.background); - Ok(Value::Null) - }), - cmd!("tools.defaultColors", "Default Foreground and Background Colors", [], Some("D"), "{}", always, |s, _| { - if s.tools.mask_targeted { - s.tools.foreground = crate::ToolState::MASK_COLORS[0]; - s.tools.background = crate::ToolState::MASK_COLORS[1]; - } else { - s.tools.foreground = [0.0, 0.0, 0.0, 1.0]; - s.tools.background = [1.0, 1.0, 1.0, 1.0]; - } - Ok(Value::Null) - }), - // Queries (not journaled) - CommandSpec { - id: "session.inspect", - label: "Inspect Session", - menu: &[], - shortcut: None, - params: "{}", - enabled: always, - run: |s, _| Ok(inspect::session(s)), - journal: false, - }, - CommandSpec { - id: "document.inspect", - label: "Inspect Document", - menu: &[], - shortcut: None, - params: r##"{"document":index?}"##, - enabled: has_doc, - run: |s, p| { - let d = match p.get("document") { - Some(v) => { - let i = v.as_u64().and_then(|v| usize::try_from(v).ok()).ok_or_else(|| bad("document.inspect", "`document` must be an index"))?; - s.documents().get(i).ok_or_else(|| EngineError::Other(format!("no document at index {i}")))? - } - None => s.active().ok_or(EngineError::NoDocument)?, - }; - Ok(inspect::document(d)) - }, - journal: false, - }, - CommandSpec { - id: "document.activate", - label: "Activate Document", - menu: &[], - shortcut: None, - params: r##"{"document":index|{"index":uint}} or {"offset":int} (numeric document: zero-based tab index; typed index: one-based opening order; offset: places after the active document in opening order, before it when negative) → {document}"##, - enabled: has_doc, - run: |s, p| { - // A null key counts as omitted. - let given = |k: &str| p.get(k).filter(|v| !v.is_null()); - let idx = match (given("document"), given("offset")) { - (Some(_), Some(_)) => return Err(bad("document.activate", "give `document` or `offset`, not both")), - (None, None) => return Err(bad("document.activate", "needs `document` (a tab index) or `offset`")), - // Recorded offsets wrap in opening order, independently of dragged tabs. - (None, Some(o)) => { - let o = o.as_i64().ok_or_else(|| bad("document.activate", "`offset` must be an integer"))?; - s.document_at_offset(o)? - } - (Some(d), None) => { - if let Some(selector) = d.as_object() { - let index = selector - .get("index") - .filter(|_| selector.len() == 1) - .and_then(Value::as_u64) - .ok_or_else(|| bad("document.activate", "document reference needs one non-negative index"))?; - return s - .document_at_index(index) - .and_then(|idx| if s.set_active(idx) { Ok(json!({"document": idx})) } else { Err(EngineError::NoDocument) }); - } - let i = d.as_u64().ok_or_else(|| bad("document.activate", "`document` must be a tab index"))?; - usize::try_from(i).map_err(|_| bad("document.activate", "`document` out of range"))? - } - }; - if s.set_active(idx) { Ok(json!({"document": idx})) } else { Err(EngineError::Other(format!("no document at index {idx}"))) } - }, - journal: true, - }, - CommandSpec { - id: "document.move", - label: "Move Document", - menu: &[], - shortcut: None, - params: r##"{"document":index?,"to":index}"##, - enabled: has_doc, - run: |s, p| { - let index = |key: &str| { - p.get(key) - .map(|v| v.as_u64().and_then(|v| usize::try_from(v).ok()).ok_or_else(|| bad("document.move", format!("`{key}` must be a tab index")))) - }; - let from = match index("document") { - Some(i) => i?, - None => s.active_index().ok_or(EngineError::NoDocument)?, - }; - let to = index("to").ok_or_else(|| bad("document.move", "missing `to`"))??; - let to = s.move_document(from, to).ok_or(EngineError::NoDocument)?; - Ok(json!({"document": to})) - }, - journal: false, - }, - CommandSpec { - id: "command.list", - label: "List Commands", - menu: &[], - shortcut: None, - params: "{}", - enabled: always, - run: |s, _| Ok(Value::Array(command_specs().iter().map(|c| list_entry(s, c, (c.enabled)(s).err())).collect())), - journal: false, - }, - CommandSpec { - id: "document.pixel", - label: "Read Composite Pixel", - menu: &[], - shortcut: None, - params: r##"{"x":i32,"y":i32}"##, - enabled: has_doc, - run: |s, p| { - let coord = |k: &str| i32::try_from(int(p, k).unwrap_or(0)).map_err(|_| bad("document.pixel", format!("{k} must fit in 32 bits"))); - let (x, y) = (coord("x")?, coord("y")?); - let d = s.active().ok_or(EngineError::NoDocument)?; - // At i32::MAX the 1x1 rect saturates to empty: a pixel that far out is transparent. - let px = photocraft_compose::render(&d.doc, Rect::from_xywh(x, y, 1, 1)).px.first().copied().unwrap_or_default(); - Ok(json!(px)) - }, - journal: false, - }, - ]; +/// A named group of commands: `SPECS` lists them in registry order. +type Fragment = (&'static str, fn() -> Vec); - // Adjustment layers + destructive adjustments, generated from one list. - // Levels/Curves channel keys follow the document: red/green/blue (RGB), gray (Grayscale), - // cyan/magenta/yellow/black (CMYK), lightness/a/b (Lab); see `adjust_params`. - const ADJ: &[(&str, &str, &str)] = &[ - ("brightnessContrast", "Brightness/Contrast…", r##"{"brightness":-150..150=0,"contrast":-50..100=0,"legacy":bool=false}"##), - ( - "levels", - "Levels…", - r##"{"inBlack":0..253=0,"gamma":0.01..9.99=1,"inWhite":2..255=255,"outBlack":0..255=0,"outWhite":0..255=255,"red":json,"green":json,"blue":json,"eyedropper":json} (top level = composite; per channel {"inBlack","gamma","inWhite","outBlack","outWhite"} under red/green/blue, gray, cyan/magenta/yellow/black or lightness/a/b; eyedropper = the dialog's Set Black/Neutral Gray/White Point picker {"point":"black|gray|white","at":[x,y],"size":1..101=1} or {"point",…,"color":[r,g,b] 0..1}: black/white set each channel's input black/white to the sample, gray each channel's gamma so the sample turns neutral at its luma; colour composites: RGB and Grayscale (no gray); Image adjustments targeting a mask, alpha or Quick Mask sample that gray plane in any document mode, applied over the given levels)"##, - ), - ( - "curves", - "Curves…", - r##"{"points":json,"red":json,"green":json,"blue":json,"pencil":bool=false,"smooth":0..10=0,"eyedropper":json} (curves as [[in,out],…] in 0..255, 2..19 points: points = composite; red/green/blue, gray, cyan/magenta/yellow/black or lightness/a/b per channel; pencil = drawn curves (Draw to modify the curve): each curve is 256 output levels in 0..255 (point curves given are drawn in, and turning pencil off fits points to the drawing); smooth = Smooth passes over the drawn curves; eyedropper = the dialog's Set Black/Neutral Gray/White Point picker {"point":"black|gray|white","at":[x,y],"size":1..101=1} or {"point",…,"color":[r,g,b] 0..1}, colour composites: RGB and Grayscale (no gray); Image adjustments targeting a mask, alpha or Quick Mask sample that gray plane in any document mode, applied over the given curves)"##, - ), - ("exposure", "Exposure…", r##"{"exposure":-20..20=0,"offset":-0.5..0.5=0,"gamma":0.01..9.99=1}"##), - ("vibrance", "Vibrance…", r##"{"vibrance":-100..100=0,"saturation":-100..100=0}"##), - ( - "hueSaturation", - "Hue/Saturation…", - r##"{"hue":-180..180=0,"saturation":-100..100=0,"lightness":-100..100=0,"colorize":bool=false,"reds":json,"yellows":json,"greens":json,"cyans":json,"blues":json,"magentas":json} (per range {"hue","saturation","lightness","range":[4 hue degrees]}; colorize: hue 0..360, saturation 0..100)"##, - ), - ( - "colorBalance", - "Color Balance…", - r##"{"shadows":json,"midtones":json,"highlights":json,"preserveLuminosity":bool=true} (each tone [cyan-red, magenta-green, yellow-blue] in -100..100)"##, - ), - ( - "blackWhite", - "Black & White…", - r##"{"reds":-200..300=40,"yellows":-200..300=60,"greens":-200..300=40,"cyans":-200..300=60,"blues":-200..300=20,"magentas":-200..300=80,"tint":bool=false,"tintColor":"#rrggbb"}"##, - ), - ( - "photoFilter", - "Photo Filter…", - r##"{"filter":"warming85|warmingLBA|warming81|cooling80|coolingLBB|cooling82|red|orange|yellow|green|cyan|blue|violet|magenta|sepia|deepRed|deepBlue|deepEmerald|deepYellow|underwater","color":"#rrggbb","density":0..100=25,"preserveLuminosity":bool=true}"##, - ), - ( - "channelMixer", - "Channel Mixer…", - r##"{"red":json,"green":json,"blue":json,"gray":json,"monochrome":bool=false} (per output channel [red %, green %, blue %, constant %] in -200..200; gray = the monochrome mix)"##, - ), - ("invert", "Invert", "{}"), - ("posterize", "Posterize…", r##"{"levels":2..255=4}"##), - ("threshold", "Threshold…", r##"{"level":1..255=128}"##), - ("gradientMap", "Gradient Map…", r##"{"stops":json,"reverse":bool=false,"dither":bool=false} (stops [[location 0..1, "#rrggbb"], …], 2..64)"##), - ( - "selectiveColor", - "Selective Color…", - r##"{"method":"relative|absolute"="relative","colors":"reds|yellows|greens|cyans|blues|magentas|whites|neutrals|blacks"="reds","cyan":-100..100=0,"magenta":-100..100=0,"yellow":-100..100=0,"black":-100..100=0,"reds":json} (per-range [c,m,y,k] arrays: reds yellows greens cyans blues magentas whites neutrals blacks)"##, - ), - ( - "colorLookup", - "Color Lookup…", - r##"{"lut":"none|warm|cool|tealOrange|bleachBypass|fadedFilm|dayForNight|monoContrast|crossProcess"="none","file":text,"interpolation":"trilinear|tetrahedral"="trilinear","dither":bool=false,"data":text,"dataEncoding":"text|base64"="text","fileName":text,"lutFormat":"auto|cube|3dl|look"="auto"} (file: LUT path; data: file text or encoded bytes; lutFormat overrides format detection, auto detects it)"##, - ), - ]; - for &(kind, label, params) in ADJ { - let layer_id: &'static str = Box::leak(format!("layer.newAdjustmentLayer.{kind}").into_boxed_str()); - let image_id: &'static str = Box::leak(format!("image.adjustments.{kind}").into_boxed_str()); - v.push(CommandSpec { - id: layer_id, - label, - menu: &["Layer", "New Adjustment Layer"], - shortcut: None, - params: Box::leak(format!(r#"{params} + {{{NEW_LAYER_PATH},"opacity":0..1=1,"name":str?=the adjustment's name + number,"mode":blend mode name="normal" (not Pass Through),"clipToPrevious":bool=false}}"#).into_boxed_str()), - enabled: has_doc, - run: |s, p| { - let kind = p.get("__kind").and_then(Value::as_str).unwrap_or("invert").to_string(); - let eyedropped = if matches!(kind.as_str(), "levels" | "curves") { crate::adjust_params::eyedropper_from_params(s, &kind, p)? } else { None }; - let adj = match eyedropped { - Some(adj) => adj, - None => crate::adjust_params::from_params(&kind, p, None, doc_mode(s))?, - }; - new_adjustment(s, adj, p, &format!("layer.newAdjustmentLayer.{kind}")) - }, - journal: true, - }); - v.push(CommandSpec { - id: image_id, - label, - menu: &["Image", "Adjustments"], - shortcut: match kind { - "levels" => Some("Cmd+L"), - "curves" => Some("Cmd+M"), - "hueSaturation" => Some("Cmd+U"), - "colorBalance" => Some("Cmd+B"), - "invert" => Some("Cmd+I"), - "blackWhite" => Some("Cmd+Alt+Shift+B"), - _ => None, - }, - params, - enabled: crate::adjust_cmds::has_adjustable, - run: |s, p| { - let kind = p.get("__kind").and_then(Value::as_str).unwrap_or("invert").to_string(); - if matches!(kind.as_str(), "levels" | "curves") { - crate::channel_cmds::resolve_tone_target(s, false, p)?; - } - let eyedropped = if matches!(kind.as_str(), "levels" | "curves") { crate::adjust_params::destructive_eyedropper(s, &kind, p)? } else { None }; - // A smart filter re-runs its params, so it records what an eyedropper resolved - // to, not the sample (#3127). - let recorded = eyedropped.as_ref().map(|adj| { - let mut q = p.clone(); - if let (Value::Object(q), Value::Object(resolved)) = (&mut q, crate::adjust_params::to_params(adj)) { - q.remove("eyedropper"); - q.extend(resolved); - } - q - }); - let adj = match eyedropped { - Some(adj) => adj, - None => { - // A gray plane target keeps the neutral tone space even over params - // carrying RGB, Lab or CMYK records (#5335). - let tone = if is_mask_target(p) || crate::channel_cmds::is_channel_target(p) { - if matches!(kind.as_str(), "levels" | "curves") { crate::adjust_params::gray_tone_params(p) } else { p.clone() } - } else { - p.clone() - }; - crate::adjust_params::from_params(&kind, &tone, None, adjust_mode(s, p))? - } - }; - let adj = if matches!(kind.as_str(), "levels" | "curves") - && let Some(colors) = crate::color_channels::target(s, p)? - { - crate::color_channels::tone_adjustment(&kind, p, adj, doc_mode(s), colors)? - } else { - adj - }; - let label = adj.label().to_string(); - // A smart object records the adjustment as a smart filter (Photoshop), which - // re-runs from the source instead of baking into a copy of the pixels. - if crate::adjust_cmds::adjust_as_smart_filter(s, &kind, &label, recorded.as_ref().unwrap_or(p))? { - return Ok(Value::Null); - } - destructive_adjust(s, &label, adj, p) - }, - journal: true, - }); - } - v.extend(crate::layer_style::specs()); - v.extend(crate::contour_lib_cmds::specs()); - v.extend(crate::layer_list_cmds::specs()); - v.extend(crate::filters::specs()); - v.extend(crate::filters_ext::specs()); - v.extend(crate::color_to_alpha_cmds::specs()); - v.extend(crate::gallery_cmds::specs()); - v.extend(crate::gradient_fill_cmds::specs()); - v.extend(crate::solid_fill_cmds::specs()); - v.extend(crate::pattern_fill_cmds::specs()); - v.extend(crate::type_cmds::specs()); - v.extend(crate::type_mask_cmds::specs()); - v.extend(crate::transform_cmds::specs()); - v.extend(crate::float_cmds::specs()); - v.extend(crate::vector_cmds::specs()); - v.extend(crate::path_edit_cmds::specs()); - v.extend(crate::smartselect_cmds::specs()); - v.extend(crate::cutout_cmds::specs()); - v.extend(crate::symmetry_cmds::specs()); - v.extend(crate::edit_cmds::specs()); - v.extend(crate::smart_svg_cmds::specs()); - v.extend(crate::color_cmds::specs()); - v.extend(crate::brush_cmds::specs()); - v.extend(crate::brush_preset_cmds::specs()); - v.extend(crate::eraser_cmds::specs()); - v.extend(crate::preset_import_cmds::specs()); - v.extend(crate::style_asl_cmds::specs()); - v.extend(crate::atn_cmds::specs()); - v.extend(crate::actions_edit_cmds::specs()); - v.extend(crate::swatch_cmds::specs()); - v.extend(crate::retouch_cmds::specs()); - v.extend(crate::redeye_cmds::specs()); - v.extend(crate::image_cmds::specs()); - v.extend(crate::perspective_crop_cmds::specs()); - v.extend(crate::selection_cmds::specs()); - v.extend(crate::magnetic_cmds::specs()); - v.extend(crate::select_extra_cmds::specs()); - v.extend(crate::paint_cmds::specs()); - v.extend(crate::extra_cmds::specs()); - v.extend(crate::background_cmds::specs()); - v.extend(crate::file_cmds::specs()); - v.extend(crate::exr_cmds::specs()); - v.extend(crate::type_extra_cmds::specs()); - v.extend(crate::type_area_cmds::specs()); - v.extend(crate::type_styles_cmds::specs()); - v.extend(crate::type_spell_cmds::specs()); - v.extend(crate::type_caret_cmds::specs()); - v.extend(crate::smart_cmds::specs()); - v.extend(crate::layer_multi_cmds::specs()); - v.extend(crate::layer_copy_cmds::specs()); - v.extend(crate::prefs::specs()); - v.extend(crate::edit_menu_cmds::specs()); - v.extend(crate::fill_key_cmds::specs()); - v.extend(crate::sample_cmds::specs()); - v.extend(crate::face_cmds::specs()); - v.extend(crate::sampler_cmds::specs()); - v.extend(crate::brush_key_cmds::specs()); - v.extend(crate::stamp_cmds::specs()); - v.extend(crate::align_cmds::specs()); - v.extend(crate::photo_cmds::specs()); - v.extend(crate::lens_cmds::specs()); - v.extend(crate::vp_cmds::specs()); - v.extend(crate::channel_cmds::specs()); - v.extend(crate::adjust_cmds::specs()); - v.extend(crate::layer_menu_cmds::specs()); - v.extend(crate::layer_label_cmds::specs()); - v.extend(crate::layer_css_cmds::specs()); - v.extend(crate::layer_xmp_cmds::specs()); - v.extend(crate::mode_cmds::specs()); - v.extend(crate::multichannel_cmds::specs()); - v.extend(crate::pattern_cmds::specs()); - v.extend(crate::warp_cmds::specs()); - v.extend(crate::comps_cmds::specs()); - v.extend(crate::artboard_cmds::specs()); - v.extend(crate::distort_cmds::specs()); - v.extend(crate::analysis_cmds::specs()); - v.extend(crate::notes_cmds::specs()); - v.extend(crate::font_library_cmds::specs()); - v.extend(crate::history_cmds::specs()); - v.extend(crate::history_options_cmds::specs()); - v.extend(crate::history_menu_cmds::specs()); - v.extend(crate::history_source_cmds::specs()); - v.extend(crate::history_select_cmds::specs()); - v.extend(crate::proof_sim::specs()); - v.extend(crate::presets::specs()); - v.extend(crate::document_preset_cmds::specs()); - v.extend(crate::export_preset_cmds::specs()); - v.extend(crate::render_cmds::specs()); - v.extend(crate::slice_cmds::specs()); - v.extend(crate::web_cmds::specs()); - v.extend(crate::automate_cmds::specs()); - v.extend(crate::print_cmds::specs()); - v.extend(crate::installed_profiles::specs()); - v.extend(crate::pick_cmds::specs()); - v.extend(crate::layer_nav_cmds::specs()); - v.extend(crate::frame_cmds::specs()); - v.extend(crate::migrate_cmds::specs()); - v.extend(crate::trap_cmds::specs()); - v.extend(crate::timeline_cmds::specs()); - v.extend(crate::video_cmds::specs()); - v.extend(crate::jobs::specs()); - v.extend(crate::wia_cmds::specs()); - v.extend(crate::rasterize_style_cmds::specs()); - v.extend(crate::variables_cmds::specs()); - v.extend(crate::plugin_cmds::specs()); - v.extend(crate::group_view_cmds::specs()); - v.extend(crate::fx_view_cmds::specs()); - v.extend(crate::fx_visibility_cmds::specs()); - v.extend(crate::mask_view_cmds::specs()); - v.extend(crate::layer_mask_props_cmds::specs()); - v.extend(crate::actions_cmds::specs()); +/// Every table fragment with its name, in registry order. The order is part of the behaviour (menus +/// list commands in it) and `command_ids.txt` pins it. The `table` fragments are grouped by the +/// crate that will own them; a menu split between owners has one fragment per contiguous run. +const SPECS: &[Fragment] = &[ + ("store::file_menu", table::store::file_menu::specs), + ("core::file_menu", table::core::file_menu::specs), + ("core::edit_menu", table::core::edit_menu::specs), + ("paint::edit_menu", table::paint::edit_menu::specs), + ("model::edit_menu", table::model::edit_menu::specs), + ("core::select_menu", table::core::select_menu::specs), + ("model::layer_menu", table::model::layer_menu::specs_before_gradient), + ("store::layer_menu", table::store::layer_menu::specs), + ("model::layer_menu", table::model::layer_menu::specs_after_gradient), + ("model::image_menu", table::model::image_menu::specs), + ("image::image_menu", table::image::image_menu::specs), + ("paint::stroke", table::paint::stroke::specs), + ("core::tools", table::core::tools::specs), + ("core::queries", table::core::queries::specs), + ("image::adjustments", table::image::adjustments::specs), + ("layer_style", crate::layer_style::specs), + ("contour_lib_cmds", crate::contour_lib_cmds::specs), + ("layer_list_cmds", crate::layer_list_cmds::specs), + ("filters", crate::filters::specs), + ("filters_ext", crate::filters_ext::specs), + ("color_to_alpha_cmds", crate::color_to_alpha_cmds::specs), + ("gallery_cmds", crate::gallery_cmds::specs), + ("gradient_fill_cmds", crate::gradient_fill_cmds::specs), + ("solid_fill_cmds", crate::solid_fill_cmds::specs), + ("pattern_fill_cmds", crate::pattern_fill_cmds::specs), + ("type_cmds", crate::type_cmds::specs), + ("type_mask_cmds", crate::type_mask_cmds::specs), + ("transform_cmds", crate::transform_cmds::specs), + ("float_cmds", crate::float_cmds::specs), + ("vector_cmds", crate::vector_cmds::specs), + ("path_edit_cmds", crate::path_edit_cmds::specs), + ("smartselect_cmds", crate::smartselect_cmds::specs), + ("cutout_cmds", crate::cutout_cmds::specs), + ("symmetry_cmds", crate::symmetry_cmds::specs), + ("edit_cmds", crate::edit_cmds::specs), + ("smart_svg_cmds", crate::smart_svg_cmds::specs), + ("color_cmds", crate::color_cmds::specs), + ("brush_cmds", crate::brush_cmds::specs), + ("brush_preset_cmds", crate::brush_preset_cmds::specs), + ("eraser_cmds", crate::eraser_cmds::specs), + ("preset_import_cmds", crate::preset_import_cmds::specs), + ("style_asl_cmds", crate::style_asl_cmds::specs), + ("atn_cmds", crate::atn_cmds::specs), + ("actions_edit_cmds", crate::actions_edit_cmds::specs), + ("swatch_cmds", crate::swatch_cmds::specs), + ("retouch_cmds", crate::retouch_cmds::specs), + ("redeye_cmds", crate::redeye_cmds::specs), + ("image_cmds", crate::image_cmds::specs), + ("perspective_crop_cmds", crate::perspective_crop_cmds::specs), + ("selection_cmds", crate::selection_cmds::specs), + ("magnetic_cmds", crate::magnetic_cmds::specs), + ("select_extra_cmds", crate::select_extra_cmds::specs), + ("paint_cmds", crate::paint_cmds::specs), + ("extra_cmds", crate::extra_cmds::specs), + ("background_cmds", crate::background_cmds::specs), + ("file_cmds", crate::file_cmds::specs), + ("exr_cmds", crate::exr_cmds::specs), + ("type_extra_cmds", crate::type_extra_cmds::specs), + ("type_area_cmds", crate::type_area_cmds::specs), + ("type_styles_cmds", crate::type_styles_cmds::specs), + ("type_spell_cmds", crate::type_spell_cmds::specs), + ("type_caret_cmds", crate::type_caret_cmds::specs), + ("smart_cmds", crate::smart_cmds::specs), + ("layer_multi_cmds", crate::layer_multi_cmds::specs), + ("layer_copy_cmds", crate::layer_copy_cmds::specs), + ("prefs", crate::prefs::specs), + ("edit_menu_cmds", crate::edit_menu_cmds::specs), + ("fill_key_cmds", crate::fill_key_cmds::specs), + ("sample_cmds", crate::sample_cmds::specs), + ("face_cmds", crate::face_cmds::specs), + ("sampler_cmds", crate::sampler_cmds::specs), + ("brush_key_cmds", crate::brush_key_cmds::specs), + ("stamp_cmds", crate::stamp_cmds::specs), + ("align_cmds", crate::align_cmds::specs), + ("photo_cmds", crate::photo_cmds::specs), + ("lens_cmds", crate::lens_cmds::specs), + ("vp_cmds", crate::vp_cmds::specs), + ("channel_cmds", crate::channel_cmds::specs), + ("adjust_cmds", crate::adjust_cmds::specs), + ("layer_menu_cmds", crate::layer_menu_cmds::specs), + ("layer_label_cmds", crate::layer_label_cmds::specs), + ("layer_css_cmds", crate::layer_css_cmds::specs), + ("layer_xmp_cmds", crate::layer_xmp_cmds::specs), + ("mode_cmds", crate::mode_cmds::specs), + ("multichannel_cmds", crate::multichannel_cmds::specs), + ("pattern_cmds", crate::pattern_cmds::specs), + ("warp_cmds", crate::warp_cmds::specs), + ("comps_cmds", crate::comps_cmds::specs), + ("artboard_cmds", crate::artboard_cmds::specs), + ("distort_cmds", crate::distort_cmds::specs), + ("analysis_cmds", crate::analysis_cmds::specs), + ("notes_cmds", crate::notes_cmds::specs), + ("font_library_cmds", crate::font_library_cmds::specs), + ("history_cmds", crate::history_cmds::specs), + ("history_options_cmds", crate::history_options_cmds::specs), + ("history_menu_cmds", crate::history_menu_cmds::specs), + ("history_source_cmds", crate::history_source_cmds::specs), + ("history_select_cmds", crate::history_select_cmds::specs), + ("proof_sim", crate::proof_sim::specs), + ("presets", crate::presets::specs), + ("document_preset_cmds", crate::document_preset_cmds::specs), + ("export_preset_cmds", crate::export_preset_cmds::specs), + ("render_cmds", crate::render_cmds::specs), + ("slice_cmds", crate::slice_cmds::specs), + ("web_cmds", crate::web_cmds::specs), + ("automate_cmds", crate::automate_cmds::specs), + ("print_cmds", crate::print_cmds::specs), + ("installed_profiles", crate::installed_profiles::specs), + ("pick_cmds", crate::pick_cmds::specs), + ("layer_nav_cmds", crate::layer_nav_cmds::specs), + ("frame_cmds", crate::frame_cmds::specs), + ("migrate_cmds", crate::migrate_cmds::specs), + ("trap_cmds", crate::trap_cmds::specs), + ("timeline_cmds", crate::timeline_cmds::specs), + ("video_cmds", crate::video_cmds::specs), + ("jobs", crate::jobs::specs), + ("wia_cmds", crate::wia_cmds::specs), + ("rasterize_style_cmds", crate::rasterize_style_cmds::specs), + ("variables_cmds", crate::variables_cmds::specs), + ("plugin_cmds", crate::plugin_cmds::specs), + ("group_view_cmds", crate::group_view_cmds::specs), + ("fx_view_cmds", crate::fx_view_cmds::specs), + ("fx_visibility_cmds", crate::fx_visibility_cmds::specs), + ("mask_view_cmds", crate::mask_view_cmds::specs), + ("layer_mask_props_cmds", crate::layer_mask_props_cmds::specs), + ("actions_cmds", crate::actions_cmds::specs), +]; + +/// Every registered command, in the order of SPECS. +fn build() -> Vec { + let specs = SPECS.iter().flat_map(|(_, specs)| specs()); // The dispatch guard's unit test needs a command that panics on purpose (REL-3). #[cfg(test)] - v.push(test_panic_command()); - v + let specs = specs.chain(std::iter::once(test_panic_command())); + specs.collect() } /// A command whose `run` panics on purpose, so the last-resort guard in `jobs::dispatch` diff --git a/crates/engine/src/cmd/adjust_cmds.rs b/crates/engine/src/cmd/adjust_cmds.rs index f7dd8925bd..e0951ee2de 100644 --- a/crates/engine/src/cmd/adjust_cmds.rs +++ b/crates/engine/src/cmd/adjust_cmds.rs @@ -403,7 +403,7 @@ pub(crate) fn adjust_as_filter(kind: &str, p: &Value, surf: &Surface, histogram_ })?; } else if kind == "desaturate" { let mode = surf.format().mode; - if crate::pixels::adjust_surface(&mut out, &crate::commands::desaturate_adjustment(), None, mode).is_err() { + if crate::pixels::adjust_surface(&mut out, &super::table::image::image_menu::desaturate_adjustment(), None, mode).is_err() { return Ok(None); } } else if kind == "equalize" { diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index af62d62696..4e7200882c 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -659,10 +659,126 @@ pub fn artboard_document(doc: &Document, id: LayerId) -> Result Ok(Some(one)) } +/// Include Overlapping Areas: each visible artboard stacked above board `id` that overlaps it, as +/// the reference application writes it into the board's file: a plain group (no longer an +/// artboard) holding its layers over a new pixel layer "Background for " filled with the +/// board's background where the two boards overlap, in source coordinates and bottom to top. A +/// group whose layers reach past its own board (effects, pixels outside the board, adjustments) +/// gets a hard mask to its board, which the artboard clipped them to. +/// +/// The artboard painted its background beneath the group and then composited the group (its +/// blend mode, opacity, effects and masks) over it. A board with any of those keeps them on a +/// group of its own inside the plain group, above the background, so they still apply to its +/// layers only and its own mask keeps its feather and Layer Mask Hides Effects setting; the plain +/// group then carries nothing but the board clip. +fn overlapping_boards(doc: &Document, id: LayerId, rect: Rect) -> Vec { + let above = doc.layers.iter().skip_while(|l| l.id != id).skip(1); + let mut out = Vec::new(); + for l in above.filter(|l| l.visible) { + let Some(ab) = l.artboard().cloned() else { continue }; + let overlap = ab.rect.intersect(&rect); + if overlap.is_empty() { + continue; + } + let mut board = l.clone(); + if let LayerContent::Group(g) = &mut board.content { + g.artboard = None; + cut_pixels(&mut g.children, overlap, 0); + } + let bg = ab.background.rgba(); + let mut group = if stacks_like_its_layers(&board) { + board + } else { + board.clipped = false; + let mut plain = Layer::group(l.name.clone(), vec![board]); + plain.label = l.label; + plain + }; + if let (Some(bg), Some(children)) = (bg, group.children_mut()) { + let fmt = doc.pixel_format(); + let mut surf = Surface::new(fmt); + surf.fill_rect(overlap, &photocraft_raster::from_rgba(&fmt, bg)); + children.insert(0, Layer::new(format!("Background for {}", l.name), LayerContent::Raster(surf))); + } + // With the background in place: its pixels widen what the group's layers can reach. + let reach = photocraft_compose::change_bounds(&group, doc.bounds()); + if reach.is_none_or(|r| !ab.rect.contains_rect(&r)) { + let mut mask = photocraft_doc::LayerMask::reveal_all(); + mask.surface = Surface::with_default(PixelFormat::GRAY8, &[0.0]); + mask.surface.fill_rect(ab.rect, &[1.0]); + group.mask = Some(mask); + } + out.push(group); + } + out +} + +/// Whether artboard `board` (already a plain group) composites over its background exactly as +/// its layers stacked over that background in one pass-through group do: pass-through (a Normal +/// group renders its layers on their own first, so a Multiply or Screen layer in it never blends +/// with the background), and no effects, masks, opacity, Blend If or other blending options of +/// its own, nor a mask the board clip would replace. +fn stacks_like_its_layers(board: &Layer) -> bool { + board.blend == photocraft_color::BlendMode::PassThrough + && board.opacity >= 1.0 + && board.fill_opacity >= 1.0 + && board.mask.is_none() + && board.vector_mask.is_none() + && board.frame.is_none() + && board.excluded_channels == 0 + && board.blend_if == photocraft_doc::BlendIf::default() + && board.advanced == photocraft_doc::AdvancedBlending::default() + && !photocraft_compose::effects::has_effects(board) +} + +/// Cuts the pixel layers in `layers` (and in groups inside them, `depth` levels down so far) to +/// `keep`, as the reference application cuts an overlapping board's layers to the file. Layers +/// whose pixels can't be cut stay whole; the group's mask still hides what lies past its board. +/// A layer with effects, or inside a group with effects, stays whole too: pixels outside `keep` +/// can cast a shadow or glow into it. +fn cut_pixels(layers: &mut [Layer], keep: Rect, depth: usize) { + const MAX_DEPTH: usize = 64; + for l in layers { + if photocraft_compose::effects::has_effects(l) { + continue; + } + match &mut l.content { + LayerContent::Group(g) if depth < MAX_DEPTH => cut_pixels(&mut g.children, keep, depth + 1), + LayerContent::Raster(surf) => { + let r = surf.content_bounds().intersect(&keep); + let mut cut = Surface::with_default(surf.format(), &surf.default_pixel()); + if !r.is_empty() { + let Ok(px) = surf.try_read_region(r) else { continue }; + if cut.try_write_region(r, &px).is_err() { + continue; + } + } + *surf = cut; + } + _ => {} + } + } +} + /// [`artboard_document`] for each chosen board, all built before any file is written so a -/// board that can't be exported fails the export without leaving a partial set behind. -fn chosen_documents(doc: &Document, p: &Value) -> Result> { - chosen_artboards(doc, p).into_iter().filter_map(|id| artboard_document(doc, id).transpose()).collect() +/// board that can't be exported fails the export without leaving a partial set behind. With +/// `overlapping`, each file also holds the boards above that overlap it ([`overlapping_boards`]). +fn chosen_documents(doc: &Document, p: &Value, overlapping: bool) -> Result> { + let mut out = Vec::new(); + for id in chosen_artboards(doc, p) { + let Some(mut one) = artboard_document(doc, id)? else { continue }; + if overlapping && let Some(r) = doc.layer(id).and_then(|l| l.artboard()).map(|a| a.rect) { + // `artboard_document` has checked that the board's origin negates. + let (dx, dy) = (r.x0.saturating_neg(), r.y0.saturating_neg()); + for mut group in overlapping_boards(doc, id, r) { + crate::commands::translate_layer(doc, &mut group, dx, dy); + crate::vector_cmds::translate_vectors(doc, &mut group, f64::from(dx), f64::from(dy)); + one.layers.push(group); + } + } + out.push(one); + } + Ok(out) } /// The artboards an export covers: `"artboards": [ids]`, else all, top of the Layers panel first. @@ -735,8 +851,16 @@ fn artboards_to_files(s: &mut Session, p: &Value) -> Result { let save = SaveOpts::from_params(s, p, cmd)?; let d = s.active().ok_or(EngineError::NoDocument)?; let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name)); + let overlapping = match p.get("content") { + None | Some(Value::Null) => true, + Some(v) => match v.as_str() { + Some("overlapping") => true, + Some("artboard") => false, + _ => return Err(bad(cmd, format!("`content` must be \"overlapping\" or \"artboard\", not {v}"))), + }, + }; let doc = d.doc.clone(); - let boards = chosen_documents(&doc, p)?; + let boards = chosen_documents(&doc, p, overlapping)?; let names: Vec<&str> = boards.iter().map(|one| one.name.as_str()).collect(); let mut files = Vec::new(); for (one, name) in boards.iter().zip(artboard_file_stems(&prefix, &names, HYPHENATED_FORMATS.contains(&format.as_str()))) { @@ -806,7 +930,7 @@ fn artboards_to_pdf(s: &mut Session, p: &Value) -> Result { let mut pages = Vec::new(); // Pages go bottom artboard of the Layers panel first, as in the reference application (#13643); // `chosen_documents` lists them top first, the order Artboards to Files keeps. - for one in chosen_documents(&doc, p)?.into_iter().rev() { + for one in chosen_documents(&doc, p, false)?.into_iter().rev() { let buf = photocraft_compose::flatten(&one).over_background([1.0, 1.0, 1.0]); let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::U8, true); let mut flat = Document::new(&one.name, one.size, ColorMode::Rgb, SampleType::U8); @@ -883,7 +1007,7 @@ pub fn specs() -> Vec { "file.export.artboardsToFiles", "Artboards to Files…", &["File", "Export"], - r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name ("" = none),"artboards":[id]? (default all),"quality":0..12?} → {files} (one "." per board, no separator or index added: spaces become "-" in PNG, JPEG, BMP, Targa and TIFF and stay in PSD and other formats, characters a file name can't hold become "_", and a name an earlier board already took, ignoring case, gets "-2", "-3"…)"##, + r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name ("" = none),"content":"overlapping|artboard"="overlapping" (Include Overlapping Areas: a board's file also shows the visible boards above it where they overlap it, each as a plain group with a \"Background for \" layer; artboard: Artboard Content Only),"artboards":[id]? (default all),"quality":0..12?} → {files} (one "." per board, no separator or index added: spaces become "-" in PNG, JPEG, BMP, Targa and TIFF and stay in PSD and other formats, characters a file name can't hold become "_", and a name an earlier board already took, ignoring case, gets "-2", "-3"…)"##, export_artboards, artboards_to_files ), @@ -905,6 +1029,9 @@ mod file_names_tests; #[path = "artboard_cmds/first_board_background_tests.rs"] mod first_board_background_tests; #[cfg(test)] +#[path = "artboard_cmds/overlapping_areas_tests.rs"] +mod overlapping_areas_tests; +#[cfg(test)] #[path = "artboard_cmds/pdf_page_order_tests.rs"] mod pdf_page_order_tests; #[cfg(test)] diff --git a/crates/engine/src/cmd/artboard_cmds/overlapping_areas_tests.rs b/crates/engine/src/cmd/artboard_cmds/overlapping_areas_tests.rs new file mode 100644 index 0000000000..86df170247 --- /dev/null +++ b/crates/engine/src/cmd/artboard_cmds/overlapping_areas_tests.rs @@ -0,0 +1,340 @@ +//! Artboards to Files › Include Overlapping Areas / Artboard Content Only (#13629): the boards +//! stacked above an exported board that overlap it show in its file (PNG pixels, PSD structure), +//! boards below never do, and the source document is left alone. + +use super::*; +use photocraft_geom::Rect; + +const RED: [u8; 3] = [220, 30, 30]; +const BLUE: [u8; 3] = [30, 30, 220]; +const WHITE: [u8; 3] = [255, 255, 255]; + +/// The measured test document: 800 x 400, transparent, bottom to top `Red Board` 0,0-200,150 +/// (pixel layer `Red` at 20,20-120,100), `Blue Board` 120,30-320,230 (pixel layer `Blue` at +/// 130,40-230,140) and `Empty Board` 600,0-700,100, all with white backgrounds. +fn session(depth: u32) -> (Session, [u64; 3]) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 400, "depth": depth, "background": "transparent"})).unwrap(); + let board = + |s: &mut Session, name: &str, rect: [i64; 4]| s.execute("layer.new.artboard", json!({"rect": rect, "name": name})).unwrap()["layer"].as_u64().unwrap(); + let red = board(&mut s, "Red Board", [0, 0, 200, 150]); + let blue = board(&mut s, "Blue Board", [120, 30, 200, 200]); + let empty = board(&mut s, "Empty Board", [600, 0, 100, 100]); + paint(&mut s, red, "Red", Rect::new(20, 20, 120, 100), RED); + paint(&mut s, blue, "Blue", Rect::new(130, 40, 230, 140), BLUE); + (s, [red, blue, empty]) +} + +/// A pixel layer `name` of `color` over `rect`, on top of board `board`'s layers. +fn paint(s: &mut Session, board: u64, name: &str, rect: Rect, color: [u8; 3]) { + s.edit(name, |doc, _| { + let fmt = doc.pixel_format(); + let mut l = Layer::raster(name, fmt); + let [r, g, b] = color.map(|c| f32::from(c) / 255.0); + l.surface_mut().unwrap().fill_rect(rect, &photocraft_raster::from_rgba(&fmt, [r, g, b, 1.0])); + doc.layer_mut(LayerId(board)).unwrap().children_mut().unwrap().push(l); + Ok(()) + }) + .unwrap(); +} + +struct Out(std::path::PathBuf); + +impl Out { + fn new(tag: &str) -> Self { + let dir = std::env::temp_dir().join(format!("photocraft-overlap-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Out(dir) + } + fn dir(&self) -> String { + self.0.to_string_lossy().into_owned() + } +} + +impl Drop for Out { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// Exports board `board` with `extra` params and reads the one file back. +fn export(s: &mut Session, out: &Out, board: u64, extra: Value) -> Document { + let mut p = json!({"dir": out.dir(), "prefix": "", "artboards": [board]}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + let format = p.get("format").and_then(Value::as_str).unwrap_or("png").to_string(); + let r = s.execute("file.export.artboardsToFiles", p).unwrap(); + let files = r["files"].as_array().unwrap(); + assert_eq!(files.len(), 1, "{r}"); + let path = files[0].as_str().unwrap(); + photocraft_io::import(&format!("x.{format}"), &std::fs::read(path).unwrap()).unwrap().document +} + +/// The file's composite pixel at (x, y) as 8-bit RGBA. +fn px(d: &Document, x: i32, y: i32) -> [u8; 4] { + let flat = photocraft_compose::flatten(d); + let w = d.size.width as usize; + flat.px[y as usize * w + x as usize].map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8) +} + +fn rgb(p: [u8; 4]) -> [u8; 3] { + [p[0], p[1], p[2]] +} + +fn names(layers: &[Layer]) -> Vec<&str> { + layers.iter().map(|l| l.name.as_str()).collect() +} + +#[test] +fn include_overlapping_areas_is_the_default_and_shows_the_board_above() { + for depth in [8, 16] { + let (mut s, [red, _, _]) = session(depth); + let out = Out::new(&format!("default-{depth}")); + for extra in [json!({}), json!({"content": "overlapping"})] { + let f = export(&mut s, &out, red, extra.clone()); + assert_eq!((f.size.width, f.size.height), (200, 150), "{depth} bit {extra}"); + assert_eq!(rgb(px(&f, 150, 60)), BLUE, "{depth} bit {extra}: Blue's pixels"); + assert_eq!(rgb(px(&f, 125, 35)), WHITE, "{depth} bit {extra}: Blue Board's background"); + assert_eq!(rgb(px(&f, 125, 50)), WHITE, "{depth} bit {extra}: Blue Board's background"); + assert_eq!(rgb(px(&f, 110, 50)), RED, "{depth} bit {extra}: Red stays red"); + } + } +} + +#[test] +fn artboard_content_only_keeps_the_board_on_its_own() { + let (mut s, [red, _, _]) = session(8); + let out = Out::new("content-only"); + let f = export(&mut s, &out, red, json!({"content": "artboard"})); + assert_eq!(rgb(px(&f, 150, 60)), WHITE, "nothing of Blue Board"); + assert_eq!(rgb(px(&f, 110, 50)), RED); + let psd = export(&mut s, &out, red, json!({"content": "artboard", "format": "psd"})); + assert_eq!(names(&psd.layers), ["Red Board"]); +} + +#[test] +fn an_overlapping_psd_holds_the_board_above_as_a_plain_group_with_its_background() { + let (mut s, [red, _, _]) = session(8); + let out = Out::new("psd"); + let psd = export(&mut s, &out, red, json!({"format": "psd"})); + assert_eq!((psd.size.width, psd.size.height), (200, 150)); + // Bottom to top: the exported artboard, then the overlapping board as a plain group. + assert_eq!(names(&psd.layers), ["Red Board", "Blue Board"]); + let [board, group] = [&psd.layers[0], &psd.layers[1]]; + assert_eq!(board.artboard().map(|a| a.rect), Some(Rect::new(0, 0, 200, 150))); + assert_eq!(names(board.children().unwrap()), ["Red"]); + assert!(matches!(&group.content, LayerContent::Group(g) if g.artboard.is_none()), "no longer an artboard"); + let kids = group.children().unwrap(); + assert_eq!(names(kids), ["Background for Blue Board", "Blue"]); + // Blue (130,40-230,140 in the source) is cut to the file: 130,40-200,140. + let blue = photocraft_compose::bounds::content_bounds(kids[1].surface().unwrap()); + assert_eq!(blue, Rect::new(130, 40, 200, 140)); + // The background covers where the boards overlap: 120..200 x 30..150. + let bg = photocraft_compose::bounds::content_bounds(kids[0].surface().unwrap()); + assert_eq!(bg, Rect::new(120, 30, 200, 150)); + assert_eq!(rgb(px(&psd, 150, 60)), BLUE); + assert_eq!(rgb(px(&psd, 125, 35)), WHITE); + assert_eq!(rgb(px(&psd, 110, 50)), RED); +} + +#[test] +fn boards_below_do_not_show_in_either_mode() { + let (mut s, [_, blue, _]) = session(8); + // A transparent Blue Board shows whatever leaks in from Red Board's white background below. + s.execute("layer.artboard.set", json!({"layer": blue, "background": "transparent"})).unwrap(); + let out = Out::new("below"); + for content in ["overlapping", "artboard"] { + let f = export(&mut s, &out, blue, json!({"content": content})); + assert_eq!((f.size.width, f.size.height), (200, 200), "{content}"); + // Source (125,35): Red Board's background, outside Blue's pixels. + assert_eq!(px(&f, 5, 5)[3], 0, "{content}: nothing of Red Board"); + assert_eq!(rgb(px(&f, 30, 30)), BLUE, "{content}"); + let psd = export(&mut s, &out, blue, json!({"content": content, "format": "psd"})); + assert_eq!(names(&psd.layers), ["Blue Board"], "{content}"); + } +} + +#[test] +fn the_source_document_is_unchanged_and_gets_no_history_entry() { + let (mut s, [red, blue, _]) = session(8); + let out = Out::new("source"); + for content in ["overlapping", "artboard"] { + for board in [red, blue] { + let d = s.active().unwrap(); + let (before, rev, past) = (d.doc.clone(), d.revision, d.history.past_len()); + export(&mut s, &out, board, json!({"content": content, "format": "psd"})); + let d = s.active().unwrap(); + assert!(d.doc == before, "{content} changed the document"); + assert_eq!((d.revision, d.history.past_len()), (rev, past), "{content}"); + } + } +} + +/// The artboard clipped its layers to the board; as a plain group in the file they still stop +/// at the board's edge, so Blue pixels outside Blue Board never cover Red Board. +#[test] +fn the_layers_of_the_board_above_stay_inside_their_board() { + let (mut s, [red, blue, _]) = session(8); + paint(&mut s, blue, "Spill", Rect::new(100, 45, 125, 55), BLUE); + let out = Out::new("spill"); + for format in ["png", "psd"] { + let f = export(&mut s, &out, red, json!({"format": format})); + assert_eq!(rgb(px(&f, 110, 50)), RED, "{format}: outside Blue Board"); + assert_eq!(rgb(px(&f, 122, 50)), BLUE, "{format}: inside Blue Board"); + assert_eq!(rgb(px(&f, 150, 60)), BLUE, "{format}"); + } +} + +/// A layer that covers the whole canvas (a solid colour fill) in the board above is clipped to +/// that board by a mask on the group, so it can't paint over the rest of the exported board. +#[test] +fn a_fill_layer_in_the_board_above_stays_inside_its_board() { + let (mut s, [red, blue, _]) = session(8); + s.edit("Fill", |doc, _| { + let fill = Layer::new("Green", LayerContent::Fill(photocraft_doc::Fill::Solid(Color::rgb(0.0, 1.0, 0.0)))); + doc.layer_mut(LayerId(blue)).unwrap().children_mut().unwrap().push(fill); + Ok(()) + }) + .unwrap(); + let out = Out::new("fill"); + for format in ["png", "psd"] { + let f = export(&mut s, &out, red, json!({"format": format})); + assert_eq!(rgb(px(&f, 110, 50)), RED, "{format}: outside Blue Board"); + assert_eq!(rgb(px(&f, 10, 140)), WHITE, "{format}: outside Blue Board"); + assert_eq!(rgb(px(&f, 150, 60)), [0, 255, 0], "{format}: inside Blue Board"); + } +} + +/// A layer of the board above that lies outside the exported board still casts its drop shadow +/// into it, as it does in the document: its pixels are not cut away before the effect is built. +#[test] +fn a_shadow_cast_into_the_exported_board_from_outside_it_still_shows() { + use photocraft_doc::effects::{Contour, FxCommon, Shadow}; + let (mut s, [red, blue, _]) = session(8); + // Caster at 210..240 x 160..180 (in Blue Board, outside Red Board); its shadow, 40 px up and + // to the left, falls on 170..200 x 120..140, inside Red Board. + paint(&mut s, blue, "Caster", Rect::new(210, 160, 240, 180), [0, 160, 0]); + s.edit("Shadow", |doc, _| { + let caster = doc.layer_mut(LayerId(blue)).unwrap().children_mut().unwrap().last_mut().unwrap(); + caster.effects.items.push(photocraft_doc::Effect::DropShadow(Shadow { + common: FxCommon::new(photocraft_color::BlendMode::Normal, 1.0), + color: Color::rgb(0.0, 0.0, 0.0), + angle: -45.0, + use_global_light: false, + distance: 40.0_f32.hypot(40.0), + spread: 0.0, + size: 0.0, + contour: Contour::Linear, + anti_alias: false, + noise: 0.0, + knocks_out: true, + })); + Ok(()) + }) + .unwrap(); + let source = px(&s.active().unwrap().doc, 185, 130); + assert_eq!(rgb(source), [0, 0, 0], "the shadow lands there in the document"); + let out = Out::new("shadow"); + for format in ["png", "psd"] { + let f = export(&mut s, &out, red, json!({"format": format})); + assert_eq!(px(&f, 185, 130), source, "{format}"); + assert_eq!(rgb(px(&f, 110, 50)), RED, "{format}"); + } +} + +/// Not measured (keeps today's behaviour): a hidden board above shows nothing. +#[test] +fn a_hidden_board_above_does_not_show() { + let (mut s, [red, blue, _]) = session(8); + s.edit("Hide", |doc, _| { + doc.layer_mut(LayerId(blue)).unwrap().visible = false; + Ok(()) + }) + .unwrap(); + let out = Out::new("hidden"); + let f = export(&mut s, &out, red, json!({})); + assert_eq!(rgb(px(&f, 150, 60)), WHITE); + let psd = export(&mut s, &out, red, json!({"format": "psd"})); + assert_eq!(names(&psd.layers), ["Red Board"]); +} + +#[test] +fn a_bad_content_value_is_rejected_without_writing_anything() { + let (mut s, _) = session(8); + let out = Out::new("bad"); + for bad in [json!("both"), json!(""), json!(1), json!(true), json!(["overlapping"])] { + let d = s.active().unwrap(); + let (before, past) = (d.doc.clone(), d.history.past_len()); + let err = s.execute("file.export.artboardsToFiles", json!({"dir": out.dir(), "content": bad})).unwrap_err(); + assert!(matches!(err, EngineError::BadParams { .. }), "{bad}: {err}"); + let d = s.active().unwrap(); + assert!(d.doc == before && d.history.past_len() == past, "{bad}"); + assert_eq!(std::fs::read_dir(&out.0).unwrap().count(), 0, "{bad}: nothing written"); + } +} + +#[test] +fn the_params_doc_names_the_option() { + let spec = specs().into_iter().find(|c| c.id == "file.export.artboardsToFiles").unwrap(); + assert!(spec.params.contains(r#""content":"overlapping|artboard"="overlapping""#), "{}", spec.params); +} + +/// The source document's composite pixel at (x, y); Red Board sits at the canvas origin, so its +/// file pixels line up with these. +fn source_px(s: &Session, x: i32, y: i32) -> [u8; 4] { + px(&s.active().unwrap().doc, x, y) +} + +/// A mask on the board above keeps hiding what it hid when the export clips that board to its +/// rect: the board clip is added beside it instead of replacing it. +#[test] +fn a_mask_on_the_board_above_still_hides_its_part() { + let (mut s, [red, blue, _]) = session(8); + s.edit("Mask", |doc, _| { + let board = doc.layer_mut(LayerId(blue)).unwrap(); + // A canvas-wide fill reaches past the board, so the export clips the board to its rect. + let fill = Layer::new("Green", LayerContent::Fill(photocraft_doc::Fill::Solid(Color::rgb(0.0, 1.0, 0.0)))); + board.children_mut().unwrap().insert(0, fill); + let mut mask = photocraft_doc::LayerMask::reveal_all(); + mask.surface.fill_rect(Rect::new(140, 50, 160, 70), &[0.0]); + board.mask = Some(mask); + Ok(()) + }) + .unwrap(); + assert_eq!(rgb(source_px(&s, 150, 60)), WHITE, "the mask shows Blue Board's background there"); + let out = Out::new("board-mask"); + for format in ["png", "psd"] { + let f = export(&mut s, &out, red, json!({"format": format})); + for (x, y) in [(150, 60), (145, 55), (170, 60), (125, 140), (110, 50), (10, 140)] { + assert_eq!(px(&f, x, y), source_px(&s, x, y), "{format} at ({x},{y})"); + } + } +} + +/// A Normal board renders its layers on their own before they go over its background, so a +/// Multiply layer in it does not blend with that background; the export keeps the board as a +/// group of its own above the background layer instead of stacking its layers on it. +#[test] +fn a_multiply_layer_in_a_normal_board_above_does_not_blend_with_its_background() { + let (mut s, [red, blue, _]) = session(8); + s.edit("Normal", |doc, _| { + let board = doc.layer_mut(LayerId(blue)).unwrap(); + board.blend = photocraft_color::BlendMode::Normal; + if let LayerContent::Group(g) = &mut board.content { + g.artboard.as_mut().unwrap().background = photocraft_doc::ArtboardBackground::Custom(Color::rgb(0.0, 1.0, 0.0)); + } + board.children_mut().unwrap().last_mut().unwrap().blend = photocraft_color::BlendMode::Multiply; + Ok(()) + }) + .unwrap(); + assert_eq!(rgb(source_px(&s, 150, 60)), BLUE, "Blue, rendered on its own, covers the green background"); + let out = Out::new("normal-multiply"); + for format in ["png", "psd"] { + let f = export(&mut s, &out, red, json!({"format": format})); + for (x, y) in [(150, 60), (125, 35), (110, 50)] { + assert_eq!(px(&f, x, y), source_px(&s, x, y), "{format} at ({x},{y})"); + } + } +} diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index afd521e942..e1f0fc4ce2 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -980,9 +980,9 @@ fn name_param(p: &Value, cmd: &str) -> Result { /// Replace the preset of that name, or append it at the end of the list. fn upsert(s: &mut Session, preset: BrushPreset) { - match s.tools.presets.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&preset.name)) { + match std::sync::Arc::make_mut(&mut s.tools.presets).iter_mut().find(|x| x.name.eq_ignore_ascii_case(&preset.name)) { Some(x) => *x = preset, - None => s.tools.presets.push(preset), + None => std::sync::Arc::make_mut(&mut s.tools.presets).push(preset), } s.brush_presets_changed(); } @@ -1010,7 +1010,7 @@ fn presets_delete(s: &mut Session, p: &Value) -> Result { let cmd = "brush.presets.delete"; let name = name_param(p, cmd)?; let before = s.tools.presets.len(); - s.tools.presets.retain(|x| !x.name.eq_ignore_ascii_case(&name)); + std::sync::Arc::make_mut(&mut s.tools.presets).retain(|x| !x.name.eq_ignore_ascii_case(&name)); if s.tools.presets.len() == before { return Err(bad(cmd, format!("no brush preset named `{name}`"))); } @@ -1043,7 +1043,10 @@ fn presets_update(s: &mut Session, p: &Value) -> Result { Some(patch) => merge_brush(&s.tools.brush, patch, cmd)?, None => s.tools.brush.clone(), }; - let pr = s.tools.presets.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&name)).ok_or_else(|| bad(cmd, format!("no brush preset named `{name}`")))?; + let pr = std::sync::Arc::make_mut(&mut s.tools.presets) + .iter_mut() + .find(|x| x.name.eq_ignore_ascii_case(&name)) + .ok_or_else(|| bad(cmd, format!("no brush preset named `{name}`")))?; pr.brush = brush; pr.builtin = false; let (name, group) = (pr.name.clone(), pr.group.clone()); diff --git a/crates/engine/src/cmd/brush_key_cmds.rs b/crates/engine/src/cmd/brush_key_cmds.rs index 0cb6f93ff0..a76f15b868 100644 --- a/crates/engine/src/cmd/brush_key_cmds.rs +++ b/crates/engine/src/cmd/brush_key_cmds.rs @@ -263,7 +263,7 @@ mod tests { #[test] fn previous_and_next_brush_walk_the_presets_and_wrap() { let mut s = Session::new(); - s.tools.presets = vec![preset("One", "", &[], 11.0), preset("Two", "", &[], 22.0), preset("Three", "", &[], 33.0)]; + s.tools.presets = std::sync::Arc::new(vec![preset("One", "", &[], 11.0), preset("Two", "", &[], 22.0), preset("Three", "", &[], 33.0)]); s.tools.current_preset = None; let picked = |s: &Session| (s.tools.current_preset.clone().unwrap_or_default(), s.tools.brush.size); s.execute("tools.nextBrush", Value::Null).unwrap(); @@ -284,7 +284,7 @@ mod tests { [Some(","), Some("."), Some("Shift+,"), Some("Shift+.")] ); // No presets: an error, and the brush and the current preset stay as they were. - s.tools.presets.clear(); + std::sync::Arc::make_mut(&mut s.tools.presets).clear(); let (brush, current) = (s.tools.brush.clone(), s.tools.current_preset.clone()); for id in ["tools.previousBrush", "tools.nextBrush", "tools.firstBrush", "tools.lastBrush"] { assert!(s.execute(id, Value::Null).is_err(), "{id}"); diff --git a/crates/engine/src/cmd/brush_preset_cmds.rs b/crates/engine/src/cmd/brush_preset_cmds.rs index 6cfe6365c7..6e8d2e1d76 100644 --- a/crates/engine/src/cmd/brush_preset_cmds.rs +++ b/crates/engine/src/cmd/brush_preset_cmds.rs @@ -120,7 +120,7 @@ pub(crate) fn rename_at(s: &mut Session, i: usize, new: &str, cmd: &str) -> Resu if index_of(&s.tools.presets, new).is_some_and(|j| j != i) { return Err(bad(cmd, format!("a brush preset named `{new}` already exists"))); } - let pr = s.tools.presets.get_mut(i).ok_or_else(|| bad(cmd, "no such preset"))?; + let pr = std::sync::Arc::make_mut(&mut s.tools.presets).get_mut(i).ok_or_else(|| bad(cmd, "no such preset"))?; if pr.name != new { let was_current = s.tools.current_preset.as_ref().is_some_and(|c| c.eq_ignore_ascii_case(&pr.name)); pr.name = new.to_string(); @@ -153,7 +153,7 @@ fn move_preset(s: &mut Session, p: &Value) -> Result { }; let folder = folder_param(p, cmd)?; let group = group_param(p, "group", cmd)?; - let lib = &mut s.tools.presets; + let lib = std::sync::Arc::make_mut(&mut s.tools.presets); let (Some(moving), before_pr) = (lib.get(i), before.and_then(|b| lib.get(b))) else { return Err(bad(cmd, "no such preset")); }; @@ -233,7 +233,7 @@ fn move_folder(s: &mut Session, p: &Value, g: String, f: Vec, cmd: &str) None | Some(Value::Null) => None, Some(v) => Some(v.as_u64().ok_or_else(|| bad(cmd, "`index` must be a non-negative integer"))?), }; - let lib = std::mem::take(&mut s.tools.presets); + let lib = std::sync::Arc::unwrap_or_clone(std::mem::take(&mut s.tools.presets)); // Where the block sits among the other presets (its place when nothing else is in the parent). let start = lib.iter().position(|x| in_folder(x, &g, &f)).unwrap_or(0); let (block, mut rest): (Vec, Vec) = lib.into_iter().partition(|x| in_folder(x, &g, &f)); @@ -252,7 +252,7 @@ fn move_folder(s: &mut Session, p: &Value, g: String, f: Vec, cmd: &str) let tail = rest.split_off(pos.min(rest.len())); rest.extend(block); rest.extend(tail); - s.tools.presets = rest; + s.tools.presets = std::sync::Arc::new(rest); s.brush_presets_changed(); let at = subfolder_order(&s.tools.presets, &g, parent).iter().position(|x| x == leaf).unwrap_or(0); Ok(json!({ "group": g, "folder": f, "index": at })) @@ -332,7 +332,7 @@ fn move_into(s: &mut Session, p: &Value, g: String, f: Vec, dest: Dest, if deepest > MAX_FOLDER_DEPTH { return Err(bad(cmd, format!("folders can be nested at most {MAX_FOLDER_DEPTH} deep"))); } - let lib = std::mem::take(&mut s.tools.presets); + let lib = std::sync::Arc::unwrap_or_clone(std::mem::take(&mut s.tools.presets)); let (mut block, mut rest): (Vec, Vec) = lib.into_iter().partition(|x| in_folder(x, &g, &f)); for x in &mut block { let tail = rest_of(x); @@ -352,7 +352,7 @@ fn move_into(s: &mut Session, p: &Value, g: String, f: Vec, dest: Dest, let tail = rest.split_off(pos.unwrap_or(rest.len()).min(rest.len())); rest.extend(block); rest.extend(tail); - s.tools.presets = rest; + s.tools.presets = std::sync::Arc::new(rest); s.brush_presets_changed(); let folder = new_prefix.get(..new_prefix.len().saturating_sub(1)).unwrap_or_default(); let at = match &dest { @@ -382,7 +382,7 @@ fn move_group(s: &mut Session, p: &Value) -> Result { None | Some(Value::Null) => None, Some(v) => Some(v.as_u64().ok_or_else(|| bad(cmd, "`index` must be a non-negative integer"))?), }; - let lib = std::mem::take(&mut s.tools.presets); + let lib = std::sync::Arc::unwrap_or_clone(std::mem::take(&mut s.tools.presets)); let (block, mut rest): (Vec, Vec) = lib.into_iter().partition(|x| x.group == g); let order = group_order(&rest); let first = |name: &str, rest: &[BrushPreset]| rest.iter().position(|x| x.group == name).unwrap_or(rest.len()); @@ -394,7 +394,7 @@ fn move_group(s: &mut Session, p: &Value) -> Result { let tail = rest.split_off(pos.min(rest.len())); rest.extend(block); rest.extend(tail); - s.tools.presets = rest; + s.tools.presets = std::sync::Arc::new(rest); s.brush_presets_changed(); let at = group_order(&s.tools.presets).iter().position(|x| *x == g).unwrap_or(0); Ok(json!({ "group": g, "index": at })) @@ -410,7 +410,7 @@ fn rename_group(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, format!("a folder named `{new}` already exists there"))); } let depth = parent.len(); - for x in s.tools.presets.iter_mut().filter(|x| in_folder(x, &g, &f)) { + for x in std::sync::Arc::make_mut(&mut s.tools.presets).iter_mut().filter(|x| in_folder(x, &g, &f)) { if let Some(n) = x.folder.get_mut(depth) { n.clone_from(&new); } @@ -426,7 +426,7 @@ fn rename_group(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, format!("a group named `{new}` already exists"))); } if new != g { - for x in s.tools.presets.iter_mut().filter(|x| x.group == g) { + for x in std::sync::Arc::make_mut(&mut s.tools.presets).iter_mut().filter(|x| x.group == g) { x.group = new.clone(); x.builtin = false; } @@ -439,7 +439,7 @@ fn delete_group(s: &mut Session, p: &Value) -> Result { let cmd = "brush.presets.deleteGroup"; let (g, f) = target_folder(s, p, cmd)?; let before = s.tools.presets.len(); - s.tools.presets.retain(|x| !in_folder(x, &g, &f)); + std::sync::Arc::make_mut(&mut s.tools.presets).retain(|x| !in_folder(x, &g, &f)); if s.tools.current_preset.as_ref().is_some_and(|c| !s.tools.presets.iter().any(|x| x.name.eq_ignore_ascii_case(c))) { s.tools.current_preset = None; s.tools.brush_changed(); diff --git a/crates/engine/src/cmd/brush_preset_cmds/tests.rs b/crates/engine/src/cmd/brush_preset_cmds/tests.rs index eeed131bc7..5bb2b6698d 100644 --- a/crates/engine/src/cmd/brush_preset_cmds/tests.rs +++ b/crates/engine/src/cmd/brush_preset_cmds/tests.rs @@ -7,7 +7,7 @@ fn names(s: &Session, g: &str) -> Vec { fn with_groups() -> Session { let mut s = Session::new(); for (n, g) in [("A1", "Alpha"), ("A2", "Alpha"), ("A3", "Alpha"), ("B1", "Beta"), ("B2", "Beta")] { - s.tools.presets.push(BrushPreset { + std::sync::Arc::make_mut(&mut s.tools.presets).push(BrushPreset { name: n.into(), brush: Default::default(), builtin: false, @@ -119,7 +119,7 @@ fn with_folders() -> Session { let mut s = Session::new(); for (n, f) in [("S0", &[][..]), ("I1", &["Ink"][..]), ("F1", &["Ink", "Fine"][..]), ("I2", &["Ink"][..]), ("D1", &["Dry"][..])] { let folder = f.iter().map(|x| x.to_string()).collect(); - s.tools.presets.push(BrushPreset { + std::sync::Arc::make_mut(&mut s.tools.presets).push(BrushPreset { name: n.into(), brush: Default::default(), builtin: false, @@ -226,7 +226,7 @@ fn with_two_groups() -> Session { let mut s = with_folders(); for (n, f) in [("O1", &[][..]), ("B1", &["Box"][..])] { let folder = f.iter().map(|x| x.to_string()).collect(); - s.tools.presets.push(BrushPreset { + std::sync::Arc::make_mut(&mut s.tools.presets).push(BrushPreset { name: n.into(), brush: Default::default(), builtin: false, @@ -266,7 +266,7 @@ fn bad_moves_into_folders_fail_without_changes() { let mut s = with_two_groups(); // A chain 31 deep under Set/Deep. let deep: Vec = std::iter::once("Deep".to_string()).chain((0..30).map(|i| format!("d{i}"))).collect(); - s.tools.presets.push(BrushPreset { + std::sync::Arc::make_mut(&mut s.tools.presets).push(BrushPreset { name: "Z".into(), brush: Default::default(), builtin: false, @@ -274,7 +274,7 @@ fn bad_moves_into_folders_fail_without_changes() { folder: deep.clone(), captures: Default::default(), }); - s.tools.presets.push(BrushPreset { + std::sync::Arc::make_mut(&mut s.tools.presets).push(BrushPreset { name: "Y".into(), brush: Default::default(), builtin: false, @@ -314,7 +314,7 @@ fn bad_moves_into_folders_fail_without_changes() { s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink", "Fine"], "into": {"group": "Set"}})).unwrap(); assert_eq!(folder_of(&s, "F1"), ["Fine"]); // An ungrouped preset's group can't move. - s.tools.presets.push(BrushPreset { + std::sync::Arc::make_mut(&mut s.tools.presets).push(BrushPreset { name: "U".into(), brush: Default::default(), builtin: false, diff --git a/crates/engine/src/cmd/channel_cmds.rs b/crates/engine/src/cmd/channel_cmds.rs index 5fe3b4fd19..cb5ddc585a 100644 --- a/crates/engine/src/cmd/channel_cmds.rs +++ b/crates/engine/src/cmd/channel_cmds.rs @@ -23,6 +23,8 @@ use serde_json::{Value, json}; use crate::commands::CommandSpec; use crate::{DocState, EngineError, Result, Session}; +#[cfg(test)] +mod apply_image_lock_transparency_tests; #[cfg(test)] mod tests; @@ -119,6 +121,9 @@ mod targeting; mod tone_target; mod view; +#[cfg(test)] +mod apply_image_locked_layer_tests; + use calc::{apply_image, calculations}; use manage::{delete_channel, duplicate_channel, move_channel, new_channel, new_spot, options, rename_channel, set_visible}; use planes::edit_mode; diff --git a/crates/engine/src/cmd/channel_cmds/apply_image_lock_transparency_tests.rs b/crates/engine/src/cmd/channel_cmds/apply_image_lock_transparency_tests.rs new file mode 100644 index 0000000000..a026a2a15a --- /dev/null +++ b/crates/engine/src/cmd/channel_cmds/apply_image_lock_transparency_tests.rs @@ -0,0 +1,103 @@ +//! Apply Image on a layer with Lock Transparent Pixels: the lock acts as Preserve Transparency. + +use super::*; + +/// A 40 x 20 document whose layer "Top" is empty except a half-transparent green 10 x 10 square +/// at (10,5), and a second document "source" filled with 50% gray. +fn session(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 20, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Top"})).unwrap(); + s.execute("select.rect", json!({"x": 10, "y": 5, "width": 10, "height": 10, "mode": "replace"})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#00ff00", "opacity": 50})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("file.new", json!({"width": 40, "height": 20, "depth": depth, "name": "source"})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#808080"})).unwrap(); + s.set_active(0); + s +} + +fn layer(s: &Session) -> &Layer { + let d = s.active().unwrap(); + d.doc.layer(d.active_layer.unwrap()).unwrap() +} + +fn pixels(s: &Session) -> Vec { + let d = s.active().unwrap(); + layer(s).surface().unwrap().read_region(d.doc.bounds()) +} + +fn px(s: &Session, x: i32, y: i32) -> Vec { + layer(s).surface().unwrap().pixel(x, y) +} + +fn close(a: &[f32], b: &[f32]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-5) +} + +/// The layer's pixels after Apply Image with `extra` params, unlocked and with Preserve transparency. +fn preserved(depth: u32, extra: &Value) -> Vec { + let mut s = session(depth); + let mut p = json!({"source": {"document": 1}, "blending": "normal", "preserveTransparency": true}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + s.execute("image.applyImage", p).unwrap(); + pixels(&s) +} + +#[test] +fn transparency_lock_acts_as_preserve_transparency() { + for depth in [8, 16, 32] { + for extra in [json!({}), json!({"blending": "multiply"}), json!({"opacity": 50})] { + let want = preserved(depth, &extra); + let mut s = session(depth); + s.execute("layer.lockLayers", json!({"transparency": true})).unwrap(); + let mut p = json!({"source": {"document": 1}, "blending": "normal"}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + s.execute("image.applyImage", p).unwrap(); + assert!(close(&pixels(&s), &want), "{depth} bit {extra}: the lock must keep the layer's transparency"); + assert_eq!(px(&s, 30, 2), vec![0.0; 4], "{depth} bit {extra}: a transparent pixel stays transparent"); + assert!((px(&s, 15, 10)[3] - px(&session(depth), 15, 10)[3]).abs() < 1e-5, "{depth} bit {extra}: the square keeps its alpha"); + } + } +} + +#[test] +fn transparency_lock_inside_a_selection_acts_as_preserve_transparency() { + let sel = |s: &mut Session| s.execute("select.rect", json!({"x": 0, "y": 0, "width": 15, "height": 20, "mode": "replace"})).unwrap(); + let mut want = session(8); + sel(&mut want); + want.execute("image.applyImage", json!({"source": {"document": 1}, "preserveTransparency": true})).unwrap(); + let mut s = session(8); + s.execute("layer.lockLayers", json!({"transparency": true})).unwrap(); + sel(&mut s); + s.execute("image.applyImage", json!({"source": {"document": 1}})).unwrap(); + assert!(close(&pixels(&s), &pixels(&want))); + assert_eq!(px(&s, 2, 2), vec![0.0; 4]); +} + +#[test] +fn lock_stays_on_and_one_history_step_is_added() { + let mut s = session(8); + s.execute("layer.lockLayers", json!({"transparency": true})).unwrap(); + let steps = s.active().unwrap().history.past_len(); + s.execute("image.applyImage", json!({"source": {"document": 1}})).unwrap(); + assert!(layer(&s).locks.transparency, "the lock stays on"); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "one Apply Image step"); + s.undo(); + assert!(close(&pixels(&s), &pixels(&session(8))), "undo restores the layer"); +} + +#[test] +fn unlocked_layer_keeps_source_over() { + for depth in [8, 16, 32] { + let mut s = session(depth); + s.execute("image.applyImage", json!({"source": {"document": 1}, "blending": "normal"})).unwrap(); + let g = 128.0 / 255.0; + let p = px(&s, 30, 2); + assert!(p[..3].iter().all(|v| (v - g).abs() < 0.003) && (p[3] - 1.0).abs() < 1e-5, "{depth} bit: {p:?}"); + } +} diff --git a/crates/engine/src/cmd/channel_cmds/apply_image_locked_layer_tests.rs b/crates/engine/src/cmd/channel_cmds/apply_image_locked_layer_tests.rs new file mode 100644 index 0000000000..6888bb7a70 --- /dev/null +++ b/crates/engine/src/cmd/channel_cmds/apply_image_locked_layer_tests.rs @@ -0,0 +1,149 @@ +//! Apply Image on a fully locked or pixel-locked layer: it applies, and the layer keeps its +//! transparency as with Preserve transparency (#14476). + +use super::*; + +/// The spec's test document "target" (400 x 300): layer "Top" is empty except a 100 x 100 square +/// at (150,100) of 0/255/0 at alpha 128. Document "source" is 128/128/128 on the left half and +/// white on the right half. +fn session(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300, "depth": depth, "name": "target"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Top"})).unwrap(); + s.execute("select.rect", json!({"x": 150, "y": 100, "width": 100, "height": 100, "mode": "replace"})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#00ff00", "opacity": 128.0 / 255.0 * 100.0})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("file.new", json!({"width": 400, "height": 300, "depth": depth, "name": "source"})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#ffffff"})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 200, "height": 300, "mode": "replace"})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#808080"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.set_active(0); + s +} + +fn apply() -> Value { + json!({"source": {"document": 1}, "blending": "normal", "opacity": 100}) +} + +fn layer(s: &Session) -> &Layer { + let d = s.active().unwrap(); + d.doc.layer(d.active_layer.unwrap()).unwrap() +} + +fn pixels(s: &Session) -> Vec { + let d = s.active().unwrap(); + layer(s).surface().unwrap().read_region(d.doc.bounds()) +} + +fn px(s: &Session, x: i32, y: i32) -> Vec { + layer(s).surface().unwrap().pixel(x, y) +} + +fn close(a: &[f32], b: &[f32]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-5) +} + +fn lock(s: &mut Session, locks: &Value) { + s.execute("layer.setProps", json!({"locks": locks})).unwrap(); +} + +const LOCKS: [&str; 2] = [r#"{"all": true}"#, r#"{"pixels": true}"#]; + +fn locks() -> impl Iterator { + LOCKS.iter().map(|l| serde_json::from_str(l).unwrap()) +} + +#[test] +fn a_locked_layer_takes_the_image_in_one_step_and_keeps_its_transparency() { + for depth in [8, 16, 32] { + for locks in locks() { + let mut s = session(depth); + lock(&mut s, &locks); + let before = px(&s, 175, 125); + let steps = s.active().unwrap().history.past_len(); + s.execute("image.applyImage", apply()).unwrap(); + let d = s.active().unwrap(); + assert_eq!(d.history.past_len(), steps + 1, "{depth} bit {locks}: one history step"); + assert_eq!(d.history.undo_label(), Some("Apply Image"), "{depth} bit {locks}"); + assert!(!close(&px(&s, 175, 125), &before), "{depth} bit {locks}: (175,125) changes"); + assert_eq!(px(&s, 50, 50), vec![0.0; 4], "{depth} bit {locks}: (50,50) stays transparent"); + assert!((px(&s, 175, 125)[3] - before[3]).abs() < 1e-5, "{depth} bit {locks}: the square keeps its alpha"); + } + } +} + +#[test] +fn a_locked_layer_gets_the_preserve_transparency_result() { + for depth in [8, 16, 32] { + for extra in [json!({}), json!({"blending": "multiply"}), json!({"opacity": 50})] { + let with = |p: Value| { + let mut p = p; + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + p + }; + let mut want = session(depth); + let mut p = with(apply()); + p["preserveTransparency"] = json!(true); + want.execute("image.applyImage", p).unwrap(); + for locks in locks() { + let mut s = session(depth); + lock(&mut s, &locks); + s.execute("image.applyImage", with(apply())).unwrap(); + assert!(close(&pixels(&s), &pixels(&want)), "{depth} bit {locks} {extra}"); + } + } + } +} + +#[test] +fn the_locks_stay_and_other_commands_keep_refusing() { + for locks in locks() { + let mut s = session(8); + lock(&mut s, &locks); + let set = layer(&s).locks; + s.execute("image.applyImage", apply()).unwrap(); + assert_eq!(layer(&s).locks, set, "{locks}: the lock flags are unchanged"); + let after = pixels(&s); + let steps = s.active().unwrap().history.past_len(); + let fill = s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap_err().to_string(); + assert!(fill.contains("is locked"), "{locks}: Fill refuses: {fill}"); + let stroke = s.execute("paint.stroke", json!({"points": [[160, 110], [240, 190]], "size": 20})).unwrap_err().to_string(); + assert!(stroke.contains("is locked"), "{locks}: a brush stroke refuses: {stroke}"); + assert!(close(&pixels(&s), &after), "{locks}: nothing else painted"); + assert_eq!(s.active().unwrap().history.past_len(), steps, "{locks}: no more steps"); + s.undo(); + assert!(close(&pixels(&s), &pixels(&session(8))), "{locks}: undo restores the layer"); + } +} + +#[test] +fn a_lock_from_a_group_still_refuses() { + // Not measured in the reference application: keeps today's refusal, also when the layer is + // locked itself as well. + for own in [None, Some(json!({"pixels": true})), Some(json!({"all": true}))] { + let mut s = session(8); + let top = s.active().unwrap().active_layer.unwrap(); + if let Some(own) = &own { + lock(&mut s, own); + } + s.execute("layer.new.groupFromLayers", json!({})).unwrap(); + lock(&mut s, &json!({"all": true})); + s.set_active_layer(Some(top)); + let before = pixels(&s); + let err = s.execute("image.applyImage", apply()).unwrap_err().to_string(); + assert!(err.contains("is locked"), "{own:?}: {err}"); + assert!(close(&pixels(&s), &before), "{own:?}"); + } +} + +#[test] +fn an_unlocked_layer_keeps_source_over() { + let mut s = session(8); + s.execute("image.applyImage", apply()).unwrap(); + let p = px(&s, 50, 50); + let g = 128.0 / 255.0; + assert!(p[..3].iter().all(|v| (v - g).abs() < 0.003) && (p[3] - 1.0).abs() < 1e-5, "{p:?}"); +} diff --git a/crates/engine/src/cmd/channel_cmds/apply_image_preserve_tests.rs b/crates/engine/src/cmd/channel_cmds/apply_image_preserve_tests.rs new file mode 100644 index 0000000000..a7cf9a7f96 --- /dev/null +++ b/crates/engine/src/cmd/channel_cmds/apply_image_preserve_tests.rs @@ -0,0 +1,104 @@ +//! #14473: Apply Image with Preserve Transparency gives a semi-transparent pixel the full blend +//! result and keeps its alpha, as the reference application does. + +use crate::Session; +use serde_json::{Value, json}; + +/// Target "target" (document 0): white Background, layer "Top" transparent except a 0/255/0 +/// square at alpha 128 over (10,4)-(19,13). Source "source" (document 1): 128/128/128. +fn session(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 20, "depth": depth, "name": "target"})).unwrap(); + s.execute("file.new", json!({"width": 40, "height": 20, "depth": depth, "name": "source"})).unwrap(); + s.execute("edit.fill", json!({"color": "#808080"})).unwrap(); + s.set_active(0); + s.execute("layer.new.layer", json!({"name": "Top"})).unwrap(); + s.execute("select.rect", json!({"x": 10, "y": 4, "width": 10, "height": 10, "mode": "replace"})).unwrap(); + s.execute("edit.fill", json!({"color": "#00ff00", "opacity": 50})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s +} + +fn px(s: &Session, x: i32, y: i32) -> Vec { + let d = s.active().unwrap(); + d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().pixel(x, y) +} + +fn apply(s: &mut Session, extra: Value) { + let mut p = json!({"source": {"document": 1, "layer": "merged", "channel": "composite"}}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) { + p.extend(extra.clone()); + } + s.execute("image.applyImage", p).unwrap(); +} + +/// Checks RGBA in 0..=255 levels, one level of slack (the fill's 50% alpha is 127.5). +fn assert_rgba(got: &[f32], want: [f32; 4], what: &str) { + let got: Vec = got.iter().map(|v| v * 255.0).collect(); + assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() <= 1.01), "{what}: {got:?}, want {want:?}"); +} + +const GRAY: f32 = 128.0; +const HALF: f32 = 127.5; + +#[test] +fn normal_with_preserve_transparency_takes_the_source_and_keeps_alpha() { + for depth in [8, 16, 32] { + let mut s = session(depth); + apply(&mut s, json!({"blending": "normal", "preserveTransparency": true})); + assert_rgba(&px(&s, 15, 8), [GRAY, GRAY, GRAY, HALF], &format!("depth {depth}: green pixel")); + assert_rgba(&px(&s, 2, 2), [0.0; 4], &format!("depth {depth}: transparent pixel")); + } +} + +#[test] +fn multiply_with_preserve_transparency_blends_fully_and_keeps_alpha() { + for depth in [8, 16, 32] { + let mut s = session(depth); + apply(&mut s, json!({"blending": "multiply", "preserveTransparency": true})); + assert_rgba(&px(&s, 15, 8), [0.0, GRAY, 0.0, HALF], &format!("depth {depth}: green pixel")); + assert_rgba(&px(&s, 2, 2), [0.0; 4], &format!("depth {depth}: transparent pixel")); + } +} + +#[test] +fn opacity_and_selection_still_scale_the_preserved_blend() { + let mut s = session(8); + // 50% Normal: the colour moves half way to the source, the alpha stays. + apply(&mut s, json!({"blending": "normal", "opacity": 50, "preserveTransparency": true})); + assert_rgba(&px(&s, 15, 8), [64.0, 191.5, 64.0, HALF], "opacity 50"); + s.undo(); + // Outside the selection nothing changes. + s.execute("select.rect", json!({"x": 10, "y": 4, "width": 5, "height": 10, "mode": "replace"})).unwrap(); + apply(&mut s, json!({"blending": "normal", "preserveTransparency": true})); + assert_rgba(&px(&s, 12, 8), [GRAY, GRAY, GRAY, HALF], "inside the selection"); + assert_rgba(&px(&s, 17, 8), [0.0, 255.0, 0.0, HALF], "outside the selection"); +} + +#[test] +fn a_mask_still_scales_the_preserved_blend() { + let mut s = session(8); + // A 50% gray alpha channel as the mask halves the effect, like 50% opacity. + s.execute("channel.new", json!({"fill": "white"})).unwrap(); + s.execute("channel.target", json!({"channel": 0})).unwrap(); + s.execute("edit.fill", json!({"color": "#808080"})).unwrap(); + s.execute("channel.target", json!({"channel": "composite"})).unwrap(); + apply(&mut s, json!({"blending": "normal", "preserveTransparency": true, "mask": {"document": 0, "channel": 0}})); + assert_rgba(&px(&s, 15, 8), [64.0, 191.5, 64.0, HALF], "mask at 50%"); +} + +#[test] +fn without_preserve_transparency_the_results_stay() { + let mut s = session(8); + apply(&mut s, json!({"blending": "normal"})); + assert_rgba(&px(&s, 15, 8), [GRAY, GRAY, GRAY, 255.0], "normal, green pixel"); + assert_rgba(&px(&s, 2, 2), [GRAY, GRAY, GRAY, 255.0], "normal, transparent pixel"); + s.undo(); + apply(&mut s, json!({"blending": "multiply"})); + assert_rgba(&px(&s, 15, 8), [64.0, GRAY, 64.0, 255.0], "multiply, green pixel"); + assert_rgba(&px(&s, 2, 2), [GRAY, GRAY, GRAY, 255.0], "multiply, transparent pixel"); + s.undo(); + apply(&mut s, json!({"blending": "normal", "opacity": 50})); + assert_rgba(&px(&s, 15, 8), [85.0, 170.0, 85.0, 191.5], "normal 50%, green pixel"); + assert_rgba(&px(&s, 2, 2), [GRAY, GRAY, GRAY, HALF], "normal 50%, transparent pixel"); +} diff --git a/crates/engine/src/cmd/channel_cmds/calc.rs b/crates/engine/src/cmd/channel_cmds/calc.rs index 9c1d0ea6b8..7645598e03 100644 --- a/crates/engine/src/cmd/channel_cmds/calc.rs +++ b/crates/engine/src/cmd/channel_cmds/calc.rs @@ -4,6 +4,10 @@ use super::refs::{Blending, bad, doc_index, mask_plane, source, source_spec}; use super::targeting::{Target, is_channel_target, is_spot_target, target_of, target_surface}; use super::{AlphaChannel, ColorMode, EngineError, Result, SelectionMode, Session, Value, json, sel}; +#[cfg(test)] +#[path = "apply_image_preserve_tests.rs"] +mod apply_image_preserve_tests; + // --------------------------------------------------------------------------------------------- // Apply Image / Calculations @@ -55,8 +59,21 @@ pub(super) fn apply_image(s: &mut Session, p: &Value) -> Result { return Ok(()); } let id = layer.ok_or_else(|| EngineError::Other("no active layer".into()))?; + // Lock Transparent Pixels works as Preserve Transparency, ticked or not. + let preserve = preserve || doc.effective_locks(id).transparency; let fmt = doc.pixel_format(); - let surf = crate::commands::paint_surface(doc, id, &Value::Null)?; + // A fully locked or pixel-locked layer still takes the image, as in the reference + // application, and keeps its transparency as with Preserve transparency. A lock that comes + // from a group around it still refuses, through `paint_surface`. + let own = doc.layer(id).map(|l| l.locks).unwrap_or_default(); + let groups = doc.path_of(id).map_or_else(Default::default, |p| doc.locks_at(p.get(..p.len().saturating_sub(1)).unwrap_or_default())); + let locked = (own.pixels || own.all) && !(groups.pixels || groups.all); + let preserve = preserve || locked; + let surf = if locked { + doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.surface_mut().ok_or_else(|| EngineError::Other("not a pixel layer".into()))? + } else { + crate::commands::paint_surface(doc, id, &Value::Null)? + }; let sf = surf.format(); if sf != fmt { return Err(EngineError::Other("the target layer's format doesn't match the document".into())); @@ -66,11 +83,9 @@ pub(super) fn apply_image(s: &mut Session, p: &Value) -> Result { let mut v = surf.read_region(area); for (i, px) in v.chunks_exact_mut(n).enumerate() { let base_a = if sf.alpha { px[colors].clamp(0.0, 1.0) } else { 1.0 }; - let mut w = weight(i); - if preserve { - w *= base_a; - } - if w <= 0.0 { + let w = weight(i); + // Preserve Transparency leaves transparent pixels as they are. + if w <= 0.0 || (preserve && base_a <= 0.0) { continue; } // Painted over the layer like a brush: the blend only acts where the layer has @@ -85,8 +100,17 @@ pub(super) fn apply_image(s: &mut Session, p: &Value) -> Result { let k = if src_mode == ColorMode::Cmyk && sf.mode != ColorMode::Cmyk { src.get(3).map_or(1.0, |pl| tone(src_mode, pl[i])) } else { 1.0 }; let top = if src.len() > 1 { tone(src_mode, src.get(c).unwrap_or(&src[0])[i]) * k } else { src[0][i] }; let base = tone(sf.mode, *b); - let blended = top + (blending.apply(base, top) - top) * base_a; - *b = tone(sf.mode, if preserve { base + (blended - base) * w } else { (w * blended + base_a * (1.0 - w) * base) / out_a }); + // With Preserve Transparency the colour takes the full blend and only the alpha + // stays the layer's (a pixel at 50% alpha turns fully to the source in Normal). + *b = tone( + sf.mode, + if preserve { + base + (blending.apply(base, top) - base) * w + } else { + let blended = top + (blending.apply(base, top) - top) * base_a; + (w * blended + base_a * (1.0 - w) * base) / out_a + }, + ); } if sf.alpha { px[colors] = out_a; diff --git a/crates/engine/src/cmd/command_ids.txt b/crates/engine/src/cmd/command_ids.txt new file mode 100644 index 0000000000..98f1ef8901 --- /dev/null +++ b/crates/engine/src/cmd/command_ids.txt @@ -0,0 +1,1017 @@ +file.new +file.close +edit.undo +edit.redo +edit.fill +edit.clear +select.all +select.deselect +select.inverse +select.rect +layer.new.layer +layer.new.group +layer.groupLayers +layer.duplicate +layer.delete +layer.select +layer.setProps +layer.arrange.bringForward +layer.arrange.sendBackward +layer.arrange.bringToFront +layer.arrange.sendToBack +layer.createClippingMask +layer.releaseClippingMask +layer.layerMask.revealAll +layer.layerMask.hideAll +layer.layerMask.revealSelection +layer.layerMask.delete +layer.layerMask.moveTo +layer.mergeDown +layer.mergeGroup +layer.flattenImage +layer.newFillLayer.solidColor +layer.newFillLayer.gradient +layer.setAdjustment +layer.moveTo +layer.translate +image.imageRotation.flipCanvasHorizontal +image.imageRotation.flipCanvasVertical +image.imageRotation.180 +image.imageRotation.90cw +image.imageRotation.90ccw +image.adjustments.desaturate +paint.stroke +tools.setColors +tools.swapColors +tools.defaultColors +session.inspect +document.inspect +document.activate +document.move +command.list +document.pixel +layer.newAdjustmentLayer.brightnessContrast +image.adjustments.brightnessContrast +layer.newAdjustmentLayer.levels +image.adjustments.levels +layer.newAdjustmentLayer.curves +image.adjustments.curves +layer.newAdjustmentLayer.exposure +image.adjustments.exposure +layer.newAdjustmentLayer.vibrance +image.adjustments.vibrance +layer.newAdjustmentLayer.hueSaturation +image.adjustments.hueSaturation +layer.newAdjustmentLayer.colorBalance +image.adjustments.colorBalance +layer.newAdjustmentLayer.blackWhite +image.adjustments.blackWhite +layer.newAdjustmentLayer.photoFilter +image.adjustments.photoFilter +layer.newAdjustmentLayer.channelMixer +image.adjustments.channelMixer +layer.newAdjustmentLayer.invert +image.adjustments.invert +layer.newAdjustmentLayer.posterize +image.adjustments.posterize +layer.newAdjustmentLayer.threshold +image.adjustments.threshold +layer.newAdjustmentLayer.gradientMap +image.adjustments.gradientMap +layer.newAdjustmentLayer.selectiveColor +image.adjustments.selectiveColor +layer.newAdjustmentLayer.colorLookup +image.adjustments.colorLookup +layer.layerStyle.dropShadow +layer.layerStyle.innerShadow +layer.layerStyle.outerGlow +layer.layerStyle.innerGlow +layer.layerStyle.stroke +layer.layerStyle.colorOverlay +layer.layerStyle.gradientOverlay +layer.layerStyle.patternOverlay +layer.layerStyle.bevelEmboss +layer.layerStyle.satin +layer.layerStyle.replace +layer.layerStyle.makeDefault +layer.layerStyle.defaultFor +layer.layerStyle.clear +layer.layerStyle.contours.list +layer.layerStyle.contours.new +layer.layerStyle.contours.delete +layer.layerStyle.contours.load +layer.layerStyle.contours.save +layer.list +filter.blur.gaussianBlur +filter.blur.average +filter.blur.blur +filter.blur.blurMore +filter.sharpen.sharpen +filter.sharpen.sharpenMore +filter.sharpen.sharpenEdges +filter.noise.despeckle +filter.blur.boxBlur +filter.blur.motionBlur +filter.blur.radialBlur +filter.blur.surfaceBlur +filter.sharpen.unsharpMask +filter.sharpen.smartSharpen +filter.noise.addNoise +filter.noise.median +filter.noise.dustAndScratches +filter.pixelate.mosaic +filter.stylize.emboss +filter.stylize.findEdges +filter.stylize.solarize +filter.distort.twirl +filter.distort.pinch +filter.distort.spherize +filter.distort.wave +filter.distort.ripple +filter.distort.polarCoordinates +filter.other.highPass +filter.other.minimum +filter.other.maximum +filter.other.offset +filter.lastFilter +filter.pixelate.colorHalftone +filter.pixelate.crystallize +filter.pixelate.facet +filter.pixelate.fragment +filter.pixelate.mezzotint +filter.pixelate.pointillize +filter.stylize.diffuse +filter.stylize.extrude +filter.stylize.oilPaint +filter.stylize.tiles +filter.stylize.traceContour +filter.stylize.wind +filter.distort.displace +filter.distort.shear +filter.distort.zigZag +filter.render.clouds +filter.render.differenceClouds +filter.render.fibers +filter.render.lensFlare +filter.render.lightingEffects +filter.render.relight +filter.noise.reduceNoise +filter.blur.smartBlur +filter.blur.lensBlur +filter.blur.shapeBlur +filter.blurGallery.tiltShift +filter.blurGallery.irisBlur +filter.blurGallery.fieldBlur +filter.blurGallery.spinBlur +filter.blurGallery.pathBlur +filter.other.custom +filter.other.hsbHsl +filter.video.deInterlace +filter.video.ntscColors +filter.other.colorToAlpha +filter.filterGallery +filter.gallery.coloredPencil +filter.gallery.cutout +filter.gallery.dryBrush +filter.gallery.filmGrain +filter.gallery.fresco +filter.gallery.neonGlow +filter.gallery.paintDaubs +filter.gallery.paletteKnife +filter.gallery.plasticWrap +filter.gallery.posterEdges +filter.gallery.roughPastels +filter.gallery.smudgeStick +filter.gallery.sponge +filter.gallery.underpainting +filter.gallery.watercolor +filter.gallery.accentedEdges +filter.gallery.angledStrokes +filter.gallery.crosshatch +filter.gallery.darkStrokes +filter.gallery.inkOutlines +filter.gallery.spatter +filter.gallery.sprayedStrokes +filter.gallery.sumiE +filter.gallery.diffuseGlow +filter.gallery.glass +filter.gallery.oceanRipple +filter.gallery.basRelief +filter.gallery.chalkCharcoal +filter.gallery.charcoal +filter.gallery.chrome +filter.gallery.conteCrayon +filter.gallery.graphicPen +filter.gallery.halftonePattern +filter.gallery.notePaper +filter.gallery.photocopy +filter.gallery.plaster +filter.gallery.reticulation +filter.gallery.stamp +filter.gallery.tornEdges +filter.gallery.waterPaper +filter.gallery.glowingEdges +filter.gallery.craquelure +filter.gallery.grain +filter.gallery.mosaicTiles +filter.gallery.patchwork +filter.gallery.stainedGlass +filter.gallery.texturizer +gradient.fill.create +gradient.fill.set +gradient.fill.stop +gradient.fill.get +layer.fill.solidColor.set +layer.fill.pattern.set +type.create +type.edit +type.setStyle +type.rasterize +type.info +type.fonts +type.increaseSize +type.decreaseSize +type.increaseSizeMore +type.decreaseSizeMore +type.createSelection +edit.transform +select.float +select.drop +shape.create +shape.edit +shape.info +shape.rasterize +path.list +path.info +path.set +path.delete +path.transform +path.clippingPath.set +path.clippingPath.clear +path.style.copyFill +path.style.copyStroke +path.style.pasteFill +path.style.pasteStroke +path.rename +path.toSelection +path.addToSelection +path.subtractFromSelection +path.intersectWithSelection +path.toShape +select.toWorkPath +path.fill +path.stroke +layer.vectorMask.add +layer.vectorMask.fromPath +layer.vectorMask.edit +layer.vectorMask.delete +layer.rasterize.vectorMask +layer.vectorMask.revealAll +layer.vectorMask.hideAll +layer.vectorMask.currentPath +layer.vectorMask.enabled +layer.vectorMask.linked +layer.rasterize.shape +layer.combineShapes.unite +layer.combineShapes.subtractFrontShape +layer.combineShapes.intersectShapeAreas +layer.combineShapes.excludeOverlappingShapes +layer.combineShapes.mergeShapeComponents +select.convertToShape +layer.vectorMask.info +path.moveAnchors +path.moveHandle +path.bendSegment +path.convertPoint +path.addAnchor +path.deleteAnchor +path.deleteSegment +path.mergeShapeComponents +path.setOperation +select.quick +select.object +select.subject +select.refineEdge +select.focusArea +layer.removeBackground +paint.setSymmetry +paint.symmetryFromPath +paint.symmetryDisable +edit.cut +edit.copy +edit.copyMerged +edit.paste +file.newFromClipboard +edit.pasteSpecial.pasteInPlace +layer.new.layerViaCopy +layer.new.layerViaCut +layer.mergeVisible +image.autoTone +image.autoContrast +image.autoColor +edit.toggleLastState +edit.transform.again +edit.transform.againCopy +view.newGuide +view.moveGuide +view.editGuide +view.deleteGuide +view.clearGuides +view.setRulerOrigin +view.resetRulerOrigin +layer.smartObjects.exportSvg +layer.smartObjects.updateVectorSource +layer.smartObjects.updateSvg +edit.assignProfile +edit.convertToProfile +edit.colorSettings +color.profileMismatch +edit.profileInfo +view.proofSetup +view.proofColors +view.gamutWarning +brush.mixer.sample +paint.pencil +paint.mixerBrush +brush.mixer.load +brush.mixer.clean +brush.mixer.autoLoad +brush.mixer.autoClean +brush.mixer.sampleAllLayers +paint.mixerLoad +paint.colorReplacement +brush.presets.list +brush.presets.save +brush.presets.update +brush.presets.delete +brush.presets.setCurrent +brush.defineFromSelection +brush.get +tools.setBrush +brush.presets.rename +brush.presets.move +brush.presets.moveGroup +brush.presets.renameGroup +brush.presets.deleteGroup +paint.magicEraser +paint.backgroundEraser +brush.presets.importAbr +brush.presets.importImage +gradient.presets.importGrd +style.presets.importAsl +style.presets.exportAsl +actions.replace +actions.load +actions.save +actions.stopMessage +actions.menuItem +actions.photoshopStep +actions.clearAll +actions.reset +actions.undoLibrary +actions.insertMenuItem +actions.insertPath +actions.allowToolRecording +actions.recordAgain +actions.duplicate +actions.insert +actions.dialog +actions.conditional +actions.assignSet +actions.newSet +swatches.list +swatches.add +swatches.delete +swatches.rename +swatches.move +swatches.moveGroup +swatches.newGroup +swatches.renameGroup +swatches.deleteGroup +swatches.use +swatches.reset +swatches.import +swatches.export +paint.cloneStamp +paint.patternStamp +paint.healingBrush +paint.spotHealing +paint.patch +paint.contentAwareMove +paint.remove +paint.dodge +paint.burn +paint.sponge +paint.blur +paint.sharpen +paint.smudge +paint.historyBrush +paint.artHistoryBrush +paint.redEye +image.imageSize +image.canvasSize +image.crop +image.trim +image.mode.rgb +image.mode.grayscale +image.mode.cmyk +image.mode.lab +image.mode.bits8 +image.mode.bits16 +image.mode.bits32 +image.duplicate +image.perspectiveCrop +select.magicWand +select.colorRange +select.modify.border +select.modify.smooth +select.modify.expand +select.modify.contract +select.modify.feather +select.grow +select.similar +select.lasso +select.magneticLasso +select.sky +select.isolateLayers +select.transformSelection +paint.bucket +paint.gradient +edit.stroke +edit.transform.rotate180 +edit.transform.rotate90Cw +edit.transform.rotate90Ccw +edit.transform.flipHorizontal +edit.transform.flipVertical +edit.pasteSpecial.pasteInto +edit.pasteSpecial.pasteOutside +select.reselect +image.adjustments.equalize +image.revealAll +layer.new.layerFromBackground +layer.layerStyle.copyLayerStyle +layer.layerStyle.pasteLayerStyle +layer.layerStyle.hideAllEffects +layer.layerStyle.showAllEffects +layer.layerMask.enabled +layer.layerMask.linked +layer.rasterize.layer +layer.rasterize.allLayers +layer.rasterize.type +layer.rasterize.fillContent +layer.rasterize.smartObject +layer.delete.hiddenLayers +file.scripts.deleteAllEmptyLayers +layer.ungroupLayers +layer.hideLayers +layer.showLayers +layer.toggleLockTransparency +layer.showOnly +layer.new.backgroundFromLayer +file.closeAll +file.closeOthers +file.revealInFinder +file.revert +file.saveACopy +file.openAs +file.openAsSmartObject +file.approveMemory +file.placeEmbedded +file.placeLinked +file.fileInfo +file.automate.fitImage +file.automate.conditionalModeChange +file.automate.batch +file.scripts.imageProcessor +file.scripts.loadFilesIntoStack +file.scripts.flattenAllLayerEffects +file.scripts.flattenAllMasks +file.export.layersToFiles +file.export.colorLookupTables +view.newGuideLayout +view.newGuidesFromShape +view.clearCanvasGuides +file.exrParts +file.openExrParts +type.antiAlias.none +type.antiAlias.sharp +type.antiAlias.crisp +type.antiAlias.strong +type.antiAlias.smooth +type.antiAlias.windowsLcd +type.antiAlias.windows +type.orientation.horizontal +type.orientation.vertical +type.openType.standardLigatures +type.openType.contextualAlternates +type.openType.discretionaryLigatures +type.openType.swash +type.openType.oldstyle +type.openType.stylisticAlternates +type.openType.titlingAlternates +type.openType.ornaments +type.openType.ordinals +type.openType.fractions +type.openType.numerals.default +type.openType.numerals.lining +type.openType.numerals.oldstyle +type.openType.numerals.proportional +type.openType.numerals.tabular +type.openType.numerals.proportionalLining +type.openType.numerals.tabularLining +type.openType.numerals.proportionalOldstyle +type.openType.numerals.tabularOldstyle +type.createWorkPath +type.convertToShape +type.rasterizeTypeLayer +type.convertToParagraphText +type.convertToPointText +type.warpText +type.attachToPath +type.setPathPlacement +type.detachFromPath +type.updateAllTextLayers +type.replaceAllMissingFonts +type.resolveMissingFonts +type.pasteLoremIpsum +type.saveDefaultTypeStyles +type.loadDefaultTypeStyles +type.openType.stylisticSets.set1 +type.openType.stylisticSets.set2 +type.openType.stylisticSets.set3 +type.openType.stylisticSets.set4 +type.openType.stylisticSets.set5 +type.openType.stylisticSets.set6 +type.openType.stylisticSets.set7 +type.openType.stylisticSets.set8 +type.openType.stylisticSets.set9 +type.openType.stylisticSets.set10 +type.openType.stylisticSets.set11 +type.openType.stylisticSets.set12 +type.openType.stylisticSets.set13 +type.openType.stylisticSets.set14 +type.openType.stylisticSets.set15 +type.openType.stylisticSets.set16 +type.openType.stylisticSets.set17 +type.openType.stylisticSets.set18 +type.openType.stylisticSets.set19 +type.openType.stylisticSets.set20 +type.fillPath +type.characterStyle.new +type.characterStyle.duplicate +type.characterStyle.delete +type.characterStyle.rename +type.characterStyle.set +type.characterStyle.apply +type.characterStyle.redefine +type.characterStyle.clearOverride +type.characterStyle.list +type.paragraphStyle.new +type.paragraphStyle.duplicate +type.paragraphStyle.delete +type.paragraphStyle.rename +type.paragraphStyle.set +type.paragraphStyle.apply +type.paragraphStyle.redefine +type.paragraphStyle.clearOverride +type.paragraphStyle.list +edit.checkSpelling +type.insertText +type.hitTest +type.caret +type.navigate +layer.smartObjects.convertToSmartObject +filter.convertForSmartFilters +layer.smartObjects.newSmartObjectViaCopy +layer.smartObjects.rasterize +layer.smartObjects.editContents +layer.smartObjects.resetTransform +layer.smartObjects.saveContents +layer.smartObjects.replaceContents +layer.smartObjects.exportContents +layer.smartObjects.relinkToFile +layer.smartObjects.updateModifiedContent +layer.smartObjects.updateChanged +layer.smartObjects.updateAllModifiedContent +layer.smartObjects.convertToLayers +layer.smartObjects.convertToEmbedded +layer.smartObjects.embedAllLinked +layer.smartObjects.convertToLinked +layer.smartFilter.disableSmartFilters +layer.smartFilter.deleteFilterMask +layer.smartFilter.disableFilterMask +layer.smartFilter.blendingOptions +layer.smartFilter.clearSmartFilters +layer.smartFilter.setVisible +layer.smartFilter.setParams +layer.smartFilter.delete +layer.smartFilter.move +layer.smartFilter.transfer +select.allLayers +select.deselectLayers +select.findLayers +layer.selectLinkedLayers +layer.align.topEdges +layer.align.verticalCenters +layer.align.bottomEdges +layer.align.leftEdges +layer.align.horizontalCenters +layer.align.rightEdges +layer.distribute.topEdges +layer.distribute.verticalCenters +layer.distribute.bottomEdges +layer.distribute.leftEdges +layer.distribute.horizontalCenters +layer.distribute.rightEdges +layer.distribute.horizontally +layer.distribute.vertically +layer.linkLayers +layer.mergeLayers +layer.new.groupFromLayers +layer.arrange.reverse +layer.lockLayers +layer.renameLayer +layer.copyToDocument +prefs.get +prefs.set +prefs.reset +edit.preferences.general +edit.preferences.interface +edit.preferences.workspace +edit.preferences.tools +edit.preferences.historyLog +edit.preferences.fileHandling +edit.preferences.export +edit.preferences.performance +edit.preferences.scratchDisks +edit.preferences.cursors +edit.preferences.transparencyAndGamut +edit.preferences.unitsAndRulers +edit.preferences.guidesGridAndSlices +edit.preferences.plugIns +edit.preferences.type +edit.preferences.enhancedControls +edit.preferences.rawDefaults +edit.preferences.integrations +edit.keyboardShortcuts +edit.menus +edit.toolbar +edit.fade +edit.purge.undo +edit.purge.clipboard +edit.purge.histories +edit.purge.videoCache +edit.purge.all +edit.contentAwareFill +edit.deleteAndFillSelection +edit.contentAwareScale +edit.defineBrushPreset +edit.defineCustomShape +edit.findAndReplaceText +edit.presets.presetManager +edit.presets.exportImportPresets +edit.fillForeground +edit.fillBackground +edit.fillForegroundPreserve +edit.fillBackgroundPreserve +edit.fillHistory +document.sampleColor +image.detectFaces +view.colorSamplers.add +view.colorSamplers.move +view.colorSamplers.delete +view.colorSamplers.clear +view.colorSamplers.list +tools.decreaseBrushSize +tools.increaseBrushSize +tools.decreaseBrushHardness +tools.increaseBrushHardness +tools.previousBrush +tools.nextBrush +tools.firstBrush +tools.lastBrush +tools.rotateBrush +layer.stampVisible +layer.stampDown +edit.autoAlignLayers +edit.autoBlendLayers +file.automate.photomerge +file.automate.mergeToHdrPro +file.automate.cropAndStraightenPhotos +filter.lensCorrection +filter.adaptiveWideAngle +filter.cameraRaw +file.automate.lensCorrection +filter.vanishingPoint +select.saveSelection +select.loadSelection +select.editInQuickMaskMode +image.applyImage +image.calculations +channel.new +channel.newSpot +channel.duplicate +channel.delete +channel.rename +channel.move +channel.target +channel.setVisible +channel.options +channel.mergeSpot +channel.split +channel.merge +channel.list +channel.target.composite +channel.target.layerMask +select.loadLuminosity +channel.target.slot3 +channel.target.slot4 +channel.target.slot5 +channel.target.slot6 +channel.target.slot7 +channel.target.slot8 +channel.target.slot9 +image.adjustments.shadowsHighlights +image.adjustments.replaceColor +image.adjustments.matchColor +image.adjustments.hdrToning +image.adjustments.blackWhite.auto +image.adjustments.colorLookup.list +layer.layerMask.apply +layer.layerMask.fromTransparency +layer.layerMask.hideSelection +layer.maskAllObjects +layer.matting.defringe +layer.matting.removeBlackMatte +layer.matting.removeWhiteMatte +layer.matting.colorDecontaminate +layer.smartObjects.stackMode.entropy +layer.smartObjects.stackMode.kurtosis +layer.smartObjects.stackMode.maximum +layer.smartObjects.stackMode.mean +layer.smartObjects.stackMode.median +layer.smartObjects.stackMode.minimum +layer.smartObjects.stackMode.range +layer.smartObjects.stackMode.skewness +layer.smartObjects.stackMode.standardDeviation +layer.smartObjects.stackMode.summation +layer.smartObjects.stackMode.variance +layer.smartObjects.stackMode.none +layer.smartObjects.revealInFinder +layer.layerStyle.blendingOptions +layer.layerStyle.globalLight +layer.layerStyle.createLayer +layer.layerStyle.scaleEffects +layer.layerStyle.transferEffects +layer.layerContentOptions +layer.quickExportAsPng +layer.exportAs +layer.setLabelColor +layer.copyCSS +layer.xmpMetadata +image.rotation.arbitrary +image.mode.indexedColor +image.mode.colorTable +image.mode.bitmap +image.mode.duotone +image.mode.multichannel +edit.definePattern +pattern.list +pattern.rename +pattern.delete +pattern.import +pattern.export +layer.newFillLayer.pattern +brush.texturePattern +edit.transform.warp +layer.smartObjects.warp +edit.transform.splitWarpCrosswise +edit.transform.splitWarpHorizontally +edit.transform.splitWarpVertically +edit.transform.removeWarpSplit +edit.transform.warpGrid +layerComp.new +layerComp.update +layerComp.apply +layerComp.previous +layerComp.next +layerComp.delete +layerComp.reorder +layerComp.duplicate +layerComp.rename +layerComp.setComment +layerComp.setOptions +layerComp.restoreLastDocumentState +layerComp.updateWarnings +layerComp.list +file.export.layerCompsToFiles +layer.new.artboard +layer.new.artboardFromGroup +layer.new.artboardFromLayers +layer.artboard.set +view.clearSelectedArtboardGuides +layer.artboard.addBeside +file.export.artboardsToFiles +file.export.artboardsToPdf +filter.liquify +edit.puppetWarp +layer.smartObjects.puppetWarp +edit.perspectiveWarp +layer.smartObjects.perspectiveWarp +image.analysis.setMeasurementScale +image.analysis.selectDataPoints +image.analysis.recordMeasurements +image.analysis.rulerTool +image.analysis.countTool +image.analysis.placeScaleMarker +image.analysis.straightenLayer +image.analysis.info +count.add +count.remove +count.move +count.clear +count.newGroup +count.deleteGroup +count.setGroup +measurementLog.list +measurementLog.delete +measurementLog.export +notes.add +notes.set +notes.delete +notes.list +file.import.notes +type.font.favorite +type.font.library +history.undo +history.redo +history.deleteState +history.newDocument +history.newSnapshot +history.selectSnapshot +history.renameSnapshot +history.deleteSnapshot +history.options +history.stepForward +history.stepBackward +history.clear +history.setSource +history.selectState +view.proofSetup.workingCyanPlate +view.proofSetup.workingMagentaPlate +view.proofSetup.workingYellowPlate +view.proofSetup.workingBlackPlate +view.proofSetup.workingCmyPlate +view.proofSetup.legacyMacintoshRgb +view.proofSetup.colorBlindnessProtanopia +view.proofSetup.colorBlindnessDeuteranopia +view.thirtyTwoBitPreviewOptions +gradient.presets.list +gradient.presets.select +gradient.presets.stop +gradient.presets.apply +gradient.presets.new +gradient.presets.edit +gradient.presets.reset +pattern.presets.list +pattern.presets.select +pattern.presets.apply +pattern.presets.new +pattern.presets.edit +style.presets.list +style.presets.apply +style.presets.new +style.presets.edit +style.presets.reset +shape.presets.importCsh +shape.presets.list +shape.presets.place +shape.presets.new +shape.presets.edit +shape.presets.reset +tool.presets.list +tool.presets.new +tool.presets.select +tool.presets.edit +tool.presets.reset +cloneSource.list +cloneSource.select +cloneSource.set +cloneSource.resetTransform +cloneSource.overlay +document.presets.list +document.presets.get +document.presets.save +document.presets.delete +document.presets.rename +document.recent.list +document.recent.add +file.export.presets.list +file.export.presets.get +file.export.presets.save +file.export.presets.delete +file.export.presets.rename +filter.render.flame +filter.render.pictureFrame +filter.render.tree +slice.new +slice.fromGuides +slice.set +slice.promote +slice.delete +slice.divide +slice.list +layer.newLayerBasedSlice +view.lockSlices +view.clearSlices +file.export.saveForWebLegacy +file.export.exportPreferences +file.export.quickExport +file.generate.imageAssets +file.automate.contactSheetII +file.automate.createDroplet +file.automate.runDroplet +file.scripts.statistics +file.scripts.browse +file.scripts.scriptEventsManager +file.print +file.print.printers +file.print.page +file.printers +file.printOneCopy +file.package +file.export.pathsToIllustrator +edit.installedProfiles +layer.selectInRect +layer.pickAt +layer.selectAbove +layer.selectBelow +layer.selectTop +layer.selectBottom +layer.addAboveToSelection +layer.addBelowToSelection +layer.new.frame +layer.new.frameFromLayers +layer.frame.set +layer.frame.info +layer.frame.convert +layer.frame.setContent +layer.frame.fit +edit.presets.migratePresets +image.trap +timeline.create +timeline.delete +timeline.setFrame +timeline.nextFrame +timeline.previousFrame +timeline.setProps +timeline.info +layer.videoLayers.newBlankVideoLayer +layer.videoLayers.insertBlankFrame +layer.videoLayers.duplicateFrame +layer.videoLayers.deleteFrame +layer.videoLayers.restoreFrame +layer.videoLayers.restoreAllFrames +layer.videoLayers.showAlteredVideo +layer.videoLayers.rasterize +layer.rasterize.video +layer.videoLayers.newVideoLayerFromFile +layer.videoLayers.replaceFootage +layer.videoLayers.interpretFootage +layer.videoLayers.reloadFrame +file.import.videoFramesToLayers +file.export.renderVideo +jobs.list +jobs.cancel +file.import.wiaSupport +layer.rasterize.layerStyle +image.variables.define +image.variables.dataSets +image.applyDataSet +file.import.variableDataSets +file.export.dataSetsAsFiles +variables.list +plugin.list +plugin.install +plugin.remove +plugin.reload +plugin.run +layer.setExpanded +layer.setEffectsExpanded +layer.setEffectsVisible +view.layerMask +layer.toggleMaskOverlay +layer.layerMask.edit +actions.setHistory +actions.setPlayback +actions.move +actions.list +actions.get +actions.record +actions.stop +actions.play +actions.delete +actions.toggle +actions.rename +actions.setColor +test.panic diff --git a/crates/engine/src/cmd/command_order_tests.rs b/crates/engine/src/cmd/command_order_tests.rs new file mode 100644 index 0000000000..74ef47ab97 --- /dev/null +++ b/crates/engine/src/cmd/command_order_tests.rs @@ -0,0 +1,35 @@ +use super::{SPECS, command_specs}; + +/// Menus, the Command Palette and the automation docs list commands in registry order, so the +/// order is part of the behaviour. `command_ids.txt` pins it; regenerate the file from main when +/// rebasing, adding each new command's id after its predecessor. With `PHOTOCRAFT_WRITE_COMMAND_IDS` +/// set, the test writes the file from the registry instead; review the diff before committing it. +const HINT: &str = "\nadd the id to src/cmd/command_ids.txt, or run this test with PHOTOCRAFT_WRITE_COMMAND_IDS=1 and review the diff"; + +#[test] +fn registered_command_ids_keep_their_order() { + let ids: Vec<&str> = command_specs().iter().map(|c| c.id).collect(); + if std::env::var_os("PHOTOCRAFT_WRITE_COMMAND_IDS").is_some() { + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/src/cmd/command_ids.txt"); + std::fs::write(path, ids.iter().map(|id| format!("{id}\n")).collect::()).expect("write command_ids.txt"); + return; + } + let expected: Vec<&str> = include_str!("command_ids.txt").lines().collect(); + if let Some(i) = ids.iter().zip(&expected).position(|(a, b)| a != b) { + panic!("command {i} is {} where {} was registered{}{HINT}", ids[i], expected[i], fragment_of(i)); + } + assert_eq!(ids.len(), expected.len(), "the number of registered commands changed{}{HINT}", fragment_of(ids.len().min(expected.len()))); +} + +/// Names the fragment that registers command `index`, for the failure message. +fn fragment_of(index: usize) -> String { + let mut first = 0; + for (name, specs) in SPECS { + let len = specs().len(); + if index < first + len { + return format!(" (fragment `{name}`, commands {first}..{})", first + len); + } + first += len; + } + String::new() +} diff --git a/crates/engine/src/cmd/edit_menu_cmds.rs b/crates/engine/src/cmd/edit_menu_cmds.rs index a78e39e49b..3dcbfd634c 100644 --- a/crates/engine/src/cmd/edit_menu_cmds.rs +++ b/crates/engine/src/cmd/edit_menu_cmds.rs @@ -314,9 +314,9 @@ fn export_import(s: &mut Session, p: &Value) -> Result { // absurd tree). b.folder.retain(|f| !f.trim().is_empty()); b.folder.truncate(crate::brush_preset_cmds::MAX_FOLDER_DEPTH); - match s.tools.presets.iter_mut().find(|x| x.name == b.name) { + match std::sync::Arc::make_mut(&mut s.tools.presets).iter_mut().find(|x| x.name == b.name) { Some(x) => *x = b, - None => s.tools.presets.push(b), + None => std::sync::Arc::make_mut(&mut s.tools.presets).push(b), } nb += 1; } diff --git a/crates/engine/src/cmd/edit_menu_cmds/presets.rs b/crates/engine/src/cmd/edit_menu_cmds/presets.rs index abc3a61172..9a73f086db 100644 --- a/crates/engine/src/cmd/edit_menu_cmds/presets.rs +++ b/crates/engine/src/cmd/edit_menu_cmds/presets.rs @@ -114,7 +114,7 @@ pub(super) fn preset_manager(s: &mut Session, p: &Value) -> Result { } "delete" => match kind.as_str() { "brushes" => { - let gone = s.tools.presets.remove(i); + let gone = std::sync::Arc::make_mut(&mut s.tools.presets).remove(i); crate::brush_cmds::forget_deleted_preset(s, &gone.name); } "patterns" => drop(s.patterns.items.remove(i)), @@ -123,7 +123,7 @@ pub(super) fn preset_manager(s: &mut Session, p: &Value) -> Result { "move" => { let to = p.get("to").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "missing `to`"))? as usize; match kind.as_str() { - "brushes" => crate::move_item(&mut s.tools.presets, i, to), + "brushes" => crate::move_item(std::sync::Arc::make_mut(&mut s.tools.presets), i, to), "patterns" => crate::move_item(&mut s.patterns.items, i, to), _ => crate::move_item(&mut s.edit_state.custom_shapes, i, to), }; diff --git a/crates/engine/src/cmd/history_source_cmds.rs b/crates/engine/src/cmd/history_source_cmds.rs index 4c85903740..bc2b44229b 100644 --- a/crates/engine/src/cmd/history_source_cmds.rs +++ b/crates/engine/src/cmd/history_source_cmds.rs @@ -86,19 +86,40 @@ fn parse(st: &DocState, p: &Value, cmd: &str) -> Result> { /// Photoshop refuses too, "the current canvas size does not match that of the history state" /// (its message as users report it; Adobe's help doesn't document the case). pub(crate) fn paint_source(st: &DocState, p: &Value, cmd: &str) -> Result> { + checked_source(st, p, cmd)?.map_err(|why| { + EngineError::Other(match why { + SourceRefusal::NoSource => "the History Brush source was deleted: set a new source in the History panel".into(), + SourceRefusal::CanvasSize { source } => format!( + "the current canvas size ({}×{}) does not match that of the History Brush source ({}×{}): set a source of this size in the History panel", + st.doc.size.width, st.doc.size.height, source.width, source.height + ), + }) + }) +} + +/// Why [`checked_source`] found no source to paint from, so each tool can word it (#12638). +#[derive(Debug)] +pub(crate) enum SourceRefusal { + /// No `state` or `snapshot` passed, and the History panel's source was deleted. + NoSource, + /// The source has another canvas size than the document. + CanvasSize { source: photocraft_geom::Size }, +} + +/// [`paint_source`] with the refusal left to the caller: bad params and a `state` or `snapshot` +/// that is gone are errors, the two refusals the tools word themselves are the inner `Err`. +pub(crate) fn checked_source(st: &DocState, p: &Value, cmd: &str) -> Result, SourceRefusal>> { let doc = match parse(st, p, cmd)? { Some(src) => source_of(st, src).ok_or_else(|| EngineError::Other("that history state or snapshot is gone".into()))?, - None => source(st) - .and_then(|src| source_of(st, src)) - .ok_or_else(|| EngineError::Other("the History Brush source was deleted: set a new source in the History panel".into()))?, + None => match source(st).and_then(|src| source_of(st, src)) { + Some(doc) => doc, + None => return Ok(Err(SourceRefusal::NoSource)), + }, }; if doc.size != st.doc.size { - return Err(EngineError::Other(format!( - "the current canvas size ({}×{}) does not match that of the History Brush source ({}×{}): set a source of this size in the History panel", - st.doc.size.width, st.doc.size.height, doc.size.width, doc.size.height - ))); + return Ok(Err(SourceRefusal::CanvasSize { source: doc.size })); } - Ok(doc) + Ok(Ok(doc)) } /// The History Brush's refusals after Image › Mode, with Photoshop's alert texts (#12842): only diff --git a/crates/engine/src/cmd/perspective_crop_cmds.rs b/crates/engine/src/cmd/perspective_crop_cmds.rs index 161fa35e70..bed7292739 100644 --- a/crates/engine/src/cmd/perspective_crop_cmds.rs +++ b/crates/engine/src/cmd/perspective_crop_cmds.rs @@ -8,12 +8,15 @@ //! Background over the background colour where the quad reaches past the image, and pixels outside //! the quad are deleted (Photoshop's Perspective Crop has no Delete Cropped Pixels option). //! -//! Type, shape, fill and smart object layers are rasterized first: a projective map has no -//! editable equivalent for them. Vector masks, paths, notes, slices and guides follow the affine -//! map closest to the homography (exact when the quad is a parallelogram). +//! A document holding a type layer or a smart object anywhere, and a Bitmap mode document, are +//! refused with the tool's alerts ([`UNSUPPORTED_LAYERS_ERROR`] and [`BITMAP_MODE_ERROR`], #11799) +//! before anything is rasterized or warped, so the document stays exactly as it was. Shape and fill +//! layers are rasterized first: a projective map has no editable equivalent for them (keeping them +//! live is #11800). Vector masks, paths, notes, slices and guides follow the affine map closest to +//! the homography (exact when the quad is a parallelogram). use photocraft_algo::transform::{Homography, Interp, convex_quad_any_winding, quad_free_size, quad_size, quad_to_rect, warp_surface_clipped}; -use photocraft_color::PixelFormat; +use photocraft_color::{ColorMode, PixelFormat}; use photocraft_doc::{Document, Layer, LayerContent, LayerId, Size}; use photocraft_geom::{Affine, Rect}; use photocraft_raster::Surface; @@ -31,6 +34,34 @@ const MAX_COORD: f64 = 1e7; /// (#11977). const MAX_RESOLUTION: f64 = 29_999.999; +/// The reference's alert when the document holds a layer the tool can't map (#11799): an alert with +/// only an OK button on the tool's first press. The UI shows this text through `tl!` (English is +/// the catalog source); the command returns it as its error. +pub const UNSUPPORTED_LAYERS_ERROR: &str = "Could not use the perspective crop tool because the image contains unsupported layers types."; +/// The reference's alert for a Bitmap mode document (#11799), shown the same way. +pub const BITMAP_MODE_ERROR: &str = + "Could not use the perspective crop tool because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +/// Does `doc` hold a layer the perspective crop can't map: a type layer or a smart object, anywhere +/// in it - visible or hidden, active or not, also inside a group (#11799)? The alert is about the +/// document, not the targeted layer. Shape, fill, adjustment, pixel and group layers do not refuse +/// it (measured); keeping shape and fill layers live is #11800. +pub fn has_unsupported_layers(doc: &Document) -> bool { + doc.walk().iter().any(|(_, _, l)| matches!(l.content, LayerContent::Text(_) | LayerContent::Smart(_))) +} + +/// The alert `doc` gets instead of a perspective crop, or `None` when the crop can go through +/// (#11799). The text is exactly what `image.perspectiveCrop` answers with, so the tool can refuse +/// the press with what the command would later refuse. Bitmap is checked first: converting to +/// Bitmap flattens the document (`mode_cmds`), so a Bitmap document never holds a type layer or a +/// smart object and the order is not observable. +pub fn refusal(doc: &Document) -> Option<&'static str> { + if doc.mode == ColorMode::Bitmap { + return Some(BITMAP_MODE_ERROR); + } + has_unsupported_layers(doc).then_some(UNSUPPORTED_LAYERS_ERROR) +} + fn bad(msg: impl Into) -> EngineError { EngineError::BadParams { cmd: CMD.into(), msg: msg.into() } } @@ -224,12 +255,15 @@ fn perspective_crop(s: &mut Session, p: &Value) -> Result { let res = resolution(p)?; let interp = interpolation(p)?; let d = s.active().ok_or(EngineError::NoDocument)?; + // #11799: what the reference answers with an alert, it answers before it touches anything: no + // rasterization, no warp, no history step. The tool shows the same text on the press. + if let Some(msg) = refusal(&d.doc) { + return Err(EngineError::Other(msg.into())); + } crate::image_cmds::check_resample_budget(CMD, &d.doc, w, h, "")?; - let rasterize = d - .doc - .walk() - .iter() - .any(|(_, _, l)| matches!(l.content, LayerContent::Text(_) | LayerContent::Shape(_) | LayerContent::Fill(_) | LayerContent::Smart(_))); + // A type layer or a smart object can't get here (they are refused above), so only shape and + // fill layers are ever rasterized (#11800 is about keeping those live). + let rasterize = d.doc.walk().iter().any(|(_, _, l)| matches!(l.content, LayerContent::Shape(_) | LayerContent::Fill(_))); let map = quad_to_rect(&q, f64::from(w), f64::from(h)).ok_or_else(|| bad("the corners don't define a perspective"))?; let bg = s.tools.background; // The Color Sampler points follow their pixels through the homography, which the edit's @@ -263,7 +297,7 @@ pub fn specs() -> Vec { label: "Perspective Crop", menu: &[], shortcut: None, - params: r##"{"corners":[[x,y],[x,y],[x,y],[x,y]] (top-left, top-right, bottom-right, bottom-left; a convex quad, document px),"width":px,"height":px,"resolution":ppi,"interpolation":"bicubic|bilinear|nearest"="bicubic"} → {width,height,resolution,corners} (the quad is mapped onto an upright width x height canvas, all layers, one undo step; no width/height: the rectangle the quad shows in perspective, one alone keeps its proportions; type, shape, fill and smart object layers are rasterized)"##, + params: r##"{"corners":[[x,y],[x,y],[x,y],[x,y]] (top-left, top-right, bottom-right, bottom-left; a convex quad, document px),"width":px,"height":px,"resolution":ppi,"interpolation":"bicubic|bilinear|nearest"="bicubic"} → {width,height,resolution,corners} (the quad is mapped onto an upright width x height canvas, all layers, one undo step; no width/height: the rectangle the quad shows in perspective, one alone keeps its proportions; shape and fill layers are rasterized; refused with the tool's alert, and nothing changes: a document holding a type layer or a smart object anywhere, hidden or inside a group included, answers "Could not use the perspective crop tool because the image contains unsupported layers types.", a Bitmap mode document "Could not use the perspective crop tool because it does not work with Bitmap images (convert image to Grayscale mode to edit).")"##, enabled: has_doc, run: perspective_crop, journal: true, diff --git a/crates/engine/src/cmd/perspective_crop_refuse_tests.rs b/crates/engine/src/cmd/perspective_crop_refuse_tests.rs new file mode 100644 index 0000000000..03d556b7e5 --- /dev/null +++ b/crates/engine/src/cmd/perspective_crop_refuse_tests.rs @@ -0,0 +1,205 @@ +//! #11799: the Perspective Crop refuses a document that holds a type layer or a smart object, and +//! a Bitmap mode document, with the reference application's alerts, before anything is rasterized +//! or warped. Nothing about the document changes on a refusal: no history step, no warped pixels, +//! and the other layers keep their kind. +//! +//! Measured (issue #11799): the alert fires for the *document*, not the active layer, so a type +//! layer or a smart object counts wherever it sits - visible or hidden, active or not, also inside +//! a group. A Levels adjustment layer, a Color Fill layer, a rectangle shape layer, a group, a +//! mask, a style, a locked and a hidden layer do not trigger it: those documents still crop. +//! Keeping shape and fill layers live instead of rasterizing them is #11800, so this file pins +//! only that they still crop. + +use photocraft_doc::{Color, ColorMode, Document, Fill, Group, Layer, LayerContent, SampleType, ShapeLayer, Size, SmartObject, SmartSource, TextLayer}; +use photocraft_geom::{Affine, Rect}; +use photocraft_raster::Surface; +use serde_json::{Value, json}; + +use crate::Session; + +/// What the reference shows (an alert with one OK button) for a type layer or a smart object. +const UNSUPPORTED: &str = "Could not use the perspective crop tool because the image contains unsupported layers types."; +/// What it shows for a Bitmap mode document. +const NOT_BITMAP: &str = "Could not use the perspective crop tool because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +const CMD: &str = "image.perspectiveCrop"; +/// A skewed quad on the 160 x 120 fixture, and the upright output it is mapped onto. +const QUAD: [[f64; 2]; 4] = [[30.0, 12.0], [140.0, 25.0], [128.0, 110.0], [14.0, 95.0]]; + +fn crop_params() -> Value { + json!({"corners": QUAD, "width": 100, "height": 80}) +} + +fn rgb_format() -> photocraft_color::PixelFormat { + Document::with_background("f", Size::new(2, 2), ColorMode::Rgb, SampleType::U8, Color::WHITE).pixel_format() +} + +/// 160 x 120 RGB/8 with a white Background and `extra` on top, in a fresh session: nothing has +/// been edited yet, so any history step the crop records shows up as `past_len() > 0`. +fn session(extra: Vec) -> Session { + let mut doc = Document::with_background("refuse", Size::new(160, 120), ColorMode::Rgb, SampleType::U8, Color::WHITE); + for l in extra { + doc.insert_above(None, l); + } + let mut s = Session::new(); + s.add_document(doc, None); + s +} + +/// A type layer reading "Hello", visible or hidden. +fn type_layer(visible: bool) -> Layer { + let mut l = Layer::new("Hello", LayerContent::Text(TextLayer { text: "Hello".into(), ..Default::default() })); + l.visible = visible; + l +} + +/// A smart object with a red cache and a linked source, visible or hidden. +fn smart_layer(visible: bool) -> Layer { + let mut cache = Surface::new(rgb_format()); + cache.fill_rect(Rect::from_xywh(20, 20, 60, 40), &[1.0, 0.0, 0.0, 1.0]); + let mut l = Layer::new("Photo", LayerContent::Smart(SmartObject::new(SmartSource::Linked { path: "photo.psd".into() }, Affine::IDENTITY, Some(cache)))); + l.visible = visible; + l +} + +/// A red rectangle shape layer: what the crop rasterizes today alongside a type layer, so a +/// refusal that comes before the rasterize leaves it a shape. +fn shape_layer() -> Layer { + let path = photocraft_vector::shapes::rect(20.0, 20.0, 40.0, 30.0); + Layer::new("Rectangle 1", LayerContent::Shape(ShapeLayer { path, fill: Some(Fill::Solid(Color::rgb(0.8, 0.2, 0.1))), ..Default::default() })) +} + +/// A group holding `children`, visible or hidden. +fn group_of(children: Vec, visible: bool) -> Layer { + let mut l = Layer::new("Group 1", LayerContent::Group(Group { children, expanded: true, artboard: None, frame_stroke: None })); + l.visible = visible; + l +} + +/// Every layer as a refusal must leave it: name, kind, visibility and, for a type layer, its text. +type LayerRecord = (String, &'static str, bool, String); + +/// What a refusal must leave alone: the layers, the canvas size, the document revision, the steps. +type Snapshot = (Vec, Size, u64, usize); + +/// Every layer in `doc`, bottom to top. A refusal leaves this list exactly as it was, so it is both +/// the layer-kind and the text check. +fn fingerprint(doc: &Document) -> Vec { + doc.walk() + .iter() + .map(|(_, _, l)| { + let text = match &l.content { + LayerContent::Text(t) => t.text.clone(), + _ => String::new(), + }; + (l.name.clone(), l.content.kind_name(), l.visible, text) + }) + .collect() +} + +/// What a refusal must leave alone. +fn snapshot(s: &Session) -> Snapshot { + let d = s.active().unwrap(); + (fingerprint(&d.doc), d.doc.size, d.revision, d.history.past_len()) +} + +/// The document holds a type layer or a smart object, wherever it sits; every other layer keeps +/// its kind, because the refusal comes before `rasterize_all`. +fn assert_refused(s: &mut Session, want: &str, case: &str) { + let before = snapshot(s); + let err = s.execute(CMD, crop_params()).unwrap_err().to_string(); + assert_eq!(err, want, "{case}"); + let d = s.active().unwrap(); + assert_eq!(fingerprint(&d.doc), before.0, "{case}: layers unchanged"); + assert_eq!(d.doc.size, before.1, "{case}: canvas unchanged"); + assert_eq!(d.revision, before.2, "{case}: document unchanged"); + assert_eq!(d.history.past_len(), 0, "{case}: no history step"); +} + +/// A type layer anywhere in the document - visible, hidden, or inside a group - is the reference's +/// unsupported-layers alert, not a rasterization (#11799). +#[test] +fn a_type_layer_anywhere_refuses_the_perspective_crop() { + for (case, extra) in [ + ("visible", vec![type_layer(true), shape_layer()]), + ("hidden", vec![type_layer(false), shape_layer()]), + ("in a group", vec![group_of(vec![type_layer(true), shape_layer()], true), shape_layer()]), + ("in a hidden group", vec![group_of(vec![type_layer(true)], false), shape_layer()]), + ] { + let mut s = session(extra); + assert_refused(&mut s, UNSUPPORTED, &format!("{case} type layer")); + let d = s.active().unwrap(); + let text: Vec<&str> = d + .doc + .walk() + .iter() + .filter_map(|(_, _, l)| match &l.content { + LayerContent::Text(t) => Some(t.text.as_str()), + _ => None, + }) + .collect(); + assert_eq!(text, ["Hello"], "{case}: the type layer is still a type layer with its text"); + assert!(d.doc.walk().iter().any(|(_, _, l)| l.content.kind_name() == "Shape"), "{case}: nothing was rasterized"); + } +} + +/// The same for a smart object: visible, hidden, or inside a group. +#[test] +fn a_smart_object_anywhere_refuses_the_perspective_crop() { + for (case, extra) in [ + ("visible", vec![smart_layer(true), shape_layer()]), + ("hidden", vec![smart_layer(false), shape_layer()]), + ("in a group", vec![group_of(vec![smart_layer(false)], true), shape_layer()]), + ] { + let mut s = session(extra); + assert_refused(&mut s, UNSUPPORTED, &format!("{case} smart object")); + } +} + +/// Both at once is still one refusal with the same message, and still changes nothing. +#[test] +fn a_type_layer_and_a_smart_object_refuse_once() { + let mut s = session(vec![type_layer(false), smart_layer(true), shape_layer()]); + assert_refused(&mut s, UNSUPPORTED, "type layer and smart object"); +} + +/// A Bitmap mode document is the reference's Bitmap alert (#11799). +#[test] +fn a_bitmap_document_refuses_the_perspective_crop() { + let doc = Document::with_background("bitmap", Size::new(160, 120), ColorMode::Bitmap, SampleType::U8, Color::WHITE); + let mut s = Session::new(); + s.add_document(doc, None); + assert_refused(&mut s, NOT_BITMAP, "Bitmap document"); +} + +/// The measured rows that keep working: a document of only pixel, adjustment, Color Fill, shape +/// and group layers still crops, in one undo step (#11799). Whether the shape and the fill stay +/// live is #11800, so this pins the crop, not their kind. +#[test] +fn pixel_adjustment_fill_shape_and_group_layers_still_crop() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 500})).unwrap(); + s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap(); + s.execute("layer.newFillLayer.solidColor", json!({"color": "#3366cc"})).unwrap(); + s.execute("shape.create", json!({"kind": "rect", "rect": [200, 300, 150, 100], "fill": "#cc3333"})).unwrap(); + s.execute("layer.groupLayers", json!({"name": "G"})).unwrap(); + let before = s.active().unwrap().history.past_len(); + let r = s.execute(CMD, json!({"corners": [[100.0, 50.0], [700.0, 60.0], [690.0, 450.0], [110.0, 440.0]], "width": 600, "height": 400})).unwrap(); + assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(600), Some(400))); + assert_eq!(s.active().unwrap().doc.size, Size::new(600, 400), "the crop went through"); + assert_eq!(s.active().unwrap().history.past_len(), before + 1, "one undo step"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.size, Size::new(800, 500), "one undo restores it"); +} + +/// Only Bitmap refuses on the mode: RGB, Grayscale and CMYK documents are unaffected (#11799). +#[test] +fn rgb_grayscale_and_cmyk_documents_are_not_refused() { + for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk] { + let doc = Document::with_background("m", Size::new(160, 120), mode, SampleType::U8, Color::WHITE); + let mut s = Session::new(); + s.add_document(doc, None); + s.execute(CMD, crop_params()).unwrap(); + assert_eq!(s.active().unwrap().doc.size, Size::new(100, 80), "{mode:?} cropped"); + } +} diff --git a/crates/engine/src/cmd/preset_import_cmds.rs b/crates/engine/src/cmd/preset_import_cmds.rs index 8b866c3f89..62c786e848 100644 --- a/crates/engine/src/cmd/preset_import_cmds.rs +++ b/crates/engine/src/cmd/preset_import_cmds.rs @@ -155,7 +155,7 @@ fn add_abr_presets(s: &mut Session, p: &Value, group: String, imp: photocraft_io // in Photoshop, unless `replace` asks to drop that group's own presets first: the group name // is only the file name, and the library is outside document history (#10640). let group = if p.get("replace").and_then(Value::as_bool).unwrap_or(false) { - s.tools.presets.retain(|x| x.builtin || x.group != group); + std::sync::Arc::make_mut(&mut s.tools.presets).retain(|x| x.builtin || x.group != group); group } else { // One pass over the library, not one per numbered candidate. @@ -168,7 +168,7 @@ fn add_abr_presets(s: &mut Session, p: &Value, group: String, imp: photocraft_io preset.group.clone_from(&group); preset.name = taken.unique(&preset.name); names.push(preset.name.clone()); - s.tools.presets.push(preset); + std::sync::Arc::make_mut(&mut s.tools.presets).push(preset); } s.brush_presets_changed(); if p.get("select").and_then(Value::as_bool).unwrap_or(false) @@ -262,7 +262,7 @@ fn import_image(s: &mut Session, p: &Value) -> Result { let (v, w, h) = image_paint(&doc, cmd)?; let (brush, tw, th) = crate::brush_cmds::sampled_brush(cmd, &v, w, h)?; let name = UniqueNames::new(s.tools.presets.iter().map(|x| x.name.as_str())).unique(&name); - s.tools.presets.push(photocraft_paint::BrushPreset { + std::sync::Arc::make_mut(&mut s.tools.presets).push(photocraft_paint::BrushPreset { name: name.clone(), brush: brush.clone(), builtin: false, @@ -541,7 +541,7 @@ mod tests { // The user's own brush moved into the group. let mut own = s.tools.presets.iter().find(|p| p.group == "Kit").unwrap().clone(); own.name = "My Ink".into(); - s.tools.presets.push(own); + std::sync::Arc::make_mut(&mut s.tools.presets).push(own); let r = s.execute("brush.presets.importAbr", json!({"data": data, "group": "Kit"})).unwrap(); assert_eq!(r["group"], "Kit (2)"); let in_group = |s: &Session, g: &str| s.tools.presets.iter().filter(|p| p.group == g).count(); diff --git a/crates/engine/src/cmd/retouch_cmds.rs b/crates/engine/src/cmd/retouch_cmds.rs index 4bb8496fa5..ecc32ebbff 100644 --- a/crates/engine/src/cmd/retouch_cmds.rs +++ b/crates/engine/src/cmd/retouch_cmds.rs @@ -35,9 +35,7 @@ pub use pattern_stamp::{ }; mod periodic; mod remove; -pub use content_aware_move::{ - ContentAwarePreview, preview as content_aware_move_preview, preview_with_pixel_budget as content_aware_move_preview_with_pixel_budget, -}; +pub use content_aware_move::{ContentAwarePreview, preview as content_aware_move_preview}; pub use patch::preview as patch_preview; fn bad(cmd: &str, msg: impl Into) -> EngineError { @@ -413,9 +411,9 @@ pub fn specs() -> Vec { menu: &[], shortcut: None, params: brush_params!( - r#","state":row (a History panel row, as history.setSource),"snapshot":id (a history.newSnapshot id; default: the History panel's source, as paint.historyBrush; a source of another canvas size or colour mode is an error),"style":"tightShort|tightMedium|tightLong|looseMedium|looseLong|dab|tightCurl|looseCurl"="tightShort","area":0..100=50,"tolerance":0..100=0,"opacity":0..100=100 (overrides the common 1..100: how strongly the history state is painted; 0 changes nothing; no flow, mode is Normal)"# + r#","state":row (a History panel row, as history.setSource),"snapshot":id (a history.newSnapshot id; default: the History panel's source, as paint.historyBrush; a source of another canvas size or colour mode is an error),"style":"tightShort|tightMedium|tightLong|looseMedium|looseLong|dab|tightCurl|looseCurl"="tightShort","area":0..500=50,"tolerance":0..100=0,"opacity":0..100=100 (overrides the common 1..100: how strongly the history state is painted; 0 changes nothing; no flow, mode is Normal)"# ), - enabled: has_pixel_layer, + enabled: art_history::enabled, run: art_history::run, journal: true, }, diff --git a/crates/engine/src/cmd/retouch_cmds/art_history.rs b/crates/engine/src/cmd/retouch_cmds/art_history.rs index a38b510f3e..0622bf0ed0 100644 --- a/crates/engine/src/cmd/retouch_cmds/art_history.rs +++ b/crates/engine/src/cmd/retouch_cmds/art_history.rs @@ -163,6 +163,64 @@ fn stamp_region( } } +/// The reference application's alerts for the refusals below (#12638); a hidden target is +/// [`crate::hidden_target::ART_HISTORY_HIDDEN`]. +pub const LOCKED: &str = "Could not use the art history brush because the layer is locked."; +pub const GROUP: &str = "Could not use the art history brush because the pixels in a group cannot be edited without merging the group."; +pub const LACKS_LAYER: &str = "Could not use the art history brush because the history state lacks a corresponding layer."; +pub const CANVAS_SIZE: &str = "Could not use the art history brush because the current canvas size does not match that of the history state."; +pub const NO_SOURCE: &str = "Could not use the art history brush because no history state has been designated as the source for painting."; + +/// The command's precondition: a pixel layer, as the other retouching tools, with the alert text +/// when a group is active. +pub(super) fn enabled(s: &Session) -> std::result::Result<(), String> { + super::has_pixel_layer(s).map_err(|why| if crate::active_layer_of(s).is_ok_and(|l| l.is_group()) { GROUP.into() } else { why }) +} + +/// The targeted layer's pixels can't be painted: a group's (also one with a mask, which the +/// precondition lets through for its mask), or Lock All or Lock Image Pixels, refused with the +/// alert texts. A mask or channel target keeps the shared checks (not measured). +fn refuse_layer(s: &Session, id: Option, p: &Value) -> Result<()> { + let (Some(id), Some(st)) = (id, s.active()) else { return Ok(()) }; + let Some(layer) = st.doc.layer(id).filter(|_| pixel_target(p)) else { return Ok(()) }; + if layer.is_group() { + return Err(EngineError::Other(GROUP.into())); + } + let locks = st.doc.effective_locks(id); + if locks.all || locks.pixels { Err(EngineError::Other(LOCKED.into())) } else { Ok(()) } +} + +fn pixel_target(p: &Value) -> bool { + crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::Pixels +} + +/// The source the stroke paints from, the History Brush's (the `state` or `snapshot` passed, else +/// the History panel's source, through the shared [`super::history_source`]), refused with the +/// alert texts: no source, then another canvas size, then another colour mode or a depth but 8 +/// bits ([`refuse_format`]), then a target layer the source state lacks. A mask or channel target +/// keeps the History Brush's texts for the source refusals (not measured). +fn source_surface(s: &Session, id: Option, p: &Value) -> Result { + use crate::history_source_cmds::{SourceRefusal, checked_source, paint_source}; + let st = s.active().ok_or(EngineError::NoDocument)?; + let pixels = pixel_target(p); + let doc = if pixels { + checked_source(st, p, CMD)?.map_err(|why| { + EngineError::Other( + match why { + SourceRefusal::NoSource => NO_SOURCE, + SourceRefusal::CanvasSize { .. } => CANVAS_SIZE, + } + .into(), + ) + })? + } else { + paint_source(st, p, CMD)? + }; + refuse_format(&st.doc, &doc)?; + super::history_source(s, id, p, CMD) + .map_err(|e| if pixels && crate::channel_cmds::read_target_surface(&doc, id, p).is_err() { EngineError::Other(LACKS_LAYER.into()) } else { e }) +} + /// A source of another colour mode, then any document but an 8-bit one, refused with the reference /// application's alert texts (#12637). The 16-bit text was seen with one layer only; two layers, /// or a depth change after the source, showed "not directly editable", so that text covers every @@ -204,7 +262,8 @@ pub fn run(s: &mut Session, p: &Value) -> Result { let hardness = ranged(p, "hardness", s.tools.brush.hardness * 100.0, 0.0, 100.0)? / 100.0; let opacity = ranged(p, "opacity", 100.0, 0.0, 100.0)? / 100.0; let flow = ranged(p, "flow", 100.0, 0.0, 100.0)? / 100.0; - let area = ranged(p, "area", 50.0, 0.0, 100.0)?; + // Area takes 0..500 px, as the reference's field does (#12630). + let area = ranged(p, "area", 50.0, 0.0, 500.0)?; // Percent of the channel range; 0 (paint everywhere) is the default, as in Photoshop. let tolerance = ranged(p, "tolerance", 0.0, 0.0, 100.0)? / 100.0; let style = style_of(p)?; @@ -215,13 +274,9 @@ pub fn run(s: &mut Session, p: &Value) -> Result { } let (stroke, id) = parse_brush(s, p, CMD)?; let _ = stroke; - // The same source as the History Brush: the `state` or `snapshot` passed, else the History - // panel's source, refused after a canvas size change, then after a colour mode change (#12826) - // or at a depth other than 8 bits, as Photoshop does, before a layer missing from it. Compare - // document modes: the pixel format reads Indexed and Multichannel as RGB. - let st = s.active().ok_or(EngineError::NoDocument)?; - refuse_format(&st.doc, &*crate::history_source_cmds::paint_source(st, p, CMD)?)?; - let src_surface = super::history_source(s, id, p, CMD)?; + refuse_layer(s, id, p)?; + // Compare document modes: the pixel format reads Indexed and Multichannel as RGB (#12826). + let src_surface = source_surface(s, id, p)?; // Truncating a huge row index only changes the seed. let seed = RNG_SEED ^ p.get("state").and_then(Value::as_u64).map_or(0, |i| i as u32); let dabs = art_history::place_dabs(&pts, size, area, style, seed).map_err(|e| match e { @@ -567,3 +622,7 @@ mod art_history_mode_mismatch_tests; #[cfg(test)] #[path = "art_history_depth_tests.rs"] mod art_history_depth_tests; + +#[cfg(test)] +#[path = "art_history_refusal_tests.rs"] +mod refusal_tests; diff --git a/crates/engine/src/cmd/retouch_cmds/art_history_refusal_tests.rs b/crates/engine/src/cmd/retouch_cmds/art_history_refusal_tests.rs new file mode 100644 index 0000000000..6d18e01a89 --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/art_history_refusal_tests.rs @@ -0,0 +1,172 @@ +//! The Art History Brush's refusals use the reference application's alert texts (#12638): a +//! hidden target, Lock All or Lock Image Pixels, a group, a target layer the source state lacks, +//! another canvas size and no source. Each adds no history state and changes no pixel, and the +//! History Brush keeps its own texts. + +use serde_json::{Value, json}; + +use super::{CANVAS_SIZE, GROUP, LACKS_LAYER, LOCKED, NO_SOURCE}; +use crate::Session; +use crate::hidden_target::{ART_HISTORY_HIDDEN, HIDDEN}; + +/// An RGB document with a red "Layer 1" above the white Background, the layer active. History +/// rows: 0 Open, 1 New Layer, 2 Fill. +fn session() -> (Session, u64) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 48, "height": 32, "background": "white"})).unwrap(); + let id = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + (s, id) +} + +fn stroke(cmd: &str) -> Value { + let mut p = json!({"points": [[8, 16], [40, 16]], "size": 12, "hardness": 100}); + if cmd == "paint.artHistoryBrush" { + p["style"] = json!("tightMedium"); + } + p +} + +/// Runs `cmd` with `extra` params, expects a refusal and returns its text, checking that the +/// document and its history are unchanged. +fn refused(s: &mut Session, cmd: &str, extra: Value) -> String { + let mut p = stroke(cmd); + if let Some(map) = extra.as_object() { + for (k, v) in map { + p[k] = v.clone(); + } + } + let (doc, steps) = (s.active().unwrap().doc.clone(), s.active().unwrap().history.entries().len()); + let e = s.execute(cmd, p).unwrap_err().to_string(); + let st = s.active().unwrap(); + assert_eq!(st.history.entries().len(), steps, "{cmd}: no history state for {e}"); + for l in &doc.layers { + assert_eq!(st.doc.layer(l.id).and_then(|n| n.surface()), l.surface(), "{cmd}: no pixel changes for {e}"); + } + e +} + +#[test] +fn a_hidden_target_layer() { + let (mut s, id) = session(); + s.execute("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + assert_eq!(refused(&mut s, "paint.artHistoryBrush", json!({})), ART_HISTORY_HIDDEN); + assert_eq!(refused(&mut s, "paint.historyBrush", json!({})), HIDDEN); +} + +#[test] +fn lock_all_or_lock_image_pixels() { + for key in ["all", "pixels"] { + let (mut s, id) = session(); + s.execute("layer.setProps", json!({"layer": id, "locks": {key: true}})).unwrap(); + assert_eq!(refused(&mut s, "paint.artHistoryBrush", json!({})), LOCKED, "{key}"); + // Row 1 holds Layer 1, so the History Brush gets as far as the lock. + let e = refused(&mut s, "paint.historyBrush", json!({"state": 1})); + assert!(e.contains("Could not complete your request because the layer \"Layer 1\" is locked"), "{key}: {e}"); + } +} + +/// Lock Transparent Pixels was not measured: it still paints, as before. +#[test] +fn lock_transparent_pixels_still_paints() { + let (mut s, id) = session(); + s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + s.execute("layer.setProps", json!({"layer": id, "locks": {"transparency": true}})).unwrap(); + s.execute("paint.artHistoryBrush", json!({"points": [[8, 16], [40, 16]], "size": 12, "hardness": 100, "state": 2})).unwrap(); +} + +#[test] +fn a_group_is_active() { + let (mut s, _) = session(); + s.execute("layer.groupLayers", json!({})).unwrap(); + let e = refused(&mut s, "paint.artHistoryBrush", json!({})); + assert!(e.contains(GROUP), "{e}"); + assert!(!s.is_enabled("paint.artHistoryBrush")); + assert_eq!(s.disabled_reason("paint.artHistoryBrush").as_deref(), Some(GROUP)); + let e = refused(&mut s, "paint.historyBrush", json!({})); + assert!(e.contains("not a pixel layer") && !e.contains("art history"), "{e}"); +} + +/// Row 1 (New Layer) holds the Background and Layer 1; a second layer added after it is missing. +#[test] +fn the_source_state_lacks_the_target_layer() { + let (mut s, _) = session(); + s.execute("layer.new.layer", json!({})).unwrap(); + assert_eq!(refused(&mut s, "paint.artHistoryBrush", json!({"state": 1})), LACKS_LAYER); + // The History panel's source too. + s.execute("history.setSource", json!({"state": 1})).unwrap(); + assert_eq!(refused(&mut s, "paint.artHistoryBrush", json!({})), LACKS_LAYER); + let e = refused(&mut s, "paint.historyBrush", json!({})); + assert!(e.contains("the target did not exist"), "{e}"); +} + +#[test] +fn the_canvas_size_changed() { + let (mut s, _) = session(); + s.execute("image.canvasSize", json!({"width": 60, "height": 32, "anchor": "topLeft"})).unwrap(); + assert_eq!(refused(&mut s, "paint.artHistoryBrush", json!({})), CANVAS_SIZE); + assert_eq!(refused(&mut s, "paint.artHistoryBrush", json!({"state": 1})), CANVAS_SIZE); + let e = refused(&mut s, "paint.historyBrush", json!({})); + assert!(e.contains("does not match that of the History Brush source (48×32)"), "{e}"); +} + +#[test] +fn no_source_is_set() { + let (mut s, _) = session(); + let snap = s.execute("history.newSnapshot", json!({})).unwrap()["snapshot"].clone(); + s.execute("history.setSource", json!({"snapshot": snap})).unwrap(); + s.execute("history.deleteSnapshot", json!({"snapshot": snap})).unwrap(); + assert_eq!(refused(&mut s, "paint.artHistoryBrush", json!({})), NO_SOURCE); + let e = refused(&mut s, "paint.historyBrush", json!({})); + assert!(e.contains("the History Brush source was deleted"), "{e}"); +} + +/// No source and another canvas size: the missing source is reported, as before. +#[test] +fn no_source_comes_before_the_canvas_size() { + let (mut s, _) = session(); + let snap = s.execute("history.newSnapshot", json!({})).unwrap()["snapshot"].clone(); + s.execute("history.setSource", json!({"snapshot": snap})).unwrap(); + s.execute("history.deleteSnapshot", json!({"snapshot": snap})).unwrap(); + s.execute("image.canvasSize", json!({"width": 60, "height": 32, "anchor": "topLeft"})).unwrap(); + assert_eq!(refused(&mut s, "paint.artHistoryBrush", json!({})), NO_SOURCE); +} + +/// The checks don't stop a stroke that may paint: row 2 is the red layer, now blue. +#[test] +fn a_valid_stroke_still_paints() { + let (mut s, _) = session(); + s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + let steps = s.active().unwrap().history.entries().len(); + s.execute("paint.artHistoryBrush", json!({"points": [[8, 16], [40, 16]], "size": 12, "hardness": 100, "state": 2})).unwrap(); + assert_eq!(s.active().unwrap().history.entries().len(), steps + 1); +} + +/// A group with a mask passes the precondition (for its mask), but its pixels are still refused. +#[test] +fn a_group_with_a_mask_and_its_pixels_targeted() { + let (mut s, _) = session(); + s.execute("layer.groupLayers", json!({})).unwrap(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + assert_eq!(refused(&mut s, "paint.artHistoryBrush", json!({"target": "pixels"})), GROUP); +} + +/// A mask target was not measured: a hidden layer, no source and another canvas size keep the +/// History Brush's texts. +#[test] +fn a_mask_target_keeps_todays_texts() { + let (mut s, id) = session(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + let mask = json!({"target": "mask"}); + s.execute("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + assert_eq!(refused(&mut s, "paint.artHistoryBrush", mask.clone()), HIDDEN); + s.execute("layer.setProps", json!({"layer": id, "visible": true})).unwrap(); + s.execute("image.canvasSize", json!({"width": 60, "height": 32, "anchor": "topLeft"})).unwrap(); + let e = refused(&mut s, "paint.artHistoryBrush", mask.clone()); + assert!(e.contains("does not match that of the History Brush source"), "{e}"); + let snap = s.execute("history.newSnapshot", json!({})).unwrap()["snapshot"].clone(); + s.execute("history.setSource", json!({"snapshot": snap})).unwrap(); + s.execute("history.deleteSnapshot", json!({"snapshot": snap})).unwrap(); + let e = refused(&mut s, "paint.artHistoryBrush", mask); + assert!(e.contains("the History Brush source was deleted"), "{e}"); +} diff --git a/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs b/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs index 89eca9973a..fa7b82ad72 100644 --- a/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs +++ b/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs @@ -700,7 +700,7 @@ pub fn preview(s: &Session, p: &Value) -> Result { } /// Prepare a preview with a bound on the number of pixels solved at full resolution. -pub fn preview_with_pixel_budget(s: &Session, p: &Value, max_pixels: u64) -> Result { +pub(crate) fn preview_with_pixel_budget(s: &Session, p: &Value, max_pixels: u64) -> Result { let captured = crate::channel_cmds::inject_target(s, CMD, p.clone()); let p = &captured; let plan = plan(s, p, PREVIEW_MARGIN)?; diff --git a/crates/engine/src/cmd/retouch_cmds/tests.rs b/crates/engine/src/cmd/retouch_cmds/tests.rs index c1096a7135..0661de7203 100644 --- a/crates/engine/src/cmd/retouch_cmds/tests.rs +++ b/crates/engine/src/cmd/retouch_cmds/tests.rs @@ -2187,6 +2187,11 @@ live_coordinate_regression!( fn live_dodge_matches_the_commit_across_cells() { let mut s = session(200, 90, 32, "rgb"); paint_layer(&mut s, texture); + // About the cells' summation order, not smoothing: the live stroke is compared before its + // release, and with the brush's default smoothing lag (#11888) the commit's end catch-up runs + // from the trailing brush along most of the last segment. Live against commit with smoothing + // is the hand-off tests' "smoothing" case. + s.tools.brush.smoothing.enabled = false; let all = [[10.0, 40.0], [100.0, 60.0], [180.0, 40.0], [60.0, 30.0], [150.0, 70.0]]; let pts = |v: &[[f64; 2]]| v.iter().map(|q| StrokePoint::new(q[0], q[1], 1.0)).collect::>(); let opts = |p: &[[f64; 2]]| json!({"points": p, "size": 40, "hardness": 30, "exposure": 60, "range": "midtones"}); @@ -2318,7 +2323,7 @@ fn live_dab_batches_match_the_accumulating_renderer() { }); let id = s.active().unwrap().active_layer.unwrap(); let pre = s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().clone(); - for case in ["soft", "hard", "sampled", "dynamics", "smoothing"] { + for case in ["soft", "hard", "sampled", "dynamics", "smoothing", "smoothing_catch_up"] { s.tools.brush = BrushSettings::default(); match case { "sampled" => s.tools.brush.tip = TipShape::Sampled(GrayTile::from_fn(9, 7, |x, y| ((x * 3 + y) % 11) as f32 / 10.0)), @@ -2339,6 +2344,10 @@ fn live_dab_batches_match_the_accumulating_renderer() { b.texture.pattern = photocraft_paint::Pattern::Tile(GrayTile::from_fn(3, 3, |x, y| (x + y) as f32 / 4.0)); } "smoothing" => s.tools.brush.smoothing.amount = 0.65, + "smoothing_catch_up" => { + s.tools.brush.smoothing.amount = 0.65; + s.tools.brush.smoothing.catch_up_on_end = true; + } _ => {} } let points = [ diff --git a/crates/engine/src/cmd/table.rs b/crates/engine/src/cmd/table.rs new file mode 100644 index 0000000000..c784954c76 --- /dev/null +++ b/crates/engine/src/cmd/table.rs @@ -0,0 +1,8 @@ +//! The command table's fragments, one directory per owner: the crate whose items the commands +//! call. Each directory moves whole into its crate; `SPECS` in `cmd.rs` fixes the order. + +pub(crate) mod core; +pub(crate) mod image; +pub(crate) mod model; +pub(crate) mod paint; +pub(crate) mod store; diff --git a/crates/engine/src/cmd/table/core.rs b/crates/engine/src/cmd/table/core.rs new file mode 100644 index 0000000000..d5311b7dcb --- /dev/null +++ b/crates/engine/src/cmd/table/core.rs @@ -0,0 +1,5 @@ +pub(crate) mod edit_menu; +pub(crate) mod file_menu; +pub(crate) mod queries; +pub(crate) mod select_menu; +pub(crate) mod tools; diff --git a/crates/engine/src/cmd/table/core/edit_menu.rs b/crates/engine/src/cmd/table/core/edit_menu.rs new file mode 100644 index 0000000000..a027818f5e --- /dev/null +++ b/crates/engine/src/cmd/table/core/edit_menu.rs @@ -0,0 +1,9 @@ +use crate::cmd::{CommandSpec, can_redo, can_undo, json}; + +/// Edit menu: Undo and Redo. +pub(crate) fn specs() -> Vec { + vec![ + cmd!("edit.undo", "Undo", ["Edit"], Some("Cmd+Z"), "{}", can_undo, |s, _| Ok(json!(s.undo()))), + cmd!("edit.redo", "Redo", ["Edit"], Some("Cmd+Shift+Z"), "{}", can_redo, |s, _| Ok(json!(s.redo()))), + ] +} diff --git a/crates/engine/src/cmd/table/core/file_menu.rs b/crates/engine/src/cmd/table/core/file_menu.rs new file mode 100644 index 0000000000..00126ebc8d --- /dev/null +++ b/crates/engine/src/cmd/table/core/file_menu.rs @@ -0,0 +1,28 @@ +use crate::cmd::{CommandSpec, EngineError, Value, bad, has_doc}; + +/// File menu: Close. +pub(crate) fn specs() -> Vec { + vec![cmd!( + "file.close", + "Close", + ["File"], + Some("Cmd+W"), + r##"{"document":index?,"save":"discard|ask"|false="discard"} (false means discard; ask refuses to close a changed document in headless playback)"##, + has_doc, + |s, p| { + let i = p.get("document").and_then(Value::as_u64).map(|v| v as usize).or(s.active_index()).ok_or(EngineError::NoDocument)?; + match p.get("save").filter(|v| !v.is_null()) { + Some(v) if v == "ask" && s.documents().get(i).ok_or(EngineError::NoDocument)?.is_dirty() => { + return Err(bad("file.close", "the document has unsaved changes; save it or explicitly discard them")); + } + Some(v) if v == "ask" => {} + // `false` (don't save) is the older spelling of discard. + Some(Value::Bool(false)) => {} + Some(v) if v != "discard" => return Err(bad("file.close", "`save` must be ask, discard or false")), + _ => {} + } + s.close(i).ok_or(EngineError::NoDocument)?; + Ok(Value::Null) + } + )] +} diff --git a/crates/engine/src/cmd/table/core/queries.rs b/crates/engine/src/cmd/table/core/queries.rs new file mode 100644 index 0000000000..03fe314a3a --- /dev/null +++ b/crates/engine/src/cmd/table/core/queries.rs @@ -0,0 +1,122 @@ +use crate::cmd::{CommandSpec, EngineError, Rect, Value, always, bad, command_specs, has_doc, inspect, int, json, list_entry}; + +/// Commands that report session and document state or switch documents. +pub(crate) fn specs() -> Vec { + vec![ + CommandSpec { + id: "session.inspect", + label: "Inspect Session", + menu: &[], + shortcut: None, + params: "{}", + enabled: always, + run: |s, _| Ok(inspect::session(s)), + journal: false, + }, + CommandSpec { + id: "document.inspect", + label: "Inspect Document", + menu: &[], + shortcut: None, + params: r##"{"document":index?}"##, + enabled: has_doc, + run: |s, p| { + let d = match p.get("document") { + Some(v) => { + let i = v.as_u64().and_then(|v| usize::try_from(v).ok()).ok_or_else(|| bad("document.inspect", "`document` must be an index"))?; + s.documents().get(i).ok_or_else(|| EngineError::Other(format!("no document at index {i}")))? + } + None => s.active().ok_or(EngineError::NoDocument)?, + }; + Ok(inspect::document(d)) + }, + journal: false, + }, + CommandSpec { + id: "document.activate", + label: "Activate Document", + menu: &[], + shortcut: None, + params: r##"{"document":index|{"index":uint}} or {"offset":int} (numeric document: zero-based tab index; typed index: one-based opening order; offset: places after the active document in opening order, before it when negative) → {document}"##, + enabled: has_doc, + run: |s, p| { + // A null key counts as omitted. + let given = |k: &str| p.get(k).filter(|v| !v.is_null()); + let idx = match (given("document"), given("offset")) { + (Some(_), Some(_)) => return Err(bad("document.activate", "give `document` or `offset`, not both")), + (None, None) => return Err(bad("document.activate", "needs `document` (a tab index) or `offset`")), + // Recorded offsets wrap in opening order, independently of dragged tabs. + (None, Some(o)) => { + let o = o.as_i64().ok_or_else(|| bad("document.activate", "`offset` must be an integer"))?; + s.document_at_offset(o)? + } + (Some(d), None) => { + if let Some(selector) = d.as_object() { + let index = selector + .get("index") + .filter(|_| selector.len() == 1) + .and_then(Value::as_u64) + .ok_or_else(|| bad("document.activate", "document reference needs one non-negative index"))?; + return s + .document_at_index(index) + .and_then(|idx| if s.set_active(idx) { Ok(json!({"document": idx})) } else { Err(EngineError::NoDocument) }); + } + let i = d.as_u64().ok_or_else(|| bad("document.activate", "`document` must be a tab index"))?; + usize::try_from(i).map_err(|_| bad("document.activate", "`document` out of range"))? + } + }; + if s.set_active(idx) { Ok(json!({"document": idx})) } else { Err(EngineError::Other(format!("no document at index {idx}"))) } + }, + journal: true, + }, + CommandSpec { + id: "document.move", + label: "Move Document", + menu: &[], + shortcut: None, + params: r##"{"document":index?,"to":index}"##, + enabled: has_doc, + run: |s, p| { + let index = |key: &str| { + p.get(key) + .map(|v| v.as_u64().and_then(|v| usize::try_from(v).ok()).ok_or_else(|| bad("document.move", format!("`{key}` must be a tab index")))) + }; + let from = match index("document") { + Some(i) => i?, + None => s.active_index().ok_or(EngineError::NoDocument)?, + }; + let to = index("to").ok_or_else(|| bad("document.move", "missing `to`"))??; + let to = s.move_document(from, to).ok_or(EngineError::NoDocument)?; + Ok(json!({"document": to})) + }, + journal: false, + }, + CommandSpec { + id: "command.list", + label: "List Commands", + menu: &[], + shortcut: None, + params: "{}", + enabled: always, + run: |s, _| Ok(Value::Array(command_specs().iter().map(|c| list_entry(s, c, (c.enabled)(s).err())).collect())), + journal: false, + }, + CommandSpec { + id: "document.pixel", + label: "Read Composite Pixel", + menu: &[], + shortcut: None, + params: r##"{"x":i32,"y":i32}"##, + enabled: has_doc, + run: |s, p| { + let coord = |k: &str| i32::try_from(int(p, k).unwrap_or(0)).map_err(|_| bad("document.pixel", format!("{k} must fit in 32 bits"))); + let (x, y) = (coord("x")?, coord("y")?); + let d = s.active().ok_or(EngineError::NoDocument)?; + // At i32::MAX the 1x1 rect saturates to empty: a pixel that far out is transparent. + let px = photocraft_compose::render(&d.doc, Rect::from_xywh(x, y, 1, 1)).px.first().copied().unwrap_or_default(); + Ok(json!(px)) + }, + journal: false, + }, + ] +} diff --git a/crates/engine/src/cmd/table/core/select_menu.rs b/crates/engine/src/cmd/table/core/select_menu.rs new file mode 100644 index 0000000000..dee9830596 --- /dev/null +++ b/crates/engine/src/cmd/table/core/select_menu.rs @@ -0,0 +1,120 @@ +use crate::cmd::{CommandSpec, Rect, Surface, TILE_SIZE, Value, bad, has_doc, has_selection, int_i32, selection_cmds}; + +/// Select menu: All, Deselect, Inverse and rectangular selections. +pub(crate) fn specs() -> Vec { + vec![ + // Select + cmd!("select.all", "All", ["Select"], Some("Cmd+A"), "{}", has_doc, |s, _| { + // With the active layer on an artboard (the board itself or a layer inside it), Select + // All selects that board, as Photoshop does; otherwise the whole canvas (#10258). + let active = s.active().and_then(|d| d.active_layer); + s.edit("Select All", |doc, _| { + let board = active.and_then(|id| doc.artboard_of(id)).and_then(|id| doc.layer(id)).and_then(|l| l.artboard()).map(|a| a.rect); + // A board the canvas no longer reaches (cropped away) selects the canvas, never an + // empty selection that would block painting. + let area = board.map(|r| r.intersect(&doc.bounds())).filter(|r| !r.is_empty()).unwrap_or_else(|| doc.bounds()); + let mut m = Surface::new(photocraft_color::PixelFormat::GRAY8); + m.fill_rect(area, &[1.0]); + doc.selection = Some(m); + Ok(()) + })?; + Ok(Value::Null) + }), + cmd!("select.deselect", "Deselect", ["Select"], Some("Cmd+D"), "{}", has_selection, |s, _| { + // Nothing selected: nothing to do and no history step, as in Photoshop (#6744). + if s.active().is_none_or(|d| d.doc.selection.is_none()) { + return Ok(Value::Null); + } + s.edit("Deselect", |doc, _| { + doc.selection = None; + Ok(()) + })?; + Ok(Value::Null) + }), + cmd!("select.inverse", "Inverse", ["Select"], Some("Cmd+Shift+I"), "{}", has_selection, |s, _| { + s.edit("Inverse", |doc, _| { + let old = doc.selection.take().unwrap_or_else(|| Surface::new(photocraft_color::PixelFormat::GRAY8)); + doc.selection = Some(photocraft_algo::selection::inverse_surface(&old, doc.bounds())); + Ok(()) + })?; + Ok(Value::Null) + }), + cmd!( + "select.rect", + "Rectangular Selection", + [], + None, + r##"{"x":i32,"y":i32,"width":u32,"height":u32,"mode":"replace|add|subtract|intersect"="replace","ellipse":bool=false,"line":"row|column"?,"antiAlias":bool=true,"feather":px=0}"##, + has_doc, + |s, p| { + let get = |k: &str| int_i32("select.rect", p, k).and_then(|v| v.ok_or_else(|| bad("select.rect", format!("missing `{k}`")))); + let r = Rect::from_xywh(get("x")?, get("y")?, get("width")?.max(0) as u32, get("height")?.max(0) as u32); + let mode = p.get("mode").and_then(Value::as_str).unwrap_or("replace").to_string(); + let ellipse = p.get("ellipse").and_then(Value::as_bool).unwrap_or(false); + // The History step is named after the tool: the Single Row / Single Column + // Marquee send `line` (Photoshop). + let step = match p.get("line").and_then(Value::as_str) { + Some("row") => "Single Row Marquee", + Some("column") => "Single Column Marquee", + Some(other) => return Err(bad("select.rect", format!("unknown `line` {other:?} (row|column)"))), + None if ellipse => "Elliptical Marquee", + None => "Rectangular Marquee", + }; + // Options bar: anti-aliased ellipse edges (4x4 supersampled) and Feather (applied to the new shape only). + let aa = p.get("antiAlias").and_then(Value::as_bool).unwrap_or(true); + let feather = p.get("feather").and_then(Value::as_f64).unwrap_or(0.0).clamp(0.0, 1000.0) as f32; + s.edit(step, |doc, _| { + let area = doc.bounds(); + // A marquee dragged past the canvas stops at its edge (Photoshop); the ellipse + // keeps the dragged shape and is only cut there. + use photocraft_algo::selection as sel; + let shape = if ellipse { + sel::ellipse_surface(r, area, aa) + } else { + let mut s = Surface::new(photocraft_color::PixelFormat::GRAY8); + s.fill_rect(r.intersect(&area), &[1.0]); + s + }; + if feather > 0.0 { + let window = selection_cmds::feather_window(r, area, feather); + let m = sel::feather(&sel::mask_from_surface(Some(&shape), window), window.width() as usize, window.height() as usize, feather); + doc.selection = selection_cmds::combine_band(doc.selection.as_ref(), &m, window, sel::SelectionMode::parse(&mode)); + return Ok(()); + } + let old = doc.selection.take(); + let combined = match (mode.as_str(), old) { + ("add", Some(o)) => sel::combine_sparse(&o, &shape, area, |a, b| a.max(b)), + ("subtract", Some(o)) => sel::combine_sparse(&o, &shape, area, |a, b| a * (1.0 - b)), + ("intersect", Some(o)) => sel::combine_surfaces(&o, &shape, area, |a, b| a.min(b)), + // With no existing selection, neither operation can select new pixels. + ("subtract" | "intersect", None) => Surface::new(photocraft_color::PixelFormat::GRAY8), + _ => shape, + }; + // Sparse Add/Subtract keeps untouched pixels outside the canvas. Only pixels + // inside the document count when deciding whether a selection remains. + let has_on_canvas_pixels = (combined.default_bytes().first().copied().unwrap_or(0) != 0 && { + let canvas_tiles = u64::from(area.width().div_ceil(TILE_SIZE as u32)) * u64::from(area.height().div_ceil(TILE_SIZE as u32)); + let stored = combined.tiles().filter(|(coord, _)| !coord.rect().intersect(&area).is_empty()).count() as u64; + stored < canvas_tiles + }) || combined.tiles().any(|(coord, tile)| { + let tile_rect = coord.rect(); + let overlap = tile_rect.intersect(&area); + if overlap.is_empty() { + return false; + } + let x0 = (overlap.x0 - tile_rect.x0) as usize; + let x1 = (overlap.x1 - tile_rect.x0) as usize; + (overlap.y0 - tile_rect.y0..overlap.y1 - tile_rect.y0).any(|y| { + let row_start = y as usize * TILE_SIZE as usize; + let start = row_start + x0; + tile.bytes().get(start..row_start + x1).is_some_and(|row| row.iter().any(|&v| v != 0)) + }) + }); + doc.selection = has_on_canvas_pixels.then_some(combined); + Ok(()) + })?; + Ok(Value::Null) + } + ), + ] +} diff --git a/crates/engine/src/cmd/table/core/tools.rs b/crates/engine/src/cmd/table/core/tools.rs new file mode 100644 index 0000000000..3a2f9666c4 --- /dev/null +++ b/crates/engine/src/cmd/table/core/tools.rs @@ -0,0 +1,46 @@ +use crate::cmd::{CommandSpec, Value, always, cmyk_param, color_param}; + +/// Tool state: foreground and background colors. +pub(crate) fn specs() -> Vec { + vec![ + cmd!( + "tools.setColors", + "Set Colors", + [], + None, + r##"{"foreground":"#rrggbb"|[r,g,b,a?]?,"background":same?,"foregroundCmyk":[c,m,y,k]? (inks 0..1 the foreground was picked as: a CMYK document is filled with exactly these),"backgroundCmyk":same?}"##, + always, + |s, p| { + let cmyk = |key: &str| cmyk_param("tools.setColors", p, key); + let (fg_cmyk, bg_cmyk) = (cmyk("foregroundCmyk")?, cmyk("backgroundCmyk")?); + let foreground = color_param("tools.setColors", p, "foreground", s.tools.foreground)?; + let background = color_param("tools.setColors", p, "background", s.tools.background)?; + s.tools.foreground = foreground; + s.tools.background = background; + if let Some(k) = fg_cmyk { + let [r, g, b, _] = s.tools.foreground; + s.tools.remember_cmyk([r, g, b], k); + } + if let Some(k) = bg_cmyk { + let [r, g, b, _] = s.tools.background; + s.tools.remember_cmyk([r, g, b], k); + } + Ok(Value::Null) + } + ), + cmd!("tools.swapColors", "Switch Foreground and Background Colors", [], Some("X"), "{}", always, |s, _| { + std::mem::swap(&mut s.tools.foreground, &mut s.tools.background); + Ok(Value::Null) + }), + cmd!("tools.defaultColors", "Default Foreground and Background Colors", [], Some("D"), "{}", always, |s, _| { + if s.tools.mask_targeted { + s.tools.foreground = crate::ToolState::MASK_COLORS[0]; + s.tools.background = crate::ToolState::MASK_COLORS[1]; + } else { + s.tools.foreground = [0.0, 0.0, 0.0, 1.0]; + s.tools.background = [1.0, 1.0, 1.0, 1.0]; + } + Ok(Value::Null) + }), + ] +} diff --git a/crates/engine/src/cmd/table/image.rs b/crates/engine/src/cmd/table/image.rs new file mode 100644 index 0000000000..b6c29faec4 --- /dev/null +++ b/crates/engine/src/cmd/table/image.rs @@ -0,0 +1,2 @@ +pub(crate) mod adjustments; +pub(crate) mod image_menu; diff --git a/crates/engine/src/cmd/table/image/adjustments.rs b/crates/engine/src/cmd/table/image/adjustments.rs new file mode 100644 index 0000000000..80cc8b33cb --- /dev/null +++ b/crates/engine/src/cmd/table/image/adjustments.rs @@ -0,0 +1,147 @@ +use crate::cmd::{CommandSpec, NEW_LAYER_PATH, Value, adjust_mode, destructive_adjust, doc_mode, has_doc, is_mask_target, new_adjustment}; + +/// The adjustment layers and the Image › Adjustments commands, generated from one table. +pub(crate) fn specs() -> Vec { + let mut v = Vec::new(); + // Adjustment layers + destructive adjustments, generated from one list. + // Levels/Curves channel keys follow the document: red/green/blue (RGB), gray (Grayscale), + // cyan/magenta/yellow/black (CMYK), lightness/a/b (Lab); see `adjust_params`. + const ADJ: &[(&str, &str, &str)] = &[ + ("brightnessContrast", "Brightness/Contrast…", r##"{"brightness":-150..150=0,"contrast":-50..100=0,"legacy":bool=false}"##), + ( + "levels", + "Levels…", + r##"{"inBlack":0..253=0,"gamma":0.01..9.99=1,"inWhite":2..255=255,"outBlack":0..255=0,"outWhite":0..255=255,"red":json,"green":json,"blue":json,"eyedropper":json} (top level = composite; per channel {"inBlack","gamma","inWhite","outBlack","outWhite"} under red/green/blue, gray, cyan/magenta/yellow/black or lightness/a/b; eyedropper = the dialog's Set Black/Neutral Gray/White Point picker {"point":"black|gray|white","at":[x,y],"size":1..101=1} or {"point",…,"color":[r,g,b] 0..1}: black/white set each channel's input black/white to the sample, gray each channel's gamma so the sample turns neutral at its luma; colour composites: RGB and Grayscale (no gray); Image adjustments targeting a mask, alpha or Quick Mask sample that gray plane in any document mode, applied over the given levels)"##, + ), + ( + "curves", + "Curves…", + r##"{"points":json,"red":json,"green":json,"blue":json,"pencil":bool=false,"smooth":0..10=0,"eyedropper":json} (curves as [[in,out],…] in 0..255, 2..19 points: points = composite; red/green/blue, gray, cyan/magenta/yellow/black or lightness/a/b per channel; pencil = drawn curves (Draw to modify the curve): each curve is 256 output levels in 0..255 (point curves given are drawn in, and turning pencil off fits points to the drawing); smooth = Smooth passes over the drawn curves; eyedropper = the dialog's Set Black/Neutral Gray/White Point picker {"point":"black|gray|white","at":[x,y],"size":1..101=1} or {"point",…,"color":[r,g,b] 0..1}, colour composites: RGB and Grayscale (no gray); Image adjustments targeting a mask, alpha or Quick Mask sample that gray plane in any document mode, applied over the given curves)"##, + ), + ("exposure", "Exposure…", r##"{"exposure":-20..20=0,"offset":-0.5..0.5=0,"gamma":0.01..9.99=1}"##), + ("vibrance", "Vibrance…", r##"{"vibrance":-100..100=0,"saturation":-100..100=0}"##), + ( + "hueSaturation", + "Hue/Saturation…", + r##"{"hue":-180..180=0,"saturation":-100..100=0,"lightness":-100..100=0,"colorize":bool=false,"reds":json,"yellows":json,"greens":json,"cyans":json,"blues":json,"magentas":json} (per range {"hue","saturation","lightness","range":[4 hue degrees]}; colorize: hue 0..360, saturation 0..100)"##, + ), + ( + "colorBalance", + "Color Balance…", + r##"{"shadows":json,"midtones":json,"highlights":json,"preserveLuminosity":bool=true} (each tone [cyan-red, magenta-green, yellow-blue] in -100..100)"##, + ), + ( + "blackWhite", + "Black & White…", + r##"{"reds":-200..300=40,"yellows":-200..300=60,"greens":-200..300=40,"cyans":-200..300=60,"blues":-200..300=20,"magentas":-200..300=80,"tint":bool=false,"tintColor":"#rrggbb"}"##, + ), + ( + "photoFilter", + "Photo Filter…", + r##"{"filter":"warming85|warmingLBA|warming81|cooling80|coolingLBB|cooling82|red|orange|yellow|green|cyan|blue|violet|magenta|sepia|deepRed|deepBlue|deepEmerald|deepYellow|underwater","color":"#rrggbb","density":0..100=25,"preserveLuminosity":bool=true}"##, + ), + ( + "channelMixer", + "Channel Mixer…", + r##"{"red":json,"green":json,"blue":json,"gray":json,"monochrome":bool=false} (per output channel [red %, green %, blue %, constant %] in -200..200; gray = the monochrome mix)"##, + ), + ("invert", "Invert", "{}"), + ("posterize", "Posterize…", r##"{"levels":2..255=4}"##), + ("threshold", "Threshold…", r##"{"level":1..255=128}"##), + ("gradientMap", "Gradient Map…", r##"{"stops":json,"reverse":bool=false,"dither":bool=false} (stops [[location 0..1, "#rrggbb"], …], 2..64)"##), + ( + "selectiveColor", + "Selective Color…", + r##"{"method":"relative|absolute"="relative","colors":"reds|yellows|greens|cyans|blues|magentas|whites|neutrals|blacks"="reds","cyan":-100..100=0,"magenta":-100..100=0,"yellow":-100..100=0,"black":-100..100=0,"reds":json} (per-range [c,m,y,k] arrays: reds yellows greens cyans blues magentas whites neutrals blacks)"##, + ), + ( + "colorLookup", + "Color Lookup…", + r##"{"lut":"none|warm|cool|tealOrange|bleachBypass|fadedFilm|dayForNight|monoContrast|crossProcess"="none","file":text,"interpolation":"trilinear|tetrahedral"="trilinear","dither":bool=false,"data":text,"dataEncoding":"text|base64"="text","fileName":text,"lutFormat":"auto|cube|3dl|look"="auto"} (file: LUT path; data: file text or encoded bytes; lutFormat overrides format detection, auto detects it)"##, + ), + ]; + for &(kind, label, params) in ADJ { + let layer_id: &'static str = Box::leak(format!("layer.newAdjustmentLayer.{kind}").into_boxed_str()); + let image_id: &'static str = Box::leak(format!("image.adjustments.{kind}").into_boxed_str()); + v.push(CommandSpec { + id: layer_id, + label, + menu: &["Layer", "New Adjustment Layer"], + shortcut: None, + params: Box::leak(format!(r#"{params} + {{{NEW_LAYER_PATH},"opacity":0..1=1,"name":str?=the adjustment's name + number,"mode":blend mode name="normal" (not Pass Through),"clipToPrevious":bool=false}}"#).into_boxed_str()), + enabled: has_doc, + run: |s, p| { + let kind = p.get("__kind").and_then(Value::as_str).unwrap_or("invert").to_string(); + let eyedropped = if matches!(kind.as_str(), "levels" | "curves") { crate::adjust_params::eyedropper_from_params(s, &kind, p)? } else { None }; + let adj = match eyedropped { + Some(adj) => adj, + None => crate::adjust_params::from_params(&kind, p, None, doc_mode(s))?, + }; + new_adjustment(s, adj, p, &format!("layer.newAdjustmentLayer.{kind}")) + }, + journal: true, + }); + v.push(CommandSpec { + id: image_id, + label, + menu: &["Image", "Adjustments"], + shortcut: match kind { + "levels" => Some("Cmd+L"), + "curves" => Some("Cmd+M"), + "hueSaturation" => Some("Cmd+U"), + "colorBalance" => Some("Cmd+B"), + "invert" => Some("Cmd+I"), + "blackWhite" => Some("Cmd+Alt+Shift+B"), + _ => None, + }, + params, + enabled: crate::adjust_cmds::has_adjustable, + run: |s, p| { + let kind = p.get("__kind").and_then(Value::as_str).unwrap_or("invert").to_string(); + if matches!(kind.as_str(), "levels" | "curves") { + crate::channel_cmds::resolve_tone_target(s, false, p)?; + } + let eyedropped = if matches!(kind.as_str(), "levels" | "curves") { crate::adjust_params::destructive_eyedropper(s, &kind, p)? } else { None }; + // A smart filter re-runs its params, so it records what an eyedropper resolved + // to, not the sample (#3127). + let recorded = eyedropped.as_ref().map(|adj| { + let mut q = p.clone(); + if let (Value::Object(q), Value::Object(resolved)) = (&mut q, crate::adjust_params::to_params(adj)) { + q.remove("eyedropper"); + q.extend(resolved); + } + q + }); + let adj = match eyedropped { + Some(adj) => adj, + None => { + // A gray plane target keeps the neutral tone space even over params + // carrying RGB, Lab or CMYK records (#5335). + let tone = if is_mask_target(p) || crate::channel_cmds::is_channel_target(p) { + if matches!(kind.as_str(), "levels" | "curves") { crate::adjust_params::gray_tone_params(p) } else { p.clone() } + } else { + p.clone() + }; + crate::adjust_params::from_params(&kind, &tone, None, adjust_mode(s, p))? + } + }; + let adj = if matches!(kind.as_str(), "levels" | "curves") + && let Some(colors) = crate::color_channels::target(s, p)? + { + crate::color_channels::tone_adjustment(&kind, p, adj, doc_mode(s), colors)? + } else { + adj + }; + let label = adj.label().to_string(); + // A smart object records the adjustment as a smart filter (Photoshop), which + // re-runs from the source instead of baking into a copy of the pixels. + if crate::adjust_cmds::adjust_as_smart_filter(s, &kind, &label, recorded.as_ref().unwrap_or(p))? { + return Ok(Value::Null); + } + destructive_adjust(s, &label, adj, p) + }, + journal: true, + }); + } + v +} diff --git a/crates/engine/src/cmd/table/image/image_menu.rs b/crates/engine/src/cmd/table/image/image_menu.rs new file mode 100644 index 0000000000..8bcd87a0ef --- /dev/null +++ b/crates/engine/src/cmd/table/image/image_menu.rs @@ -0,0 +1,24 @@ +use crate::cmd::{Adjustment, CommandSpec, Value, destructive_adjust}; + +/// Image › Adjustments › Desaturate: Hue/Saturation with saturation at -100. +pub(crate) fn desaturate_adjustment() -> Adjustment { + Adjustment::HueSaturation { hue: 0.0, saturation: -100.0, lightness: 0.0, colorize: false, ranges: photocraft_doc::adjust::HueRange::defaults() } +} + +/// Image menu: Desaturate. +pub(crate) fn specs() -> Vec { + vec![cmd!( + "image.adjustments.desaturate", + "Desaturate", + ["Image", "Adjustments"], + Some("Cmd+Shift+U"), + r##"{"target":"pixels"|"mask"|{"color":i}|{"colors":[i,…]}?=Channels panel target,"layer":id|name?=active}"##, + crate::adjust_cmds::has_adjustable, + |s, p| { + if crate::adjust_cmds::adjust_as_smart_filter(s, "desaturate", "Desaturate", p)? { + return Ok(Value::Null); + } + destructive_adjust(s, "Desaturate", desaturate_adjustment(), p) + } + )] +} diff --git a/crates/engine/src/cmd/table/model.rs b/crates/engine/src/cmd/table/model.rs new file mode 100644 index 0000000000..a1154cd1a3 --- /dev/null +++ b/crates/engine/src/cmd/table/model.rs @@ -0,0 +1,3 @@ +pub(crate) mod edit_menu; +pub(crate) mod image_menu; +pub(crate) mod layer_menu; diff --git a/crates/engine/src/cmd/table/model/edit_menu.rs b/crates/engine/src/cmd/table/model/edit_menu.rs new file mode 100644 index 0000000000..46efa9ae85 --- /dev/null +++ b/crates/engine/src/cmd/table/model/edit_menu.rs @@ -0,0 +1,49 @@ +use crate::cmd::{CommandSpec, Value, has_pixel_or_channel, is_mask_target, layer_param}; + +/// Edit menu: Clear (channel and mask targets). +pub(crate) fn specs() -> Vec { + vec![cmd!( + "edit.clear", + "Clear", + ["Edit"], + None, + r##"{"target":"mask"|{"color":i}|{"colors":[i,…]}?=Channels panel target,"layer":id|name?=active} (a targeted mask, channel or Quick Mask is cleared alone)"##, + has_pixel_or_channel, + |s, p| { + let bg = s.tools.background; + // A targeted alpha channel or Quick Mask is filled instead (#2734). + let channel = if crate::channel_cmds::is_channel_target(p) { + Some(p.clone()) + } else if p.get("target").is_none() { + crate::channel_cmds::targeted_channel(s) + } else { + None + }; + if let Some(t) = channel { + s.edit("Clear", |doc, _| crate::channel_cmds::clear_channel(doc, &t, bg))?; + return Ok(Value::Null); + } + let id = layer_param(s, p)?; + if is_mask_target(p) { + s.edit("Clear Mask", |doc, _| crate::edit_cmds::clear_mask(doc, id, bg, p))?; + return Ok(Value::Null); + } + // A targeted colour channel clears that channel only (#2720). + if let Some(colors) = crate::color_channels::target(s, p)? { + s.edit("Clear", |doc, _| { + for k in colors.indices() { + crate::channel_cmds::clear_color_channel(doc, id, k, bg)?; + } + Ok(()) + })?; + return Ok(Value::Null); + } + s.edit("Clear", |doc, _| { + let sel = doc.selection.clone(); + let area = sel.as_ref().map(|m| m.content_bounds()).unwrap_or(doc.bounds()); + crate::edit_cmds::clear_area(doc, id, area, sel.as_ref(), bg) + })?; + Ok(Value::Null) + } + )] +} diff --git a/crates/engine/src/cmd/table/model/image_menu.rs b/crates/engine/src/cmd/table/model/image_menu.rs new file mode 100644 index 0000000000..4beca02e10 --- /dev/null +++ b/crates/engine/src/cmd/table/model/image_menu.rs @@ -0,0 +1,38 @@ +use crate::cmd::{CommandSpec, Result, Session, Value, has_doc}; + +/// Image › Image Rotation by a right angle or a flip (pixels, vectors, guides, … all move). +fn turn(s: &mut Session, label: &str, t: crate::canvas_geom::Turn) -> Result { + if let Some(d) = s.active() { + let a = t.affine(f64::from(d.doc.size.width), f64::from(d.doc.size.height)); + // Sampler points are pixel indices, not pixel edges: map the pixel's centre, so the point + // lands on the same pixel `Turn::pixel_map` moves the pixels to (`w - 1 - x`). + let half = photocraft_geom::Affine::translate(0.5, 0.5); + s.set_canvas_map(a, half.then(&a).then(&photocraft_geom::Affine::translate(-0.5, -0.5))); + } + s.edit(label, |doc, _| { + crate::canvas_geom::keeping_count_points(doc, |doc| crate::canvas_geom::turn_canvas(doc, t)); + Ok(()) + })?; + Ok(Value::Null) +} + +/// Image menu: canvas rotations and flips. +pub(crate) fn specs() -> Vec { + vec![ + cmd!("image.imageRotation.flipCanvasHorizontal", "Flip Canvas Horizontal", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| { + turn(s, "Flip Canvas Horizontal", crate::canvas_geom::Turn::FlipHorizontal) + }), + cmd!("image.imageRotation.flipCanvasVertical", "Flip Canvas Vertical", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| { + turn(s, "Flip Canvas Vertical", crate::canvas_geom::Turn::FlipVertical) + }), + cmd!("image.imageRotation.180", "180°", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| { + turn(s, "Rotate Canvas", crate::canvas_geom::Turn::Rotate180) + }), + cmd!("image.imageRotation.90cw", "90° Clockwise", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| { + turn(s, "Rotate Canvas", crate::canvas_geom::Turn::Cw90) + }), + cmd!("image.imageRotation.90ccw", "90° Counter Clockwise", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| { + turn(s, "Rotate Canvas", crate::canvas_geom::Turn::Ccw90) + }), + ] +} diff --git a/crates/engine/src/cmd/table/model/layer_menu.rs b/crates/engine/src/cmd/table/model/layer_menu.rs new file mode 100644 index 0000000000..42bc4961d5 --- /dev/null +++ b/crates/engine/src/cmd/table/model/layer_menu.rs @@ -0,0 +1,536 @@ +use crate::cmd::{ + Adjustment, Color, ColorMode, CommandSpec, EngineError, Fill, Layer, LayerContent, LayerId, LayerMask, Result, Session, Value, adjustment_kind, arrange, + bad, cmyk_param, color_param, has_doc, has_layer, has_selection, json, layer_copy, layer_panel_option, layer_param, mask_new_layer, merge_group, move_mask, + parse_blend, pixels, set_clipped, set_mask, set_mask_and_deselect, +}; +use photocraft_color::BlendMode; + +/// Layer menu, first run: new layers and groups to the solid color fill layer. +pub(crate) fn specs_before_gradient() -> Vec { + [creation(), duplication(), deletion_and_selection(), order_and_clipping(), masks(), merging(), solid_color_fill()].into_iter().flatten().collect() +} + +/// Layer menu, last run: adjustment layers, move and translate. +pub(crate) fn specs_after_gradient() -> Vec { + [adjustments(), placement()].into_iter().flatten().collect() +} + +/// New layers and groups, and grouping the selected layers. +fn creation() -> Vec { + vec![ + cmd!( + "layer.new.layer", + "Layer…", + ["Layer", "New"], + Some("Cmd+Shift+N"), + r##"{"name":str?,"clipToPrevious":bool=false (Use Previous Layer to Create Clipping Mask; inside a clip group the layer joins it anyway),"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":"Normal|Multiply|…"="Normal","opacity":0..1=1,"fillNeutral":bool=false (fill with the mode's neutral color: modes without one are an error),"position":"above|below"="above" (below: the Layers panel's Cmd/Ctrl-click; never under the Background)} (above the active layer, or the top layer inside it when it is an open group)"##, + has_doc, + crate::new_layer::run + ), + cmd!( + "layer.new.group", + "Group…", + ["Layer", "New"], + None, + r##"{"name":text?,"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":str="passThrough" (blend mode),"opacity":0..100=100 (percent),"position":"above|below"="above" (below: the Layers panel's Cmd/Ctrl-click; never under the Background)} (above the active layer, or inside it when it is an open group; clipped when it lands inside a clipping mask)"##, + has_doc, + |s, p| { + let opts = crate::group_options::GroupOptions::parse("layer.new.group", p)?; + let below = crate::group_options::below("layer.new.group", p)?; + let place = if below { crate::layer_place::Place::Below } else { crate::layer_place::Place::Auto }; + let id = s.edit("New Group", |doc, active| { + let name = opts.name.clone().unwrap_or_else(|| doc.next_layer_name("Group")); + let mut group = Layer::group(name, vec![]); + opts.apply(&mut group); + let bg = crate::background_cmds::background_id(doc); + let id = crate::layer_place::insert_new(doc, *active, group, place); + crate::background_cmds::keep_background_at_bottom(bg, doc)?; + *active = Some(id); + Ok(id) + })?; + Ok(json!({ "layer": id.0 })) + } + ), + cmd!( + "layer.groupLayers", + "Group Layers", + ["Layer"], + Some("Cmd+G"), + r##"{"layer":id?,"name":text?,"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":str="passThrough" (blend mode),"opacity":0..100=100 (percent)} (no layer: every selected layer; the new group starts collapsed)"##, + has_layer, + crate::layer_multi_cmds::group_layers + ), + ] +} + +/// Duplicate Layer, into the same document or a new one. +fn duplication() -> Vec { + vec![cmd!( + "layer.duplicate", + "Duplicate Layer…", + ["Layer"], + None, + r##"{"layer":id?,"inPlace":bool=false (artboards: keep the copy on the original instead of beside it),"name":str? (one layer: the copy's name),"document":index|"new"=same document (Photoshop's Destination: "new" makes a new document the size of this canvas holding just the copies),"documentName":str? (the new document's name)} (no layer: every selected layer)"##, + has_layer, + |s, p| { + if let Some(d) = p.get("document") { + if d.as_str() == Some("new") { + return crate::layer_copy_cmds::duplicate_to_new_document(s, p); + } + let same = d.as_u64().is_some_and(|i| s.active_index().is_some_and(|a| i == a as u64)); + if !same { + return Err(EngineError::BadParams { + cmd: "layer.duplicate".into(), + msg: if d.as_u64().is_some() { + "the destination is another open document (use layer.copyToDocument)".into() + } else { + "`document` must be a document index or \"new\"".into() + }, + }); + } + } + let in_place = p.get("inPlace").and_then(Value::as_bool).unwrap_or(false); + let name = p.get("name").and_then(Value::as_str).filter(|n| !n.is_empty()).map(str::to_string); + if crate::layer_multi_cmds::multi(s, p) { + return crate::layer_multi_cmds::duplicate_selected(s, in_place, "Duplicate Layers"); + } + let id = layer_param(s, p)?; + let add_copy = layer_panel_option(s, "addCopyToCopiedLayersAndGroups", true); + // The dialog offers Duplicate Layer's own name: only a different one was typed (#9023). + let mut typed = None; + let mut shift = (0, 0); + let nid = s.edit("Duplicate Layer", |doc, active| { + let mut dup = layer_copy(doc, id, add_copy)?; + if let Some(name) = name.as_ref().filter(|n| **n != dup.name) { + dup.name.clone_from(name); + typed = Some(name.clone()); + } + let nid = doc.insert_above(Some(id), dup); + // A lone copy joins its original's link group, as in the reference application (#11217). + crate::layer_multi_cmds::relink_copies(doc, &[nid])?; + if !in_place { + shift = crate::artboard_cmds::place_copy(doc, nid)?; + } + *active = Some(nid); + Ok(nid) + })?; + crate::artboard_cmds::follow_shift(s, shift); + if let Some(name) = typed { + crate::type_cmds::note_typed_name(s, nid, &name); + } + Ok(json!({ "layer": nid.0 })) + } + )] +} + +/// Deleting and selecting layers, and setting their properties. +fn deletion_and_selection() -> Vec { + vec![ + cmd!("layer.delete", "Delete Layer", ["Layer", "Delete"], None, r##"{"layer":id?} (no layer: every selected layer)"##, has_layer, |s, p| { + if crate::layer_multi_cmds::multi(s, p) { + return crate::layer_multi_cmds::delete_selected(s); + } + let id = layer_param(s, p)?; + s.edit("Delete Layer", |doc, active| { + let neighbours = crate::layer_multi_cmds::deletion_neighbours(doc, id); + let before = crate::clip_group::Before::read(doc, &[id]); + doc.remove(id).ok_or(EngineError::NoLayer(id))?; + crate::clip_group::settle(doc, &[], &before, false); + if doc.layers.is_empty() { + return Err(EngineError::Other("a document must keep at least one layer".into())); + } + if active.is_some_and(|current| doc.layer(current).is_none()) { + *active = neighbours.into_iter().find(|candidate| doc.layer(*candidate).is_some()); + } + Ok(()) + })?; + Ok(Value::Null) + }), + cmd!( + "layer.select", + "Select Layer", + [], + None, + r##"{"layer":id|str|{"index":uint}|{"ordinal":"Trgt|Frwr|Bckw|Frnt|Back"} | "name":str,"occurrence":index?,"mode":"replace|toggle|range|add|remove"="replace"} | {"layers":[id,…]} (layers: exactly these selected, the last active; typed references use the recorded full layer stack; name occurrence: zero-based document walk order; required for duplicate names; toggle = ⌘-click, range = ⇧-click, remove = deselect it, keeping at least one)"##, + has_doc, + crate::layer_multi_cmds::select + ), + cmd!( + "layer.setProps", + "Layer Properties", + [], + None, + r##"{"layer":id?,"layers":[id,…]? (the same change to each, one step: the Layers panel's controls with several layers selected),"name":str? (one layer only),"visible":bool?,"opacity":0..1?,"fill":0..1?,"blend":"Multiply|…"?,"clipped":bool?,"locked":bool?,"locks":{"transparency","pixels","position","artboard","all":bool}?,"channels":[bool,…]? (Advanced Blending: which colour channels blend, R G B / C M Y K / L a b)}"##, + has_layer, + set_props + ), + ] +} + +/// Arranging layers and clipping masks. +fn order_and_clipping() -> Vec { + vec![ + cmd!("layer.arrange.bringForward", "Bring Forward", ["Layer", "Arrange"], Some("Cmd+]"), r##"{"layer":id?}"##, has_layer, |s, p| arrange(s, p, 1)), + cmd!("layer.arrange.sendBackward", "Send Backward", ["Layer", "Arrange"], Some("Cmd+["), r##"{"layer":id?}"##, has_layer, |s, p| arrange(s, p, -1)), + cmd!("layer.arrange.bringToFront", "Bring to Front", ["Layer", "Arrange"], Some("Cmd+Shift+]"), r##"{"layer":id?}"##, has_layer, |s, p| arrange( + s, + p, + i32::MAX + )), + cmd!("layer.arrange.sendToBack", "Send to Back", ["Layer", "Arrange"], Some("Cmd+Shift+["), r##"{"layer":id?}"##, has_layer, |s, p| arrange( + s, + p, + i32::MIN + )), + cmd!( + "layer.createClippingMask", + "Create Clipping Mask", + ["Layer"], + Some("Cmd+Alt+G"), + r##"{"layer":id?} (no layer: every selected layer but the lowest clips to the layer below it)"##, + has_layer, + |s, p| set_clipped(s, p, true) + ), + cmd!( + "layer.releaseClippingMask", + "Release Clipping Mask", + ["Layer"], + None, + r##"{"layer":id?} (no layer: every selected layer)"##, + has_layer, + |s, p| set_clipped(s, p, false) + ), + ] +} + +/// Layer mask commands. +fn masks() -> Vec { + vec![ + cmd!( + "layer.layerMask.revealAll", + "Reveal All", + ["Layer", "Layer Mask"], + None, + r##"{"layer":id?} (no layer: every selected layer that can take a mask)"##, + has_layer, + |s, p| set_mask(s, p, "Add Layer Mask", Some(LayerMask::reveal_all())) + ), + cmd!( + "layer.layerMask.hideAll", + "Hide All", + ["Layer", "Layer Mask"], + None, + r##"{"layer":id?} (no layer: every selected layer that can take a mask)"##, + has_layer, + |s, p| set_mask(s, p, "Add Layer Mask", Some(LayerMask::hide_all())) + ), + cmd!( + "layer.layerMask.revealSelection", + "Reveal Selection", + ["Layer", "Layer Mask"], + None, + r##"{"layer":id?} (no layer: every selected layer that can take a mask)"##, + has_selection, + |s, p| { + let sel = s.active().and_then(|d| d.doc.selection.clone()).ok_or(EngineError::Other("no selection".into()))?; + let mask = LayerMask { surface: sel, ..LayerMask::reveal_all() }; + // The selection becomes the mask, so Photoshop drops it (as Hide Selection does): a + // following Invert (⌘I) on the targeted mask then inverts all of it, not just the + // part inside the old selection. Same undo step as the mask. + set_mask_and_deselect(s, p, "Add Layer Mask", mask) + } + ), + cmd!("layer.layerMask.delete", "Delete", ["Layer", "Layer Mask"], None, r##"{"layer":id?}"##, has_layer, |s, p| set_mask( + s, + p, + "Delete Layer Mask", + None + )), + cmd!( + "layer.layerMask.moveTo", + "Move Layer Mask", + [], + None, + r##"{"layer":id? (the mask's layer, default active),"to":id|name (the layer or group it goes to; a recorded step names it),"toOccurrence":n? (which of several layers named `to`, in document order),"copy":bool=false (⌥-drag: a copy goes and the original stays),"replace":bool=false (replace a mask already there; otherwise refused)} → {layer,to,copy}"##, + has_layer, + move_mask + ), + ] +} + +/// Merge Down, Merge Group and Flatten Image. +fn merging() -> Vec { + vec![ + cmd!("layer.mergeDown", "Merge Down", ["Layer"], None, r##"{"layer":id?}"##, has_layer, |s, p| { + let id = layer_param(s, p)?; + s.edit("Merge Down", |doc, active| { + let path = doc.path_of(id).ok_or(EngineError::NoLayer(id))?; + let Some((&idx, parent)) = path.split_last() else { return Err(EngineError::NoLayer(id)) }; + if idx == 0 { + return Err(EngineError::Other("no layer below to merge into".into())); + } + let mut below = parent.to_vec(); + below.push(idx - 1); + let lower = doc.layer_at(&below).ok_or(EngineError::NoLayer(id))?.clone(); + let upper = doc.layer(id).ok_or(EngineError::NoLayer(id))?.clone(); + let merged = pixels::merge_down(doc, &lower, &upper); + doc.remove(id); + *doc.layer_at_mut(&below).ok_or(EngineError::NoLayer(lower.id))? = merged; + *active = Some(lower.id); + Ok(()) + })?; + Ok(Value::Null) + }), + cmd!("layer.mergeGroup", "Merge Group", ["Layer"], None, r##"{"layer":id?}"##, has_layer, |s, p| { + let id = layer_param(s, p)?; + if !s.active().and_then(|d| d.doc.layer(id)).is_some_and(|l| matches!(l.content, LayerContent::Group(_))) { + return Err(EngineError::Other("Merge Group needs a group".into())); + } + merge_group(s, id) + }), + cmd!("layer.flattenImage", "Flatten Image", ["Layer"], None, "{}", has_doc, |s, _| { + s.edit("Flatten Image", |doc, active| { + let fmt = doc.pixel_format(); + let mut bg = Layer::raster("Background", fmt); + bg.locks.transparency = true; + bg.locks.position = true; + *crate::pixels_mut(&mut bg)? = photocraft_compose::flatten_to_surface(doc, fmt, Some([1.0, 1.0, 1.0])); + *active = Some(bg.id); + doc.layers = vec![bg].into(); + Ok(()) + })?; + Ok(Value::Null) + }), + ] +} + +/// Solid color fill layer. +fn solid_color_fill() -> Vec { + vec![cmd!( + "layer.newFillLayer.solidColor", + "Solid Color…", + ["Layer", "New Fill Layer"], + None, + r##"{"color":"#rrggbb"=foreground,"cmyk":[c,m,y,k]? (inks 0..1 the colour was picked as: a CMYK document's fill holds exactly these; default the foreground's CMYK pick),"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask, making a shape; else the selection is the layer mask)}"##, + has_doc, + |s, p| { + let c = color_param("layer.newFillLayer.solidColor", p, "color", s.tools.foreground)?; + // The inks the colour was picked as, so CMYK 50/50/50/100 stays 50/50/50/100 instead + // of what its sRGB stand-in converts back to through the document profile (#8568). + let inks = match cmyk_param("layer.newFillLayer.solidColor", p, "cmyk")? { + Some(k) => Some(k), + None => s.tools.picked_cmyk([c[0], c[1], c[2]]), + }; + let default_mask = layer_panel_option(s, "useDefaultMasksOnFillLayers", true); + let id = s.edit("New Color Fill Layer", |doc, active| { + let fill = match inks { + Some(k) if doc.mode == ColorMode::Cmyk => Fill::Solid(Color { mode: ColorMode::Cmyk, c: k, alpha: c[3] }), + _ => Fill::Solid(Color::rgba(c[0], c[1], c[2], c[3])).in_mode(doc.mode), + }; + let mut l = Layer::new(doc.next_layer_name("Color Fill"), LayerContent::Fill(fill)); + mask_new_layer(doc, &mut l, p, "layer.newFillLayer.solidColor", default_mask)?; + let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); + *active = Some(id); + Ok(id) + })?; + Ok(json!({ "layer": id.0 })) + } + )] +} + +/// Editing an adjustment layer's properties. +fn adjustments() -> Vec { + vec![cmd!( + "layer.setAdjustment", + "Adjustment Properties", + [], + None, + r##"{"layer":id?, …params of that adjustment kind} (Levels, Curves: "eyedropper":{"point":"black|gray|white","at":[x,y],"size":1..101=1} or {"point",…,"color":[r,g,b] 0..1} = the Properties panel's Set Black/Neutral Gray/White Point, sampling the image below the layer, RGB and Grayscale (no gray) only)"##, + has_layer, + |s, p| { + let id = layer_param(s, p)?; + let eyedropped = crate::adjust_params::layer_eyedropper(s, id, p)?; + s.edit("Modify Adjustment", |doc, _| { + let mode = doc.mode; + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + let LayerContent::Adjustment(adj) = &mut l.content else { return Err(EngineError::Other("not an adjustment layer".into())) }; + if matches!(adj, Adjustment::Unsupported { .. }) { + return Err(EngineError::Other("this adjustment can't be edited (kept as imported)".into())); + } + let kind = adjustment_kind(adj); + // No params resets to the defaults; otherwise params merge over the current values. + *adj = if let Some(eyedropped) = eyedropped { + eyedropped + } else if crate::adjust_params::user_keys(p).is_empty() { + crate::adjust_params::default_for(kind, mode)? + } else { + crate::adjust_params::from_params(kind, p, Some(adj), mode)? + }; + Ok(()) + })?; + Ok(Value::Null) + } + )] +} + +/// Moving layers in the stack and on the canvas. +fn placement() -> Vec { + vec![ + cmd!( + "layer.moveTo", + "Reorder Layer", + [], + None, + r##"{"layer":id|{"index":uint}|{"ordinal":"Trgt|Frwr|Bckw|Frnt|Back"}?| "layers":[id,…]?, "target":id|name|{"index":uint},"targetOccurrence":n? (which of several layers named `target`, in document order),"position":"above|below|into"="above","copy":bool=false} (typed target: pre-move recorded stack boundary, omit position; layers: one undoable move, document order preserved; copy: place duplicates there and leave the layers, as ⌥-dragging a Layers panel row; recorded typed references retain their form)"##, + has_layer, + crate::layer_multi_cmds::move_to + ), + cmd!( + "layer.translate", + "Move Layer", + [], + None, + r##"{"layer":id?,"dx":i32,"dy":i32,"units":"px"|"pt"="px" (pt: points, whole pixels at the document's resolution),"target":"pixels"|"mask"="pixels","selection":bool=false,"wrap":bool=false,"nest":bool=false} → null | {nested:[id]} (no layer: every selected layer; linked layers follow; target mask: a layer whose mask is unlinked moves that mask alone, a linked mask moves with the layer; selection: the selection moves too, in the same step; wrap: View › Pattern Preview, pixels that leave the canvas come back on the opposite edge so the tile stays seamless; nest: auto-nesting as the Move tool does it, a layer whose bounds centre lands on another artboard joins it and one whose centre is off every artboard leaves for the top level; a clipping base takes the layers clipped to it along and a clipped layer goes only where its base goes; artboards, the Background, empty layers, layers whose board doesn't change, groups that would nest too deep and layers locked with Prevent Auto-Nesting (on the layer, a group around it or the destination board) stay put, with their whole clipping group; nested lists the layers that changed board)"##, + has_layer, + crate::layer_multi_cmds::translate + ), + ] +} + +/// Applies layer.setProps to its target layers as one history step. +fn set_props(s: &mut Session, p: &Value) -> Result { + let ids = prop_targets(s, p)?; + if ids.len() > 1 && p.get("name").is_some() { + return Err(bad("layer.setProps", "`name` renames one layer, not several")); + } + let (opacity, fill) = (unit_prop(p, "opacity")?, unit_prop(p, "fill")?); + let label = props_label(p); + // The eye: a history state only with History Options › Make Layer Visibility + // Changes Undoable. + let record = label != "Layer Visibility" || s.visibility_undoable(); + s.edit_with(label, record, |doc, _| { + // The Background has no opacity, fill or blend mode: like Photoshop, setting + // one that changes its look turns it into a normal layer ("Layer 0") first. + let num = |k: &str| p.get(k).and_then(Value::as_f64).is_some_and(|v| v < 1.0); + let blends = p.get("blend").and_then(Value::as_str).and_then(parse_blend).is_some_and(|b| b != photocraft_color::BlendMode::Normal); + for &id in &ids { + if num("opacity") || num("fill") || blends { + crate::extra_cmds::background_to_layer(doc, id); + } + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + apply_props(l, p, opacity, fill)?; + } + Ok(()) + })?; + // The Layers panel's in-place rename: a name the user typed (#9023). + if let (Some(name), [id]) = (p.get("name").and_then(Value::as_str), ids.as_slice()) { + crate::type_cmds::note_typed_name(s, *id, name); + } + Ok(Value::Null) +} + +/// Several layers at once (the Layers panel with several selected, as in Photoshop), +/// else the given or active one. +fn prop_targets(s: &Session, p: &Value) -> Result> { + match p.get("layers") { + None | Some(Value::Null) => Ok(vec![layer_param(s, p)?]), + Some(Value::Array(a)) if !a.is_empty() && a.len() <= 10_000 => { + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + let mut ids = Vec::with_capacity(a.len()); + for v in a { + let id = v.as_u64().map(LayerId).ok_or_else(|| bad("layer.setProps", format!("`layers` holds layer ids, got {v}")))?; + if doc.layer(id).is_none() { + return Err(EngineError::NoLayer(id)); + } + if !ids.contains(&id) { + ids.push(id); + } + } + Ok(ids) + } + Some(v) => Err(bad("layer.setProps", format!("`layers` is a non-empty list of layer ids, got {v}"))), + } +} + +/// Opacity and Fill are fractions here, while the Layer Style commands take +/// percentages: a value outside 0..1 is refused, never clamped to 100 % (#5242). +fn unit_prop(p: &Value, key: &str) -> Result> { + let Some(v) = p.get(key) else { return Ok(None) }; + match v.as_f64() { + Some(x) if (0.0..=1.0).contains(&x) => Ok(Some(x as f32)), + _ => Err(bad("layer.setProps", format!("{key} must be a number in 0..1 (1 = 100 %), got {v}"))), + } +} + +/// Photoshop's History names for a single kind of change; a mix is "Layer Properties". +fn props_label(p: &Value) -> &'static str { + let changed: Vec<&str> = + p.as_object().map(|o| o.keys().map(String::as_str).filter(|k| !matches!(*k, "layer" | "layers" | "coalesce")).collect()).unwrap_or_default(); + match changed.as_slice() { + ["visible"] => "Layer Visibility", + ["opacity"] => "Opacity Change", + ["fill"] => "Fill Opacity Change", + ["blend"] => "Blending Change", + ["name"] => "Rename Layer", + _ => "Layer Properties", + } +} + +/// Sets the requested name, visibility, opacity, fill and blend mode on one layer. +fn apply_props(l: &mut Layer, p: &Value, opacity: Option, fill: Option) -> Result<()> { + if let Some(v) = p.get("name").and_then(Value::as_str) { + l.name = v.to_string(); + } + if let Some(v) = p.get("visible").and_then(Value::as_bool) { + l.visible = v; + } + if let Some(v) = opacity { + l.opacity = v; + } + if let Some(v) = fill { + l.fill_opacity = v; + } + if let Some(v) = p.get("blend").and_then(Value::as_str) { + l.blend = blend_prop(l, v)?; + } + apply_clip_and_locks(l, p) +} + +/// Sets the requested clipping, channel and lock flags on one layer. +fn apply_clip_and_locks(l: &mut Layer, p: &Value) -> Result<()> { + if let Some(v) = p.get("clipped").and_then(Value::as_bool) { + l.clipped = v; + } + if let Some(v) = p.get("locked").and_then(Value::as_bool) { + l.locks.all = v; + } + if let Some(Value::Array(ch)) = p.get("channels") { + // Blending Options › Advanced Blending › Channels: unchecked = left out. + l.excluded_channels = ch.iter().take(32).enumerate().filter(|(_, v)| v.as_bool() == Some(false)).fold(0, |m, (i, _)| m | 1 << i); + } + if let Some(Value::Object(m)) = p.get("locks") { + set_locks(l, m)?; + } + Ok(()) +} + +/// Parses a blend mode for the layer, refusing Pass Through on anything but a group. +fn blend_prop(l: &Layer, v: &str) -> Result { + let b = parse_blend(v).ok_or_else(|| bad("layer.setProps", format!("unknown blend mode `{v}`")))?; + // Pass Through is a group's mode only, as in Photoshop. + if b == BlendMode::PassThrough && !l.is_group() { + return Err(bad("layer.setProps", format!("Pass Through applies to groups only; layer {} isn't one", l.id.0))); + } + Ok(b) +} + +/// Sets each named lock, refusing an unknown name. +fn set_locks(l: &mut Layer, m: &serde_json::Map) -> Result<()> { + for (k, v) in m { + let v = v.as_bool().unwrap_or(false); + if !l.locks.set(k, v) { + return Err(bad("layer.setProps", format!("unknown lock `{k}`"))); + } + } + Ok(()) +} diff --git a/crates/engine/src/cmd/table/paint.rs b/crates/engine/src/cmd/table/paint.rs new file mode 100644 index 0000000000..67945b6de2 --- /dev/null +++ b/crates/engine/src/cmd/table/paint.rs @@ -0,0 +1,2 @@ +pub(crate) mod edit_menu; +pub(crate) mod stroke; diff --git a/crates/engine/src/cmd/table/paint/edit_menu.rs b/crates/engine/src/cmd/table/paint/edit_menu.rs new file mode 100644 index 0000000000..b1ee43e47f --- /dev/null +++ b/crates/engine/src/cmd/table/paint/edit_menu.rs @@ -0,0 +1,14 @@ +use crate::cmd::{CommandSpec, has_pixel_or_channel}; + +/// Edit menu: Fill. +pub(crate) fn specs() -> Vec { + vec![cmd!( + "edit.fill", + "Fill…", + ["Edit"], + Some("Shift+F5"), + r##"{"contents":"foreground|background|color|contentAware|pattern|history|black|gray|white"="color","color":"#rrggbb|[r,g,b,a]"=foreground (contents=color),"pattern":id|name (contents=pattern),"scale":%=100,"angle":deg,"state":row?,"snapshot":id? (contents=history: a History panel row as history.setSource, redo rows last, or a snapshot; default the History Brush source),"colorAdaptation":bool=true,"scaleAdaptation":bool=false,"mirror":bool=false,"rotationAdaptation":bool=false (contents=contentAware: enable quarter-turn source candidates within the sampling budget),"mode":"normal|multiply|…"="normal","opacity":0..100=100,"preserveTransparency":bool=false,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}?}"##, + has_pixel_or_channel, + crate::fill_cmds::fill + )] +} diff --git a/crates/engine/src/cmd/table/paint/stroke.rs b/crates/engine/src/cmd/table/paint/stroke.rs new file mode 100644 index 0000000000..8e456d5c48 --- /dev/null +++ b/crates/engine/src/cmd/table/paint/stroke.rs @@ -0,0 +1,14 @@ +use crate::cmd::{CommandSpec, has_paintable}; + +/// Painting: the stroke command. +pub(crate) fn specs() -> Vec { + vec![cmd!( + "paint.stroke", + "Brush Stroke", + [], + None, + r##"{"points":[[x,y,pressure?,tiltX?,tiltY?,rotation?,timeMs?,wheel?],…],"brush":{…BrushSettings}?,"preset":name?,"size":0.5..5000 px?,"hardness":0..1?,"opacity":0..1?,"flow":0..1?,"fill":bool=false (fill the region the closed `points` enclose with the brush colour, its edge anti-aliased and softened by hardness, instead of stamping the outline; a closed gesture paints a filled dab, not a ring),"spacing":0..10?,"color":"#rrggbb"?=foreground,"mode":"normal|multiply|screen|…|clear (erases with this brush)"="normal","erase":bool?,"smoothing":0..1?,"zoom":number=1,"seed":u64?,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target}"##, + has_paintable, + crate::brush_cmds::paint_stroke + )] +} diff --git a/crates/engine/src/cmd/table/store.rs b/crates/engine/src/cmd/table/store.rs new file mode 100644 index 0000000000..f176c41361 --- /dev/null +++ b/crates/engine/src/cmd/table/store.rs @@ -0,0 +1,2 @@ +pub(crate) mod file_menu; +pub(crate) mod layer_menu; diff --git a/crates/engine/src/cmd/table/store/file_menu.rs b/crates/engine/src/cmd/table/store/file_menu.rs new file mode 100644 index 0000000000..97e62f9f5a --- /dev/null +++ b/crates/engine/src/cmd/table/store/file_menu.rs @@ -0,0 +1,76 @@ +use crate::cmd::{Color, ColorMode, CommandSpec, Document, EngineError, Layer, SampleType, Size, Value, always, json, parse_hex}; + +/// File menu: New (new documents take their presets from the document preset store). +pub(crate) fn specs() -> Vec { + vec![ + // File + cmd!( + "file.new", + "New…", + ["File"], + Some("Cmd+N"), + r##"{"width":1..300000=1920,"height":1..300000=1080 (pixel counts are rounded),"mode":"bitmap|rgb|gray|grayscale|cmyk|lab"="rgb","depth":8|16|32=8 (bitmap: 1, its only depth),"background":"white|black|backgroundColor|transparent|#rrggbb"="white" (bitmap: not transparent),"backgroundColor":[r,g,b]? (0..1; defaults to toolbox colour),"resolution":1..30000=72 (ppi),"name":str,"artboard":bool=false (one artboard over the canvas, its background the chosen one, holding an empty Layer 1; no Background layer),"profile":"working"|built-in id|path to an .icc file="working" (the colour profile it is tagged with; it must suit the mode)}"##, + always, + |s, p| { + use crate::document_preset_cmds::{MAX_DIMENSION, MAX_RESOLUTION, background_color, color_mode, sample_type}; + crate::document_preset_cmds::validate_new_params(s, p)?; + // A size given as a float (`512.0`, as JSON from a UI field) is still that size (#254). + let px = |k: &str, d: u32| match p.get(k) { + Some(v) => v + .as_u64() + .map(|n| n.clamp(1, MAX_DIMENSION as u64) as u32) + .or_else(|| v.as_f64().filter(|f| f.is_finite()).map(|f| f.round().clamp(1.0, MAX_DIMENSION as f64) as u32)) + .unwrap_or(d), + None => d, + }; + let (w, h) = (px("width", 1920), px("height", 1080)); + let mode = color_mode(p.get("mode").and_then(Value::as_str).unwrap_or("rgb")).unwrap_or(ColorMode::Rgb); + // A 1-bit Bitmap document is stored as 8-bit gray, like a converted Bitmap image. + let depth = sample_type(p.get("depth").and_then(Value::as_u64).unwrap_or(8)).filter(|_| mode != ColorMode::Bitmap).unwrap_or(SampleType::U8); + let name = p.get("name").and_then(Value::as_str).unwrap_or("Untitled").to_string(); + let res = p.get("resolution").and_then(Value::as_f64).unwrap_or(72.0).clamp(1.0, MAX_RESOLUTION) as f32; + // The background colour; `None` for Transparent. + let background = match p.get("background").and_then(Value::as_str).unwrap_or("white") { + "backgroundColor" => { + let bgc = background_color(p, s.tools.background, "file.new")?; + Some(Color::rgba(bgc[0], bgc[1], bgc[2], 1.0)) + } + "transparent" => None, + "black" => Some(Color::BLACK), + other => { + let c = parse_hex(other).unwrap_or([1.0; 4]); + Some(Color::rgba(c[0], c[1], c[2], c[3])) + } + }; + let mut doc = if p.get("artboard").and_then(Value::as_bool).unwrap_or(false) { + crate::artboard_cmds::new_artboard_document(name, Size::new(w, h), mode, depth, background) + } else if let Some(c) = background { + Document::with_background(name, Size::new(w, h), mode, depth, c) + } else { + let mut d = Document::new(name, Size::new(w, h), mode, depth); + d.layers.push(Layer::raster("Layer 1", d.pixel_format())); + d + }; + doc.resolution_dpi = res; + // Photoshop's New Document › Color Profile: tag the document with another profile + // than the working space (#321). Checked before the document opens. + if let Some(spec) = p.get("profile").and_then(Value::as_str).filter(|spec| !matches!(*spec, "working" | "none")) { + let prof = s.color.resolve(spec, Some(&doc), None)?; + if prof.color_space != crate::color_cmds::mode_space(doc.mode) { + return Err(EngineError::BadParams { + cmd: "file.new".into(), + msg: format!("profile `{}` is {:?}; the document is {:?}", prof.description, prof.color_space, doc.mode), + }); + } + doc.icc_profile = Some(prof.to_bytes()); + } + let i = s.add_document(doc, None); + // A new document's first History state is "New"; opened files keep "Open" (#14029). + if let Some(st) = s.active_mut() { + st.history.set_current_label("New"); + } + Ok(json!({ "document": i })) + } + ), + ] +} diff --git a/crates/engine/src/cmd/table/store/layer_menu.rs b/crates/engine/src/cmd/table/store/layer_menu.rs new file mode 100644 index 0000000000..817b346aa8 --- /dev/null +++ b/crates/engine/src/cmd/table/store/layer_menu.rs @@ -0,0 +1,43 @@ +use crate::cmd::{Color, CommandSpec, Fill, Layer, LayerContent, Value, color_param, has_doc, json, layer_panel_option, mask_new_layer}; + +/// Layer menu: the gradient fill layer. +pub(crate) fn specs() -> Vec { + vec![cmd!( + "layer.newFillLayer.gradient", + "Gradient…", + ["Layer", "New Fill Layer"], + None, + r##"{"from":"#rrggbb","to":"#rrggbb","angle":deg=90,"style":"linear|radial|angle|reflected|diamond","reverse":bool,"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask; else the selection is the layer mask),"stops"?,"transparency"?,"midpoints"?,"scale"?,"offset"?,"dither"?,"align"? (as gradient.fill.set; stops replace from/to)}"##, + has_doc, + |s, p| { + let a = color_param("layer.newFillLayer.gradient", p, "from", s.tools.foreground)?; + let b = color_param("layer.newFillLayer.gradient", p, "to", s.tools.background)?; + let angle = crate::gradient_fill_cmds::angle_param("layer.newFillLayer.gradient", p, 90.0)?; + let style = crate::layer_style::gradient_style(p.get("style").and_then(Value::as_str).unwrap_or("linear")); + let reverse = p.get("reverse").and_then(Value::as_bool).unwrap_or(false); + let default_mask = layer_panel_option(s, "useDefaultMasksOnFillLayers", true); + // The rest of a recorded Gradient Fill (a loaded action's Make): applied as + // `gradient.fill.set` would, in the same step. + let rest: serde_json::Map = ["stops", "transparency", "midpoints", "scale", "offset", "dither", "align"] + .iter() + .filter_map(|k| p.get(*k).map(|v| ((*k).to_string(), v.clone()))) + .collect(); + let (fg, bg) = (s.tools.foreground, s.tools.background); + let id = s.edit("New Gradient Fill Layer", |doc, active| { + let mut fill = + Fill::gradient(vec![(0.0, Color::rgba(a[0], a[1], a[2], a[3])), (1.0, Color::rgba(b[0], b[1], b[2], b[3]))], angle, 1.0, style, reverse); + if !rest.is_empty() { + let l = Layer::new(String::new(), LayerContent::Fill(fill.clone())); + fill = crate::gradient_fill_cmds::apply_set(&l, &fill, doc.bounds(), &Value::Object(rest.clone()), fg, bg)?; + } + let fill = fill.in_mode(doc.mode); + let mut l = Layer::new(doc.next_layer_name("Gradient Fill"), LayerContent::Fill(fill)); + mask_new_layer(doc, &mut l, p, "layer.newFillLayer.gradient", default_mask)?; + let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); + *active = Some(id); + Ok(id) + })?; + Ok(json!({ "layer": id.0 })) + } + )] +} diff --git a/crates/engine/src/cmd/variables_cmds.rs b/crates/engine/src/cmd/variables_cmds.rs index b5e373edf4..367bc8e46e 100644 --- a/crates/engine/src/cmd/variables_cmds.rs +++ b/crates/engine/src/cmd/variables_cmds.rs @@ -278,11 +278,35 @@ fn apply_data_set(s: &mut Session, p: &Value) -> Result { let (set, idx) = resolve_set(s, p, "image.applyDataSet")?; let vars = s.active().ok_or(EngineError::NoDocument)?.doc.variables.clone(); authorize_pixel_paths(s, &set)?; - s.edit("Apply Data Set", |doc, _| apply_to_doc(doc, &vars, &set))?; + // One history state named exactly "Apply Data Set", whatever the set is called (#14498). + let label = "Apply Data Set"; + if replaces_locked_text(&s.active().ok_or(EngineError::NoDocument)?.doc, &vars, &set) { + // As in the reference application, nothing of the set is applied, but the attempt is + // still a history state (one that changes nothing), and the alert names no layer (#14499). + s.edit(label, |_, _| Ok(()))?; + return Err(EngineError::Other(DATA_SET_LAYER_LOCKED.into())); + } + s.edit(label, |doc, _| apply_to_doc(doc, &vars, &set))?; set_vars(s, |v| v.active = Some(idx))?; Ok(json!({"applied": set.name, "index": idx})) } +/// The reference application's alert when Apply Data Set would replace the text of a layer +/// under Lock All. +pub const DATA_SET_LAYER_LOCKED: &str = "Could not apply data set because the layer is locked."; + +/// Whether `set` has a Text value for a type layer with its own Lock All. Visibility and Pixel +/// Replacement values still apply to locked layers, as in the reference application; partial +/// locks and a locked group were not measured and keep applying (#14499). +fn replaces_locked_text(doc: &Document, vars: &Variables, set: &DataSet) -> bool { + set.values.iter().any(|dv| { + matches!(dv.value, VarValue::Text(_)) + && vars.def(&dv.variable).is_some_and(|def| { + matches!(def.kind, VarKind::TextReplacement) && doc.layer(def.layer).is_some_and(|l| l.locks.all && matches!(l.content, LayerContent::Text(_))) + }) + }) +} + /// Resolve a data set from `{name}` or `{index}`. fn resolve_set(s: &Session, p: &Value, cmd: &str) -> Result<(DataSet, usize)> { let vars = &s.active().ok_or(EngineError::NoDocument)?.doc.variables; @@ -575,5 +599,8 @@ mod tests; #[cfg(test)] mod import_enabled_tests; +#[cfg(test)] +mod locked_text_layer_tests; + #[cfg(test)] mod apply_history_name_tests; diff --git a/crates/engine/src/cmd/variables_cmds/locked_text_layer_tests.rs b/crates/engine/src/cmd/variables_cmds/locked_text_layer_tests.rs new file mode 100644 index 0000000000..dbd0ca2995 --- /dev/null +++ b/crates/engine/src/cmd/variables_cmds/locked_text_layer_tests.rs @@ -0,0 +1,208 @@ +//! #14499: Apply Data Set refuses with the reference application's alert when a Text value would +//! replace the text of a type layer under Lock All. Nothing of the set is applied, but one history +//! state that changes nothing is still added. Visibility and Pixel Replacement values keep +//! applying to locked layers; partial locks and Data Sets as Files keep today's behaviour. + +use super::*; +use photocraft_doc::{Layer, Locks, TextLayer}; +use photocraft_geom::Rect; + +const APPLY: &str = "image.applyDataSet"; + +/// A document with a raster layer "photo", a red raster "badge" and a text layer "title", bound +/// to the variables `photo` (pixels), `showBadge`, `showTitle` (visibility) and `headline` (text). +fn session() -> (Session, LayerId, LayerId, LayerId) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); + let (photo, badge, title) = s + .edit("setup", |doc, _| { + let fmt = doc.pixel_format(); + let mut photo = Layer::raster("photo", fmt); + photo.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 64, 48), &photocraft_raster::from_rgba(&fmt, [0.5, 0.5, 0.5, 1.0])); + let mut badge = Layer::raster("badge", fmt); + badge.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 10, 10), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); + let title = Layer::new("title", LayerContent::Text(TextLayer { text: "Old".into(), ..Default::default() })); + let ids = (photo.id, badge.id, title.id); + doc.layers.extend([photo, badge, title]); + Ok(ids) + }) + .unwrap(); + s.execute( + "image.variables.define", + json!({"defs": [ + {"name": "photo", "layer": photo.0, "type": "pixelReplacement", "method": "conform"}, + {"name": "showBadge", "layer": badge.0, "type": "visibility"}, + {"name": "showTitle", "layer": title.0, "type": "visibility"}, + {"name": "headline", "layer": title.0, "type": "textReplacement"}, + ]}), + ) + .unwrap(); + (s, photo, badge, title) +} + +/// A blue 8x8 PNG for the `photo` variable. +fn blue_png(name: &str) -> (String, String) { + let dir = std::env::temp_dir().join(format!("pc-vars-{}-locked-{name}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + let png = dir.join("blue.png"); + let mut src = Session::new(); + src.execute("file.new", json!({"width": 8, "height": 8, "background": "#0000ff"})).unwrap(); + let bytes = photocraft_io::export(&src.active().unwrap().doc, "png", &photocraft_io::ExportOptions::default()).unwrap().bytes; + std::fs::write(&png, bytes).unwrap(); + (dir.to_string_lossy().into_owned(), png.to_string_lossy().into_owned()) +} + +fn data_sets(s: &mut Session, sets: Value) { + s.execute("image.variables.dataSets", json!({ "dataSets": sets })).unwrap(); +} + +fn lock(s: &mut Session, id: LayerId, locks: Locks) { + s.edit("lock", |doc, _| { + doc.layer_mut(id).unwrap().locks = locks; + Ok(()) + }) + .unwrap(); +} + +fn all() -> Locks { + Locks { all: true, ..Locks::default() } +} + +fn doc(s: &Session) -> &Document { + &s.active().unwrap().doc +} + +fn text_of(s: &Session, id: LayerId) -> String { + match &doc(s).layer(id).unwrap().content { + LayerContent::Text(t) => t.text.clone(), + _ => panic!("not a text layer"), + } +} + +fn visible(s: &Session, id: LayerId) -> bool { + doc(s).layer(id).unwrap().visible +} + +fn pixel(s: &Session, id: LayerId) -> Vec { + doc(s).layer(id).unwrap().surface().unwrap().pixel(32, 24) +} + +fn history(s: &Session) -> (usize, Option) { + let h = &s.active().unwrap().history; + (h.past_len(), h.entries().last().map(|e| e.to_string())) +} + +#[test] +fn a_text_value_for_a_locked_type_layer_applies_nothing_and_alerts() { + let (mut s, photo, badge, title) = session(); + let (dir, png) = blue_png("refuse"); + data_sets( + &mut s, + json!([{"name": "Zed", "values": [ + {"variable": "photo", "kind": "pixels", "value": png}, + {"variable": "showBadge", "kind": "visibility", "value": false}, + {"variable": "showTitle", "kind": "visibility", "value": false}, + {"variable": "headline", "kind": "text", "value": "Alpha\rLine2"}, + ]}]), + ); + lock(&mut s, title, all()); + let photo_before = pixel(&s, photo); + let (n, _) = history(&s); + + let r = s.execute(APPLY, json!({"name": "Zed"})); + assert!(matches!(&r, Err(EngineError::Other(m)) if m == DATA_SET_LAYER_LOCKED), "{r:?}"); + assert_eq!(DATA_SET_LAYER_LOCKED, "Could not apply data set because the layer is locked."); + + // Nothing of the set: the text, both visibilities and the photo's pixels stay. + assert_eq!(text_of(&s, title), "Old"); + assert!(visible(&s, title) && visible(&s, badge)); + assert_eq!(pixel(&s, photo), photo_before); + assert_eq!(doc(&s).variables.active, None, "the set did not become the applied one"); + + // One history state for the attempt, which changes nothing. + let (after, label) = history(&s); + assert_eq!(after, n + 1); + assert!(label.as_deref().is_some_and(|l| l.starts_with("Apply Data Set")), "{label:?}"); + let applied = doc(&s).clone(); + assert!(s.undo()); + assert_eq!(history(&s).0, n); + assert_eq!(text_of(&s, title), "Old"); + assert!(s.redo()); + assert_eq!(doc(&s).layers, applied.layers, "the state changes nothing"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn the_same_set_applies_once_the_layer_is_unlocked() { + let (mut s, _photo, badge, title) = session(); + data_sets( + &mut s, + json!([{"name": "Zed", "values": [ + {"variable": "showBadge", "kind": "visibility", "value": false}, + {"variable": "headline", "kind": "text", "value": "Alpha"}, + ]}]), + ); + lock(&mut s, title, all()); + assert!(s.execute(APPLY, json!({"name": "Zed"})).is_err()); + lock(&mut s, title, Locks::default()); + s.execute(APPLY, json!({"name": "Zed"})).unwrap(); + assert_eq!(text_of(&s, title), "Alpha"); + assert!(!visible(&s, badge)); + assert_eq!(doc(&s).variables.active, Some(0)); +} + +#[test] +fn visibility_values_still_apply_to_locked_layers() { + let (mut s, _photo, badge, title) = session(); + data_sets( + &mut s, + json!([{"name": "Hide", "values": [ + {"variable": "showBadge", "kind": "visibility", "value": false}, + {"variable": "showTitle", "kind": "visibility", "value": false}, + ]}]), + ); + lock(&mut s, badge, all()); + lock(&mut s, title, all()); + s.execute(APPLY, json!({"name": "Hide"})).unwrap(); + assert!(!visible(&s, badge) && !visible(&s, title)); +} + +#[test] +fn pixel_replacement_still_applies_to_a_locked_pixel_layer() { + let (mut s, photo, _badge, _title) = session(); + let (dir, png) = blue_png("pixels"); + data_sets(&mut s, json!([{"name": "Blue", "values": [{"variable": "photo", "kind": "pixels", "value": png}]}])); + lock(&mut s, photo, all()); + s.execute(APPLY, json!({"name": "Blue"})).unwrap(); + assert_eq!(pixel(&s, photo), vec![0.0, 0.0, 1.0, 1.0]); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn partial_locks_keep_applying_text() { + let partial = [ + Locks { transparency: true, ..Locks::default() }, + Locks { pixels: true, ..Locks::default() }, + Locks { position: true, ..Locks::default() }, + Locks { transparency: true, pixels: true, position: true, artboard: true, all: false }, + ]; + for locks in partial { + let (mut s, _photo, _badge, title) = session(); + data_sets(&mut s, json!([{"name": "T", "values": [{"variable": "headline", "kind": "text", "value": "New"}]}])); + lock(&mut s, title, locks); + s.execute(APPLY, json!({"name": "T"})).unwrap_or_else(|e| panic!("{locks:?}: {e}")); + assert_eq!(text_of(&s, title), "New", "{locks:?}"); + } +} + +#[test] +fn data_sets_as_files_keeps_exporting_a_locked_type_layer() { + let (mut s, _photo, _badge, title) = session(); + data_sets(&mut s, json!([{"name": "T", "values": [{"variable": "headline", "kind": "text", "value": "New"}]}])); + lock(&mut s, title, all()); + let dir = std::env::temp_dir().join(format!("pc-vars-{}-locked-export", std::process::id())); + let out = s.execute("file.export.dataSetsAsFiles", json!({"dir": dir.to_string_lossy(), "format": "png"})).unwrap(); + assert_eq!(out["files"].as_array().map(Vec::len), Some(1), "{out}"); + assert_eq!(text_of(&s, title), "Old", "the export leaves the document alone"); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 4bb6dcfa85..7c30247f6a 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -191,7 +191,7 @@ pub struct ToolState { pub background: [f32; 4], pub brush: photocraft_paint::BrushSettings, /// Brush presets (built-ins plus user presets; see `brush.presets.*`). - pub presets: Vec, + pub presets: Arc>, /// Bumped whenever `presets` changes ([`Session::brush_presets_changed`]); the preset store /// syncs when it moves. pub presets_rev: u64, @@ -292,7 +292,7 @@ impl Default for ToolState { smoothing: photocraft_paint::brush::Smoothing { amount: 0.1, ..Default::default() }, ..Default::default() }, - presets: photocraft_paint::presets::builtin(), + presets: photocraft_paint::presets::builtin_shared(), presets_rev: 0, mixer: Default::default(), brush_gesture: None, diff --git a/crates/engine/src/hidden_target.rs b/crates/engine/src/hidden_target.rs index c8bcbf54db..01e9ec0959 100644 --- a/crates/engine/src/hidden_target.rs +++ b/crates/engine/src/hidden_target.rs @@ -11,6 +11,9 @@ use crate::Session; /// Photoshop's alert text. pub const HIDDEN: &str = "Could not complete your request because the target layer is hidden."; +/// 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."; + /// Commands that paint on, or move, the target layer. const GATED: &[&str] = &[ "paint.stroke", @@ -53,7 +56,10 @@ pub fn refusal(s: &Session, id: &str, params: &Value) -> Option<&'static str> { } let st = s.active()?; let layer = crate::commands::layer_param(s, ¶ms).ok()?; - (st.doc.layer(layer).is_some() && !shown(&st.doc, layer)).then_some(HIDDEN) + // The Art History Brush's text was measured on a layer's pixels only. + let pixels = crate::channel_cmds::target_of(¶ms) == crate::channel_cmds::Target::Pixels; + let why = if id == "paint.artHistoryBrush" && pixels { ART_HISTORY_HIDDEN } else { HIDDEN }; + (st.doc.layer(layer).is_some() && !shown(&st.doc, layer)).then_some(why) } #[cfg(test)] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 4dbb442134..ba13d41e61 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -45,7 +45,7 @@ pub mod select_mask_edits; pub mod shell_commands; pub mod shortcut_sets; pub mod snap; -pub use variables_cmds::{export_data_sets_with, import_data_sets_text}; +pub use variables_cmds::{DATA_SET_LAYER_LOCKED, export_data_sets_with, import_data_sets_text}; pub use video_cmds::render_video_with; use std::sync::Arc; diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index d193d89c34..23a0a97042 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -1946,6 +1946,12 @@ impl Session { self.prefs.get() } + /// Revision of the framework preference section `key`: it moves when an edit changes that + /// section. + pub fn section_rev(&self, key: &str) -> u64 { + self.prefs.section_rev(key) + } + /// Change preferences and apply the engine-side ones. pub fn edit_prefs(&mut self, f: impl FnOnce(&mut Preferences) -> R) -> R { let r = self.prefs.edit(f); diff --git a/crates/engine/src/preset_store.rs b/crates/engine/src/preset_store.rs index c654de811f..dff99794fc 100644 --- a/crates/engine/src/preset_store.rs +++ b/crates/engine/src/preset_store.rs @@ -879,7 +879,7 @@ impl PresetStore { /// Bring the files in line with `presets` (built-ins skipped): write changed groups, delete /// removed ones and their unreferenced tips, update the index. The bitmaps of every group /// written become stored tiles (#1843): the files hold them, so the presets keep previews only. - pub fn sync(&mut self, presets: &mut [BrushPreset]) { + pub fn sync(&mut self, presets: &mut std::sync::Arc>) { // User presets by group, in first-appearance order. let mut order: Vec<(String, Vec)> = Vec::new(); for (i, p) in presets.iter().enumerate().filter(|(_, p)| !p.builtin) { @@ -906,7 +906,7 @@ impl PresetStore { )); continue; } - let mut items: Vec<&mut BrushPreset> = presets.iter_mut().filter(|p| !p.builtin && p.group == *group).collect(); + let mut items: Vec<&mut BrushPreset> = std::sync::Arc::make_mut(presets).iter_mut().filter(|p| !p.builtin && p.group == *group).collect(); if let Err(e) = self.write_group(&file, group, &mut items) { self.warnings.push(format!("Couldn't save brush presets `{}`: {e}", if group.is_empty() { "(ungrouped)" } else { group })); } @@ -1103,7 +1103,7 @@ impl PresetStore { fn builtin_names() -> &'static [String] { static NAMES: std::sync::OnceLock> = std::sync::OnceLock::new(); - NAMES.get_or_init(|| photocraft_paint::presets::builtin().into_iter().map(|p| p.name).collect()) + NAMES.get_or_init(|| photocraft_paint::presets::builtin_shared().iter().map(|p| p.name.clone()).collect()) } impl Session { @@ -1141,19 +1141,26 @@ impl Session { } } } - let lib = &mut self.tools.presets; - lib.retain(|p| !(p.builtin && hidden_builtins.iter().any(|h| h.eq_ignore_ascii_case(&p.name)))); + // The list stays shared (`make_mut` is taken at the first write) when the store changes nothing. + let hide = |p: &BrushPreset| p.builtin && hidden_builtins.iter().any(|h| h.eq_ignore_ascii_case(&p.name)); + if self.tools.presets.iter().any(hide) { + std::sync::Arc::make_mut(&mut self.tools.presets).retain(|p| !hide(p)); + } for p in presets { - match lib.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&p.name)) { - Some(x) if x.builtin => *x = p, + let found = self.tools.presets.iter().position(|x| x.name.eq_ignore_ascii_case(&p.name)); + match found { + Some(i) if self.tools.presets[i].builtin && self.tools.presets[i] != p => std::sync::Arc::make_mut(&mut self.tools.presets)[i] = p, Some(_) => {} - None => lib.push(p), + None => std::sync::Arc::make_mut(&mut self.tools.presets).push(p), } } // The saved panel order (stable: presets it doesn't name keep their order, at the end). if !order.is_empty() { let pos: HashMap = order.iter().enumerate().map(|(i, n)| (n.to_lowercase(), i)).collect(); - lib.sort_by_key(|p| pos.get(&p.name.to_lowercase()).copied().unwrap_or(usize::MAX)); + let key = |p: &BrushPreset| pos.get(&p.name.to_lowercase()).copied().unwrap_or(usize::MAX); + if !self.tools.presets.iter().map(key).is_sorted() { + std::sync::Arc::make_mut(&mut self.tools.presets).sort_by_key(key); + } } self.preset_store = Some(store); // Clear All, Reset or Replace before the store loaded made the session's list the whole diff --git a/crates/engine/src/preset_store/tests.rs b/crates/engine/src/preset_store/tests.rs index 368d74e155..18f5f96182 100644 --- a/crates/engine/src/preset_store/tests.rs +++ b/crates/engine/src/preset_store/tests.rs @@ -52,6 +52,20 @@ fn user(s: &Session) -> Vec { s.tools.presets.iter().filter(|p| !p.builtin).cloned().collect() } +#[test] +fn empty_stores_preserve_shared_builtin_presets() { + let first_dir = TempDir::new("shared-first"); + let second_dir = TempDir::new("shared-second"); + let (mut first, warnings) = session(&first_dir); + assert!(warnings.is_empty(), "{warnings:?}"); + let (second, warnings) = session(&second_dir); + assert!(warnings.is_empty(), "{warnings:?}"); + assert!(std::sync::Arc::ptr_eq(&first.tools.presets, &second.tools.presets)); + first.execute("brush.presets.save", json!({"name": "Only first"})).unwrap(); + assert!(second.tools.presets.iter().all(|p| p.name != "Only first")); + assert!(!std::sync::Arc::ptr_eq(&first.tools.presets, &second.tools.presets)); +} + #[test] fn sessions_have_no_store_by_default() { let mut s = Session::new(); @@ -119,7 +133,7 @@ fn group_with_sampled_8_and_16_bit_tips_round_trips() { let b = sampled("Sixteen", "Inks", tip16(50, 70, 2)); let mut c = sampled("Shared tip", "Other", tip8(64, 48, 1)); c.brush.size = 9.0; - s.tools.presets.extend([a, b, c]); + std::sync::Arc::make_mut(&mut s.tools.presets).extend([a, b, c]); s.brush_presets_changed(); s.sync_preset_store(); let files = dir.files(); @@ -243,7 +257,7 @@ fn startup_with_many_groups_loads_them_all() { let (mut s, _) = session(&dir); for g in 0..25 { for i in 0..4 { - s.tools.presets.push(sampled(&format!("P{g}-{i}"), &format!("Group {g}"), tip8(16 + i, 16, g))); + std::sync::Arc::make_mut(&mut s.tools.presets).push(sampled(&format!("P{g}-{i}"), &format!("Group {g}"), tip8(16 + i, 16, g))); } } s.brush_presets_changed(); @@ -267,7 +281,7 @@ fn reordering_presets_and_groups_persists() { let (mut s, _) = session(&dir); for (n, g) in [("Ink 1", "Inks"), ("Ink 2", "Inks"), ("Wash", "Washes")] { s.execute("brush.presets.save", json!({"name": n})).unwrap(); - s.tools.presets.iter_mut().find(|p| p.name == n).unwrap().group = g.into(); + std::sync::Arc::make_mut(&mut s.tools.presets).iter_mut().find(|p| p.name == n).unwrap().group = g.into(); } s.brush_presets_changed(); s.sync_preset_store(); @@ -295,12 +309,28 @@ fn reordering_presets_and_groups_persists() { assert!(t.tools.presets.iter().all(|p| p.group != "Washes" && p.group != "Inks")); } +#[test] +fn reordering_only_built_in_presets_persists() { + let names = |s: &Session| s.tools.presets.iter().map(|p| p.name.clone()).collect::>(); + let dir = TempDir::new("reorder-builtin"); + let (mut s, _) = session(&dir); + let group = s.tools.presets[0].group.clone(); + let last = s.tools.presets.iter().rfind(|p| p.builtin && p.group == group).unwrap().name.clone(); + let first = s.tools.presets[0].name.clone(); + assert_ne!(last, first); + s.execute("brush.presets.move", json!({"name": last, "before": first})).unwrap(); + assert_eq!(s.tools.presets[0].name, last); + let (t, w) = session(&dir); + assert!(w.is_empty(), "{w:?}"); + assert_eq!(names(&t), names(&s), "the new built-in order survives a restart"); +} + #[test] fn corrupt_and_oversized_files_are_skipped_with_a_warning() { let dir = TempDir::new("corrupt"); let (mut s, _) = session(&dir); - s.tools.presets.push(sampled("Good", "Fine", tip8(8, 8, 1))); - s.tools.presets.push(sampled("Lost", "Broken tip", tip16(9, 9, 2))); + std::sync::Arc::make_mut(&mut s.tools.presets).push(sampled("Good", "Fine", tip8(8, 8, 1))); + std::sync::Arc::make_mut(&mut s.tools.presets).push(sampled("Lost", "Broken tip", tip16(9, 9, 2))); s.brush_presets_changed(); s.sync_preset_store(); let be = DirBackend::new(&dir.0); @@ -370,7 +400,7 @@ fn bench_load_500_sampled_presets() { // A mix of 8-bit (most .abr tips) and 16-bit tips, 64..319 px. let side = 64 + (i * 37) % 256; let t = if i % 4 == 0 { tip16(side, side, i) } else { tip8(side, side, i) }; - s.tools.presets.push(sampled(&format!("Brush {i}"), &format!("Set {}", i / 50), t)); + std::sync::Arc::make_mut(&mut s.tools.presets).push(sampled(&format!("Brush {i}"), &format!("Set {}", i / 50), t)); } s.brush_presets_changed(); let t0 = std::time::Instant::now(); @@ -411,7 +441,7 @@ fn library(n: u32, side: u32) -> (Session, MemBackend) { let mut s = Session::new(); s.attach_preset_store(open(Box::new(mem.clone()))); for i in 0..n { - s.tools.presets.push(sampled(&format!("Big {i}"), "Big Set", tip8(side, side, i))); + std::sync::Arc::make_mut(&mut s.tools.presets).push(sampled(&format!("Big {i}"), "Big Set", tip8(side, side, i))); } s.brush_presets_changed(); s.sync_preset_store(); @@ -519,7 +549,7 @@ fn missing_corrupt_or_unknown_tips_fail_when_used_without_panicking() { let k0 = key(&t, "Big 0"); mem.remove(&tip_file(&k0)).unwrap(); t.execute("tools.setBrush", json!({"preset": "Hard Round"})).unwrap(); - let broken = t.tools.presets.iter_mut().find(|p| p.name == "Big 0").unwrap(); + let broken = std::sync::Arc::make_mut(&mut t.tools.presets).iter_mut().find(|p| p.name == "Big 0").unwrap(); broken.captures.color = true; broken.brush.color = [1.0, 0.0, 0.0, 1.0]; t.tools.foreground = [0.0, 0.0, 1.0, 1.0]; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index b15add018c..2e6b02aa32 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2063,3 +2063,16 @@ fn the_active_layer_marker_advances_for_a_new_document_and_not_for_a_same_layer_ s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); assert!(s.active_layer_changes() > before, "a new active document advances the marker"); } + +#[test] +fn sessions_share_builtin_brushes_until_edited() { + let mut first = Session::new(); + let second = Session::new(); + assert!(std::sync::Arc::ptr_eq(&first.tools.presets, &second.tools.presets)); + let count = second.tools.presets.len(); + first.execute("brush.presets.save", serde_json::json!({"name": "Session-only test brush"})).unwrap(); + assert_eq!(second.tools.presets.len(), count); + assert!(second.tools.presets.iter().all(|preset| preset.name != "Session-only test brush")); + assert!(first.tools.presets.iter().any(|preset| preset.name == "Session-only test brush")); + assert!(!std::sync::Arc::ptr_eq(&first.tools.presets, &second.tools.presets)); +} diff --git a/crates/gpu/src/compose.wgsl b/crates/gpu/src/compose.wgsl index ce201714ba..2383c43fe8 100644 --- a/crates/gpu/src/compose.wgsl +++ b/crates/gpu/src/compose.wgsl @@ -1553,8 +1553,9 @@ fn bevel_part(p: vec2, depth: f32, region: f32) -> f32 { let shade = (n.x * op.p0.x + n.y * op.p0.y + n.z * op.p0.z) / len; let se = op.p0.w; var k = shade - se; - // effects::bevel_maps: the gloss contour maps the shading, a flat face's as the neutral (#7360). - if (op.p1.w > 0.5) { k = lut(0, shade) - lut(0, se); } + // effects::bevel_maps: the gloss contour maps the shading; a flat face's unmapped shading + // stays the neutral (#7360). + if (op.p1.w > 0.5) { k = lut(0, shade) - se; } var v = 0.0; if (op.p1.z > 0.5) { if (k <= 0.0) { v = clamp(-k / max(se, 1e-3), 0.0, 1.0) * region; } diff --git a/crates/gpu/tests/it/parity.rs b/crates/gpu/tests/it/parity.rs index e12030fe52..7ccb4a5f8d 100644 --- a/crates/gpu/tests/it/parity.rs +++ b/crates/gpu/tests/it/parity.rs @@ -1703,6 +1703,10 @@ fn effect_cases() -> Vec<(&'static str, Vec)> { points: vec![Cp { input: 0.0, output: 1.0 }, Cp { input: 0.4, output: 0.4 }, Cp { input: 1.0, output: 0.0 }], corners: vec![], }; + // The same contour under a high light, deep (altitude 69, 358 %): the unmapped flat shading + // stays the neutral, so only the slope facing away glints, on both renderers. + let mut bevel_gloss_high_alt = bevel_gloss_high.clone(); + (bevel_gloss_high_alt.use_global_light, bevel_gloss_high_alt.angle, bevel_gloss_high_alt.altitude, bevel_gloss_high_alt.depth) = (false, 146.0, 69.0, 3.58); vec![ ("drop shadow", vec![Effect::DropShadow(shadow(BlendMode::Multiply, 0.75, 120.0, 6.0, 8.0, 0.0))]), ("drop shadow spread contour", vec![Effect::DropShadow(ds_contour)]), @@ -1795,6 +1799,7 @@ fn effect_cases() -> Vec<(&'static str, Vec)> { ), ("bevel contour own light", vec![Effect::BevelEmboss(bevel_contour)]), ("bevel gloss starting high", vec![Effect::BevelEmboss(bevel_gloss_high)]), + ("bevel gloss starting high, high light", vec![Effect::BevelEmboss(bevel_gloss_high_alt)]), ("satin", vec![Effect::Satin(satin)]), ("satin inverted contour", vec![Effect::Satin(satin_inv)]), ("stroke outside colour", vec![Effect::Stroke(stroke(4.0, StrokePosition::Outside, FxPaint::Color(Color::rgb(0.95, 0.85, 0.1))))]), diff --git a/crates/io/src/blocks.rs b/crates/io/src/blocks.rs index 24cfba224a..5fa2056888 100644 --- a/crates/io/src/blocks.rs +++ b/crates/io/src/blocks.rs @@ -9,14 +9,10 @@ use photocraft_geom::Affine; /// `brst` (channel blending restrictions): a list of big-endian u32 channel indices left out of /// blending → a bit mask (bit `i` = channel `i`; indices above 31 are ignored). -pub fn parse_brst(data: &[u8]) -> u32 { - data.as_chunks::<4>().0.iter().map(|c| u32::from_be_bytes([c[0], c[1], c[2], c[3]])).filter(|&i| i < 32).fold(0, |m, i| m | 1 << i) -} +pub use craft_psd::tagged::channel_restrictions as parse_brst; /// Inverse of [`parse_brst`]; `None` when every channel blends (no block). -pub fn brst_data(mask: u32) -> Option> { - (mask != 0).then(|| (0..32u32).filter(|i| mask & 1 << i != 0).flat_map(u32::to_be_bytes).collect()) -} +pub use craft_psd::tagged::channel_restrictions_data as brst_data; /// The Advanced Blending blocks, as (key, value for `a`, Photoshop's default value): `knko` /// (0 none, 1 shallow, 2 deep), `infx`, `clbl`, `tsly`, `lmgm`, `vmgm`. Each is stored as one diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index 6ab2dc4134..7b0fd16d0a 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -609,7 +609,7 @@ impl Ex<'_> { None => raw.retain(|(k, _)| k != b"fxrp"), } // Advanced Blending channel restrictions: written from the field (in place). - match crate::blocks::brst_data(l.excluded_channels) { + match craft_psd::tagged::channel_restrictions_data(l.excluded_channels) { Some(data) => match raw.iter_mut().find(|(k, _)| k == b"brst") { Some(e) => e.1 = data, None => raw.push((*b"brst", data)), diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs index 706802ee26..e5c3e59330 100644 --- a/crates/io/src/psd_import.rs +++ b/crates/io/src/psd_import.rs @@ -479,7 +479,7 @@ impl Ctx<'_> { // Advanced Blending channel restrictions (`brst`: the u32 ids of channels left out); // also kept in `psd_blocks`, where export rewrites it from the field. if let Some(b) = rec.block(b"brst") { - l.excluded_channels = crate::blocks::parse_brst(&b.data); + l.excluded_channels = craft_psd::tagged::channel_restrictions(&b.data); } // Advanced Blending (`knko`, `infx`, `clbl`, `tsly`, `lmgm`, `vmgm`); the blocks stay in // `psd_blocks`, where export rewrites them from the field in place. diff --git a/crates/io/tests/it/roundtrip.rs b/crates/io/tests/it/roundtrip.rs index af72cd1e1c..076fbc7553 100644 --- a/crates/io/tests/it/roundtrip.rs +++ b/crates/io/tests/it/roundtrip.rs @@ -474,6 +474,58 @@ fn channel_restrictions_round_trip_as_brst() { assert!(f.layers().iter().find(|r| r.name() == "a").unwrap().block(b"brst").is_none()); } +fn channel_restrictions_psd(payload: Vec) -> Vec { + use craft_psd::{LayerSpec, PixelData, PsdBuilder, TaggedBlock}; + let mut layer = LayerSpec::new("restricted", 0, 0, 1, 1, PixelData::Rgba8(vec![80, 120, 160, 255])); + layer.extra_blocks = vec![TaggedBlock::new(*b"zBef", vec![1, 2, 3, 4]), TaggedBlock::new(*b"brst", payload), TaggedBlock::new(*b"zAft", vec![5, 6, 7, 8])]; + let mut builder = PsdBuilder::new(1, 1); + builder.push_layer(layer); + builder.composite(PixelData::Rgba8(vec![80, 120, 160, 255])); + builder.to_bytes().unwrap() +} + +#[test] +fn channel_restrictions_partial_records_preserve_valid_indices_and_neighboring_blocks() { + for trailing in [vec![0xaa], vec![0xaa, 0xbb], vec![0xaa, 0xbb, 0xcc]] { + // The complete indices are 31, 32, 0, 31: 32 is ignored and 31 is a duplicate. + let mut payload = vec![0, 0, 0, 31, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 31]; + payload.extend(trailing); + let bytes = channel_restrictions_psd(payload.clone()); + let document = import("restrictions.psd", &bytes).unwrap().document; + let layer = document.layers.iter().find(|layer| layer.name == "restricted").unwrap(); + assert_eq!(layer.excluded_channels, 0x8000_0001); + assert!(layer.psd_blocks.iter().any(|(key, data)| key == b"brst" && data.as_slice() == payload)); + + let saved = export(&document, "restrictions.psd", &ExportOptions::default()).unwrap().bytes; + let file = PsdFile::from_bytes(&saved).unwrap(); + let record = file.layers().iter().find(|record| record.name() == "restricted").unwrap(); + let preserved: Vec<_> = record.blocks.iter().filter(|block| [*b"zBef", *b"brst", *b"zAft"].contains(&block.key)).collect(); + assert_eq!(preserved.iter().map(|block| block.key).collect::>(), vec![*b"zBef", *b"brst", *b"zAft"]); + assert_eq!(preserved[0].data, vec![1, 2, 3, 4]); + assert_eq!(preserved[1].data, vec![0, 0, 0, 0, 0, 0, 0, 31]); + assert_eq!(preserved[2].data, vec![5, 6, 7, 8]); + let reopened = import("restrictions.psd", &saved).unwrap().document; + assert_eq!(reopened.layers.iter().find(|layer| layer.name == "restricted").unwrap().excluded_channels, 0x8000_0001); + } +} + +#[test] +fn channel_restrictions_without_valid_records_are_omitted() { + for payload in [vec![], vec![0xaa], vec![0xaa, 0xbb], vec![0xaa, 0xbb, 0xcc], vec![0, 0, 0, 32, 255, 255, 255, 255]] { + let bytes = channel_restrictions_psd(payload); + let document = import("restrictions.psd", &bytes).unwrap().document; + assert_eq!(document.layers.iter().find(|layer| layer.name == "restricted").unwrap().excluded_channels, 0); + let saved = export(&document, "restrictions.psd", &ExportOptions::default()).unwrap().bytes; + let file = PsdFile::from_bytes(&saved).unwrap(); + let record = file.layers().iter().find(|record| record.name() == "restricted").unwrap(); + assert!(record.block(b"brst").is_none()); + assert_eq!(record.block(b"zBef").unwrap().data, vec![1, 2, 3, 4]); + assert_eq!(record.block(b"zAft").unwrap().data, vec![5, 6, 7, 8]); + let reopened = import("restrictions.psd", &saved).unwrap().document; + assert_eq!(reopened.layers.iter().find(|layer| layer.name == "restricted").unwrap().excluded_channels, 0); + } +} + /// Advanced Blending maps to `knko` / `infx` / `clbl` / `tsly` / `lmgm` / `vmgm` (one byte + /// three of padding), at every depth: non-default values are written, default layers gain no /// blocks, and imported blocks are rewritten in place. diff --git a/crates/paint/src/brush.rs b/crates/paint/src/brush.rs index c5b06941c3..9ba59dc75d 100644 --- a/crates/paint/src/brush.rs +++ b/crates/paint/src/brush.rs @@ -531,11 +531,13 @@ pub struct Smoothing { pub enabled: bool, /// 0..1. pub amount: f32, - /// Lazy-mouse: paint only when the pointer pulls a string of `amount × 100 px` taut. + /// Lazy-mouse: paint only when the pointer pulls a string of `amount × 300 px` taut + /// ([`crate::dynamics::MAX_STRING_PX`], screen pixels before Adjust for Zoom). pub pulled_string: bool, /// Keep catching up with the pointer while it pauses (uses point timestamps). pub catch_up: bool, - /// Finish the stroke at the last pointer position. + /// Finish the stroke at the last pointer position. No effect in Pulled String Mode, where the + /// stroke ends the string's length behind the pointer (measured, #11888). pub catch_up_on_end: bool, /// Divide the string length by the view zoom (the command's `zoom` param). pub adjust_for_zoom: bool, diff --git a/crates/paint/src/brush_tests.rs b/crates/paint/src/brush_tests.rs index da5f546b0f..4880f0a5ab 100644 --- a/crates/paint/src/brush_tests.rs +++ b/crates/paint/src/brush_tests.rs @@ -359,6 +359,10 @@ fn hard_round_presets_have_continuous_pressure_opacity_tapers() { b.size = 150.0; b.pressure_opacity = true; b.smoothing.amount = smoothing; + // The measured lag (#11888) leaves a 49 % stroke ~150 px short of the pointer, so + // its end cap would fall inside the span checked below; catch-up on end paints it + // through to the last point. + b.smoothing.catch_up_on_end = true; let mut s = Surface::new(fmt); render_stroke(&mut s, &b, &points, None, false, 1.0); assert!(s.rgba(200, 120)[3] > 0.7 && s.rgba(699, 120)[3] < 0.3, "{}: the stroke must still taper", preset.name); @@ -882,26 +886,27 @@ fn smoothing_modes() { // Pulled string: jitter smaller than the string moves nothing; the brush trails by the string. let ps = Smoothing { amount: 0.2, pulled_string: true, catch_up_on_end: false, ..Default::default() }; let jitter: Vec = (0..20).map(|i| StrokePoint::new(if i % 2 == 0 { 0.0 } else { 5.0 }, 0.0, 1.0)).collect(); - assert_eq!(smooth_points(&ps, 1.0, &jitter).len(), 1, "within the 20 px string: no motion"); + assert_eq!(smooth_points(&ps, 1.0, &jitter).len(), 1, "within the 60 px string: no motion"); let far = smooth_points(&ps, 1.0, &[StrokePoint::new(0.0, 0.0, 1.0), StrokePoint::new(100.0, 0.0, 1.0)]); - assert!((far.last().unwrap().x - 80.0).abs() < 1e-4); + assert!((far.last().unwrap().x - 40.0).abs() < 1e-4); // Adjust for zoom: at 200 % zoom the string is half as long in image pixels. let far = smooth_points(&ps, 2.0, &[StrokePoint::new(0.0, 0.0, 1.0), StrokePoint::new(100.0, 0.0, 1.0)]); - assert!((far.last().unwrap().x - 90.0).abs() < 1e-4); + assert!((far.last().unwrap().x - 70.0).abs() < 1e-4); // Stroke catch-up: a pause (timestamps) lets the brush converge on the pointer. let mut a = StrokePoint::new(0.0, 0.0, 1.0); a.time = 0.0; let b = StrokePoint { x: 100.0, time: 16.0, ..a }; - let c = StrokePoint { time: 500.0, ..b }; + let c = StrokePoint { time: 1000.0, ..b }; + let d = StrokePoint { time: 2000.0, ..b }; let mut s = Smoother::new(&Smoothing { amount: 0.8, catch_up: true, catch_up_on_end: false, ..Default::default() }, 1.0); let mut out = Vec::new(); - for p in [a, b, c] { + for p in [a, b, c, d] { s.push(p, &mut out); } assert!(out.last().unwrap().x > 99.0, "{}", out.last().unwrap().x); let mut s = Smoother::new(&Smoothing { amount: 0.8, catch_up: false, catch_up_on_end: false, ..Default::default() }, 1.0); let mut out = Vec::new(); - for p in [a, b, c] { + for p in [a, b, c, d] { s.push(p, &mut out); } assert!(out.last().unwrap().x < 70.0, "{}", out.last().unwrap().x); @@ -933,7 +938,10 @@ fn disabled_smoothing_keeps_its_settings_and_paints_unsmoothed_at_every_depth() let mut back: Smoothing = serde_json::from_value(serde_json::to_value(&smoothing).unwrap()).unwrap(); assert_eq!(back, smoothing); back.enabled = true; - assert!(smooth_points(&back, 1.0, &pts).iter().zip(&pts).any(|(a, b)| a.x != b.x || a.y != b.y)); + // Re-enabled, it smooths again: different points, or fewer (a pulled string that hasn't + // been pulled taut leaves the brush where it started, #11888). + let again = smooth_points(&back, 1.0, &pts); + assert!(again.len() != pts.len() || again.iter().zip(&pts).any(|(a, b)| a.x != b.x || a.y != b.y)); } // Existing brush JSON has no switch and must retain its old smoothing behavior. let legacy: Smoothing = serde_json::from_str(r#"{"amount":0.8,"pulledString":true}"#).unwrap(); @@ -975,8 +983,9 @@ fn smoothing_pulls_by_time_not_by_how_often_the_device_reports() { out.last().map_or(0.0, |p| p.x) }; let (fast, slow) = (run(1.0), run(16.0)); - // Two 16 ms steps of a 0.2 pull: 1 - 0.8² = 36 % of the way. - assert!((slow - 36.0).abs() < 1e-4, "{slow}"); + // Two 16 ms steps of one step's pull `a`: 1 - (1 - a)² of the way. + let a = crate::dynamics::smoothing_pull(0.8); + assert!((slow - 100.0 * (1.0 - (1.0 - a).powi(2))).abs() < 1e-4, "{slow}"); assert!((fast - slow).abs() < 1e-4, "1000 Hz {fast} vs 60 Hz {slow}"); // Without timestamps each point is one step, as before. let mut s = Smoother::new(&cfg, 1.0); @@ -1024,13 +1033,13 @@ fn a_pulled_string_brush_takes_the_pose_along_the_string() { let a = StrokePoint { rotation: 350.0, ..StrokePoint::new(0.0, 0.0, 1.0) }; let b = StrokePoint { rotation: 10.0, tilt_x: 40.0, ..StrokePoint::new(100.0, 0.0, 0.0) }; let out = smooth_points(&ps, 1.0, &[a, b]); - // The 20 px string leaves the brush 80 % of the way to the pointer. + // The 60 px string leaves the brush 40 % of the way to the pointer. let p = out.last().unwrap(); - assert!((p.x - 80.0).abs() < 1e-4, "{}", p.x); - assert!((p.pressure - 0.2).abs() < 1e-4, "{}", p.pressure); - assert!((p.tilt_x - 32.0).abs() < 1e-3, "{}", p.tilt_x); - // Rotation the short way round: 350° + 80 % of 20°. - assert!((p.rotation - 6.0).abs() < 1e-3, "{}", p.rotation); + assert!((p.x - 40.0).abs() < 1e-4, "{}", p.x); + assert!((p.pressure - 0.6).abs() < 1e-4, "{}", p.pressure); + assert!((p.tilt_x - 16.0).abs() < 1e-3, "{}", p.tilt_x); + // Rotation the short way round: 350° + 40 % of 20°. + assert!((p.rotation - 358.0).abs() < 1e-3, "{}", p.rotation); } #[test] diff --git a/crates/paint/src/dynamics.rs b/crates/paint/src/dynamics.rs index e9987cc899..343e2cbda1 100644 --- a/crates/paint/src/dynamics.rs +++ b/crates/paint/src/dynamics.rs @@ -10,10 +10,24 @@ use crate::brush::{BrushSettings, Control, Dynamic, Smoothing}; use crate::rng::{rand_signed, rand01, stream}; use crate::{Dab, StrokePoint}; -/// Maximum pulled-string length at 100 % smoothing, in screen pixels. -pub const MAX_STRING_PX: f64 = 100.0; +/// Maximum pulled-string length at 100 % smoothing, in screen pixels: 150 px at 50 %, as measured +/// in the reference application (#11888). +pub const MAX_STRING_PX: f64 = 300.0; /// Stroke time over which exponential smoothing moves its fraction of the way to the pointer. pub const SMOOTHING_STEP_MS: f64 = 16.0; +/// Exponential smoothing's time constant at 100 % smoothing, in ms, and the power of the amount +/// it scales by: `tau = SMOOTHING_TAU_MS · amount^SMOOTHING_TAU_EXP`. Fitted to the reference +/// application's lag (#11888): a 200 px drag in 40 moves 10 ms apart ends 19 px short at 10 % +/// (tau 43 ms) and 78 px short at 50 % (tau 173 ms). +pub const SMOOTHING_TAU_MS: f64 = 314.0; +pub const SMOOTHING_TAU_EXP: f64 = 0.864; + +/// The fraction of the way to the pointer exponential smoothing moves in one +/// [`SMOOTHING_STEP_MS`] at `amount`, clamped to 0..1. At 0 (or NaN) it is 1.0: no smoothing. +pub fn smoothing_pull(amount: f64) -> f64 { + let tau = SMOOTHING_TAU_MS * amount.clamp(0.0, 1.0).powf(SMOOTHING_TAU_EXP); + if tau > 0.0 { 1.0 - (-SMOOTHING_STEP_MS / tau).exp() } else { 1.0 } +} /// With Spacing unchecked, one dab per this many milliseconds of stroke time, so faster strokes /// space their dabs further apart (Photoshop: "the speed of the cursor determines the spacing"). @@ -103,12 +117,15 @@ pub struct Smoother { zoom: f64, pos: Option, last_input: Option, + /// Has time passed between two input points? Then the stroke is timed, and a later point + /// with no time since the last one moves the brush no further (not by the untimed pull). + timed: bool, } impl Smoother { /// `zoom` is the view zoom (only used with `adjust_for_zoom`). pub fn new(cfg: &Smoothing, zoom: f32) -> Self { - Self { cfg: cfg.clone(), zoom: f64::from(zoom.max(0.01)), pos: None, last_input: None } + Self { cfg: cfg.clone(), zoom: f64::from(zoom.max(0.01)), pos: None, last_input: None, timed: false } } fn active(&self) -> bool { @@ -149,21 +166,27 @@ impl Smoother { } // Exponential: every SMOOTHING_STEP_MS of stroke time moves `a` of the way towards the // pointer, so the feel doesn't depend on how often the device reports. Input without - // timestamps takes one step per point. - let a = 1.0 - amount.min(0.95); + // timestamps was never measured: it takes one step per point with the pull it always had. + let a = smoothing_pull(amount); let dt = prev_input.map_or(0.0, |q| p.time - q.time); let still = prev_input.is_some_and(|q| q.x == p.x && q.y == p.y); if still && !self.cfg.catch_up { // Without Stroke Catch-Up the brush stops while the pointer pauses (Photoshop). return; } - let (iters, step) = if dt > 0.0 && dt.is_finite() { + let has_time = dt > 0.0 && dt.is_finite(); + self.timed |= has_time; + if self.timed && !has_time { + // No time passed (two reports in one millisecond): the brush stays where it is. + return; + } + let (iters, step) = if has_time { let steps = dt / SMOOTHING_STEP_MS; let iters = steps.ceil().clamp(1.0, 64.0); // Each of `iters` moves covers `steps / iters` steps' worth of pull. (iters as usize, 1.0 - (1.0 - a).powf(steps.min(64.0) / iters)) } else { - (1, a) + (1, 1.0 - amount.min(0.95)) }; let mut cur = pos; for _ in 0..iters { @@ -191,9 +214,10 @@ impl Smoother { } /// End of stroke: with Catch-Up On Stroke End the brush finishes at the last pointer position - /// and pose. + /// and pose. Not in Pulled String Mode: the brush stays the string's length behind the pointer + /// (measured, #11888). pub fn finish(&mut self, out: &mut Vec) { - if !self.active() || !self.cfg.catch_up_on_end { + if !self.active() || !self.cfg.catch_up_on_end || self.cfg.pulled_string { return; } if let (Some(pos), Some(last)) = (self.pos, self.last_input) @@ -1082,3 +1106,7 @@ mod streaming_tests { assert_eq!(dabs.len(), 2_000_001); } } + +#[cfg(test)] +#[path = "smoothing_lag_tests.rs"] +mod smoothing_lag_tests; diff --git a/crates/paint/src/presets.rs b/crates/paint/src/presets.rs index e40902a78f..f7411fcc82 100644 --- a/crates/paint/src/presets.rs +++ b/crates/paint/src/presets.rs @@ -438,8 +438,10 @@ impl Texture { } } -/// The built-in preset set, in display order (grouped by [`GROUPS`]). -pub fn builtin() -> Vec { +#[cfg(test)] +static BUILTIN_INITIALIZATIONS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +fn build_builtin() -> Vec { let base = BrushSettings { pressure_size: false, spacing: 0.25, ..Default::default() }; let mut v = general(&base); v.extend(dry_media(&base)); @@ -448,6 +450,23 @@ pub fn builtin() -> Vec { v } +/// An owned copy of the built-in preset set, in display order (grouped by [`GROUPS`]). +pub fn builtin() -> Vec { + builtin_shared().as_ref().clone() +} + +/// The built-in set shared by new sessions until one is edited. +pub fn builtin_shared() -> std::sync::Arc> { + static BUILTIN: std::sync::OnceLock>> = std::sync::OnceLock::new(); + BUILTIN + .get_or_init(|| { + #[cfg(test)] + BUILTIN_INITIALIZATIONS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + std::sync::Arc::new(build_builtin()) + }) + .clone() +} + /// Find a preset by name (case-insensitive). pub fn find<'a>(presets: &'a [BrushPreset], name: &str) -> Option<&'a BrushPreset> { presets.iter().find(|p| p.name.eq_ignore_ascii_case(name)) @@ -457,6 +476,16 @@ pub fn find<'a>(presets: &'a [BrushPreset], name: &str) -> Option<&'a BrushPrese mod tests { use super::*; + #[test] + fn builtins_initialize_once_across_owned_and_shared_calls() { + let first = builtin_shared(); + let owned = builtin(); + let second = builtin_shared(); + assert!(std::sync::Arc::ptr_eq(&first, &second)); + assert_eq!(*first, owned); + assert_eq!(BUILTIN_INITIALIZATIONS.load(std::sync::atomic::Ordering::Relaxed), 1); + } + #[test] fn builtins_are_grouped_and_unique() { let v = builtin(); diff --git a/crates/paint/src/smoothing_lag_tests.rs b/crates/paint/src/smoothing_lag_tests.rs new file mode 100644 index 0000000000..30d278e80e --- /dev/null +++ b/crates/paint/src/smoothing_lag_tests.rs @@ -0,0 +1,87 @@ +//! #11888: Smoothing trails the pointer as far as in the reference application, and Pulled String +//! Mode stops the string's length short of the release point, with or without Catch-up on Stroke +//! End. The drag is the issue's: (100, 199) to (300, 199) in 40 moves 10 ms apart, then released. + +use super::*; +use crate::brush::Smoothing; + +fn drag() -> Vec { + (0..=40).map(|i| StrokePoint { time: f64::from(i) * 10.0, ..StrokePoint::new(100.0 + f64::from(i) * 5.0, 199.0, 1.0) }).collect() +} + +/// How far short of the release point (300) the smoothed stroke ends. +fn short(cfg: &Smoothing) -> f64 { + let out = smooth_points(cfg, 1.0, &drag()); + 300.0 - out.last().map_or(f64::NAN, |p| p.x) +} + +fn within(got: f64, want: f64, tolerance: f64) -> bool { + (got - want).abs() <= want * tolerance +} + +#[test] +fn ten_and_fifty_percent_lag_as_measured() { + let off_end = Smoothing { catch_up_on_end: false, ..Default::default() }; + let ten = short(&Smoothing { amount: 0.1, ..off_end.clone() }); + let fifty = short(&Smoothing { amount: 0.5, ..off_end }); + assert!(within(ten, 19.0, 0.25), "10 %: {ten} px short (reference 19)"); + assert!(within(fifty, 78.0, 0.25), "50 %: {fifty} px short (reference 78)"); +} + +#[test] +fn catch_up_on_stroke_end_still_reaches_the_release_point() { + let cfg = Smoothing { amount: 0.5, catch_up_on_end: true, ..Default::default() }; + assert_eq!(short(&cfg), 0.0); +} + +#[test] +fn the_pulled_string_stops_its_length_short_either_way() { + for catch_up_on_end in [false, true] { + let cfg = Smoothing { amount: 0.5, pulled_string: true, catch_up_on_end, ..Default::default() }; + let s = short(&cfg); + assert!((s - 150.0).abs() < 1e-9, "catch-up on end {catch_up_on_end}: {s} px short (reference about 150)"); + } +} + +#[test] +fn zero_and_disabled_smoothing_paint_through_every_point() { + let pts = drag(); + for cfg in [Smoothing { amount: 0.0, ..Default::default() }, Smoothing { enabled: false, amount: 0.5, ..Default::default() }] { + let out = smooth_points(&cfg, 1.0, &pts); + assert_eq!(out.len(), pts.len(), "{cfg:?}"); + assert!(out.iter().zip(&pts).all(|(a, b)| (a.x, a.y, a.pressure) == (b.x, b.y, b.pressure)), "{cfg:?}"); + } +} + +#[test] +fn the_pull_grows_with_less_smoothing_and_stays_a_fraction() { + let pulls: Vec = [0.01, 0.1, 0.25, 0.5, 0.75, 1.0].iter().map(|a| smoothing_pull(*a)).collect(); + assert!(pulls.windows(2).all(|w| w[0] > w[1]), "{pulls:?}"); + assert!(pulls.iter().all(|p| *p > 0.0 && *p < 1.0), "{pulls:?}"); + assert_eq!(smoothing_pull(0.0), 1.0, "no time constant: straight to the pointer"); + assert_eq!(smoothing_pull(f64::NAN), 1.0, "a bad amount never makes a NaN position"); +} + +/// Input without timestamps (a control-client stroke, a script, an old file) was never measured, +/// so each point keeps the pull it always had: `1 - amount` of the way to the pointer. At the +/// default 10 % a two-point stroke still ends 90 % of the way, not a third of it. +#[test] +fn strokes_without_timestamps_keep_their_per_point_pull() { + let cfg = Smoothing { amount: 0.1, catch_up_on_end: false, ..Default::default() }; + let out = smooth_points(&cfg, 1.0, &[StrokePoint::new(0.0, 0.0, 1.0), StrokePoint::new(100.0, 0.0, 1.0)]); + let x = out.last().map_or(f64::NAN, |p| p.x); + assert!((x - 90.0).abs() < 1e-4, "a 10 % untimed step reached {x}, want 90"); +} + +/// A timed stroke stays timed: a report with no time since the last one (two events in one +/// millisecond) leaves the brush where it is, instead of jumping it by the untimed per-point pull. +#[test] +fn a_report_with_no_time_passed_does_not_move_a_timed_brush() { + let cfg = Smoothing { amount: 0.1, catch_up: true, catch_up_on_end: false, ..Default::default() }; + let at = |x: f64, time: f64| StrokePoint { time, ..StrokePoint::new(x, 0.0, 1.0) }; + let timed = smooth_points(&cfg, 1.0, &[at(0.0, 0.0), at(100.0, 10.0)]); + let twice = smooth_points(&cfg, 1.0, &[at(0.0, 0.0), at(100.0, 10.0), at(100.0, 10.0)]); + let (before, after) = (timed.last().map_or(f64::NAN, |p| p.x), twice.last().map_or(f64::NAN, |p| p.x)); + assert!(before > 0.0 && before < 90.0, "the timed move lags: {before}"); + assert_eq!(after, before, "no time passed, so the brush stays"); +} diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index 9ccf9e67e7..59474e6ab5 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -309,14 +309,27 @@ impl PruneCursor { } } -#[derive(Clone)] pub struct Surface { - generation: u64, + /// 0 means no number assigned yet; see [`Surface::generation`]. + generation: std::sync::atomic::AtomicU64, format: PixelFormat, default_pixel: Box<[u8]>, tiles: BTreeMap>, } +impl Clone for Surface { + fn clone(&self) -> Self { + // Read first so the clone and the original share one number: they hold the same pixels. + let generation = self.generation(); + Self { + generation: std::sync::atomic::AtomicU64::new(generation), + format: self.format, + default_pixel: self.default_pixel.clone(), + tiles: self.tiles.clone(), + } + } +} + impl std::fmt::Debug for Surface { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { // The generation identifies an edit history. Independently opened copies of the same @@ -601,14 +614,29 @@ fn fresh_surface_generation() -> u64 { NEXT_SURFACE_GENERATION.fetch_add(1, std::sync::atomic::Ordering::Relaxed) } +/// A generation slot with no number yet; the first [`Surface::generation`] read assigns one. +fn unassigned_generation() -> std::sync::atomic::AtomicU64 { + std::sync::atomic::AtomicU64::new(0) +} + impl Surface { - /// Equal generations identify the same pixel state, including across clones. + /// Equal generations identify the same pixel state, including across clones. Numbers are + /// assigned on first read after a mutation, so writes never touch the shared counter. pub fn generation(&self) -> u64 { - self.generation + use std::sync::atomic::Ordering::Relaxed; + let current = self.generation.load(Relaxed); + if current != 0 { + return current; + } + let fresh = fresh_surface_generation(); + match self.generation.compare_exchange(0, fresh, Relaxed, Relaxed) { + Ok(_) => fresh, + Err(assigned) => assigned, + } } fn note_mutation(&mut self) { - self.generation = fresh_surface_generation(); + *self.generation.get_mut() = 0; } /// Reads a region into a newly allocated buffer, returning an error instead of aborting if @@ -672,7 +700,7 @@ impl Surface { /// Transparent/zero surface. pub fn new(format: PixelFormat) -> Self { - Self { generation: fresh_surface_generation(), format, default_pixel: vec![0u8; format.bytes_per_pixel()].into_boxed_slice(), tiles: BTreeMap::new() } + Self { generation: unassigned_generation(), format, default_pixel: vec![0u8; format.bytes_per_pixel()].into_boxed_slice(), tiles: BTreeMap::new() } } /// Surface whose untouched pixels read as `pixel` (normalised channel values). @@ -1397,8 +1425,7 @@ impl Surface { /// `content` must hold every pixel that isn't the default one (`content_bounds`, say): only /// tiles it reaches are kept. pub fn translated(&self, dx: i32, dy: i32, content: Rect) -> Surface { - let mut out = - Surface { generation: fresh_surface_generation(), format: self.format, default_pixel: self.default_pixel.clone(), tiles: BTreeMap::new() }; + let mut out = Surface { generation: unassigned_generation(), format: self.format, default_pixel: self.default_pixel.clone(), tiles: BTreeMap::new() }; let sources = || self.tiles.iter().filter(move |(c, _)| !c.rect().intersect(&content).is_empty()); if dx % TILE_SIZE == 0 && dy % TILE_SIZE == 0 { let (tx, ty) = (dx / TILE_SIZE, dy / TILE_SIZE); diff --git a/crates/raster/src/shift.rs b/crates/raster/src/shift.rs index c75ebf3401..9320db8cc1 100644 --- a/crates/raster/src/shift.rs +++ b/crates/raster/src/shift.rs @@ -222,7 +222,7 @@ impl TranslateSteps { let tiles: Vec<(TileCoord, Arc)> = if whole_tiles { Vec::new() } else { ShiftBuilder::sources(&src, content).map(|(c, t)| (*c, Arc::clone(t))).collect() }; let out = - Surface { generation: super::fresh_surface_generation(), format: src.format, default_pixel: src.default_pixel.clone(), tiles: Default::default() }; + Surface { generation: super::unassigned_generation(), format: src.format, default_pixel: src.default_pixel.clone(), tiles: Default::default() }; Self { sources: tiles.len(), scan: tiles.into_iter(), @@ -276,7 +276,7 @@ impl TranslateSteps { return Some(std::mem::replace( &mut self.out, Surface { - generation: super::fresh_surface_generation(), + generation: super::unassigned_generation(), format: self.src.format, default_pixel: self.src.default_pixel.clone(), tiles: Default::default(), diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 35ee42c765..c631f51299 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -334,3 +334,6 @@ impl eframe::App for Box { #[cfg(test)] mod clipboard_tests; + +#[cfg(test)] +mod apply_data_set_alert_tests; diff --git a/crates/ui-egui/src/app/apply_data_set_alert_tests.rs b/crates/ui-egui/src/app/apply_data_set_alert_tests.rs new file mode 100644 index 0000000000..873649ecec --- /dev/null +++ b/crates/ui-egui/src/app/apply_data_set_alert_tests.rs @@ -0,0 +1,44 @@ +//! #14499: Apply Data Set on a type layer under Lock All shows the reference application's alert; +//! its other refusals stay status-bar messages. + +use super::*; +use serde_json::json; + +const LOCKED: &str = "Could not apply data set because the layer is locked."; + +/// An app with a type layer bound to a `headline` text variable and one data set `Zed` for it, +/// the layer under Lock All when `locked`. +fn app(locked: bool) -> Box { + let mut app = PhotocraftApp::new(Session::new(), Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); + let id = app.session.execute("type.create", json!({"x": 4, "y": 30, "text": "Old", "size": 12})).unwrap()["layer"].clone(); + app.session.execute("image.variables.define", json!({"defs": [{"name": "headline", "layer": id, "type": "textReplacement"}]})).unwrap(); + app.session + .execute("image.variables.dataSets", json!({"dataSets": [{"name": "Zed", "values": [{"variable": "headline", "kind": "text", "value": "New"}]}]})) + .unwrap(); + if locked { + app.session.execute("layer.lockLayers", json!({"all": true})).unwrap(); + } + app.sync_views(); + app +} + +/// The messages of the open framework alerts. +fn alerts(app: &PhotocraftApp) -> Vec { + app.framework.dialogs.open_dialogs().iter().filter_map(|d| d.fields.as_ref()?.get("message")?.as_str().map(String::from)).collect() +} + +#[test] +fn a_locked_type_layer_refuses_with_an_alert() { + let mut app = app(true); + assert_eq!(app.run("image.applyDataSet", json!({"name": "Zed"})), Err(LOCKED.to_string())); + assert_eq!(alerts(&app), [LOCKED]); +} + +#[test] +fn other_refusals_and_an_unlocked_layer_show_no_alert() { + let mut app = app(false); + assert!(app.run("image.applyDataSet", json!({"name": "Missing"})).is_err()); + app.run("image.applyDataSet", json!({"name": "Zed"})).unwrap(); + assert!(alerts(&app).is_empty(), "{:?}", alerts(&app)); +} diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index b3a942ec11..ee9bbe7683 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -220,6 +220,10 @@ impl PhotocraftApp { Err(e) => { self.ui.status = e.clone(); self.ui.status_error = true; + if id == "image.applyDataSet" && e == photocraft_engine::DATA_SET_LAYER_LOCKED { + // The reference application refuses a locked type layer with an alert (#14499). + let _ = crate::dialogs::alerts::alert(self, tl!(photocraft_engine::DATA_SET_LAYER_LOCKED)); + } } } if suppress_events { diff --git a/crates/ui-egui/src/app/framework.rs b/crates/ui-egui/src/app/framework.rs index 4adf2e7624..ca2802879f 100644 --- a/crates/ui-egui/src/app/framework.rs +++ b/crates/ui-egui/src/app/framework.rs @@ -10,7 +10,7 @@ //! The `craft` facade features PhotoCraft enables for this: `text`, `text-font-picker`, //! `font-manager`, `menu`, `timeline` and `print`, plus `dialogs` on native targets. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::sync::{Arc, Mutex, PoisonError}; use craft::host::target::{Backend, ShellInfo}; @@ -89,14 +89,28 @@ pub struct Framework { /// The runtime's keymap overrides. The runtime rebuilds its keymap when the `Arc` changes, so /// it is replaced only when the bindings it carries change. overrides: Arc, - /// The preferences revision `overrides` and `catalog` were last built at. - overrides_rev: Option, - /// The app's command catalog as of `overrides_rev`. + /// What `overrides` was built from: the preferences' catalog revision and the catalog's generation. + overrides_key: Option<(u64, u64)>, + /// Advances each time `overrides` is replaced. + overrides_generation: u64, + /// The app's command catalog, built from `catalog_rows`. catalog: Option, - /// The rows `catalog` was built from, and its generation: the runtime rebuilds its keymap when the generation - /// changes, so it advances only when the rows differ. + /// The rows `catalog` was built from ([`command_rows`](crate::shortcut_dispatch::command_rows)), the action + /// names they were built from (their one input that changes at run time), the actions list's revision those names + /// were last read at, and the catalog's generation: the runtime rebuilds its keymap when the generation changes, + /// so it advances only when the names change. The revision is the fast check; it assumes the list is edited in + /// place or through `ActionList::replace`, which keep it moving forward. catalog_rows: Vec, + catalog_actions: Vec, + catalog_rows_rev: Option, catalog_generation: u64, + /// How many times the rows and the overrides were built, for the count trials. + #[cfg(test)] + pub(crate) catalog_builds: usize, + #[cfg(test)] + pub(crate) overrides_builds: usize, + /// The states the keyed command sources last computed ([`command_states`]). + pub(crate) held_states: HeldStates, /// The file services the host gives components (pickers, reads and writes); `None` keeps the /// host's own default. files: Option>, @@ -271,10 +285,18 @@ impl Framework { dialogs: DialogHost::new(), captured: Default::default(), overrides: Arc::new(Overrides::new()), - overrides_rev: None, + overrides_key: None, + overrides_generation: 0, catalog: None, catalog_rows: Vec::new(), + catalog_actions: Vec::new(), + catalog_rows_rev: None, catalog_generation: 0, + #[cfg(test)] + catalog_builds: 0, + #[cfg(test)] + overrides_builds: 0, + held_states: HeldStates::default(), files, fired: Vec::new(), refused: false, @@ -476,26 +498,49 @@ impl Framework { .unwrap_or_else(|| id.as_str().to_owned()) } - /// What the runtime's keymap was last built from: the preferences revision of the overrides and the catalog's - /// generation. They change at the start of the frame whose keymap follows them, so a surface that shows the - /// keymap's chords (the menu model) hashes them to rebuild in that frame. - pub(crate) fn keymap_inputs(&self) -> (Option, u64) { - (self.overrides_rev, self.catalog_generation) + /// What the runtime's keymap was last built from: the generations of the overrides and of the catalog. They + /// change at the start of the frame whose keymap follows them, so a surface that shows the keymap's chords (the + /// menu model) hashes them to rebuild in that frame. + pub(crate) fn keymap_inputs(&self) -> (u64, u64) { + (self.overrides_generation, self.catalog_generation) } - /// Rebuilds the catalog and the runtime's keymap overrides at preferences revision `rev`. The - /// pane moves are unbound in the overrides, because PhotoCraft's own table binds F6 and - /// Shift+F6 (Window › Color, Select › Modify › Feather) until those are a framework - /// `CommandSet`. The held `Arc` is replaced only when the bindings differ, so the runtime - /// rebuilds its keymap only on a change. - fn set_overrides(&mut self, rev: u64, catalog: Option, mut overrides: Overrides) { - self.overrides_rev = Some(rev); - self.catalog = catalog; + /// The catalog's rows when they were built at actions list revision `actions_rev`, else `None`. + pub(crate) fn catalog_rows_at(&self, actions_rev: u64) -> Option<&[craft::keymap::CommandDef]> { + (self.catalog_rows_rev == Some(actions_rev)).then_some(self.catalog_rows.as_slice()) + } + + /// Takes `rows`, built from the action names `actions` at actions list revision `actions_rev`, as the catalog's + /// rows: a new catalog generation. + fn set_catalog(&mut self, actions_rev: u64, actions: Vec, rows: Vec) { + self.catalog_generation += 1; + self.catalog = crate::shortcut_dispatch::catalog(rows.clone(), self.catalog_generation); + self.catalog_rows = rows; + self.catalog_actions = actions; + self.catalog_rows_rev = Some(actions_rev); + #[cfg(test)] + { + self.catalog_builds += 1; + } + } + + /// Takes the runtime's keymap overrides built from `key` ([`Self::overrides_key`]). The pane + /// moves are unbound in the overrides, because PhotoCraft's own table binds F6 and Shift+F6 + /// (Window › Color, Select › Modify › Feather) until those are a framework `CommandSet`. The + /// held `Arc` is replaced only when the bindings differ, so the runtime rebuilds its keymap + /// only on a change. + fn set_overrides(&mut self, key: (u64, u64), mut overrides: Overrides) { + self.overrides_key = Some(key); for command in [NavCommand::NextPane, NavCommand::PreviousPane] { overrides.insert(CommandRef::from(command).key(), Vec::new()); } if *self.overrides != overrides { self.overrides = Arc::new(overrides); + self.overrides_generation += 1; + } + #[cfg(test)] + { + self.overrides_builds += 1; } } } @@ -505,6 +550,10 @@ impl Framework { pub(crate) struct CommandSource { /// The states of the source's commands for the coming frame. states: fn(&PhotocraftApp) -> Vec<(CommandRef, CommandState)>, + /// What `states` reads, for a source whose every input is a plain value or a revision that moves exactly when + /// the data changes: the states are computed again only when the key changes. `None`: computed every frame, + /// because what the source reads has no such revision yet. + key: Option StatesKey>, /// Runs `command` when it is this source's; whether it was. run: fn(&mut PhotocraftApp, &egui::Context, &CommandRef) -> bool, } @@ -512,23 +561,76 @@ pub(crate) struct CommandSource { /// Every command source, in the order [`run_command`] tries them. The theme has no entry: it has /// no command state, and its picks run through `menus::invoke`. pub(crate) const COMMAND_SOURCES: &[CommandSource] = &[ - CommandSource { states: crate::panels::registry::states, run: crate::panels::registry::run_fired }, - CommandSource { states: tool_states, run: run_tool }, - CommandSource { states: crate::workspace_ui::states, run: crate::workspace_ui::run_fired }, - CommandSource { states: crate::slice_ui::command_states, run: crate::slice_ui::run_fired }, - CommandSource { states: crate::align_bar::command_states, run: crate::align_bar::run_fired }, - CommandSource { states: crate::artboard_tool::command_states, run: crate::artboard_tool::run_fired }, + CommandSource { states: crate::panels::registry::states, key: None, run: crate::panels::registry::run_fired }, + CommandSource { states: tool_states, key: Some(tool_states_key), run: run_tool }, + CommandSource { states: crate::workspace_ui::states, key: None, run: crate::workspace_ui::run_fired }, + CommandSource { states: crate::slice_ui::command_states, key: Some(crate::slice_ui::command_states_key), run: crate::slice_ui::run_fired }, + CommandSource { states: crate::align_bar::command_states, key: None, run: crate::align_bar::run_fired }, + CommandSource { states: crate::artboard_tool::command_states, key: Some(crate::artboard_tool::command_states_key), run: crate::artboard_tool::run_fired }, // Space+F: the pasteboard colour keys of the held Hand. - CommandSource { states: |_| Vec::new(), run: crate::canvas_tool_menu::run_canvas_color }, + CommandSource { states: |_| Vec::new(), key: Some(|_| StatesKey::default()), run: crate::canvas_tool_menu::run_canvas_color }, // The options bar's engine-command buttons: their commands run through `shortcuts::handle`. - CommandSource { states: crate::panels::options_bar::selection::command_states, run: |_, _, _| false }, + CommandSource { states: crate::panels::options_bar::selection::command_states, key: None, run: |_, _, _| false }, ]; +/// The key of a [`CommandSource`]'s states: the plain values and exact revisions they are computed from, so equal +/// keys mean equal states. +pub(crate) type StatesKey = [u64; 4]; + +/// The states each keyed [`CommandSource`] last computed, by its place in [`COMMAND_SOURCES`], with their key. +#[derive(Default)] +pub(crate) struct HeldStates { + kept: Vec>, + /// How many times each source computed its states, for the count trials. + #[cfg(test)] + pub(crate) runs: Vec, +} + +/// One keyed source's states and the key they were computed at. +#[derive(Clone)] +struct KeptStates { + key: StatesKey, + states: Vec<(CommandRef, CommandState)>, +} + /// The tool commands: the current tool's row is checked. fn tool_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandState)> { Tool::ALL.iter().map(|&tool| (CommandRef::from(crate::panels::tool_commands::command_of(tool)), CommandState::new().checked(app.ui.tool == tool))).collect() } +/// What [`tool_states`] reads: the tool. +fn tool_states_key(app: &PhotocraftApp) -> StatesKey { + [app.ui.tool as u64, 0, 0, 0] +} + +/// The states of every command source for the coming frame. A keyed source runs only when its key changed since it +/// last ran. +fn command_states(app: &PhotocraftApp, held: &mut HeldStates) -> Vec<(CommandRef, CommandState)> { + held.kept.resize(COMMAND_SOURCES.len(), None); + #[cfg(test)] + held.runs.resize(COMMAND_SOURCES.len(), 0); + let mut states = Vec::new(); + for (at, source) in COMMAND_SOURCES.iter().enumerate() { + let key = source.key.map(|key| key(app)); + match (&held.kept[at], key) { + (Some(kept), Some(key)) if kept.key == key => states.extend_from_slice(&kept.states), + _ => { + #[cfg(test)] + { + held.runs[at] += 1; + } + let computed = (source.states)(app); + states.extend_from_slice(&computed); + held.kept[at] = key.map(|key| KeptStates { key, states: computed }); + } + } + } + states +} + +#[cfg(test)] +mod catalog_tests; + /// Selects the tool a tool command names. fn run_tool(app: &mut PhotocraftApp, _ctx: &egui::Context, command: &CommandRef) -> bool { let Some(command) = crate::panels::tool_commands::ToolCommand::from_ref(command) else { @@ -549,23 +651,32 @@ impl PhotocraftApp { /// runs them), the commands the canvas ran (`record_view_commands`, in `logic`) and whether a /// component refused its input. pub(crate) fn framework_before_input(&mut self, ctx: &egui::Context) { - // The catalog and the bindings come from walking the whole command table: only after a - // preferences change. - let rev = self.session.prefs.rev(); - if self.framework.overrides_rev != Some(rev) { - let rows = crate::shortcut_dispatch::command_rows(self); - if !crate::shortcut_dispatch::same_rows(&self.framework.catalog_rows, &rows) { - self.framework.catalog_generation += 1; - self.framework.catalog_rows = rows.clone(); + // The catalog's rows change only with the action names; the bindings with the rows and the + // shortcut preferences. + let list = &self.session.actions.list; + let actions_rev = list.revision(); + if self.framework.catalog_rows_rev != Some(actions_rev) { + let same = self.framework.catalog_rows_rev.is_some() + && self.framework.catalog_actions.iter().map(String::as_str).eq(list.actions().iter().map(|action| action.name.as_str())); + if same { + self.framework.catalog_rows_rev = Some(actions_rev); + } else { + let actions = list.actions().iter().map(|action| action.name.clone()).collect(); + let rows = crate::shortcut_dispatch::command_rows(self); + self.framework.set_catalog(actions_rev, actions, rows); } - let catalog = crate::shortcut_dispatch::catalog(rows, self.framework.catalog_generation); - let overrides = crate::shortcut_dispatch::overrides(self); - self.framework.set_overrides(rev, catalog, overrides); + } + let overrides_key = (self.session.prefs.catalog_rev(), self.framework.catalog_generation); + if self.framework.overrides_key != Some(overrides_key) { + let overrides = crate::shortcut_dispatch::overrides(self, &self.framework.catalog_rows); + self.framework.set_overrides(overrides_key, overrides); } if self.framework.sync_theme(&mut self.session) { crate::prefs_ui::show_selected_theme(self, ctx); } - let states: Vec<(CommandRef, CommandState)> = COMMAND_SOURCES.iter().flat_map(|source| (source.states)(self)).collect(); + let mut held = std::mem::take(&mut self.framework.held_states); + let states = command_states(self, &mut held); + self.framework.held_states = held; let gate = crate::menus::command_gate(self); let latched = self.ui.shell.latched; embed::before_input(ctx, |output: FrameOutput| { @@ -603,27 +714,53 @@ struct PrefSections(Mutex); #[derive(Default)] struct Tables { tables: BTreeMap, - /// A component wrote since the last sync. - written: bool, - /// The preferences' sections as last synced, to notice a change from elsewhere (a reset, - /// the control channel). - seen: BTreeMap, + /// The sections a component wrote since the last sync. + written: BTreeSet, + /// Each section's preference revision as last synced, to notice a change from elsewhere (a + /// reset, the control channel) without comparing the sections. + seen: BTreeMap, + /// How many sections a sync has read from the preferences. + #[cfg(test)] + loaded: usize, } impl PrefSections { - /// Writes the components' changes into the preferences, or takes a change made there. + /// Writes the sections the components wrote into the preferences, and takes the sections whose + /// preference revision moved. fn sync(&self, session: &mut Session) { let mut t = self.0.lock().unwrap_or_else(PoisonError::into_inner); - if std::mem::take(&mut t.written) { - let json: BTreeMap = t.tables.iter().filter_map(|(key, table)| Some((key.clone(), serde_json::to_value(table).ok()?))).collect(); - if session.prefs().sections != json { - session.edit_prefs(|p| p.sections = json.clone()); + let written = std::mem::take(&mut t.written); + if !written.is_empty() { + let changed: Vec<(String, Value)> = written + .iter() + .filter_map(|key| Some((key.clone(), serde_json::to_value(t.tables.get(key)?).ok()?))) + .filter(|(key, value)| session.prefs().sections.get(key) != Some(value)) + .collect(); + if !changed.is_empty() { + session.edit_prefs(|p| p.sections.extend(changed)); } - t.seen = json; - } else if session.prefs().sections != t.seen { - let seen = session.prefs().sections.clone(); - t.tables = seen.iter().filter_map(|(key, value)| Some((key.clone(), serde_json::from_value(value.clone()).ok()?))).collect(); - t.seen = seen; + for key in written { + let rev = session.section_rev(&key); + t.seen.insert(key, rev); + } + } + let sections = &session.prefs().sections; + let moved: Vec<&String> = sections.keys().filter(|key| t.seen.get(*key) != Some(&session.section_rev(key))).collect(); + let gone: Vec = t.seen.keys().filter(|key| !sections.contains_key(*key)).cloned().collect(); + for key in moved { + match serde_json::from_value(sections[key].clone()) { + Ok(table) => t.tables.insert(key.clone(), table), + Err(_) => t.tables.remove(key), + }; + t.seen.insert(key.clone(), session.section_rev(key)); + #[cfg(test)] + { + t.loaded += 1; + } + } + for key in gone { + t.tables.remove(&key); + t.seen.remove(&key); } } } @@ -636,7 +773,7 @@ impl SectionStore for PrefSections { fn write(&self, key: &str, table: toml::Table) { let mut t = self.0.lock().unwrap_or_else(PoisonError::into_inner); t.tables.insert(key.to_owned(), table); - t.written = true; + t.written.insert(key.to_owned()); } } @@ -689,6 +826,51 @@ pub(crate) fn keys_pass(app: &mut PhotocraftApp, ctx: &egui::Context, input: egu #[cfg(test)] mod tests { + use super::*; + + fn table(n: i64) -> toml::Table { + let mut t = toml::Table::new(); + t.insert("n".into(), toml::Value::Integer(n)); + t + } + + /// A sync reads and writes only the sections that changed, one revision per section. + #[test] + fn section_sync_touches_only_changed_sections() { + let store = PrefSections::default(); + let mut session = Session::new(); + store.write("one", table(1)); + store.write("two", table(2)); + store.sync(&mut session); + assert_eq!(session.prefs().sections.len(), 2); + let (one, two) = (session.section_rev("one"), session.section_rev("two")); + let loaded = store.0.lock().unwrap().loaded; + + store.sync(&mut session); + assert_eq!((session.section_rev("one"), session.section_rev("two")), (one, two)); + assert_eq!(store.0.lock().unwrap().loaded, loaded, "an idle sync reads nothing"); + + store.write("two", table(3)); + store.sync(&mut session); + assert_eq!(session.section_rev("one"), one, "a section nobody wrote keeps its revision"); + assert_eq!(session.section_rev("two"), two.wrapping_add(1)); + assert_eq!(store.0.lock().unwrap().loaded, loaded, "a component's own write is not read back"); + + session.edit_prefs(|p| { + p.sections.insert("one".into(), serde_json::json!({ "n": 9 })); + }); + store.sync(&mut session); + assert_eq!(store.0.lock().unwrap().loaded, loaded + 1, "only the changed section is read"); + assert_eq!(store.read("one"), Some(table(9))); + assert_eq!(store.read("two"), Some(table(3))); + + session.edit_prefs(|p| { + p.sections.remove("one"); + }); + store.sync(&mut session); + assert_eq!(store.read("one"), None); + } + /// Every theme PhotoCraft has a palette for names a framework built-in. #[test] fn every_palette_theme_is_a_builtin() { diff --git a/crates/ui-egui/src/app/framework/catalog_tests.rs b/crates/ui-egui/src/app/framework/catalog_tests.rs new file mode 100644 index 0000000000..24cf76cce6 --- /dev/null +++ b/crates/ui-egui/src/app/framework/catalog_tests.rs @@ -0,0 +1,130 @@ +//! Count trials: the command catalog, the keymap overrides and the keyed command states are built only when what +//! they read changes. + +use craft::automation::actions::ActionStep; +use serde_json::json; + +use super::{COMMAND_SOURCES, PhotocraftApp}; +use crate::canvas::testing; +use crate::state::Tool; + +/// The places of the keyed sources in [`COMMAND_SOURCES`]. +const TOOL_SOURCE: usize = 1; +const SLICE_SOURCE: usize = 3; +const ARTBOARD_SOURCE: usize = 5; + +fn app() -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + testing::frame(&mut app); + app +} + +/// How many times the rows and the overrides were built. +fn builds(app: &PhotocraftApp) -> (usize, usize) { + (app.framework.catalog_builds, app.framework.overrides_builds) +} + +/// How many times each keyed command source computed its states, by its place in [`COMMAND_SOURCES`]; `None` for a +/// source that computes them every frame. +fn keyed_runs(app: &PhotocraftApp) -> Vec> { + COMMAND_SOURCES.iter().zip(&app.framework.held_states.runs).map(|(source, &runs)| source.key.map(|_| runs)).collect() +} + +/// The keyed sources that computed their states between `before` and `after`. +fn ran(before: &[Option], after: &[Option]) -> Vec { + before.iter().zip(after).enumerate().filter(|(_, (was, now))| was.is_some() && was != now).map(|(at, _)| at).collect() +} + +fn frames(app: &mut PhotocraftApp, n: usize) { + for _ in 0..n { + testing::frame(app); + } +} + +#[test] +fn the_catalog_is_built_only_when_its_inputs_change() { + let mut app = app(); + assert_eq!(builds(&app), (1, 1), "the first frame builds the catalog and the overrides"); + + frames(&mut app, 100); + assert_eq!(builds(&app), (1, 1), "idle frames build nothing"); + + // The tool and the colours as the app saves them: preference edits outside the catalog's inputs. + let prefs = app.session.prefs.rev(); + crate::tool_memory::select(&mut app, Tool::Brush); + app.run("tools.swapColors", json!({})).unwrap(); + app.session.edit_prefs(|p| { + p.selected_tool = json!("Brush"); + p.tool_colors = Default::default(); + }); + frames(&mut app, 2); + assert_ne!(app.session.prefs.rev(), prefs); + assert_eq!(builds(&app), (1, 1), "a tool or colour change builds nothing"); + + let generation = app.framework.keymap_inputs().1; + assert_eq!(app.framework.overrides.get("filter.blur.gaussian"), None); + app.session.edit_prefs(|p| { + p.shortcuts.insert("filter.blur.gaussian".into(), "Cmd+Alt+G".into()); + }); + frames(&mut app, 2); + assert_eq!(builds(&app), (1, 2), "a shortcut edit builds the overrides once and leaves the rows"); + assert!(app.framework.overrides.get("filter.blur.gaussian").is_some_and(|keys| !keys.is_empty()), "the overrides carry the new key"); + assert_eq!(app.framework.keymap_inputs().1, generation, "the catalog keeps its generation"); + + app.session.actions.list.new_action("Trial", None).unwrap(); + frames(&mut app, 2); + assert_eq!(builds(&app), (2, 3), "a new action builds the rows and the overrides once"); + assert_eq!(app.framework.keymap_inputs().1, generation + 1, "the catalog takes a new generation"); + assert!(app.framework.catalog_rows.iter().any(|row| row.label == "Trial"), "the action has its row"); + + // Edits that keep every action's name leave the rows. + let list = &mut app.session.actions.list; + let at = list.actions().iter().position(|action| action.name == "Trial").unwrap(); + list.insert_step(at, 0, ActionStep::new("layer.new", json!({}))).unwrap(); + list.toggle_step(at, 0).unwrap(); + frames(&mut app, 2); + assert_eq!(builds(&app), (2, 3), "a step edit builds nothing"); + assert_eq!(app.framework.keymap_inputs().1, generation + 1, "the catalog keeps its generation"); +} + +#[test] +fn keyed_command_states_run_only_when_their_key_changes() { + let mut app = app(); + assert_eq!((COMMAND_SOURCES[TOOL_SOURCE].states)(&app).len(), Tool::ALL.len(), "TOOL_SOURCE names the tool commands"); + let before = keyed_runs(&app); + assert!(before.iter().flatten().all(|&runs| runs == 1), "the first frame computes every keyed source once"); + + frames(&mut app, 100); + assert_eq!(keyed_runs(&app), before, "idle frames compute no keyed source"); + + let other = if app.ui.tool == Tool::Brush { Tool::Move } else { Tool::Brush }; + crate::tool_memory::select(&mut app, other); + frames(&mut app, 2); + let after = keyed_runs(&app); + for (at, (was, now)) in before.iter().zip(&after).enumerate() { + let moved = usize::from(at == TOOL_SOURCE); + assert_eq!(now.map(|n| n - was.unwrap_or_default()), was.map(|_| moved), "source {at} after a tool change"); + } + + let before = keyed_runs(&app); + app.ui.artboard_tool.adding = true; + frames(&mut app, 2); + assert_eq!(ran(&before, &keyed_runs(&app)), [ARTBOARD_SOURCE], "the placing mode"); + + let before = keyed_runs(&app); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + frames(&mut app, 2); + let after = keyed_runs(&app); + assert!(ran(&before, &after).contains(&SLICE_SOURCE) && ran(&before, &after).contains(&ARTBOARD_SOURCE), "a document opens"); + let has_doc = |app: &PhotocraftApp| (COMMAND_SOURCES[ARTBOARD_SOURCE].states)(app)[0].1.is_enabled(); + assert!(has_doc(&app)); + + let before = keyed_runs(&app); + app.ui.slices.selected = Some(1); + frames(&mut app, 2); + let selected = keyed_runs(&app); + assert_eq!(ran(&before, &selected), [SLICE_SOURCE], "the selected slice"); + app.session.file_menu.slices_locked = true; + frames(&mut app, 2); + assert_eq!(ran(&selected, &keyed_runs(&app)), [SLICE_SOURCE], "the slice lock"); +} diff --git a/crates/ui-egui/src/artboards_overlap_dialog_tests.rs b/crates/ui-egui/src/artboards_overlap_dialog_tests.rs new file mode 100644 index 0000000000..0d79a8e886 --- /dev/null +++ b/crates/ui-egui/src/artboards_overlap_dialog_tests.rs @@ -0,0 +1,87 @@ +//! #13629: the Artboards to Files dialog has the radio pair Include Overlapping Areas (selected +//! by default) / Artboard Content Only right below the prefix, and OK passes the choice to +//! `file.export.artboardsToFiles` as `content`. Layer Comps to Files has no such choice. +use crate::PhotocraftApp; +use craft::ui::dialog::DialogId; +use craft::ui::patterns::form_dialogs::HostedParamDialog; +use egui::accesskit::{Role, Toggled}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::{Value, json}; + +const ARTBOARDS: &str = "file.export.artboardsToFiles"; +const OVERLAPPING: &str = "Include Overlapping Areas"; +const CONTENT_ONLY: &str = "Artboard Content Only"; + +type H = Harness<'static, Box>; + +fn harness() -> H { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.run("layer.new.artboard", json!({"rect": [0, 0, 64, 64]})).unwrap(); + app.run("layerComp.new", json!({"name": "Comp"})).unwrap(); + app.sync_views(); + let h = Harness::builder() + .with_size(egui::vec2(1440.0, 900.0)) + .with_max_steps(64) + .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 +} + +fn open(h: &mut H, command: &str) -> DialogId { + let ctx = h.ctx.clone(); + let reply = crate::menus::invoke(h.state_mut(), &ctx, command, json!({})).unwrap(); + let want = reply["dialog"].as_str().unwrap().to_owned(); + let dialog = h.state().framework.dialogs.open_dialogs().into_iter().map(|d| d.id).find(|d| d.value().to_string() == want).unwrap(); + h.run_steps(4); + dialog +} + +fn field(h: &H, dialog: DialogId, key: &str) -> Option { + let form = h.state().framework.dialogs.get_by_id::(dialog)?; + serde_json::to_value(form.fields()).ok()?.get(key).cloned() +} + +fn selected(h: &H, label: &str) -> bool { + h.get_by_role_and_label(Role::RadioButton, label).accesskit_node().toggled() == Some(Toggled::True) +} + +/// The top edge of the first node labelled `label`. +fn top(h: &H, label: &str) -> f32 { + h.query_all_by_label(label).next().unwrap_or_else(|| panic!("{label} is shown")).rect().top() +} + +#[test] +fn the_dialog_offers_the_two_radios_below_the_prefix_overlapping_first_and_selected() { + let mut h = harness(); + let dialog = open(&mut h, ARTBOARDS); + let radios: Vec = h.query_all_by_role(Role::RadioButton).filter_map(|n| n.accesskit_node().label()).collect(); + assert_eq!(radios, [OVERLAPPING, CONTENT_ONLY]); + assert!(selected(&h, OVERLAPPING) && !selected(&h, CONTENT_ONLY)); + let radio = top(&h, OVERLAPPING); + assert!(top(&h, "File Name Prefix") < radio && radio < top(&h, "File Type"), "the radios sit between the prefix and the file type"); + assert_eq!(field(&h, dialog, "content"), Some(json!("overlapping"))); +} + +#[test] +fn clicking_artboard_content_only_passes_it_to_the_command() { + let mut h = harness(); + let dialog = open(&mut h, ARTBOARDS); + h.get_by_role_and_label(Role::RadioButton, CONTENT_ONLY).click(); + h.run_steps(4); + assert!(selected(&h, CONTENT_ONLY) && !selected(&h, OVERLAPPING)); + assert_eq!(field(&h, dialog, "content"), Some(json!("artboard"))); + h.get_by_role_and_label(Role::RadioButton, OVERLAPPING).click(); + h.run_steps(4); + assert_eq!(field(&h, dialog, "content"), Some(json!("overlapping"))); +} + +#[test] +fn layer_comps_to_files_has_no_overlap_choice() { + let mut h = harness(); + let dialog = open(&mut h, "file.export.layerCompsToFiles"); + assert_eq!(h.query_all_by_role(Role::RadioButton).count(), 0); + assert_eq!(field(&h, dialog, "content"), None); +} diff --git a/crates/ui-egui/src/canvas/document_display.rs b/crates/ui-egui/src/canvas/document_display.rs index 8607e67718..294c117a63 100644 --- a/crates/ui-egui/src/canvas/document_display.rs +++ b/crates/ui-egui/src/canvas/document_display.rs @@ -335,6 +335,8 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut View, // What the controls report for the host's pass. let mut body_shown = tools::BodyShown::default(); let live = canvas_controls(app, ui, body.rect, host, &space, &mut turned, &mut body_shown); + // The Free Transform preview joins the picture slot after the document, which is prepared after the tools. + let transform_picture = std::mem::take(&mut body_shown.transform_picture); // The body can run more than once in a frame; a report from any of its runs counts. if let Some(context) = body_shown.crop.as_mut().and_then(craft::draw::ui::CropShown::take_context) { overlay_context = Some(context); @@ -414,6 +416,8 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut View, }; display.show_at(ui, body.rect); } + // The moving pixels over the document, which hides the layer they come from, and under the controls. + space.paint_picture(ctx, transform_picture); space.paint_picture(ctx, clipping); // The grid is drawn over the picture. if app.ui.view.shows(app.ui.view.show.pixel_grid) { @@ -529,6 +533,7 @@ fn canvas_controls( let session = if primary { crate::transform_tool::show_in_canvas(app, ui, rect, now) } else { crate::transform_tool::SessionShown::default() }; let session_box_shown = session.shown; reported.transform_snapped = session.snapped; + reported.transform_picture = session.picture; crate::cam_transform::show(app, ui, rect); super::transform_controls::show(app, ui, rect, session_box_shown); crate::move_box::show(app, ui, rect); diff --git a/crates/ui-egui/src/canvas/paint_mouse.rs b/crates/ui-egui/src/canvas/paint_mouse.rs index 992c1c825c..1d900d8a55 100644 --- a/crates/ui-egui/src/canvas/paint_mouse.rs +++ b/crates/ui-egui/src/canvas/paint_mouse.rs @@ -45,14 +45,18 @@ pub fn sync_tool_brush(app: &mut PhotocraftApp) { // A tool seen for the first time takes what the brush has, at Photoshop's smoothing, but // in Normal mode: each tool's Mode starts at Normal, so a Multiply Brush doesn't make the // first Pattern Stamp stroke multiply (or give Healing a mode its menu doesn't have). - // The Art History Brush also starts at full opacity (#10263), and the Pattern Stamp at full - // opacity and flow (#12616): those fields are their own. + // The Pattern Stamp also starts at full opacity and flow (#12616): those fields are its own. // The Background Eraser, the Healing Brush, the Burn, Dodge and Sponge tools, the Clone - // Stamp and the Smudge tool start with their own measured tips instead, as the whole brush - // Reset Tool gives them (#11911, #12099, #12671, #12684, #13029, #12601, #12964). + // Stamp, the Smudge tool and the Art History Brush start with their own measured tips + // instead, as the whole brush Reset Tool gives them (#11911, #12099, #12671, #12684, + // #13029, #12601, #12964, #12631); the Art History Brush's is at full opacity (#10263). None if matches!(tool, Tool::BackgroundEraser | Tool::Healing | Tool::Burn | Tool::Dodge | Tool::Sponge | Tool::CloneStamp | Tool::Smudge) => { fresh_brush(tool, ¤t) } + // Its pressure toggles are not measured, so its first use keeps the outgoing ones (#12631). + None if tool == Tool::ArtHistoryBrush => { + BrushSettings { pressure_size: current.pressure_size, pressure_opacity: current.pressure_opacity, ..fresh_brush(tool, ¤t) } + } // The Pencil starts with its own 1 px hard round (#12200) regardless of the Brush, keeping // the outgoing opacity. None if tool == Tool::Pencil => BrushSettings { opacity: current.opacity, ..fresh_brush(tool, ¤t) }, @@ -62,7 +66,6 @@ pub fn sync_tool_brush(app: &mut PhotocraftApp) { None => { let fresh = BrushSettings::default(); let (opacity, flow) = match tool { - Tool::ArtHistoryBrush => (fresh.opacity, current.flow), Tool::PatternStamp => (fresh.opacity, fresh.flow), _ => (current.opacity, current.flow), }; @@ -110,6 +113,8 @@ const PENCIL_TOOL_TIP: (f32, f32, f32) = (1.0, 1.0, 0.25); const TONING_TOOL_TIP: (f32, f32, f32) = (65.0, 0.0, 0.25); /// The Clone Stamp's tip after Reset Tool (#12601): a 21 px soft round at 25 % spacing. const CLONE_STAMP_TIP: (f32, f32, f32) = (21.0, 0.0, 0.25); +/// The Art History Brush's tip after Reset Tool (#12631): a 21 px soft round at 25 % spacing. +const ART_HISTORY_BRUSH_TIP: (f32, f32, f32) = (21.0, 0.0, 0.25); /// The Remove tool's size after Reset Tool (#12548): 19 px. Its hardness and spacing are not /// measured, so they stay the default brush's. const REMOVE_TOOL_SIZE: f32 = 19.0; @@ -120,7 +125,8 @@ const SMUDGE_TOOL_TIP: (f32, f32, f32) = (13.0, 0.0, 0.25); /// smoothing, with the session's own fields of `current`. The Brush tool's tip is /// [`BRUSH_TOOL_TIP`], the Eraser's [`ERASER_TOOL_TIP`] with no smoothing, the Background Eraser's [`BACKGROUND_ERASER_TIP`], the Healing Brush's /// [`HEALING_BRUSH_TIP`], the Burn, Dodge and Sponge tools' [`TONING_TOOL_TIP`], the Clone Stamp's -/// [`CLONE_STAMP_TIP`] with no smoothing, the Remove tool's size [`REMOVE_TOOL_SIZE`], the Smudge +/// [`CLONE_STAMP_TIP`] and the Art History Brush's [`ART_HISTORY_BRUSH_TIP`], both with no +/// smoothing, the Remove tool's size [`REMOVE_TOOL_SIZE`], the Smudge /// tool's [`SMUDGE_TOOL_TIP`] and the Pencil's [`PENCIL_TOOL_TIP`]; the other tools keep the /// default tip. pub(crate) fn fresh_brush(tool: Tool, current: &BrushSettings) -> BrushSettings { @@ -140,6 +146,10 @@ pub(crate) fn fresh_brush(tool: Tool, current: &BrushSettings) -> BrushSettings (brush.size, brush.hardness, brush.spacing) = CLONE_STAMP_TIP; brush.smoothing.amount = 0.0; } + Tool::ArtHistoryBrush => { + (brush.size, brush.hardness, brush.spacing) = ART_HISTORY_BRUSH_TIP; + brush.smoothing.amount = 0.0; + } Tool::Remove => brush.size = REMOVE_TOOL_SIZE, _ => {} } diff --git a/crates/ui-egui/src/canvas/paint_mouse/tests.rs b/crates/ui-egui/src/canvas/paint_mouse/tests.rs index 14d780ea41..679a90cbe8 100644 --- a/crates/ui-egui/src/canvas/paint_mouse/tests.rs +++ b/crates/ui-egui/src/canvas/paint_mouse/tests.rs @@ -372,8 +372,8 @@ fn the_brush_is_a_per_tool_option_that_presets_keep() { tool_event(&mut app, ToolEvent::Up { x: 30.0, y: 5.0 }, Modifiers::NONE); } -/// #10263: the Art History Brush starts at full opacity the first time it is picked, though it -/// keeps the rest of the brush the old tool left (other tools still take its opacity). +/// #10263: the Art History Brush starts at full opacity the first time it is picked, with its own +/// tip rather than the old tool's (#12631; other tools still take its opacity). #[test] fn art_history_brush_starts_at_full_opacity() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); @@ -384,7 +384,7 @@ fn art_history_brush_starts_at_full_opacity() { app.ui.tool = Tool::ArtHistoryBrush; sync_tool_brush(&mut app); assert_eq!(app.session.tools.brush.opacity, 1.0, "Art History starts at 100%"); - assert_eq!(app.session.tools.brush.size, 40.0, "and inherits the size"); + assert_eq!(app.session.tools.brush.size, 21.0, "with its own 21 px tip"); app.ui.tool = Tool::HistoryBrush; sync_tool_brush(&mut app); assert_eq!(app.session.tools.brush.opacity, 1.0, "the History Brush takes the Art History brush's opacity"); diff --git a/crates/ui-egui/src/canvas/paint_tool/tests.rs b/crates/ui-egui/src/canvas/paint_tool/tests.rs index 4498653fda..fb37337064 100644 --- a/crates/ui-egui/src/canvas/paint_tool/tests.rs +++ b/crates/ui-egui/src/canvas/paint_tool/tests.rs @@ -215,7 +215,12 @@ fn mixer_drag_shows_actual_mixed_paint_before_release_and_alt_never_paints() { #[test] fn mixer_release_includes_a_new_endpoint_and_deferred_frame_samples() { for failed in [false, true] { - let mut h = harness(mixer_app()); + let mut app = mixer_app(); + // Smoothing off: this is about which points reach the commit, and the Mixer Brush's + // first-use 10 % lag (measured, #11888) would hold the brush short of the release point. + crate::paint_mouse::sync_tool_brush(&mut app); + app.run("tools.setBrush", json!({"brush": {"smoothing": {"amount": 0.0}}})).unwrap(); + let mut h = harness(app); let before = h.state().session.active().unwrap().doc.clone(); let p = |h: &Harness<'static, Box>, x: f64| at(h, x, 30.0); let start = p(&h, 20.0); @@ -371,7 +376,10 @@ fn live_stroke_uses_pen_tilt_and_redraws_partially() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); let ctx = app.ctx().clone(); app.run("file.new", json!({"width": 4097, "height": 90, "background": "transparent"})).unwrap(); - let tilt = json!({"size": 30, "hardness": 1.0, "spacing": 0.05, "shapeDynamics": {"enabled": true, "size": {"control": "penTilt"}}}); + // Smoothing off: the default 10 % lag (measured, #11888) on wall-clock times would leave the + // preview's tail anywhere short of the release, so the comparison below couldn't hold. + let tilt = + json!({"size": 30, "hardness": 1.0, "spacing": 0.05, "smoothing": {"amount": 0.0}, "shapeDynamics": {"enabled": true, "size": {"control": "penTilt"}}}); app.run("tools.setBrush", json!({ "brush": tilt })).unwrap(); app.ui.tool = Tool::Brush; let mut seen = composite_revision(&mut app, &ctx, 0, None); @@ -390,7 +398,6 @@ fn live_stroke_uses_pen_tilt_and_redraws_partially() { let (a, b) = (doc.layers[0].surface().unwrap(), shown.layers[0].surface().unwrap()); // 60° tilt shrinks the dab well below 30 px: the preview shows that size, as committed. assert!(a.rgba(500, 45)[3] > 0.5 && a.rgba(500, 45 + 12)[3] == 0.0); - // (The smoothed tail catches up to the end point only when the stroke finishes.) assert!((0..90).all(|y| (0..700).all(|x| a.rgba(x, y) == b.rgba(x, y))), "commit matches the preview"); } diff --git a/crates/ui-egui/src/canvas/tools/mod.rs b/crates/ui-egui/src/canvas/tools/mod.rs index 019e289041..8e39edf481 100644 --- a/crates/ui-egui/src/canvas/tools/mod.rs +++ b/crates/ui-egui/src/canvas/tools/mod.rs @@ -477,6 +477,8 @@ pub(crate) struct BodyShown { pub(crate) crop: Option, /// The snap lines of the open Free Transform's box, which its canvas tool hands to the host. pub(crate) transform_snapped: Vec, + /// The open Free Transform's preview, which the body adds to the canvas's picture slot after the document. + pub(crate) transform_picture: Vec, } /// Borrows a family tool as the host's `dyn`. @@ -513,7 +515,7 @@ fn with_rig( let transform_open = app.ui.transform.is_some(); let lends_transform = stand_ins && (!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 BodyShown { crop: crop_shown, transform_snapped, .. } = shown; let mut transform = free_transform.as_ref().map(|session| crate::transform_tool::canvas_tool(session, transform_snapped)); // The symmetry session moves into the pass the same way. let symmetry_transform = if stand_ins && fam == Family::Paint { app.ui.symmetry_transform.take() } else { None }; diff --git a/crates/ui-egui/src/control/dialogs.rs b/crates/ui-egui/src/control/dialogs.rs index f7423d0441..e1bd171839 100644 --- a/crates/ui-egui/src/control/dialogs.rs +++ b/crates/ui-egui/src/control/dialogs.rs @@ -356,9 +356,26 @@ pub(crate) fn method(app: &mut PhotocraftApp, ctx: &egui::Context, req: &Control if !matches!(req.method.as_str(), "ui.dialog.set" | "ui.dialog.confirm" | "ui.dialog.cancel" | "ui.dialog.apply") { return None; } - let id = match dialog_id(host(app), p) { - Ok(id) => id, - Err(e) => return Some(err(e)), + // Keyboard Shortcuts and Menus draws outside the host: Cancel closes it; its changes go through + // `edit.keyboardShortcuts` params (#15544). + if p.get("dialog").and_then(Value::as_str) == Some(crate::prefs_ui::shortcuts::CONTROL_ID) { + return Some(match req.method.as_str() { + "ui.dialog.cancel" if crate::prefs_ui::shortcuts::cancel(app) => ok(Value::Null), + "ui.dialog.cancel" => err("Keyboard Shortcuts and Menus is not open"), + _ => err("Keyboard Shortcuts and Menus takes its changes as `edit.keyboardShortcuts` params; `ui.dialog.cancel` closes it"), + }); + } + // The unsaved-changes prompt is listed as "discard" and answered by that id. + let id = if p.get("dialog").and_then(Value::as_str) == Some(crate::discard_ui::CONTROL_ID) { + match crate::discard_ui::host_id(app) { + Some(id) => id, + None => return Some(err("no unsaved-changes prompt is open")), + } + } else { + match dialog_id(host(app), p) { + Ok(id) => id, + Err(e) => return Some(err(e)), + } }; Some(match req.method.as_str() { "ui.dialog.set" => set(app, ctx, id, p), diff --git a/crates/ui-egui/src/control/inspect.rs b/crates/ui-egui/src/control/inspect.rs index b4ac2a24f6..6b542994c2 100644 --- a/crates/ui-egui/src/control/inspect.rs +++ b/crates/ui-egui/src/control/inspect.rs @@ -60,12 +60,18 @@ fn rects(app: &PhotocraftApp, ctx: &egui::Context) -> Value { } for dialog in app.framework.dialogs.open_dialogs() { if let Some(r) = rect(dialog.id) { - out.insert(dialog.id.value().to_string(), r); + out.insert(dialog_key(app, dialog.id), r); } } Value::Object(out) } +/// The key `rects` stores hosted dialog `id` under: the id `dialogs` lists it by, so the unsaved-changes prompt is +/// [`crate::discard_ui::CONTROL_ID`] there too (#15544), any other dialog its host id. +pub(super) fn dialog_key(app: &PhotocraftApp, id: egui::Id) -> String { + if crate::discard_ui::host_id(app) == Some(id) { crate::discard_ui::CONTROL_ID.to_string() } else { id.value().to_string() } +} + /// The notices posted since the last pass and the toast cards on screen in every window. fn notices(app: &PhotocraftApp, ctx: &egui::Context) -> Value { let mut all: Vec = app.ui.notices.iter().map(|notice| serde_json::to_value(notice).unwrap_or_default()).collect(); @@ -87,6 +93,11 @@ pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value { // The framework host's dialogs in their one stack order (top last). let mut dialogs = craft::automation::dialogs::inspect(&app.framework.dialogs); crate::layer_style::describe_params(app, &mut dialogs); + crate::discard_ui::describe(app, &mut dialogs); + // Keyboard Shortcuts and Menus draws beneath the host's dialogs, outside the host (#15544). + if let (Some(shortcuts), Some(list)) = (crate::prefs_ui::shortcuts::inspect(app), dialogs.as_array_mut()) { + list.insert(0, shortcuts); + } // Last frame's task bar rect, unless the bar can't show now (hidden by `ui.set` before the // next draw). let task_bar_rect = app.ui.task_bar_shown.filter(|_| crate::crop_task_bar::eligible(app)); diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index aa8e65df7a..dc88c6efed 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -986,11 +986,11 @@ fn preferences_apply_is_available_over_control_without_closing() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); let ctx = app.ctx().clone(); let r = call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "edit.preferences.interface"})); - // The Preferences window is held by the app; control addresses it by the id `ui.inspect` lists - // and the reply names it by its key. + // The Preferences window is held by the app; control addresses it by the id `ui.inspect` lists, + // and the reply names it by that id (#15544). let listed = dialogs(&mut app, &ctx); let window = listed.iter().find(|d| d["key"] == "preferences").expect("the Preferences window is listed"); - assert_eq!(r["result"]["dialog"], window["key"], "{r}"); + assert_eq!(r["result"]["dialog"], window["id"], "{r}"); let id = window["id"].clone(); let mut values = window["fields"]["values"].clone(); values["interface"]["uiScale"] = json!("200"); @@ -1354,7 +1354,8 @@ fn dirty_close_prompted() -> (Box, egui::Context, std::rc::Rc Result<(), String> { let prompt = top_dialog(app, ctx)["id"].clone(); if synthetic { - let id = craft::automation::dialogs::dialog_id(&app.framework.dialogs, &json!({"dialog": prompt})).expect("the prompt is listed"); + assert_eq!(prompt, crate::discard_ui::CONTROL_ID, "the prompt is listed as discard"); + let id = crate::discard_ui::host_id(app).expect("the prompt is open"); app.automation_input = true; let r = crate::dialogs::confirm(app, ctx, id); app.automation_input = false; @@ -2223,3 +2224,108 @@ fn shift_right_menu_choose_rejects_bad_choices_and_sets_the_tool() { shift_right(&mut app, "magicEraser"); assert!(inspect(&app, &ctx)["brushModeMenu"].is_null()); } + +/// A fresh app with a document, as a control client finds it, and the context the control channel runs on. +fn app_with_document() -> (Box, egui::Context) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.sync_views(); + let ctx = app.ctx().clone(); + (app, ctx) +} + +/// The id `ui.menu.invoke {id, wait: false}` replied for the dialog it opened. +fn invoked_dialog(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str) -> Value { + let reply = call(app, ctx, "ui.menu.invoke", json!({"id": id, "wait": false})); + assert_eq!(reply["ok"], true, "{id}: {reply}"); + crate::canvas::testing::frame(app); + reply["result"]["dialog"].clone() +} + +/// #15544: Keyboard Shortcuts and Menus is listed under the id its menu items reply with, and +/// `ui.dialog.cancel` with that id closes it, so a control client is never stuck behind it. +#[test] +fn keyboard_shortcuts_is_listed_and_cancelled_by_the_id_invoke_replies() { + for command in ["edit.keyboardShortcuts", "edit.menus"] { + let (mut app, ctx) = app_with_document(); + let id = invoked_dialog(&mut app, &ctx, command); + assert!(id.is_string(), "{command}: the reply names the dialog: {id}"); + let listed = dialogs(&mut app, &ctx); + assert!(listed.iter().any(|d| d["id"] == id), "{command}: {id} is listed in {listed:?}"); + assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "select.all"}))["ok"], false, "{command}: the dialog is modal"); + let cancelled = call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": id})); + assert_eq!(cancelled["ok"], true, "{command}: {cancelled}"); + assert!(!crate::prefs_ui::shortcuts_open(&app), "{command}: Cancel closed it"); + assert!(dialogs(&mut app, &ctx).is_empty()); + assert_eq!(call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": id}))["ok"], false, "{command}: nothing left to cancel"); + let next = call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "select.all"})); + assert_eq!(next["ok"], true, "{command}: commands run again: {next}"); + } +} + +/// #15544: Preferences replies with the id `ui.inspect` lists it under, and cancelling that id closes it. +#[test] +fn preferences_replies_with_the_id_it_is_listed_under() { + let (mut app, ctx) = app_with_document(); + let id = invoked_dialog(&mut app, &ctx, "edit.preferences.interface"); + let listed = dialogs(&mut app, &ctx); + assert_eq!(listed.len(), 1, "{listed:?}"); + assert_eq!(listed[0]["id"], id, "the reply is the listed id"); + assert_eq!(listed[0]["key"], "preferences"); + let cancelled = call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": id})); + assert_eq!(cancelled["ok"], true, "{cancelled}"); + crate::canvas::testing::frame(&mut app); + assert!(dialogs(&mut app, &ctx).is_empty()); + assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "select.all"}))["ok"], true); +} + +/// #15544: Select › Color Range… replies with the bare id, as every other dialog does, not a `Result` around it. +#[test] +fn color_range_replies_with_the_bare_dialog_id() { + let (mut app, ctx) = app_with_document(); + let id = invoked_dialog(&mut app, &ctx, "select.colorRange"); + assert!(id.is_string(), "a bare id, not a wrapper: {id}"); + assert_eq!(top_dialog(&mut app, &ctx)["id"], id); + assert_eq!(top_dialog(&mut app, &ctx)["key"], "select.colorRange"); + let cancelled = call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": id})); + assert_eq!(cancelled["ok"], true, "{cancelled}"); + assert!(dialogs(&mut app, &ctx).is_empty()); +} + +/// #15544: the unsaved-changes prompt is listed as `"discard"` with the command it holds back, the document it +/// asks about, how many are left and the choices, and `ui.dialog.confirm` / `ui.dialog.cancel` take that id +/// (docs/control-protocol.md). +#[test] +fn the_unsaved_changes_prompt_is_listed_as_discard_and_answered_by_that_id() { + let (mut app, ctx) = app_with_document(); + app.run("layer.new.layer", json!({})).unwrap(); + let prompt = |app: &mut PhotocraftApp| dialogs(app, &ctx).into_iter().find(|d| d["id"] == "discard"); + assert!(prompt(&mut app).is_none()); + // Close the changed document: the prompt is listed; Cancel keeps the document. + assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "file.close"}))["ok"], true); + crate::canvas::testing::frame(&mut app); + let listed = prompt(&mut app).unwrap_or_else(|| panic!("listed as discard: {:?}", dialogs(&mut app, &ctx))); + let name = app.session.active().unwrap().doc.name.clone(); + assert_eq!(listed["fields"]["command"], "file.close"); + assert_eq!(listed["fields"]["document"], name.as_str()); + assert_eq!(listed["fields"]["remaining"], 1); + assert_eq!(listed["fields"]["choices"], json!(["save", "dontSave", "cancel"])); + // Its rect is keyed by that id too, as `rects` keys every hosted dialog by its `dialogs` id; others keep theirs. + let host = crate::discard_ui::host_id(&app).expect("the prompt is open"); + assert_eq!(super::inspect::dialog_key(&app, host), "discard"); + let other = egui::Id::unique("another dialog"); + assert_eq!(super::inspect::dialog_key(&app, other), other.value().to_string()); + let cancelled = call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": "discard"})); + assert_eq!(cancelled["ok"], true, "{cancelled}"); + crate::canvas::testing::frame(&mut app); + assert!(prompt(&mut app).is_none()); + assert_eq!(app.session.documents().len(), 1, "Cancel keeps the document"); + assert_eq!(call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": "discard"}))["ok"], false, "nothing left to answer"); + // Don't Save by that id closes it. + assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "file.close"}))["ok"], true); + crate::canvas::testing::frame(&mut app); + let answered = call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog": "discard", "choice": "dontSave"})); + assert_eq!(answered["ok"], true, "{answered}"); + crate::canvas::testing::frame(&mut app); + assert!(app.session.documents().is_empty(), "Don't Save closed the document"); +} diff --git a/crates/ui-egui/src/dialog_title_ellipsis_tests.rs b/crates/ui-egui/src/dialog_title_ellipsis_tests.rs new file mode 100644 index 0000000000..014c7dc1c5 --- /dev/null +++ b/crates/ui-egui/src/dialog_title_ellipsis_tests.rs @@ -0,0 +1,49 @@ +//! A dialog's title is its command's name without the menu item's ellipsis (#15541): Edit › Stroke… +//! opens "Stroke", as in Photoshop. Covers the dialogs that name themselves after their menu item. + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; + +use crate::PhotocraftApp; + +/// Opens one dialog. +type Open = fn(&mut PhotocraftApp); + +fn harness() -> Harness<'static, Box> { + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 1000.0)).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::AppTheme::pro()); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 120})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.all", json!({})).unwrap(); + app + }); + h.run_steps(6); + h +} + +#[test] +fn dialog_titles_drop_the_menu_ellipsis() { + let cases: [(&str, Open); 4] = [ + ("Stroke", |app| { + crate::stroke_ui::open(app); + }), + ("New Group", |app| { + crate::new_group_ui::open(app, crate::new_group_ui::NEW_GROUP); + }), + ("New Group from Layers", |app| { + crate::new_group_ui::open(app, crate::new_group_ui::FROM_LAYERS); + }), + ("New Brush Preset", |app| { + crate::brush_preset_dialog::open(app, None); + }), + ]; + for (title, open) in cases { + let mut h = harness(); + open(h.state_mut()); + h.run_steps(4); + assert!(h.query_all_by_label(&format!("{title}…")).next().is_none(), "the {title} dialog's title has no ellipsis"); + assert!(h.query_all_by_label(title).next().is_some(), "the dialog is titled {title}"); + } +} diff --git a/crates/ui-egui/src/dialogs/brush_preset_dialog.rs b/crates/ui-egui/src/dialogs/brush_preset_dialog.rs index 30d680888d..fde37ee089 100644 --- a/crates/ui-egui/src/dialogs/brush_preset_dialog.rs +++ b/crates/ui-egui/src/dialogs/brush_preset_dialog.rs @@ -67,7 +67,7 @@ pub fn open(app: &mut PhotocraftApp, brush: Option<&BrushSettings>) -> DialogId // Include Color belongs to the tool settings: only with them, as in Photoshop. Param::new("color", tl!("Include Color"), ParamKind::bool(false)).enabled_when("toolSettings", true), ]; - let mut dialog = ParamDialog::command(KEY, tl!("New Brush Preset…"), rows).values(Bind::bound(fields)).ok_enabled(why.is_none()); + let mut dialog = ParamDialog::command(KEY, tl!("New Brush Preset"), rows).values(Bind::bound(fields)).ok_enabled(why.is_none()); if let Some(why) = why { dialog = dialog.ok_reason(Label::from(why)); } diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui.rs b/crates/ui-egui/src/dialogs/camera_raw_ui.rs index 87d51024a6..f2f40b7020 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui.rs @@ -159,6 +159,9 @@ pub(crate) struct SourceInit { pub(crate) ctx: egui::Context, } +#[cfg(test)] +type BeforePreviewPublish = Arc; + /// PhotoCraft's develop for the RAW Develop workspace: the proxy, the selection coverage, the GPU handle and the /// result slot the develop jobs fill. Nothing in it is kept across passes beyond those results. pub(crate) struct PcRawSource { @@ -191,6 +194,9 @@ pub(crate) struct PcRawSource { running: Arc, /// Develops started so far: the order of the results. issued: AtomicU64, + /// Tests can hold one real job after its cancellation check, before the revision guard. + #[cfg(test)] + before_preview_publish: Mutex>, /// The side of the blocks the proxy averaged: the pictures' reduction. block: u32, /// Wakes the UI when a refinement lands. @@ -237,6 +243,8 @@ impl PcRawSource { developed: Arc::default(), running: Arc::default(), issued: AtomicU64::new(0), + #[cfg(test)] + before_preview_publish: Mutex::new(None), block: block as u32, ctx, } @@ -324,6 +332,8 @@ impl RawDevelopSource for PcRawSource { let before_histogram = self.before_histogram.clone(); let (pw, ph) = (self.pw, self.ph); let block = self.block; + #[cfg(test)] + let before_preview_publish = self.before_preview_publish.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone(); let running = Running::start(&self.running); Job::new(move |_progress, cancel| { let _running = running; @@ -354,6 +364,10 @@ impl RawDevelopSource for PcRawSource { backend: frame.backend, scope, }; + #[cfg(test)] + if let Some(before_publish) = before_preview_publish { + before_publish(order, &result.settings); + } // A job for older settings that finishes after a newer one must not replace its result. let mut slot = developed.lock().unwrap_or_else(std::sync::PoisonError::into_inner); if slot.as_ref().is_none_or(|current| current.revision <= result.revision) { diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs index d042e52d22..48cf85f086 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs @@ -181,7 +181,11 @@ fn worker_preview_matches_the_synchronous_render_and_ends_on_the_latest_settings assert_eq!(last["previewPending"], false); let now = shown(&app); assert_eq!((now.exposure, now.highlights, now.shadows), (1.0, -60.0, 45.0)); - // PLAN: the develop `Job` cannot be run outside the runtime, so the frame is compared with a fresh dialog's develop of the same settings, not a direct `ProxyJob::run`. + // The runtime owns the real job; its published pixels must also match the synchronous proxy calculation. + let synchronous = session(&app).source.proxy_job(&now).run(); + assert_eq!(processed(&app), synchronous.px, "the real worker develops exactly the same proxy pixels"); + assert_eq!(session(&app).source.developed().unwrap().after_histogram.channels, synchronous.histogram.channels); + assert!(craft::ui::runtime::pending::finish_jobs(&ctx, std::time::Duration::from_secs(30)), "all actual preview jobs have terminated"); assert_eq!( last["histogram"], single_develop_histogram(json!({"exposure": 1.0, "highlights": -60, "shadows": 45})), @@ -189,23 +193,125 @@ fn worker_preview_matches_the_synchronous_render_and_ends_on_the_latest_settings ); } +/// An old job held after its real cancellation check. Drop always releases it and drains its queue, including on +/// an assertion failure; all waits have bounds. This never substitutes for the production menu or develop job. +#[cfg(not(target_arch = "wasm32"))] +struct HeldPreview { + ctx: egui::Context, + release: Arc<(std::sync::Mutex, std::sync::Condvar)>, + timed_out: Arc, +} + +#[cfg(not(target_arch = "wasm32"))] +impl HeldPreview { + fn release_and_finish(&self) -> bool { + let (released, wake) = &*self.release; + *released.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = true; + wake.notify_all(); + craft::ui::runtime::pending::finish_jobs(&self.ctx, std::time::Duration::from_secs(30)) + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl Drop for HeldPreview { + fn drop(&mut self) { + let _ = self.release_and_finish(); + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn hold_old_preview(app: &PhotocraftApp) -> (HeldPreview, std::sync::mpsc::Receiver) { + let release = Arc::new((std::sync::Mutex::new(false), std::sync::Condvar::new())); + let timed_out = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let (arrived, waiting) = std::sync::mpsc::channel(); + let held = HeldPreview { ctx: app.ctx().clone(), release: release.clone(), timed_out: timed_out.clone() }; + *session(app).source.before_preview_publish.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Arc::new(move |order, settings| { + if settings.highlights != -80.0 { + return; + } + let _ = arrived.send(order); + let (released, wake) = &*release; + let released = released.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (released, _) = + wake.wait_timeout_while(released, std::time::Duration::from_secs(30), |released| !*released).unwrap_or_else(std::sync::PoisonError::into_inner); + if !*released { + timed_out.store(true, std::sync::atomic::Ordering::Relaxed); + } + })); + (held, waiting) +} + +/// Observe only the newer publication: `settle` deliberately waits for the older held job too. +#[cfg(not(target_arch = "wasm32"))] +fn wait_for_newer_preview(app: &mut PhotocraftApp, order: u64) { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + loop { + frame(app); + if session(app) + .source + .developed() + .is_some_and(|result| result.revision > order && result.settings.exposure == -1.0 && result.settings.highlights == 0.0) + { + return; + } + assert!(std::time::Instant::now() < deadline, "the real newer request must publish while the older job is held"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } +} + /// An older develop that lands after a newer request must not replace the frame of the newer /// settings. #[test] fn a_stale_worker_never_replaces_a_newer_synchronous_render() { - let (mut app, ctx) = worker_app(); - menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"highlights": -80}}})).unwrap().unwrap(); - // The develop of the older request is running. - frame(&mut app); - menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"highlights": 0, "exposure": -1.0}}})).unwrap().unwrap(); - settle(&mut app); - let landed = describe(&app); - std::thread::sleep(std::time::Duration::from_millis(200)); - frame(&mut app); - frame(&mut app); - let later = describe(&app); - assert_eq!((&later["previewRevision"], &later["histogram"]), (&landed["previewRevision"], &landed["histogram"]), "nothing replaced the newer frame"); - assert_eq!(landed["histogram"], single_develop_histogram(json!({"exposure": -1.0})), "the frame shown is the one for the latest settings"); + #[cfg(not(target_arch = "wasm32"))] + { + let (mut app, ctx) = worker_app(); + let (held, arrived) = hold_old_preview(&app); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"highlights": -80}}})).unwrap().unwrap(); + frame(&mut app); + let old_order = arrived.recv_timeout(std::time::Duration::from_secs(10)).expect("the real old request passed cancellation and reached publication"); + assert!(session(&app).source.pending(), "the old job remains live at the gate"); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"highlights": 0, "exposure": -1.0}}})).unwrap().unwrap(); + wait_for_newer_preview(&mut app, old_order); + let landed = describe(&app); + let shown_pixels = processed(&app); + assert_eq!(landed["previewPending"], true, "observing the new publication did not release the older job"); + assert!(landed["previewRevision"].as_u64().unwrap() > old_order); + assert!(held.release_and_finish(), "every actual queued or running develop has terminated"); + assert!(!held.timed_out.load(std::sync::atomic::Ordering::Relaxed), "the old result was released by the test, not its deadline"); + frame(&mut app); + frame(&mut app); + let later = describe(&app); + assert_eq!(later["previewPending"], false); + assert_eq!( + (&later["previewRevision"], &later["histogram"]), + (&landed["previewRevision"], &landed["histogram"]), + "the old result reached publication last and did not replace the newer frame" + ); + assert_eq!(processed(&app), shown_pixels, "the old result did not replace the displayed proxy pixels"); + assert_eq!( + session(&app).source.proxy_job(&shown(&app)).run().px, + shown_pixels, + "the pixels still match a synchronous develop of the control channel's settings" + ); + assert_eq!(landed["histogram"], single_develop_histogram(json!({"exposure": -1.0})), "the frame shown is the one for the latest settings"); + } + #[cfg(target_arch = "wasm32")] + { + let (mut app, ctx) = worker_app(); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"highlights": -80}}})).unwrap().unwrap(); + // The develop of the older request is running. + frame(&mut app); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"highlights": 0, "exposure": -1.0}}})).unwrap().unwrap(); + settle(&mut app); + let landed = describe(&app); + assert!(craft::ui::runtime::pending::finish_jobs(&ctx, std::time::Duration::from_secs(30)), "all preview jobs have terminated"); + frame(&mut app); + frame(&mut app); + let later = describe(&app); + assert_eq!((&later["previewRevision"], &later["histogram"]), (&landed["previewRevision"], &landed["histogram"]), "nothing replaced the newer frame"); + assert_eq!(landed["histogram"], single_develop_histogram(json!({"exposure": -1.0})), "the frame shown is the one for the latest settings"); + } } #[test] diff --git a/crates/ui-egui/src/dialogs/discard_ui.rs b/crates/ui-egui/src/dialogs/discard_ui.rs index 8ca632d0c7..f96391a6fb 100644 --- a/crates/ui-egui/src/dialogs/discard_ui.rs +++ b/crates/ui-egui/src/dialogs/discard_ui.rs @@ -418,6 +418,43 @@ pub(crate) fn authorize_save(app: &PhotocraftApp, from_control: bool) -> Result< } } +/// The id the control channel knows the prompt by: `ui.inspect` lists it under this id, and `ui.dialog.confirm` and +/// `ui.dialog.cancel` answer it by it (docs/control-protocol.md, #4920, #15544). +pub const CONTROL_ID: &str = "discard"; + +/// The host's id of the open question, for a control request naming [`CONTROL_ID`]. +pub(crate) fn host_id(app: &PhotocraftApp) -> Option { + app.framework.dialogs.get::().map(craft::ui::dialog::StackDialog::id) +} + +/// Lists the open question in `dialogs` (the host's `ui.inspect` entries) under [`CONTROL_ID`], its fields adding the +/// command it holds back, the document it asks about, how many are left to answer, the choices `ui.dialog.confirm` +/// takes and the default one. +pub(crate) fn describe(app: &PhotocraftApp, dialogs: &mut Value) { + let Some(key) = host_id(app).map(|id| id.value().to_string()) else { return }; + let Some(entry) = dialogs.as_array_mut().and_then(|list| list.iter_mut().find(|d| d["id"] == key.as_str())) else { return }; + entry["id"] = json!(CONTROL_ID); + let Some(p) = app.discard.as_ref() else { return }; + let name = p.docs.first().and_then(|&doc| index_of(app, doc)).and_then(|i| app.session.documents().get(i)).map(|d| d.doc.name.clone()); + let reverts = p.id == "file.revert"; + let choices: &[&str] = match (reverts, p.docs.len() > 1) { + (true, _) => &["dontSave", "cancel"], + (false, false) => &["save", "dontSave", "cancel"], + (false, true) => &["save", "saveAll", "dontSave", "dontSaveAll", "cancel"], + }; + let described = json!({ + "command": p.id, + "document": name, + "remaining": p.docs.len(), + "choices": choices, + "default": if reverts { "dontSave" } else { "save" }, + }); + match entry.get_mut("fields").and_then(Value::as_object_mut) { + Some(fields) => fields.extend(described.as_object().cloned().unwrap_or_default()), + None => entry["fields"] = described, + } +} + /// The command the prompt holds back and its params, for the automation policy to see before a /// control client answers it. pub fn pending_command(app: &PhotocraftApp) -> Option<(String, Value)> { diff --git a/crates/ui-egui/src/dialogs/new_group_ui.rs b/crates/ui-egui/src/dialogs/new_group_ui.rs index 2412592556..af393044ea 100644 --- a/crates/ui-egui/src/dialogs/new_group_ui.rs +++ b/crates/ui-egui/src/dialogs/new_group_ui.rs @@ -33,7 +33,7 @@ pub fn open(app: &mut PhotocraftApp, command: &str) -> DialogId { let command = if command == FROM_LAYERS { FROM_LAYERS } else { NEW_GROUP }; let name = app.session.active().map(|st| st.doc.next_layer_name("Group")).unwrap_or_else(|| "Group 1".into()); // The window title, as in Photoshop. - let title = if command == FROM_LAYERS { tl!("New Group from Layers…") } else { tl!("New Group…") }; + let title = if command == FROM_LAYERS { tl!("New Group from Layers") } else { tl!("New Group") }; params::open_param(app, command, DialogFields::new(), Value::Null, move |fields: &mut DialogFields| { let rows = vec![ Param::new("name", tl!("Name:"), ParamKind::text(name.clone())), diff --git a/crates/ui-egui/src/dialogs/preset_group_prompt/tests.rs b/crates/ui-egui/src/dialogs/preset_group_prompt/tests.rs index 96de48ce66..160238e8a4 100644 --- a/crates/ui-egui/src/dialogs/preset_group_prompt/tests.rs +++ b/crates/ui-egui/src/dialogs/preset_group_prompt/tests.rs @@ -38,7 +38,7 @@ fn group(app: &PhotocraftApp, kind: Kind, name: &str) -> Value { } fn library(app: &PhotocraftApp) -> Value { - json!({"brushes": app.session.tools.presets, "gradients": app.session.presets.gradients, "selectedBrush": app.session.tools.brush}) + json!({"brushes": app.session.tools.presets.as_ref(), "gradients": app.session.presets.gradients, "selectedBrush": app.session.tools.brush}) } impl Fixture { @@ -74,7 +74,7 @@ impl Fixture { match kind { Kind::Brushes => { assert_eq!(original.as_array().unwrap().len(), 2); - app.session.tools.presets.iter_mut().find(|p| p.group == stem).unwrap().brush.size = 77.0; + std::sync::Arc::make_mut(&mut app.session.tools.presets).iter_mut().find(|p| p.group == stem).unwrap().brush.size = 77.0; } Kind::Gradients => { assert_eq!(original[0]["items"].as_array().unwrap().len(), 2); diff --git a/crates/ui-egui/src/dialogs/stroke_ui.rs b/crates/ui-egui/src/dialogs/stroke_ui.rs index e5a07a6707..2048251e57 100644 --- a/crates/ui-egui/src/dialogs/stroke_ui.rs +++ b/crates/ui-egui/src/dialogs/stroke_ui.rs @@ -43,7 +43,7 @@ pub fn open(app: &mut PhotocraftApp) -> DialogId { } let [r, g, b, _] = app.session.tools.foreground; let rows = rows([r, g, b]); - let title = Label::from(tl!("Stroke…")); + let title = Label::from(tl!("Stroke")); open_param(app, COMMAND, DialogFields::new(), held, move |fields| { ParamDialog::new(COMMAND, title.clone(), Cow::Owned(rows.clone())).values(Bind::bound(fields)).remember(SaveKey::named(REMEMBER)) }) diff --git a/crates/ui-egui/src/home_recent_ui.rs b/crates/ui-egui/src/home_recent_ui.rs index f7cbbc7255..9518515318 100644 --- a/crates/ui-egui/src/home_recent_ui.rs +++ b/crates/ui-egui/src/home_recent_ui.rs @@ -480,6 +480,99 @@ mod tests { assert!(loaded.is_none()); } + /// Drive the real Home source and store with one explicitly completed background lane. + #[cfg(not(target_arch = "wasm32"))] + fn recent_thumbnail_pass(app: &PhotocraftApp, frames: &mut craft::ui::testing::Frames, key: &ThumbKey) -> craft::ui::primitives::TextureState { + let ctx = app.ctx().clone(); + let mut state = None; + frames.frame(Vec::new(), |_| { + state = Some(thumbnails(&ctx).state(&ctx, &source(app, &ctx), key, &ThumbRequest::for_cell(64.0, 1.0), craft::ui::primitives::Priority::VISIBLE)); + }); + state.expect("the Home thumbnail caller ran") + } + + #[cfg(not(target_arch = "wasm32"))] + fn manual_recent_thumbnails(app: &PhotocraftApp) -> (craft::ui::testing::Frames, std::sync::Arc) { + let ctx = app.ctx().clone(); + let jobs = std::sync::Arc::new(craft::host::ManualJobs::new()); + // The production accessor uses this same salt; its later options keep this first-created loader. + Thumbnails::::in_context(&ctx, "home-recent", ThumbnailOptions::new().lanes(1).jobs(jobs.clone())); + let mut frames = craft::ui::testing::Frames::over(ctx); + frames.record_paint(); + (frames, jobs) + } + + #[cfg(not(target_arch = "wasm32"))] + fn assert_recent_picture(frames: &mut craft::ui::testing::Frames, state: craft::ui::primitives::TextureState, rgba: [u8; 4]) { + let craft::ui::primitives::TextureState::Ready(texture) = state else { panic!("the completed decoder must supply a ready picture") }; + assert_eq!((texture.size.width, texture.size.height), (4, 4)); + let mut paint = frames.take_paint().expect("texture uploads were recorded"); + let delta = paint.textures_delta.set.get(&texture.id).and_then(|changes| changes.last()).expect("the real decoder's texture was uploaded"); + let egui::ImageData::Color(image) = &delta.image; + assert_eq!(image.size, [4, 4]); + assert!(image.pixels.iter().all(|pixel| pixel.to_array() == rgba), "the picture contains the decoded file's pixels"); + // The headless test inspected the uploads instead of rendering them. + paint.textures_delta.clear(); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn recent_thumbnail_loads_in_background_when_background_jobs_enabled() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("background.png"); + std::fs::write(&path, flat_png([20, 60, 100, 255])).unwrap(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = true; + app.push_recent(&path.to_string_lossy()); + let key = ThumbKey::Recent(path); + let (mut frames, jobs) = manual_recent_thumbnails(&app); + + assert!(matches!(recent_thumbnail_pass(&app, &mut frames, &key), craft::ui::primitives::TextureState::Loading { stand_in: None, .. })); + assert_eq!(jobs.waiting(), 1, "the real source returned a background decoder, rather than decoding inline"); + assert!(jobs.run_next(), "the queued decoder actually ran to completion"); + assert_eq!(jobs.waiting(), 0, "no worker remains deferred"); + let state = recent_thumbnail_pass(&app, &mut frames, &key); + assert_recent_picture(&mut frames, state, [20, 60, 100, 255]); + assert!(!jobs.run_next(), "the ready picture starts no duplicate job"); + assert!(thumbnails(app.ctx()).shutdown(std::time::Duration::from_secs(2)), "the completed loader has no running work"); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn recent_thumbnail_discards_background_result_if_invalidated_while_loading() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("invalidated.png"); + std::fs::write(&path, flat_png([100, 20, 60, 255])).unwrap(); + let path_string = path.to_string_lossy().into_owned(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = true; + app.push_recent(&path_string); + let key = ThumbKey::Recent(path); + let (mut frames, jobs) = manual_recent_thumbnails(&app); + + assert!(matches!(recent_thumbnail_pass(&app, &mut frames, &key), craft::ui::primitives::TextureState::Loading { .. })); + let before = revision_of(&app, &path_string); + assert!(jobs.run_next(), "finish the actual decoder before invalidation and before its result is uploaded"); + assert_eq!(jobs.waiting(), 0); + lock(&app.thumbnail_cache).invalidate(&path_string); + assert_ne!(before, revision_of(&app, &path_string), "invalidation must change the real source's revision"); + // Check invalidation with unchanged metadata first, then make stale and fresh decoder pixels distinct. + std::fs::write(&path_string, flat_png([20, 100, 60, 255])).unwrap(); + + // The former picture may be a stand-in, but it cannot satisfy the invalidated revision as Ready. + assert!( + matches!(recent_thumbnail_pass(&app, &mut frames, &key), craft::ui::primitives::TextureState::Loading { .. }), + "the completed old result is not current" + ); + assert_eq!(jobs.waiting(), 1, "the production source requests a replacement decoder"); + assert!(jobs.run_next(), "the replacement decoder completes"); + let state = recent_thumbnail_pass(&app, &mut frames, &key); + assert_recent_picture(&mut frames, state, [20, 100, 60, 255]); + assert_eq!(jobs.waiting(), 0); + assert!(!jobs.run_next()); + assert!(thumbnails(app.ctx()).shutdown(std::time::Duration::from_secs(2)), "both decoder jobs have terminated"); + } + /// The thumbnail source of a fresh pass over `app`. #[cfg(not(target_arch = "wasm32"))] fn revision_of(app: &PhotocraftApp, path: &str) -> Revision { diff --git a/crates/ui-egui/src/input/shortcut_dispatch.rs b/crates/ui-egui/src/input/shortcut_dispatch.rs index 9bd05d2714..a629f0c7c1 100644 --- a/crates/ui-egui/src/input/shortcut_dispatch.rs +++ b/crates/ui-egui/src/input/shortcut_dispatch.rs @@ -10,7 +10,7 @@ //! shortcut whose command is disabled in the current state reports why on the status bar instead //! of doing nothing silently, as the greyed menu item shows. -use std::collections::HashSet; +use std::collections::HashMap; use craft::color_ui::ui::SwatchesCommand; use craft::keymap::{Binding, Chord, CommandDef, CommandKind, Overrides, Scope}; @@ -208,17 +208,31 @@ fn binding(text: &str) -> Option { /// The menu path of command `id`: its menu, then its label. fn menu_path(id: &str) -> Option> { - let (menu, label): (&[&str], &str) = crate::menu_catalog::CATALOG - .iter() - .find(|c| c.3 == id) - .map(|c| (c.0, c.1)) - .or_else(|| crate::menus::UI_COMMANDS.iter().find(|c| c.0 == id && !c.2.is_empty()).map(|c| (c.2, c.1)))?; - Some(menu.iter().chain([&label]).map(|part| (*part).to_string()).collect()) + let (menu, label) = menu_paths().get(id)?; + Some(menu.iter().chain([label]).map(|part| (*part).to_string()).collect()) } -/// Adds `def` unless an earlier source gave its id or the runtime defines it. -fn push_row(rows: &mut Vec, seen: &mut HashSet, def: CommandDef) { - if !is_bridged(&def.command.id) && seen.insert(def.command.id.clone()) { +/// Each command's menu and label: the catalogue's first row of the command, else the first shell command of that id +/// that has a menu. +fn menu_paths() -> &'static HashMap<&'static str, (&'static [&'static str], &'static str)> { + static PATHS: std::sync::OnceLock> = std::sync::OnceLock::new(); + PATHS.get_or_init(|| { + let mut paths = HashMap::new(); + for &(menu, label, _, id) in crate::menu_catalog::CATALOG { + paths.entry(id).or_insert((menu, label)); + } + for &(id, label, menu, _) in crate::menus::UI_COMMANDS.iter().filter(|c| !c.2.is_empty()) { + paths.entry(id).or_insert((menu, label)); + } + paths + }) +} + +/// Adds `def` unless an earlier source gave its id or the runtime defines it. `index` holds each row's place in +/// `rows` by its id. +fn push_row(rows: &mut Vec, index: &mut HashMap, def: CommandDef) { + if !is_bridged(&def.command.id) && !index.contains_key(&def.command.id) { + index.insert(def.command.id.clone(), rows.len()); rows.push(def); } } @@ -229,18 +243,18 @@ fn push_row(rows: &mut Vec, seen: &mut HashSet, def: Command /// ([`RUNTIME_COMMANDS`]) are not rows. The Keyboard Shortcuts dialog lists exactly these rows. pub(crate) fn command_rows(app: &PhotocraftApp) -> Vec { let mut rows: Vec = Vec::new(); - let mut seen: HashSet = HashSet::new(); + let mut index: HashMap = HashMap::new(); let app_row = |id: &str, label: &str| CommandDef::new(CommandRef::new(id), label, Scope::app()); // The tool letters, and the Shift+letter step of each group. for def in crate::tool_shortcuts::defs(app) { - push_row(&mut rows, &mut seen, def); + push_row(&mut rows, &mut index, def); } for (letter, first) in crate::tool_shortcuts::group_letters() { let label = format!("Next {}", first.label()); let mut def = app_row(&next_in_group_id(letter), &label).with_path(vec!["Tools".into(), label.clone()]); def.defaults.extend(binding(&format!("Shift+{}", letter.to_ascii_uppercase()))); - push_row(&mut rows, &mut seen, def); + push_row(&mut rows, &mut index, def); } // The held erase key is momentary; the hand and zoom keys are the runtime's. for &(id, label, key) in photocraft_engine::prefs::TEMPORARY_TOOLS { @@ -249,7 +263,7 @@ pub(crate) fn command_rows(app: &PhotocraftApp) -> Vec { } let mut def = app_row(id, label).with_kind(CommandKind::Momentary).with_path(vec!["Tools".into(), "Temporary".into(), label.into()]); def.defaults.extend(binding(key)); - push_row(&mut rows, &mut seen, def); + push_row(&mut rows, &mut index, def); } // Alt+1 … Alt+0 set the brush smoothing (press only). The opacity and blend digits are command sets of the // framework (`OpacityDigit`, `BlendStep`, `BlendShortcut`), so they are no rows here. @@ -258,7 +272,7 @@ pub(crate) fn command_rows(app: &PhotocraftApp) -> Vec { let label = format!("Brush Smoothing {}%", digit * 10); let mut def = app_row(&format!("tools.smoothing.{key}"), &label).with_path(vec!["Tools".into(), "Smoothing".into(), label.clone()]); def.defaults.extend(binding(&format!("Alt+{key}"))); - push_row(&mut rows, &mut seen, def); + push_row(&mut rows, &mut index, def); } // The engine's and the shell's commands, with the menu paths the shell knows. @@ -267,43 +281,43 @@ pub(crate) fn command_rows(app: &PhotocraftApp) -> Vec { if def.paths.is_empty() { def.paths.extend(menu_path(&def.command.id)); } - push_row(&mut rows, &mut seen, def); + push_row(&mut rows, &mut index, def); } // Live menu items whose command has no row yet carry the catalogue's key. for &(_, label, shortcut, id) in crate::menu_catalog::CATALOG { // A Window panel item runs its shell command (`menus::panel_alias`), which has the row. - let owner = crate::menus::panel_alias(id).filter(|alias| seen.contains(*alias)).unwrap_or(id); + let owner = crate::menus::panel_alias(id).filter(|alias| index.contains_key(*alias)).unwrap_or(id); if label == "---" || !crate::menus::is_live(id) { continue; } - if seen.contains(owner) { + if let Some(&at) = index.get(owner) { // An engine row that names no key takes the catalogue's. if let Some(key) = shortcut.and_then(binding) - && let Some(row) = rows.iter_mut().find(|row| row.command.id == owner && row.defaults.is_empty()) + && rows[at].defaults.is_empty() { - row.defaults.push(key); + rows[at].defaults.push(key); } continue; } let mut def = app_row(id, label.trim_end_matches('…')); def.paths.extend(menu_path(id)); def.defaults.extend(shortcut.and_then(binding)); - push_row(&mut rows, &mut seen, def); + push_row(&mut rows, &mut index, def); } // Recorded actions run on their own key (the user's assignment is an override). for action in app.session.actions.list.actions() { let id = crate::actions::shortcut_id(&action.name); - push_row(&mut rows, &mut seen, app_row(&id, &action.name).with_path(vec!["Actions".into(), action.name.clone()])); + push_row(&mut rows, &mut index, app_row(&id, &action.name).with_path(vec!["Actions".into(), action.name.clone()])); } // A command's alternate keys (#3665: F3 is Copy as well as ⌘C), after every main key. for &(id, key) in photocraft_engine::prefs::ALTERNATE_SHORTCUTS { let Some(alternate) = binding(key) else { continue }; - if let Some(def) = rows.iter_mut().find(|d| d.command.id == id) - && !def.defaults.contains(&alternate) + if let Some(&at) = index.get(id) + && !rows[at].defaults.contains(&alternate) { - def.defaults.push(alternate); + rows[at].defaults.push(alternate); } } // Photoshop: ⌥ added to an adjustment's own key opens it at its last settings (⌥⌘L, ⌥⌘M, #8900); Layer › New › Layer's @@ -314,12 +328,12 @@ pub(crate) fn command_rows(app: &PhotocraftApp) -> Vec { } } // Edit in Quick Mask Mode is a button in the tool rail's footer, which shows its command's icon. - if let Some(def) = rows.iter_mut().find(|d| d.command.id == crate::panels::QUICK_MASK) { - def.icon = Some("square-dashed".into()); + if let Some(&at) = index.get(crate::panels::QUICK_MASK) { + rows[at].icon = Some("square-dashed".into()); } // Smart Objects › Reveal in Finder names this platform's file manager, in the list as in the menu. - if let Some(def) = rows.iter_mut().find(|d| d.command.id == "layer.smartObjects.revealInFinder") { - def.label = crate::menus::reveal_label().into(); + if let Some(&at) = index.get("layer.smartObjects.revealInFinder") { + rows[at].label = crate::menus::reveal_label().into(); } rows } @@ -350,25 +364,19 @@ pub(crate) fn bridged_rows() -> Vec { } /// The app's command catalog over `rows` ([`command_rows`]). The runtime rebuilds its keymap when `generation` -/// changes, so the holder takes a new one only when [`same_rows`] says the rows differ from the held ones. It -/// compares where the menu model rebuilds, which covers a new action and a tool list change. -// PLAN: hub-w1's `framework_before_input` holds the rows and the generation, and calls this in place of `catalog(app)`. +/// changes, so the holder (`framework_before_input`) takes a new one only when it rebuilds the rows: when the actions +/// list's revision moved. pub(crate) fn catalog(rows: Vec, generation: u64) -> Option { // `command_rows` gives each id once and every row the app scope, the two things `new` refuses; a refusal leaves the // runtime with no app catalog. AppCatalog::new(rows, generation).ok() } -/// Whether two row lists describe the same commands, labels, paths and keys. -pub(crate) fn same_rows(a: &[CommandDef], b: &[CommandDef]) -> bool { - a.len() == b.len() && a.iter().zip(b).all(|(x, y)| serde_json::to_value(x).ok() == serde_json::to_value(y).ok()) -} - /// The user's bindings for the runtime's keymap: Edit › Keyboard Shortcuts changes (`prefs.shortcuts`, /// `prefs.alternate_shortcuts`), the panel alias rule (#1272), and each row of [`RUNTIME_COMMANDS`] with its /// effective keys, so the framework command carries PhotoCraft's keys. The pane moves stay unbound -/// (`app::framework`: PhotoCraft binds F6 and Shift+F6). -pub(crate) fn overrides(app: &PhotocraftApp) -> Overrides { +/// (`app::framework`: PhotoCraft binds F6 and Shift+F6). `rows` are the app's catalog rows ([`command_rows`]). +pub(crate) fn overrides(app: &PhotocraftApp, rows: &[CommandDef]) -> Overrides { let prefs = app.session.prefs(); // PLAN: `keymap_defs::prefs_overrides` is top-w20's tp.PT25 row, assumed as `prefs_overrides(&Preferences) -> Overrides`. let mut overrides = photocraft_engine::keymap_defs::prefs_overrides(prefs); @@ -409,7 +417,7 @@ pub(crate) fn overrides(app: &PhotocraftApp) -> Overrides { // A key an action holds is the action's alone (it is checked before every command's key, as in Photoshop): the // command that has it by default keeps its other keys. if !taken.is_empty() { - for row in command_rows(app) { + for row in rows { let id = row.command.id.as_str(); if id.starts_with(crate::actions::SHORTCUT_PREFIX) || is_bridged(id) { continue; diff --git a/crates/ui-egui/src/input/shortcut_dispatch/tests.rs b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs index 472b385157..77163189e0 100644 --- a/crates/ui-egui/src/input/shortcut_dispatch/tests.rs +++ b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs @@ -1,6 +1,9 @@ //! #127: every shortcut the UI displays (menu items, shell commands, tool tooltips) dispatches its -//! command, or the item is visibly disabled with a reason — through the whole app, with a -//! realistic layered document, from the places focus usually is. +//! command, or the item is visibly disabled with a reason, in the whole app with a realistic layered +//! document. Every shortcut's command is fired into the dispatcher directly; one shortcut of each kind +//! of key and route is pressed from the places focus usually is (#15678). + +use std::collections::HashSet; use craft::keymap::Chord; use craft::ui::runtime::focus; @@ -204,11 +207,146 @@ fn displayed(app: &PhotocraftApp) -> Vec<(String, String, bool)> { v } -/// Press every displayed shortcut from each place focus usually is: each dispatches its command, -/// or the menu shows it disabled and the press reports why. (Dry run: File › Exit, Open, Help +/// The way [`super::run_fired`] takes a fired command `id`: a row of [`super::RUNTIME_COMMANDS`] by its kind, a tool +/// letter, a Shift+letter group step, a recorded action, else an app command through [`super::dispatch_as`]. +fn route(id: &str) -> String { + if let Some((_, bridged)) = super::RUNTIME_COMMANDS.iter().find(|(row, _)| *row == id) { + let kind = format!("{bridged:?}"); + return kind.split('(').next().unwrap_or(&kind).to_string(); + } + if crate::tool_shortcuts::tool(id).is_some() { + "tool".into() + } else if super::next_in_group_letter(id).is_some() { + "group".into() + } else if id.starts_with(crate::actions::SHORTCUT_PREFIX) { + "action".into() + } else { + "app".into() + } +} + +/// What a press of `chord` shares with every other chord of its group: the keyboard path (the runtime's key stage, +/// a focused field's typing rule, a focused component's held keys) depends on the kind of key and the modifiers, +/// not on the command. Letters, digits and function keys are one kind each; every other key is its own kind. +fn key_kind(chord: &Chord) -> String { + let key = chord.key; + let kind = if key.is_letter() { + "letter".to_string() + } else if key.is_digit() { + "digit".to_string() + } else if key.is_function_key() { + "function".to_string() + } else { + format!("{key:?}") + }; + let m = chord.mods; + format!("{kind} cmd={} ctrl={} alt={} shift={}", m.cmd, m.ctrl, m.alt, m.shift) +} + +/// Every live displayed shortcut (id, text) and its chord. +fn live_chords(app: &PhotocraftApp) -> Vec<(String, String, Chord)> { + displayed(app) + .into_iter() + .filter(|(_, _, live)| *live) + .map(|(id, sc, _)| { + let chord = Chord::parse(&sc).unwrap_or_else(|_| panic!("{id}: unparsable {sc}")); + (id, sc, chord) + }) + .collect() +} + +/// One displayed shortcut per (route, kind of key, modifiers): the shortcuts whose press goes the same way. +fn representatives(app: &PhotocraftApp) -> Vec<(String, String, Chord)> { + let mut seen = HashSet::new(); + live_chords(app).into_iter().filter(|(id, _, chord)| seen.insert((route(id), key_kind(chord)))).collect() +} + +/// The command the runtime fires for `chord`, shown for menu row `id`: the row's own command when the keymap shows +/// the chord for it (no other command wins it where the binding applies), else the key's holder. +fn fired_by(ctx: &egui::Context, id: &str, chord: &Chord) -> Option { + let own = super::keymap_command(id); + if craft::ui::runtime::commands::chord(ctx, &own) == Some(*chord) { + return Some(own); + } + // `holder` answers with no panel active; it falls back to a panel's binding when no unscoped command holds the key. + craft::ui::runtime::commands::holder(ctx, chord) +} + +/// Every displayed shortcut runs its menu item's command, or the menu shows the item disabled and the shortcut +/// says why: the keymap's command for each chord is fired into [`super::run_fired`] as a key press, with no key +/// events and no frames between them. The keyboard's way to the keymap is the same for every chord of a kind, and +/// [`every_kind_of_shortcut_dispatches_from_where_focus_usually_is`] presses one of each. The view, screen-mode, +/// momentary, Swatches and Workspace rows run in the runtime, the canvas or the shell instead of `run_fired`; that +/// test presses one of each kind of key for them. Every tool letter picks a tool of that letter. +#[test] +fn every_displayed_shortcut_runs_its_menu_item() { + use craft::ui::runtime::commands::{FirePhase, FireSource, Fired}; + let mut h = harness(); + set_dry_run(&h.ctx, true); + put_focus(&mut h, Place::Canvas); + let ctx = h.ctx.clone(); + let items = crate::menus::menu_rows(h.state()); + let chords = live_chords(h.state()); + assert!(chords.len() > 100, "the menus show their shortcuts: {}", chords.len()); + let fire = |h: &mut Harness<'_, Box>, command| { + super::run_fired(h.state_mut(), &ctx, &[Fired::new(command, FireSource::Key, FirePhase::Press, 0.0)]); + take_log(&ctx) + }; + let mut failures = Vec::new(); + let mut fired = 0; + for (id, sc, chord) in &chords { + let Some(command) = fired_by(&ctx, id, chord) else { + failures.push(format!("{sc} ({id}) runs nothing")); + continue; + }; + match route(id).as_str() { + "View" | "Momentary" | "ScreenMode" | "Swatches" | "Workspace" => { + if command != super::keymap_command(id) { + failures.push(format!("{sc} ({id}) fires {command:?}")); + } + continue; + } + "tool" | "group" => { + let want = crate::tool_shortcuts::tool(id).map(Tool::key).or_else(|| super::next_in_group_letter(id)); + fire(&mut h, command); + if Some(h.state().ui.tool.key()) != want { + failures.push(format!("{sc} ({id}) left {:?}", h.state().ui.tool)); + } + continue; + } + _ => {} + } + let enabled = items.iter().find(|i| i.command.id == *id).map_or_else(|| crate::menus::is_enabled(h.state(), id), |i| i.enabled); + fired += 1; + match fire(&mut h, command).as_slice() { + [(bound, Outcome::Ran)] if same(id, bound) && enabled => {} + [(bound, Outcome::Disabled(why))] if same(id, bound) && !enabled && !why.is_empty() => {} + other => failures.push(format!("{sc} ({id}, menu enabled: {enabled}) -> {other:?}")), + } + } + assert!(fired > 80, "most displayed shortcuts go through run_fired: {fired}"); + for t in Tool::ALL.into_iter().filter(|t| t.key() != '\0') { + let chord = Chord::parse(&t.key().to_string()).unwrap_or_else(|_| panic!("tool key {}", t.key())); + let Some(command) = craft::ui::runtime::commands::holder(&ctx, &chord) else { + failures.push(format!("tool key {} runs nothing", t.key())); + continue; + }; + h.state_mut().ui.tool = if t.key() == 'H' { Tool::Move } else { Tool::Hand }; + fire(&mut h, command); + if h.state().ui.tool.key() != t.key() { + failures.push(format!("tool key {} left {:?}", t.key(), h.state().ui.tool)); + } + } + assert!(failures.is_empty(), "{} shortcut failures:\n{}", failures.len(), failures.join("\n")); +} + +/// Press one displayed shortcut of each (route, kind of key, modifiers) from each place focus usually is: each +/// dispatches its command, or the menu shows it disabled and the press reports why; a focused field keeps its typing +/// keys and a focused component the keys it holds. The other shortcuts of a group take the same path to a different +/// row of the table [`every_displayed_shortcut_runs_its_menu_item`] checks. (Dry run: File › Exit, Open, Help /// links… resolve and check enablement without running.) #[test] -fn every_displayed_shortcut_dispatches_from_where_focus_usually_is() { +fn every_kind_of_shortcut_dispatches_from_where_focus_usually_is() { let mut failures = Vec::new(); for place in [Place::Canvas, Place::LayersRow, Place::FocusedWidget, Place::OpacityField] { let mut h = harness(); @@ -216,11 +354,7 @@ fn every_displayed_shortcut_dispatches_from_where_focus_usually_is() { put_focus(&mut h, place); let typing = WindowHost::of(&h.ctx).typing(); let items = crate::menus::menu_rows(h.state()); - for (id, sc, live) in displayed(h.state()) { - if !live { - continue; - } - let chord = Chord::parse(&sc).unwrap_or_else(|_| panic!("{id}: unparsable {sc}")); + for (id, sc, chord) in representatives(h.state()) { // A press the focused component holds (the Layers rows' stacking and visibility keys) // is the component's and reaches no app command. let held = focus_holds(&h.ctx, chord); @@ -241,14 +375,19 @@ fn every_displayed_shortcut_dispatches_from_where_focus_usually_is() { other => failures.push(format!("{place:?}: {sc} ({id}, menu enabled: {enabled}) -> {other:?}")), } } - // Tool letters from the tools panel tooltips ("Brush Tool (B)"). - if !typing { - for t in Tool::ALL.into_iter().filter(|t| t.key() != '\0') { - h.state_mut().ui.tool = if t.key() == 'H' { Tool::Move } else { Tool::Hand }; - press_in_one_frame(&mut h, &t.key().to_string()); - if h.state().ui.tool.key() != t.key() { - failures.push(format!("{place:?}: tool key {} left {:?}", t.key(), h.state().ui.tool)); - } + // Tool letters from the tools panel tooltips ("Brush Tool (B)"): a letter of one tool and a letter its group + // shares take different picks (`pick_tool`); the table checks every letter's tool. In a focused text field the + // letter is typed and the tool stays. + let shared = |t: &Tool| Tool::ALL.iter().filter(|o| o.key() == t.key()).count() > 1; + let one = Tool::ALL.into_iter().find(|t| t.key() != '\0' && !shared(t)); + let many = Tool::ALL.into_iter().find(|t| t.key() != '\0' && shared(t)); + for t in one.into_iter().chain(many) { + let start = if t.key() == 'H' { Tool::Move } else { Tool::Hand }; + h.state_mut().ui.tool = start; + press_in_one_frame(&mut h, &t.key().to_string()); + let want = if typing { start } else { t }; + if h.state().ui.tool.key() != want.key() { + failures.push(format!("{place:?}: tool key {} left {:?}, expected a {} tool", t.key(), h.state().ui.tool, want.key())); } } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7d58e40208..6788eb6c7d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -804,6 +804,8 @@ mod navigator_gpu_tests; #[cfg(test)] mod color_swatch_tests; +#[cfg(test)] +mod dialog_title_ellipsis_tests; #[cfg(test)] mod profile_open_tests; @@ -994,6 +996,8 @@ mod polygon_lasso_tests; #[cfg(test)] mod window_frame_tests; +#[cfg(test)] +mod artboards_overlap_dialog_tests; #[cfg(test)] mod browse_field_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index c7e1cf2378..5f442d0bc5 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -523,9 +523,7 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: "select.findLayers" => crate::layer_filter_ui::find::invoke(app, params), // Photoshop's "Select and Mask…" is the engine's select.refineEdge. // Select › Color Range… from the menu: the dialog (with params: the engine directly). - "select.colorRange" if params.as_object().is_none_or(|o| o.is_empty()) => { - Ok(json!({"dialog": crate::color_range_ui::open(app).map(|dialog| dialog.value().to_string())})) - } + "select.colorRange" if params.as_object().is_none_or(|o| o.is_empty()) => crate::color_range_ui::open(app).map(dialog_reply), // Layer › New Fill Layer › Pattern… from the menu: the Pattern Fill dialog (with params: // the engine directly). photocraft_engine::pattern_fill_cmds::CREATE if params.as_object().is_none_or(|o| o.is_empty()) => { diff --git a/crates/ui-egui/src/menus/native_menu.rs b/crates/ui-egui/src/menus/native_menu.rs index 793776e391..42a60ed18d 100644 --- a/crates/ui-egui/src/menus/native_menu.rs +++ b/crates/ui-egui/src/menus/native_menu.rs @@ -76,7 +76,7 @@ pub fn sync(app: &mut PhotocraftApp, ctx: &egui::Context) { /// What the menus' rows depend on, cheaply: commands run, the documents (their names, in tab /// order, for the Window menu) and the active one's revision, selection, recent files, panels and -/// view state, the language. `input` forces a change on frames with a click or key press, which +/// view state, the keymap, and the preferences the rows show. `input` forces a change on frames with a click or key press, which /// covers state the hash doesn't list. pub(crate) fn state_hash(app: &PhotocraftApp, input: Option) -> u64 { let mut h = DefaultHasher::new(); @@ -119,7 +119,12 @@ pub(crate) fn state_hash(app: &PhotocraftApp, input: Option) -> u64 { crate::panel_docking::is_checked(app, panel.id).hash(&mut h); } serde_json::to_string(&(&ui.extras, &ui.view, ui.theme.id().as_str(), ui.theme.is_dark(), ui.tool)).unwrap_or_default().hash(&mut h); - s.prefs().interface.language.hash(&mut h); + // The preferences the rows show: the language, Edit › Menus (hidden rows, colours), the Quick Export label and + // the Font Preview Size tick. + let prefs = s.prefs(); + prefs.interface.language.hash(&mut h); + (&prefs.menus.hidden, &prefs.menus.colors, prefs.interface.show_menu_colors).hash(&mut h); + (prefs.export.quick_export_format, prefs.type_.font_preview).hash(&mut h); h.finish() } diff --git a/crates/ui-egui/src/menus/native_menu/tests.rs b/crates/ui-egui/src/menus/native_menu/tests.rs index 24defb62cc..81083493c4 100644 --- a/crates/ui-egui/src/menus/native_menu/tests.rs +++ b/crates/ui-egui/src/menus/native_menu/tests.rs @@ -237,3 +237,22 @@ fn the_task_bar_tick_follows_the_bar_hidden_without_a_menu_click() { h.run_steps(2); assert_eq!(ticked(&synced), Some(true), "ticked again once it shows"); } + +/// The menus follow the preferences they show, even when they change without input (settings merged from another +/// instance), and not the tool and colour preferences the app saves on every change. +#[test] +fn the_menu_state_follows_the_preferences_the_rows_show() { + let mut app = app(false); + let shown = state_hash(&app, None); + app.session.edit_prefs(|p| { + p.selected_tool = json!("Brush"); + p.tool_colors = Default::default(); + }); + assert_eq!(state_hash(&app, None), shown, "the saved tool and colours are not in the menus"); + + app.session.edit_prefs(|p| p.menus.hidden.push("filter.blur.gaussian".into())); + let hidden = state_hash(&app, None); + assert_ne!(hidden, shown, "Edit › Menus hides a row"); + app.session.edit_prefs(|p| p.export.quick_export_format = photocraft_engine::prefs::QuickExportFormat::Jpg); + assert_ne!(state_hash(&app, None), hidden, "the Quick Export label names the format"); +} diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index 9d3befb5a9..47080b68ad 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -262,6 +262,15 @@ pub(super) fn params_for(app: &mut PhotocraftApp, id: &str) -> Option<(Vec impl Fn(&ContentPainterCx, Rect) + /// The rows of every preset in the engine's panel order (the order `,` and `.` step through): a /// group row before the first preset of each group and each folder, with its count. pub(crate) fn preset_rows(app: &PhotocraftApp, env: &Env, parts: BrushCardParts) -> Vec> { - let presets = &app.session.tools.presets; + let presets = app.session.tools.presets.as_ref(); let mut counts: std::collections::HashMap<(&str, &[String]), usize> = std::collections::HashMap::new(); for p in presets { let path = path_of(p); @@ -204,7 +204,7 @@ pub(crate) fn apply_events(app: &mut PhotocraftApp, events: Vec, rows: &[BrushKey]) -> Option<(&'static str, Value)> { - let presets = &app.session.tools.presets; + let presets = app.session.tools.presets.as_ref(); match event { PresetEvent::Select { key: BrushKey::Preset(name), .. } => Some(("tools.setBrush", json!({ "preset": name }))), // The double click's first click already picked it. diff --git a/crates/ui-egui/src/panels/brush_panel/tests.rs b/crates/ui-egui/src/panels/brush_panel/tests.rs index 6d52d98708..57264f5603 100644 --- a/crates/ui-egui/src/panels/brush_panel/tests.rs +++ b/crates/ui-egui/src/panels/brush_panel/tests.rs @@ -487,14 +487,14 @@ fn preset_rows_nest_presets_in_panel_order() { let max = photocraft_engine::brush_preset_cmds::MAX_FOLDER_DEPTH; let deep: Vec<&str> = vec!["d"; max + 5]; let mut app = app(); - app.session.tools.presets = vec![ + app.session.tools.presets = std::sync::Arc::new(vec![ kit("Top", "Kit", &[]), kit("Pen", "Kit", &["Inks"]), kit("Chalk", "Kit", &["Dry"]), kit("Nib", "Kit", &["Inks", "Fine"]), kit("Quill", "Kit", &["Inks"]), kit("Deep", "Kit", &deep), - ]; + ]); let out: Vec = rows_of(app, PresetView::List) .iter() .map(|r| match r.count { @@ -509,7 +509,7 @@ fn preset_rows_nest_presets_in_panel_order() { fn fixture() -> Box { let mut app = app(); - app.session.tools.presets = vec![ + app.session.tools.presets = std::sync::Arc::new(vec![ kit("A1", "Alpha", &[]), kit("A2", "Alpha", &[]), kit("A3", "Alpha", &[]), @@ -518,7 +518,7 @@ fn fixture() -> Box { kit("Kit Pen", "Kit", &["Inks"]), kit("Kit Nib", "Kit", &["Inks", "Fine"]), kit("Kit Chalk", "Kit", &["Dry"]), - ]; + ]); app } diff --git a/crates/ui-egui/src/panels/layers_events.rs b/crates/ui-egui/src/panels/layers_events.rs index f975c679e4..bfcbdffb6d 100644 --- a/crates/ui-egui/src/panels/layers_events.rs +++ b/crates/ui-egui/src/panels/layers_events.rs @@ -594,13 +594,23 @@ pub(crate) fn selection_actions(change: SelectionChange, selected: &[La } } +/// The layer ids a `layer.select` payload names: the single `layer`, or every id of the `layers` +/// list a multi-row selection carries. +fn select_param_ids(p: &Value) -> Vec { + match p.get("layer").and_then(Value::as_u64) { + Some(id) => vec![id], + None => p.get("layers").and_then(Value::as_array).map(|ids| ids.iter().filter_map(Value::as_u64).collect()).unwrap_or_default(), + } +} + /// Runs the actions in order: a type session commits before a select, the mask targets switch, /// `Value::Null` params (and the fill layers that open a dialog) run as the menu item does. pub(crate) fn run_actions(app: &mut PhotocraftApp, ctx: &egui::Context, actions: Vec) { for (id, p) in actions { - // A row click commits even when it selects the layer already being edited (#5584). + // A row click commits even when it selects the layer already being edited (#5584); a + // multi-row selection that leaves the edited layer out is a layer switch (#6483). if id == "layer.select" && app.ui.text_edit.is_some() { - crate::type_tool::commit(app); + crate::type_tool::commit_before_selecting(app, &select_param_ids(&p)); } if id == "ui.maskTarget" { app.end_filter_mask_view(); diff --git a/crates/ui-egui/src/panels/options_bar.rs b/crates/ui-egui/src/panels/options_bar.rs index f3987dd75f..d6fd9ce55b 100644 --- a/crates/ui-egui/src/panels/options_bar.rs +++ b/crates/ui-egui/src/panels/options_bar.rs @@ -240,10 +240,16 @@ fn stamp_members(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) { edit_brush(app, &flow, |b, v| b.flow = v); return; } - if matches!(tool, Tool::CloneStamp | Tool::HistoryBrush | Tool::ArtHistoryBrush) { + if matches!(tool, Tool::CloneStamp | Tool::HistoryBrush) { let opacity = percent_field(ui, tl!("Opacity"), brush.opacity, 1.0..=100.0); edit_brush(app, &opacity, |b, v| b.opacity = v); } + // The Art History Brush's Opacity carries the reference's tooltip (#12630). + if tool == Tool::ArtHistoryBrush { + let opacity = number_field_with_tip(ui, tl!("Opacity"), brush.opacity * 100.0, 1.0..=100.0, "%", Some(tl!("Set opacity for stroke"))) + .map(|percent| percent / 100.0); + edit_brush(app, &opacity, |b, v| b.opacity = v); + } if matches!(tool, Tool::CloneStamp | Tool::HistoryBrush) { let flow = percent_field(ui, tl!("Flow"), brush.flow, 1.0..=100.0); edit_brush(app, &flow, |b, v| b.flow = v); @@ -276,9 +282,18 @@ pub(super) fn check(ui: &mut egui::Ui, label: &str, value: &mut bool) { /// A number field named `label` over `value` (in `unit` when it is not empty), limited to `range`. The events of this /// pass carry the edited value; an emptied field gives none. pub(super) fn number_field(ui: &mut egui::Ui, label: &str, value: f32, range: RangeInclusive, unit: &'static str) -> EditEvents { + number_field_with_tip(ui, label, value, range, unit, None) +} + +/// [`number_field`] with `tip` as the field's tooltip when there is one. +fn number_field_with_tip(ui: &mut egui::Ui, label: &str, value: f32, range: RangeInclusive, unit: &'static str, tip: Option<&str>) -> EditEvents { let events = labelled(ui, label, |ui| { let field = NumberField::new(label.to_owned(), Bind::given(Some(f64::from(value)))).range(range.clone()).scrub_by_label(); let field = if unit.is_empty() { field } else { field.unit(unit) }; + let field = match tip { + Some(tip) => field.tooltip(tip.to_owned()), + None => field, + }; field.show(ui).events.clone() }); events.unwrap_or_default().filter_map(|v| v.map(|v| v as f32)) diff --git a/crates/ui-egui/src/panels/panel_docking.rs b/crates/ui-egui/src/panels/panel_docking.rs index a0fc682f50..24e2cb331c 100644 --- a/crates/ui-egui/src/panels/panel_docking.rs +++ b/crates/ui-egui/src/panels/panel_docking.rs @@ -6,7 +6,6 @@ //! The lock is `app.workspaces.set.locked`. use craft::behavior::dock::{Action, DockEdge, DockPlacement, Layout, Node, PanelPlace, PanelState, Permissions, SplitSize, Target}; -use craft::behavior::overlay::Side; use craft::behavior::{DockSide, EditEvent, EditEvents, IconId}; use craft::ui::contract::{Bind, BodyCx, Lazy, SizeLimits}; use craft::ui::docking::{ @@ -56,16 +55,6 @@ pub(crate) fn is_front(app: &PhotocraftApp, id: &str) -> bool { layout.panel_state(&panel) == PanelState::Front || (layout.opens_in_flyout(&panel) && app.ui.flyout.as_ref() == Some(&panel)) } -/// The side of the Toolbar its flyouts and drawer open on: the side of the canvas. A toolbar in the end dock opens -/// towards the start, any other toward the end. -pub(crate) fn toolbar_opens(app: &PhotocraftApp) -> Side { - let layout = &app.ui.docking.layout; - match layout.place(&TOOLBAR.to_owned()) { - Some(PanelPlace::Dock { path, .. }) if layout.dock_path(DockEdge::End).is_some_and(|end| end == path) => Side::Start, - _ => Side::End, - } -} - /// Shows or hides panel `id` (an id or a label). `Some(true)` opens a hidden panel at its place, and brings a shown /// one to the front, expanding its minimized group; `Some(false)` closes it; `None` shows a panel that is hidden, /// minimized or behind another tab and closes one that is in front. A panel in a column collapsed to icons opens and diff --git a/crates/ui-egui/src/panels/region_versions.rs b/crates/ui-egui/src/panels/region_versions.rs index 7f789f3ff3..25d3c3daf0 100644 --- a/crates/ui-egui/src/panels/region_versions.rs +++ b/crates/ui-egui/src/panels/region_versions.rs @@ -40,8 +40,8 @@ pub(crate) fn panel(app: &PhotocraftApp, id: &str) -> u64 { } /// The version of the Toolbar's rail: the toolbar slots (the preferences revision), the remembered group tools, the -/// Edit Toolbar drawer, the side its flyouts open on, Quick Mask and the screen mode. The active tool and the colours -/// are in every version. +/// Edit Toolbar drawer, Quick Mask and the screen mode. Its flyouts always open on the same side. The active tool and +/// the colours are in every version. pub(crate) fn toolbar(app: &PhotocraftApp) -> u64 { toolbar_with(app, 0) } @@ -55,9 +55,8 @@ pub(crate) fn toolbar_drawn(app: &PhotocraftApp, ui: &egui::Ui) -> u64 { /// [`toolbar`] with the tokens it was drawn with named by `tokens`. fn toolbar_with(app: &PhotocraftApp, tokens: usize) -> u64 { let quick_mask = app.session.active().is_some_and(|st| st.doc.quick_mask.is_some()); - let opens_start = crate::panel_docking::toolbar_opens(app) == craft::behavior::overlay::Side::Start; let screen_mode = format!("{:?}", app.ui.view.screen_mode); - version(app, (app.session.prefs.rev(), &app.ui.group_tools, app.ui.toolbar_drawer, opens_start, quick_mask, screen_mode, tokens)) + version(app, (app.session.prefs.rev(), &app.ui.group_tools, app.ui.toolbar_drawer, quick_mask, screen_mode, tokens)) } /// What every region may show, joined with `extra`: the commands run (any of them may change anything), the active diff --git a/crates/ui-egui/src/panels/tool_commands.rs b/crates/ui-egui/src/panels/tool_commands.rs index a948757aae..2abdd835b2 100644 --- a/crates/ui-egui/src/panels/tool_commands.rs +++ b/crates/ui-egui/src/panels/tool_commands.rs @@ -338,14 +338,14 @@ pub(crate) fn slots(toolbar: &ToolbarCustomization) -> Vec> { slots } -/// The rail's [`slots`] for the stored layout, built once per preferences revision ([`PrefsStore::rev`]): the toolbar, its -/// measure and the dock's grid read them several times a frame, and the layout changes only with the preferences. +/// The rail's [`slots`] for the stored layout, built once per catalog revision ([`PrefsStore::catalog_rev`], which moves +/// with the toolbar layout): the toolbar, its measure and the dock's grid read them several times a frame. /// -/// [`PrefsStore::rev`]: photocraft_engine::prefs::PrefsStore::rev +/// [`PrefsStore::catalog_rev`]: photocraft_engine::prefs::PrefsStore::catalog_rev #[derive(Default)] pub(crate) struct ToolbarSlots(std::cell::RefCell>); -/// The rail's slots, shared by the readers of one preferences revision. +/// The rail's slots, shared by the readers of one catalog revision. type RailSlots = std::sync::Arc<[ToolSlot]>; impl ToolbarSlots { @@ -353,10 +353,10 @@ impl ToolbarSlots { pub(crate) fn get(&self, prefs: &photocraft_engine::prefs::PrefsStore) -> RailSlots { let mut held = self.0.borrow_mut(); match &*held { - Some((rev, slots)) if *rev == prefs.rev() => slots.clone(), + Some((rev, slots)) if *rev == prefs.catalog_rev() => slots.clone(), _ => { let built: RailSlots = slots(&prefs.get().toolbar).into(); - *held = Some((prefs.rev(), built.clone())); + *held = Some((prefs.catalog_rev(), built.clone())); built } } diff --git a/crates/ui-egui/src/panels/toolbar.rs b/crates/ui-egui/src/panels/toolbar.rs index 8853feedd1..f80b73bf9a 100644 --- a/crates/ui-egui/src/panels/toolbar.rs +++ b/crates/ui-egui/src/panels/toolbar.rs @@ -14,6 +14,9 @@ use photocraft_engine::prefs::ToolbarCustomization; use super::tool_commands; +#[cfg(test)] +#[path = "toolbar_docking_tests.rs"] +mod toolbar_docking_tests; #[cfg(test)] #[path = "toolbar_tab_reveal_tests.rs"] mod toolbar_tab_reveal_tests; @@ -158,7 +161,13 @@ fn quick_mask_button(app: &PhotocraftApp, ui: &mut egui::Ui) { let _ = FlyoutButton::new(&tools, &0).id_salt("quick-mask").selected(on).show(ui); } -/// The rail over `slots`, its flyouts and drawer opening on `opens`, the side of the canvas. +/// The side of the toolbar its tool flyouts, "…" flyout and Edit Toolbar drawer open on: the end (the right in a +/// left-to-right layout) wherever the toolbar is docked or floats, as in the reference application, which opens them +/// to the right even when the toolbar sits on the right between the dock's columns. The overlay flips them to the +/// other side only when they would leave the window. +const FLYOUTS_OPEN: Side = Side::End; + +/// The rail over `slots`, its flyouts and drawer opening on `opens`. fn rail<'a>(slots: &'a [ToolSlot], current: &'a Tool, remembered: &'a LastUsed, opens: Side, editing: bool) -> ToolRail<'a, Tool> { let rail = ToolRail::new(Label::Empty, slots, current, remembered).opens(opens).edit_toolbar(tl!("Edit Toolbar…").to_string()); // The drawer's open flag is the one source of "editing". @@ -218,7 +227,7 @@ pub(crate) fn measure(app: &mut PhotocraftApp, ui: &egui::Ui, width: f32) -> f32 static LAST: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; } let slots = app.toolbar_slots.get(&app.session.prefs); - let (opens, editing) = (crate::panel_docking::toolbar_opens(app), app.ui.toolbar_drawer); + let (opens, editing) = (FLYOUTS_OPEN, app.ui.toolbar_drawer); let env = craft::ui::runtime::env::Env::of(ui); let room = ui.available_size(); let key = MeasureKey { @@ -244,7 +253,7 @@ fn measure_now(app: &mut PhotocraftApp, ui: &egui::Ui, width: f32) -> f32 { let slots = app.toolbar_slots.get(&app.session.prefs); let remembered = last_used(&slots, &app.ui.group_tools); let current = app.ui.tool; - let (opens, editing) = (crate::panel_docking::toolbar_opens(app), app.ui.toolbar_drawer); + let (opens, editing) = (FLYOUTS_OPEN, app.ui.toolbar_drawer); rail(&slots, ¤t, &remembered, opens, editing).measure_rail(ui, width, |ui, at| footer(app, ui, at)).y } @@ -259,7 +268,7 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let slots = app.toolbar_slots.get(&app.session.prefs); let remembered = last_used(&slots, &app.ui.group_tools); let current = app.ui.tool; - let (opens, editing) = (crate::panel_docking::toolbar_opens(app), app.ui.toolbar_drawer); + let (opens, editing) = (FLYOUTS_OPEN, app.ui.toolbar_drawer); let out = rail(&slots, ¤t, &remembered, opens, editing).show_rail(ui, |ui, at| footer(app, ui, at)); if let Some(tool) = out.select { diff --git a/crates/ui-egui/src/panels/toolbar_docking_tests.rs b/crates/ui-egui/src/panels/toolbar_docking_tests.rs new file mode 100644 index 0000000000..0570b46ce5 --- /dev/null +++ b/crates/ui-egui/src/panels/toolbar_docking_tests.rs @@ -0,0 +1,89 @@ +//! The toolbar as a dock panel (#12517): its tool flyouts open to the right of the button wherever it is docked, and +//! flip to the left only where they would leave the window. + +use super::*; +use crate::panels::registry::TOOLBAR; +use craft::behavior::dock::{Action, DockPlacement, Target}; +use egui::{PointerButton, Pos2, Rect}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; + +const SIZE: egui::Vec2 = egui::vec2(1200.0, 800.0); + +/// The whole app in a 1200 x 800 window with a small document open. +fn harness() -> Harness<'static, Box> { + let mut h = Harness::builder().with_size(SIZE).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::AppTheme::pro()); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 64})).expect("new document"); + app + }); + h.run_steps(4); + h +} + +/// Moves the toolbar's column beside the column holding `anchor`, after it in the dock's column order or before it. +fn dock_toolbar_beside(h: &mut Harness<'static, Box>, anchor: &str, after: bool) { + let action = Action::move_column(TOOLBAR.to_owned(), Target::at(anchor.to_owned(), DockPlacement::column(after))); + crate::panel_docking::apply(h.state_mut(), vec![action]).expect("the toolbar docks beside the column"); + h.run_steps(6); +} + +/// The rect of the innermost node named `label`. +fn rect_of(h: &Harness<'static, Box>, label: &str) -> Option { + h.query_all_by_label(label).last().map(|node| node.rect()) +} + +/// Right-clicks the middle of `rect`, which opens a tool slot's flyout. +fn right_click(h: &mut Harness<'static, Box>, rect: Rect) { + let at: Pos2 = rect.center(); + h.event(egui::Event::PointerMoved(at)); + h.run_steps(1); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + } + h.run_steps(4); +} + +/// The Lasso slot's flyout rows, opened from the toolbar: the slot's button and the Polygonal Lasso row. +fn lasso_flyout(h: &mut Harness<'static, Box>) -> (Rect, Rect) { + let button = rect_of(h, "Lasso Tool").expect("the Lasso slot is drawn"); + right_click(h, button); + let row = rect_of(h, "Polygonal Lasso Tool").expect("the Lasso flyout is open"); + (button, row) +} + +/// Docked on the right between the dock's icon column and its panel column, the toolbar still opens its flyouts to the +/// right of the button, over the panels, as the reference application does (they used to open toward the canvas). +#[test] +fn flyouts_open_to_the_right_between_the_end_docks_columns() { + let mut h = harness(); + dock_toolbar_beside(&mut h, "color", true); + let toolbar = crate::panel_docking::probe::group_rect(&h, "toolbar"); + let panels = crate::panel_docking::probe::group_rect(&h, "color").expect("the Color group is drawn"); + let (button, row) = lasso_flyout(&mut h); + assert!(button.right() < panels.left(), "the toolbar sits left of the panel column: {button:?}, {panels:?}, {toolbar:?}"); + assert!(button.center().x > SIZE.x * 0.5, "the toolbar is on the right half of the window: {button:?}"); + assert!(row.left() >= button.right() - 0.5, "the flyout opens to the right of the button: row {row:?}, button {button:?}"); +} + +/// At the right window edge there is no room to the right, so the flyout flips to the left of the button. +#[test] +fn flyouts_flip_left_at_the_right_window_edge() { + let mut h = harness(); + dock_toolbar_beside(&mut h, "color", false); + let (button, row) = lasso_flyout(&mut h); + assert!(button.right() > SIZE.x - 80.0, "the toolbar is at the right window edge: {button:?}"); + assert!(row.right() <= button.left() + 0.5, "the flyout flips to the left of the button: row {row:?}, button {button:?}"); +} + +/// Docked at the left edge (the default), the flyout opens to the right. +#[test] +fn flyouts_open_to_the_right_at_the_left_edge() { + let mut h = harness(); + let (button, row) = lasso_flyout(&mut h); + assert!(button.left() < 80.0, "the toolbar is at the left window edge: {button:?}"); + assert!(row.left() >= button.right() - 0.5, "the flyout opens to the right of the button: row {row:?}, button {button:?}"); +} diff --git a/crates/ui-egui/src/prefs/kys_import.rs b/crates/ui-egui/src/prefs/kys_import.rs index 8d45d3a61f..bdec2dd9f0 100644 --- a/crates/ui-egui/src/prefs/kys_import.rs +++ b/crates/ui-egui/src/prefs/kys_import.rs @@ -14,7 +14,7 @@ use craft::keymap::import::kys; use craft::menu::shortcuts::{ImportOffer, OfferAnswer, OfferRecord}; use craft::ui::dialog::{DialogResult, StartupStage}; -use serde_json::{Value, json}; +use serde_json::Value; use crate::PhotocraftApp; use crate::prefs_ui::shortcuts::{draft_keymap, import_options, kys_text, profiles_of, queue_import, save_keys}; @@ -28,7 +28,7 @@ pub const IMPORTED_PREF: &str = "photoshopShortcuts"; pub fn open_bytes(app: &mut PhotocraftApp, name: &str, bytes: &[u8]) -> Result { let text = kys_text(name, bytes)?; queue_import(app, text); - Ok(json!({"dialog": "shortcuts"})) + Ok(crate::prefs_ui::shortcuts::control_reply()) } fn remember(app: &mut PhotocraftApp, record: &OfferRecord) { diff --git a/crates/ui-egui/src/prefs/prefs_ui/dialogs.rs b/crates/ui-egui/src/prefs/prefs_ui/dialogs.rs index 1fc4722e94..64a0727d53 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/dialogs.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/dialogs.rs @@ -41,17 +41,20 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &V } if let Some(section) = id.strip_prefix("edit.preferences.") { open_preferences(app, section); - return Some(Ok(json!({"dialog": "preferences"}))); + // The id `ui.inspect` lists the window under, as every hosted dialog replies (#15544); the status says why it + // did not open. + let opened = app.framework.dialogs.get::().map(|d| json!({"dialog": d.id().value().to_string()})); + return Some(opened.ok_or_else(|| app.ui.status.clone())); } let dialog = |d: Result| Some(d.map(|d| json!({"dialog": d.value().to_string()}))); match id { "edit.keyboardShortcuts" => { super::shortcuts::open(app, 0); - Some(Ok(json!({"dialog": "shortcuts"}))) + Some(Ok(super::shortcuts::control_reply())) } "edit.menus" => { super::shortcuts::open(app, 1); - Some(Ok(json!({"dialog": "shortcuts"}))) + Some(Ok(super::shortcuts::control_reply())) } "edit.toolbar" => { crate::panels::toolbar::open_drawer(app); diff --git a/crates/ui-egui/src/prefs/prefs_ui/shortcuts.rs b/crates/ui-egui/src/prefs/prefs_ui/shortcuts.rs index 282c69dba3..f8e519e735 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/shortcuts.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/shortcuts.rs @@ -4,7 +4,7 @@ //! The session holds everything the dialog edits: the draft keymap, the shortcut sets, the Menus //! draft and the text of a set waiting to be reviewed. Cancel drops it and the runtime never saw //! a change; OK writes the preferences once ([`save_keys`], then the menus), and the runtime's -//! keymap follows the new preferences revision (`shortcut_dispatch::overrides`). +//! keymap follows the new shortcut preferences (`shortcut_dispatch::overrides`). //! //! The Toolbar tab is not here: Edit › Toolbar opens the toolbar drawer. @@ -79,7 +79,12 @@ pub(crate) fn profiles_of(prefs: &Preferences) -> Profiles { /// runtime's keymap is built for, and the preferences' bindings as overrides. pub(crate) fn draft_keymap(app: &PhotocraftApp) -> Keymap { let platform = windows::os_of(app.ctx()); - Keymap::new(crate::shortcut_dispatch::command_rows(app).into_iter().chain(crate::shortcut_dispatch::bridged_rows()).collect(), Scopes::new(), platform) + // The runtime catalog's held rows while they are current; built here before the first frame holds them. + let rows = match app.framework.catalog_rows_at(app.session.actions.list.revision()) { + Some(rows) => rows.to_vec(), + None => crate::shortcut_dispatch::command_rows(app), + }; + Keymap::new(rows.into_iter().chain(crate::shortcut_dispatch::bridged_rows()).collect(), Scopes::new(), platform) .with_reserved(reserved::system(platform)) .with_overrides(keymap_defs::prefs_overrides(app.session.prefs())) } @@ -117,6 +122,27 @@ pub fn shortcuts_open(app: &PhotocraftApp) -> bool { app.prefs_rt.shortcuts.is_some() } +/// The id the control channel knows the dialog by: Edit › Keyboard Shortcuts and Edit › Menus reply with it, +/// `ui.inspect` lists the dialog under it, and `ui.dialog.cancel` closes it. The dialog draws outside the framework's +/// dialog host, which has no id for it (#15544). +pub(crate) const CONTROL_ID: &str = "shortcuts"; + +/// The reply of a command that opened the dialog. +pub(crate) fn control_reply() -> Value { + json!({"dialog": CONTROL_ID}) +} + +/// The dialog as `ui.inspect` lists it among the dialogs while it is open, in the host's entry shape. +pub(crate) fn inspect(app: &PhotocraftApp) -> Option { + shortcuts_open(app).then(|| json!({"id": CONTROL_ID, "key": "edit.keyboardShortcuts", "parent": null, "fields": {}})) +} + +/// Cancel for a control client, as the dialog's Cancel: the session goes and nothing it edited is saved. False with +/// the dialog closed. +pub(crate) fn cancel(app: &mut PhotocraftApp) -> bool { + app.prefs_rt.shortcuts.take().is_some() +} + /// Whether the dialog is recording a chord: the key goes to the recorder and runs nothing, and the /// native menu bar pauses its key equivalents. pub fn recording(app: &PhotocraftApp) -> bool { @@ -213,7 +239,7 @@ fn ask_import(app: &mut PhotocraftApp, state: &mut DialogState) { let picked = app.pick_file_bytes_filtered(&["kys", "psp", "json"], |app, name, bytes| { let text = kys_text(&name, &bytes)?; queue_import(app, text); - Ok(json!({"dialog": "shortcuts"})) + Ok(control_reply()) }); if let Err(e) = picked { state.show_error(e); diff --git a/crates/ui-egui/src/preset_files_ui.rs b/crates/ui-egui/src/preset_files_ui.rs index 2b84f9de6d..4d7b9cae8b 100644 --- a/crates/ui-egui/src/preset_files_ui.rs +++ b/crates/ui-egui/src/preset_files_ui.rs @@ -211,7 +211,7 @@ mod tests { assert!(prompt(&app).is_none(), "a new group imports without asking"); assert!(app.ui.status.ends_with("brushes from Kit"), "{}", app.ui.status); // The user edits one of its brushes. - let edited = app.session.tools.presets.iter_mut().find(|p| p.group == "Kit").unwrap(); + let edited = std::sync::Arc::make_mut(&mut app.session.tools.presets).iter_mut().find(|p| p.group == "Kit").unwrap(); edited.brush.size = 77.0; let edited = edited.name.clone(); diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index 8080910375..9fd7991723 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -51,6 +51,9 @@ pub mod type_tool; pub(super) mod type_transform; pub mod vector_ui; +#[cfg(test)] +mod art_history_fields_tests; + #[cfg(test)] mod art_history_default_style_tests; #[cfg(test)] @@ -70,3 +73,6 @@ mod object_selection_mode_tests; mod path_selection_ctrl_direct_tests; #[cfg(test)] mod path_selection_shape_over_saved_path_tests; + +#[cfg(test)] +mod art_history_reset_tip_tests; diff --git a/crates/ui-egui/src/tools/art_history_fields_tests.rs b/crates/ui-egui/src/tools/art_history_fields_tests.rs new file mode 100644 index 0000000000..5047a0a7fb --- /dev/null +++ b/crates/ui-egui/src/tools/art_history_fields_tests.rs @@ -0,0 +1,125 @@ +//! #12630: the Art History Brush's Area takes whole pixels 0..500 and Tolerance whole percents +//! 0..100; a value typed past either range becomes the closest one with the reference's "Closest +//! value inserted" alert. Opacity, Area and Tolerance carry the reference's tooltips, and the bar +//! has no hint text. + +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use super::retouch_ui::bar::history::{ART_HISTORY_AREA_ALERT, ART_HISTORY_TOLERANCE_ALERT}; +use crate::PhotocraftApp; +use crate::state::Tool; + +type H = Harness<'static, Box>; + +/// The options bar with the Art History Brush active, and the dialog host its alerts open on. +fn bar() -> H { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 80})).unwrap(); + app.ui.tool = Tool::ArtHistoryBrush; + crate::theme::install_fonts(app.ctx()); + crate::theme::apply(app.ctx(), &crate::theme::AppTheme::pro()); + let mut h = Harness::builder().with_context(app.ctx().clone()).with_size(vec2(1800.0, 300.0)).with_step_dt(1.0 / 60.0).build_ui_state( + move |ui, app: &mut Box| { + crate::panels::options_bar(app, ui); + crate::dialogs::run(app, ui); + }, + app, + ); + h.run_steps(4); + h +} + +/// The number field named `label`, with or without its caption's colon. +fn field<'a>(h: &'a H, label: &str) -> Option> { + h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().is_some_and(|l| l.trim_end_matches(':') == label)) +} + +/// Types `text` into the field named `label` and commits it with Enter. +fn type_into(h: &mut H, label: &str, text: &str) { + field(h, label).unwrap_or_else(|| panic!("the {label} field")).click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Enter); + h.run_steps(3); +} + +/// The messages of the open framework alerts. +fn alerts(h: &H) -> Vec { + h.state().framework.dialogs.open_dialogs().iter().filter_map(|d| d.fields.as_ref()?.get("message")?.as_str().map(str::to_string)).collect() +} + +/// The description (tooltip) of the number field named `label`. +fn tip(h: &H, label: &str) -> Option { + field(h, label)?.accesskit_node().description().map(|d| d.to_string()) +} + +#[test] +fn area_past_0_500_takes_the_closest_value_and_alerts() { + for (typed, want) in [("600", 500.0), ("-5", 0.0)] { + let mut h = bar(); + type_into(&mut h, "Area", typed); + assert_eq!(h.state().ui.tool_options.art_history_area, want, "{typed}"); + assert_eq!(alerts(&h), vec![ART_HISTORY_AREA_ALERT.to_string()], "{typed}: one alert"); + } +} + +#[test] +fn area_in_range_is_a_whole_number_without_an_alert() { + for (typed, want) in [("500", 500.0), ("250", 250.0), ("0", 0.0), ("37.6", 38.0)] { + let mut h = bar(); + type_into(&mut h, "Area", typed); + assert_eq!(h.state().ui.tool_options.art_history_area, want, "{typed}"); + assert!(alerts(&h).is_empty(), "{typed} is in range: {:?}", alerts(&h)); + } +} + +#[test] +fn tolerance_past_0_100_takes_the_closest_value_and_alerts() { + for (typed, want) in [("150", 100.0), ("-3", 0.0)] { + let mut h = bar(); + type_into(&mut h, "Tolerance", typed); + assert_eq!(h.state().ui.tool_options.art_history_tolerance, want, "{typed}"); + assert_eq!(alerts(&h), vec![ART_HISTORY_TOLERANCE_ALERT.to_string()], "{typed}: one alert"); + } +} + +#[test] +fn tolerance_in_range_is_a_whole_number_without_an_alert() { + for (typed, want) in [("100", 100.0), ("12.4", 12.0)] { + let mut h = bar(); + type_into(&mut h, "Tolerance", typed); + assert_eq!(h.state().ui.tool_options.art_history_tolerance, want, "{typed}"); + assert!(alerts(&h).is_empty(), "{typed} is in range"); + } +} + +#[test] +fn opacity_area_and_tolerance_have_the_reference_tooltips() { + let h = bar(); + assert_eq!(tip(&h, "Opacity").as_deref(), Some("Set opacity for stroke")); + assert_eq!(tip(&h, "Area").as_deref(), Some("Painting area diameter")); + assert_eq!(tip(&h, "Tolerance").as_deref(), Some("Painting tolerance")); +} + +#[test] +fn the_bar_has_no_hint_text() { + let h = bar(); + assert!(h.query_by_label("Stylized dabs from a history state").is_none()); +} + +#[test] +fn the_command_takes_an_area_up_to_500() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 80})).unwrap(); + let stroke = |area: f64| json!({"points": [[10, 40], [70, 40]], "size": 8, "area": area}); + assert!(app.run("paint.artHistoryBrush", stroke(500.0)).is_ok()); + assert!(app.run("paint.artHistoryBrush", stroke(250.0)).is_ok()); + assert!(app.run("paint.artHistoryBrush", stroke(500.5)).is_err()); + assert!(app.run("paint.artHistoryBrush", stroke(-1.0)).is_err()); +} diff --git a/crates/ui-egui/src/tools/art_history_refusal_alert_tests.rs b/crates/ui-egui/src/tools/art_history_refusal_alert_tests.rs new file mode 100644 index 0000000000..b292173892 --- /dev/null +++ b/crates/ui-egui/src/tools/art_history_refusal_alert_tests.rs @@ -0,0 +1,87 @@ +//! #12638: when the Art History Brush can't paint, a stroke opens the reference application's +//! alert with OK and paints nothing: at the press for a hidden target layer, Lock All, Lock Image +//! Pixels or a group's pixels; at the release for the source refusals (another canvas size, no +//! source, a target layer the source state lacks). The History Brush keeps today's status bar. + +use serde_json::json; + +use super::brush_refusal_alert_tests::{active, alerts, app, refused, steps, stroke}; +use super::*; + +/// The fixture's history: 0 Open, 1 New Layer, 2 Fill; the source is the Open state, which holds +/// only the Background, so a stroke paints from row 1, which holds the active layer. +fn art_history() -> Box { + let mut app = app(Tool::ArtHistoryBrush); + app.run("history.setSource", json!({"state": 1})).unwrap(); + app +} + +#[test] +fn a_hidden_target_layer() { + let mut app = art_history(); + let id = active(&app); + app.run("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + refused(&mut app, "Could not use the art history brush because the target layer is hidden."); + assert!(app.ui.status.is_empty() || !app.ui.status_error, "no status-bar error as well: {:?}", app.ui.status); +} + +#[test] +fn lock_all_and_lock_image_pixels() { + for lock in ["all", "pixels"] { + let mut app = art_history(); + app.run("layer.lockLayers", json!({ lock: true })).unwrap(); + refused(&mut app, "Could not use the art history brush because the layer is locked."); + } +} + +#[test] +fn a_group_is_active() { + let mut app = art_history(); + app.run("layer.new.group", json!({})).unwrap(); + refused(&mut app, "Could not use the art history brush because the pixels in a group cannot be edited without merging the group."); +} + +#[test] +fn the_canvas_size_changed() { + let mut app = art_history(); + app.run("image.canvasSize", json!({"width": 80, "height": 64, "anchor": "topLeft"})).unwrap(); + refused(&mut app, "Could not use the art history brush because the current canvas size does not match that of the history state."); + assert!(app.ui.status.is_empty() || !app.ui.status_error, "no status-bar error as well: {:?}", app.ui.status); +} + +#[test] +fn no_source_is_set() { + let mut app = app(Tool::ArtHistoryBrush); + let snap = app.run("history.newSnapshot", json!({})).unwrap()["snapshot"].clone(); + app.run("history.setSource", json!({"snapshot": snap})).unwrap(); + app.run("history.deleteSnapshot", json!({"snapshot": snap})).unwrap(); + refused(&mut app, "Could not use the art history brush because no history state has been designated as the source for painting."); +} + +#[test] +fn the_source_state_lacks_the_target_layer() { + let mut app = art_history(); + app.run("layer.new.layer", json!({})).unwrap(); + refused(&mut app, "Could not use the art history brush because the history state lacks a corresponding layer."); +} + +#[test] +fn a_stroke_from_a_valid_source_paints() { + let mut app = art_history(); + app.run("history.setSource", json!({"state": 2})).unwrap(); + app.run("edit.fill", json!({"color": "#1e1edc"})).unwrap(); + let before = steps(&app); + stroke(&mut app); + assert!(alerts(&app).is_empty(), "{:?}", alerts(&app)); + assert_eq!(steps(&app), before + 1); +} + +/// The History Brush keeps its status-bar texts. +#[test] +fn the_history_brush_keeps_the_status_bar() { + let mut app = app(Tool::HistoryBrush); + app.run("image.canvasSize", json!({"width": 80, "height": 64, "anchor": "topLeft"})).unwrap(); + stroke(&mut app); + assert!(alerts(&app).is_empty(), "{:?}", alerts(&app)); + assert!(!app.ui.status.contains("art history"), "{}", app.ui.status); +} diff --git a/crates/ui-egui/src/tools/art_history_reset_tip_tests.rs b/crates/ui-egui/src/tools/art_history_reset_tip_tests.rs new file mode 100644 index 0000000000..6f85b3d65f --- /dev/null +++ b/crates/ui-egui/src/tools/art_history_reset_tip_tests.rs @@ -0,0 +1,116 @@ +//! #12631: the Art History Brush starts, and comes back after Reset Tool, with the reference +//! application's tip: a 21 px soft round (hardness 0 %, angle 0°, roundness 100 %) at 25 % +//! spacing and full opacity, with no smoothing. Other tools' starting tips are checked by `reset_tip_tests`. + +use serde_json::json; + +use crate::PhotocraftApp; +use crate::control::{ControlRequest, handle}; +use crate::state::Tool; + +fn app() -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.sync_views(); + app +} + +/// Run a menu command as the control channel does, then the frame's sync. +fn invoke(app: &mut PhotocraftApp, id: &str, params: serde_json::Value) { + let ctx = app.ctx().clone(); + let (req, _rx) = ControlRequest::new("ui.menu.invoke", json!({"id": id, "params": params})); + handle(app, &ctx, &req); + app.sync_views(); +} + +/// Pick `tool`, and swap its brush in as a frame does. +fn pick(app: &mut PhotocraftApp, tool: Tool) { + app.ui.tool = tool; + crate::paint_mouse::sync_tool_brush(app); + app.sync_views(); +} + +/// Size, hardness, spacing, angle, roundness, opacity and smoothing of the live brush, as +/// `brush.get` reports the tip. +fn tip(app: &mut PhotocraftApp) -> [f64; 7] { + let b = app.run("brush.get", json!({})).unwrap(); + let [size, hardness, spacing, angle, roundness] = ["size", "hardness", "spacing", "angle", "roundness"].map(|k| b[k].as_f64().unwrap()); + let brush = &app.session.tools.brush; + let (opacity, smoothing) = (f64::from(brush.opacity), f64::from(brush.smoothing.amount)); + [size, hardness, spacing, angle, roundness, opacity, smoothing].map(|v| (v * 1e4).round() / 1e4) +} + +/// A tip that is no tool's starting tip, so a reset has something to undo. +fn scramble(app: &mut PhotocraftApp) { + let b = &mut app.session.tools.brush; + (b.size, b.hardness, b.spacing, b.angle, b.roundness, b.opacity, b.smoothing.amount) = (57.0, 0.4, 0.6, 30.0, 0.5, 0.3, 0.3); +} + +const ART_HISTORY_TIP: [f64; 7] = [21.0, 0.0, 0.25, 0.0, 1.0, 1.0, 0.0]; + +#[test] +fn reset_tool_gives_the_art_history_brush_a_21_px_soft_tip() { + let mut app = app(); + pick(&mut app, Tool::ArtHistoryBrush); + scramble(&mut app); + invoke(&mut app, "tool.reset", json!({})); + assert_eq!(tip(&mut app), ART_HISTORY_TIP); + // The options-bar brush chip reads the live brush's rounded size. + assert_eq!(app.session.tools.brush.size.round(), 21.0); +} + +#[test] +fn a_first_use_starts_with_the_tip() { + // No stored tool brushes, as on a fresh install: the Art History Brush's first pick, after + // another tool's tip. + let mut app = app(); + pick(&mut app, Tool::Brush); + scramble(&mut app); + pick(&mut app, Tool::ArtHistoryBrush); + assert_eq!(tip(&mut app), ART_HISTORY_TIP); + // Its own tip is then kept across tool switches. + app.session.tools.brush.size = 42.0; + pick(&mut app, Tool::Brush); + pick(&mut app, Tool::ArtHistoryBrush); + assert_eq!(tip(&mut app)[0], 42.0); +} + +#[test] +fn a_first_use_keeps_the_outgoing_pressure_toggles() { + // The pressure settings of the tip are not measured, so they stay what the first pick gave + // before: the outgoing brush's. + let mut app = app(); + pick(&mut app, Tool::Brush); + (app.session.tools.brush.pressure_size, app.session.tools.brush.pressure_opacity) = (true, true); + pick(&mut app, Tool::ArtHistoryBrush); + let b = &app.session.tools.brush; + assert_eq!((b.pressure_size, b.pressure_opacity), (true, true)); + assert_eq!(tip(&mut app), ART_HISTORY_TIP); +} + +#[test] +fn reset_all_tools_gives_it_the_tip_active_or_picked_later() { + let mut app = app(); + pick(&mut app, Tool::ArtHistoryBrush); + scramble(&mut app); + invoke(&mut app, "tool.resetAll", json!({"confirmed": true})); + assert_eq!(tip(&mut app), ART_HISTORY_TIP, "active"); + let mut app = self::app(); + pick(&mut app, Tool::ArtHistoryBrush); + scramble(&mut app); + pick(&mut app, Tool::Pencil); + invoke(&mut app, "tool.resetAll", json!({"confirmed": true})); + pick(&mut app, Tool::ArtHistoryBrush); + assert_eq!(tip(&mut app), ART_HISTORY_TIP, "picked after the reset"); +} + +/// The other tools' starting tips are checked by `reset_tip_tests`; the History Brush's first use +/// still takes the current tip, as before. +#[test] +fn the_history_brush_first_use_keeps_the_current_tip() { + let mut a = app(); + pick(&mut a, Tool::Pencil); + scramble(&mut a); + pick(&mut a, Tool::HistoryBrush); + assert_eq!(tip(&mut a)[0], 57.0, "History Brush, first use"); +} diff --git a/crates/ui-egui/src/tools/artboard_tool.rs b/crates/ui-egui/src/tools/artboard_tool.rs index aa1604f9b2..982ed64deb 100644 --- a/crates/ui-egui/src/tools/artboard_tool.rs +++ b/crates/ui-egui/src/tools/artboard_tool.rs @@ -287,6 +287,11 @@ pub(crate) fn command_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandSta vec![(ArtboardCommand::AddNew.into(), state)] } +/// What [`command_states`] reads: whether a document is open, and the placing mode. +pub(crate) fn command_states_key(app: &PhotocraftApp) -> crate::app::framework::StatesKey { + [u64::from(app.session.active().is_some()), u64::from(app.ui.artboard_tool.adding), 0, 0] +} + /// Runs a fired Artboard command: Add New Artboard flips the placing mode and adds no board. `ctx` is the shape every /// command source takes. pub(crate) fn run_fired(app: &mut PhotocraftApp, _ctx: &egui::Context, command: &CommandRef) -> bool { diff --git a/crates/ui-egui/src/tools/brush_refusal.rs b/crates/ui-egui/src/tools/brush_refusal.rs index 9521a03e2e..ed76093d49 100644 --- a/crates/ui-egui/src/tools/brush_refusal.rs +++ b/crates/ui-egui/src/tools/brush_refusal.rs @@ -38,14 +38,15 @@ fn mode_tool_name(tool: Tool) -> Option<&'static str> { } /// The tool's name in the alerts, for the tools whose wording was measured: the Brush, the -/// Sharpen tool (#12952), the Sponge (#13030), the Smudge tool (#12965) and the Classic gradient -/// (the live Gradient makes a fill layer and isn't measured, #12017). +/// Sharpen tool (#12952), the Sponge (#13030), the Smudge tool (#12965), the Art History Brush +/// (#12638) and the Classic gradient (the live Gradient makes a fill layer and isn't measured, #12017). pub fn tool_name(app: &PhotocraftApp, tool: Tool) -> Option<&'static str> { match tool { Tool::Brush => Some(tl!("brush tool")), Tool::Sharpen => Some(tl!("sharpen tool")), Tool::Sponge => Some(tl!("sponge tool")), Tool::Smudge => Some(tl!("smudge tool")), + Tool::ArtHistoryBrush => Some(tl!("art history brush")), Tool::Gradient if app.ui.tool_options.gradient_classic => Some(tl!("gradient tool")), _ => None, } @@ -99,10 +100,11 @@ fn layer_refusal(app: &PhotocraftApp, tool: Tool) -> Option<&'static str> { } } -/// Whether `locks` refuse `tool`: Lock All, and for the Sharpen, Sponge and Smudge tools Lock Image -/// Pixels as well (measured for them; the Brush keeps today's behaviour there). +/// Whether `locks` refuse `tool`: Lock All, and for the Sharpen, Sponge and Smudge tools and the +/// Art History Brush Lock Image Pixels as well (measured for them; the Brush keeps today's +/// behaviour there). fn locked(locks: photocraft_doc::Locks, tool: Tool) -> bool { - locks.all || (matches!(tool, Tool::Sharpen | Tool::Sponge | Tool::Smudge) && locks.pixels) + locks.all || (matches!(tool, Tool::Sharpen | Tool::Sponge | Tool::Smudge | Tool::ArtHistoryBrush) && locks.pixels) } #[cfg(test)] @@ -120,3 +122,7 @@ mod smudge_refusal_alert_tests; #[cfg(test)] #[path = "remove_hidden_layer_tests.rs"] mod remove_hidden_layer_tests; + +#[cfg(test)] +#[path = "art_history_refusal_alert_tests.rs"] +mod art_history_refusal_alert_tests; diff --git a/crates/ui-egui/src/tools/perspective_crop_ui.rs b/crates/ui-egui/src/tools/perspective_crop_ui.rs index 83a9784659..120add25a6 100644 --- a/crates/ui-egui/src/tools/perspective_crop_ui.rs +++ b/crates/ui-egui/src/tools/perspective_crop_ui.rs @@ -8,6 +8,9 @@ //! - ↵ (or ✓) applies: `image.perspectiveCrop` maps the quad onto an upright rectangle, the whole document in one //! undo step. Its size comes from the options bar's W × H and resolution (`CropSizeFields`), or with them empty //! from the rectangle the quad shows in perspective. Esc (or ⊘) cancels. +//! - a document holding a type layer or a smart object, and a Bitmap document, refuse the press with the reference's +//! alert (message + OK) and start nothing: no box, no corner, no session (#11799). `image.perspectiveCrop` answers +//! with the same text, so ↵ is refused the same way. //! //! The quad lives in the tool, not in the document: its edits are no history steps. A pending quad belongs to the //! document it was drawn on, like the Crop tool's frame. @@ -19,6 +22,7 @@ use craft::ui::bars::BarOutput; use craft::ui::canvas::{CropShield, ToolHostResponse}; use craft::ui::contract::Bind; use craft::ui::runtime::edit::cancel_all; +use photocraft_engine::perspective_crop_cmds::{BITMAP_MODE_ERROR, UNSUPPORTED_LAYERS_ERROR}; use serde_json::json; use crate::PhotocraftApp; @@ -65,6 +69,36 @@ fn input<'a>(app: &PhotocraftApp) -> PerspectiveInput<'a> { input } +/// The alert this document gets instead of a perspective crop (#11799): `Some(text)` means the tool +/// refuses the press. The check is the engine's, so the press and `image.perspectiveCrop` can never +/// disagree about what is cropped. +fn document_alert(app: &PhotocraftApp) -> Option<&'static str> { + app.session.active().and_then(|st| photocraft_engine::perspective_crop_cmds::refusal(&st.doc)) +} + +/// The alert as `image.perspectiveCrop`'s error text (#11799), so ↵ shows what the press shows +/// rather than only the status bar. +fn error_alert(error: &str) -> Option<&'static str> { + [UNSUPPORTED_LAYERS_ERROR, BITMAP_MODE_ERROR].into_iter().find(|text| *text == error) +} + +/// Opens the alert: the message and an OK button, as a refused Move does (`move_lock::prompt`). +fn refuse(app: &mut PhotocraftApp, message: &str) { + crate::dialogs::alerts::alert(app, alert_text(message)); +} + +/// The alert in the UI language. Literal keys, so `cargo xtask i18n-coverage` lists both alerts for +/// the translators; `alert_keys_match_the_engine_texts` keeps them equal to the engine's texts. +fn alert_text(message: &str) -> &str { + match message { + UNSUPPORTED_LAYERS_ERROR => tl!("Could not use the perspective crop tool because the image contains unsupported layers types."), + BITMAP_MODE_ERROR => { + tl!("Could not use the perspective crop tool because it does not work with Bitmap images (convert image to Grayscale mode to edit).") + } + other => tl!(other), + } +} + /// What the app does with a finished pass: a new quad's first press drops an active selection as its own "Deselect" /// step, as in Photoshop (#11975), so it is gone after the commit and after Esc too. The pass reports the session's /// first press as `Started`; refused (a job locks the document, the reason in the status bar), the press is cancelled @@ -80,6 +114,15 @@ pub(crate) fn drain(app: &mut PhotocraftApp, state: &mut PerspectiveCrop, _respo if !events.iter().any(|event| matches!(event, PerspectiveCropEvent::Started)) { return; } + // A document the tool can't crop (#11799): the press shows the reference's alert and starts + // nothing - cancelled and cleared like a refused Deselect, so no box, no clicked corner and no + // session are left. It runs no Deselect either: the press never gets that far. + if let Some(message) = document_alert(app) { + refuse(app, message); + cancel_all(app.ctx(), CancelReason::HostChanged); + state.tool.clear(); + return; + } let selected = app.session.active().is_some_and(|st| st.doc.selection.is_some()); if selected && app.run("select.deselect", json!({})).is_err() { cancel_all(app.ctx(), CancelReason::HostChanged); @@ -132,6 +175,11 @@ pub fn apply(app: &mut PhotocraftApp) { match app.run("image.perspectiveCrop", params) { Ok(_) => cancel(app), Err(err) => { + // A document the crop refuses (#11799) gets the alert the press gets, not just the status + // bar; the quad stays for fixing or cancelling after the document can be cropped. + if let Some(message) = error_alert(&err) { + refuse(app, message); + } app.ui.status = err.to_string(); app.ui.status_error = true; } @@ -185,7 +233,7 @@ mod tests { use craft::draw::ui::CropLength; use craft::ui::runtime::env::UnitKind; use egui::Modifiers; - use photocraft_doc::{Color, ColorMode, Document, SampleType, Size as DocSize}; + use photocraft_doc::{Color, ColorMode, Document, Layer, LayerContent, SampleType, ShapeLayer, Size as DocSize, SmartObject, SmartSource, TextLayer}; use super::*; use crate::canvas::testing::{ToolEvent, tool_event}; @@ -213,6 +261,131 @@ mod tests { (size.width, size.height) } + /// #11799: a document holding a type layer or a smart object (hidden or not), and a Bitmap + /// document, refuse the press with the reference's alert - the message and an OK button - and + /// start nothing: no quad, no clicked corner, no drag, and the document is untouched. + #[test] + fn a_press_on_a_refused_document_shows_the_alert_and_starts_nothing() { + /// The reference's two alerts, as measured. + const UNSUPPORTED: &str = "Could not use the perspective crop tool because the image contains unsupported layers types."; + const NOT_BITMAP: &str = + "Could not use the perspective crop tool because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + + /// A 200 x 150 RGB document with `extra` on the Background. + fn doc(mode: ColorMode, extra: Option) -> Document { + let mut d = Document::with_background("p", DocSize::new(200, 150), mode, SampleType::U8, Color::WHITE); + if let Some(l) = extra { + d.insert_above(None, l); + } + d + } + + fn text(visible: bool) -> Layer { + let mut l = Layer::new("Hello", LayerContent::Text(TextLayer { text: "Hello".into(), ..Default::default() })); + l.visible = visible; + l + } + + fn smart(visible: bool) -> Layer { + let mut l = Layer::new( + "Photo", + LayerContent::Smart(SmartObject::new(SmartSource::Linked { path: "photo.psd".into() }, photocraft_geom::Affine::IDENTITY, None)), + ); + l.visible = visible; + l + } + + let cases = [ + ("visible type layer", doc(ColorMode::Rgb, Some(text(true))), UNSUPPORTED), + ("hidden type layer", doc(ColorMode::Rgb, Some(text(false))), UNSUPPORTED), + ("visible smart object", doc(ColorMode::Rgb, Some(smart(true))), UNSUPPORTED), + ("hidden smart object", doc(ColorMode::Rgb, Some(smart(false))), UNSUPPORTED), + ("Bitmap", doc(ColorMode::Bitmap, None), NOT_BITMAP), + ]; + for (case, document, want) in cases { + let mut s = photocraft_engine::Session::new(); + s.add_document(document, None); + s.set_active(0); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + app.sync_views(); + app.ui.tool = Tool::PerspectiveCrop; + let st = app.session.active().unwrap(); + let (size, layer_kinds, steps) = (st.doc.size, kinds(&st.doc), st.history.past_len()); + // The first press-and-drag: one alert with the reference's text (message and an OK + // button), and nothing started: no box, no drag, no session. + drag(&mut app, [10.0, 10.0], [120.0, 90.0]); + assert_eq!(alert_message(&app).as_deref(), Some(want), "{case}: the alert, with its text"); + assert_eq!(quad(&app), None, "{case}: no quad"); + assert!(!pending(&app), "{case}: no session"); + // OK closes the alert: it answers with nothing but closing. + close_alerts(&mut app); + // A press after that is refused the same way: it places no corner. + drag(&mut app, [30.0, 30.0], [30.0, 30.0]); + assert_eq!(alert_message(&app).as_deref(), Some(want), "{case}: the click is refused too"); + assert_eq!(app.canvas_tools.perspective.tool.placing(), 0, "{case}: no clicked corner"); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.size, size, "{case}: canvas untouched"); + assert_eq!(kinds(&st.doc), layer_kinds, "{case}: layers untouched"); + assert_eq!(st.history.past_len(), steps, "{case}: no history step"); + } + } + + /// Every layer's kind, bottom to top. + fn kinds(doc: &Document) -> Vec<&'static str> { + doc.walk().iter().map(|(_, _, l)| l.content.kind_name()).collect() + } + + /// #11874: the literal translation keys are the engine's alert texts, so an English UI shows + /// exactly what `image.perspectiveCrop` answers and the catalogs translate the right string. + #[test] + fn alert_keys_match_the_engine_texts() { + crate::i18n::with_language(crate::i18n::Lang::EN, || { + for text in [UNSUPPORTED_LAYERS_ERROR, BITMAP_MODE_ERROR] { + assert_eq!(alert_text(text), text); + } + }); + } + + /// The message of the open alert, if any (the host keeps one alert at a time). + fn alert_message(app: &PhotocraftApp) -> Option { + use craft::ui::dialog::StackDialog; + app.framework + .dialogs + .get::() + .and_then(|alert| alert.json_fields()) + .and_then(|fields| fields.get("message").and_then(|m| m.as_str()).map(str::to_owned)) + } + + /// Closes every open dialog: OK closes the alert. + fn close_alerts(app: &mut PhotocraftApp) { + let ctx = app.ctx().clone(); + let ids: Vec<_> = app.framework.dialogs.stack().ids().collect(); + for id in ids { + app.framework.dialogs.cancel_by_id(&ctx, id); + } + } + + /// #11799: a document of only pixel, shape and fill layers takes the press as before, and a + /// commit on such a document keeps working (the refusal is about type and smart object layers + /// and the Bitmap mode alone). + #[test] + fn a_press_on_a_cropable_document_still_draws_the_quad() { + let mut d = Document::with_background("p", DocSize::new(200, 150), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let path = photocraft_vector::shapes::rect(20.0, 20.0, 40.0, 30.0); + d.insert_above(None, Layer::new("Rectangle 1", LayerContent::Shape(ShapeLayer { path, ..Default::default() }))); + let mut s = photocraft_engine::Session::new(); + s.add_document(d, None); + s.set_active(0); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + app.sync_views(); + app.ui.tool = Tool::PerspectiveCrop; + drag(&mut app, [20.0, 10.0], [120.0, 90.0]); + assert_eq!(quad(&app), Some([[20.0, 10.0], [120.0, 10.0], [120.0, 90.0], [20.0, 90.0]])); + assert_eq!(alert_message(&app), None, "no alert"); + apply(&mut app); + assert_eq!(size(&app), (100, 80), "the quad's mean side lengths"); + } + /// Apply sends `image.perspectiveCrop` with the quad drawn on the canvas and the size from the fields: typed /// lengths at the typed resolution, empty W and H the perspective size; one undo step, and the tool is cleared. #[test] diff --git a/crates/ui-egui/src/tools/retouch_ui.rs b/crates/ui-egui/src/tools/retouch_ui.rs index 04dc82f1a5..205024a818 100644 --- a/crates/ui-egui/src/tools/retouch_ui.rs +++ b/crates/ui-egui/src/tools/retouch_ui.rs @@ -276,6 +276,13 @@ pub(crate) fn finish_stroke_with(app: &mut PhotocraftApp, tool: Tool, points: &[ app.ui.pattern_stamp_phase = r.get("phase").and_then(|v| serde_json::from_value(v.clone()).ok()).filter(|_| o.pattern_stamp_aligned); } Ok(_) => {} + // The Art History Brush's source refusals are alerts with OK, as the press-time ones, and + // not in the status bar as well (#12638). + Err(e) if tool == Tool::ArtHistoryBrush && e.starts_with("Could not use the art history brush because") => { + app.ui.status.clear(); + app.ui.status_error = false; + let _ = crate::dialogs::alerts::alert(app, tl!(&e).to_owned()); + } Err(e) => { app.ui.status = e; app.ui.status_error = true; diff --git a/crates/ui-egui/src/tools/retouch_ui/bar/history.rs b/crates/ui-egui/src/tools/retouch_ui/bar/history.rs index ad92a10acc..45d908c1d5 100644 --- a/crates/ui-egui/src/tools/retouch_ui/bar/history.rs +++ b/crates/ui-egui/src/tools/retouch_ui/bar/history.rs @@ -50,7 +50,7 @@ pub(super) fn history_brush(ui: &mut egui::Ui, app: &mut PhotocraftApp) -> Optio None } -/// Art History Brush: Style, Area, Tolerance. +/// Art History Brush: Style, Area, Tolerance. Its alerts carry the reference's words, so it opens them itself. pub(super) fn art_history(ui: &mut egui::Ui, app: &mut PhotocraftApp) -> Option { let styles: Vec> = [ ("tightShort", tl!("Tight Short")), @@ -69,13 +69,30 @@ pub(super) fn art_history(ui: &mut egui::Ui, app: &mut PhotocraftApp) -> Option< Field::new(tl!("Style")).side(SideLabel::new().scrub(true)).sizing(Sizing::Content).show(ui, |ui, _| { Select::new(tl!("Style"), Bind::bound(&mut o.art_history_style), &styles).show(ui); }); - let area = number(tl!("Area"), &mut o.art_history_area, 0.0..=100.0).show(ui).out_of_range; - let tolerance = number(tl!("Tolerance"), &mut o.art_history_tolerance, 0.0..=100.0).show(ui).out_of_range; - Divider::vertical().show(ui); - hint(ui, tl!("Stylized dabs from a history state")); - area.or(tolerance) + // Area: whole pixels 0..500, no slider; Tolerance: whole percents 0..100 with a slider. A value + // typed past either range becomes the closest one with the reference's own alert (#12630). + let area = number(tl!("Area"), &mut o.art_history_area, 0.0..=500.0).whole().unit("px").tooltip(tl!("Painting area diameter")).show(ui).out_of_range; + let tolerance = number(tl!("Tolerance"), &mut o.art_history_tolerance, 0.0..=100.0) + .whole() + .unit("%") + .popup_slider() + .tooltip(tl!("Painting tolerance")) + .show(ui) + .out_of_range; + if area.is_some() { + let _ = crate::dialogs::alerts::alert(app, tl!(ART_HISTORY_AREA_ALERT)); + } else if tolerance.is_some() { + let _ = crate::dialogs::alerts::alert(app, tl!(ART_HISTORY_TOLERANCE_ALERT)); + } + None } +/// The reference's alert for an Art History Brush Area typed past 0..500 px (#12630). +pub(crate) const ART_HISTORY_AREA_ALERT: &str = "An integer between 0 pixel and 500 Pixels is required. Closest value inserted."; + +/// The reference's alert for an Art History Brush Tolerance typed past 0..100 (#12630). +pub(crate) const ART_HISTORY_TOLERANCE_ALERT: &str = "An integer between 0 and 100 is required. Closest value inserted."; + /// Pattern Stamp: Aligned, Impressionist, Pattern, Scale, Angle. pub(super) fn pattern_stamp(ui: &mut egui::Ui, app: &mut PhotocraftApp) -> Option { let patterns: Vec> = app.session.patterns.items.iter().map(|p| Entry::new(p.id.clone(), p.display_name().to_string())).collect(); diff --git a/crates/ui-egui/src/tools/slice_ui.rs b/crates/ui-egui/src/tools/slice_ui.rs index c09a67a0e3..dd2d513fcd 100644 --- a/crates/ui-egui/src/tools/slice_ui.rs +++ b/crates/ui-egui/src/tools/slice_ui.rs @@ -317,6 +317,14 @@ pub(crate) fn command_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandSta .collect() } +/// What [`command_states`] reads: the active document and its revision (the selected slice resolves from its +/// slices), the selected slice's number and the lock. +pub(crate) fn command_states_key(app: &PhotocraftApp) -> crate::app::framework::StatesKey { + let revision = app.session.active().map_or(u64::MAX, |st| st.revision); + let selected = app.ui.slices.selected.map_or(u64::MAX, |n| n as u64); + [app.session.active_generation(), revision, selected, u64::from(app.session.file_menu.slices_locked)] +} + /// Runs a fired slice command; whether it was one. pub(crate) fn run_fired(app: &mut PhotocraftApp, _ctx: &egui::Context, command: &CommandRef) -> bool { let Some(command) = SliceCommand::from_ref(command) else { return false }; diff --git a/crates/ui-egui/src/tools/transform_tool/draw.rs b/crates/ui-egui/src/tools/transform_tool/draw.rs index 0eab00e4f0..dc7d45275b 100644 --- a/crates/ui-egui/src/tools/transform_tool/draw.rs +++ b/crates/ui-egui/src/tools/transform_tool/draw.rs @@ -12,6 +12,7 @@ use craft::imaging::ui::transform_preview::{PreviewDisplay, PreviewMap, Transfor use craft::imaging::ui::warp::{CylinderValues, CylinderWarp, WarpEdit, WarpGrid, WarpMesh}; use craft::ui::canvas::RasterDisplay; use craft::ui::contract::{Bind, Show as _}; +use craft::ui::primitives::PaintSlot; use photocraft_doc::DocId; use photocraft_geom::warp::WarpStyle; @@ -38,11 +39,16 @@ struct Shown { cylinder: Option>, /// A warp control has the pointer button down on it. busy: bool, + /// The preview's shapes, for the canvas's picture slot after the document ([`SessionShown::picture`]). + picture: Vec, } /// Shows the open Free Transform in the canvas body at `rect`, and applies what its controls /// report: the preview (moving pixels, covering layers, path outline), then the box or warp -/// controls. The canvas calls it after the document display and before the tool overlays. +/// controls. The canvas calls it with its controls, before it prepares the document's picture, so +/// the preview's moving pixels come back in [`SessionShown::picture`] for the canvas to add to its +/// picture slot after the document: added here, the document (which hides the moving layer) would +/// paint over them (#15546). /// /// Every control reads the frame's input once for its own pass, so a second pass of a frame /// reports no edit again and this applies only what the pass it ran in reported. @@ -55,7 +61,7 @@ pub fn show_in_canvas(app: &mut PhotocraftApp, ui: &mut egui::Ui, rect: egui::Re let (Some(t), Some(pv)) = (&app.ui.transform, &app.transform_preview) else { return SessionShown::default() }; show_session(app, t, pv, ui, rect) }; - let Shown { edits, snapped, apply, discard, mesh, cylinder, busy } = shown; + let Shown { edits, snapped, apply, discard, mesh, cylinder, busy, picture } = shown; let mut need_warp = false; if let Some(t) = app.ui.transform.as_mut() { for edit in edits.iter().cloned() { @@ -85,13 +91,16 @@ pub fn show_in_canvas(app: &mut PhotocraftApp, ui: &mut egui::Ui, rect: egui::Re if let Some(t) = app.ui.transform.as_mut() { t.session.settle(now, busy); } - SessionShown { shown: true, snapped } + // A pass that ended the session (Cancel, or a commit that finished at once) hands back no picture: its moving + // pixels would paint over the restored document. A commit still running in the background keeps the preview, and + // with it the picture. + let picture = if app.transform_preview.is_some() { picture } else { Vec::new() }; + SessionShown { shown: true, snapped, picture } } /// The pass's shows, in paint order. fn show_session(app: &PhotocraftApp, t: &FreeTransform, pv: &OpenPreview, ui: &mut egui::Ui, rect: egui::Rect) -> Shown { - show_preview(app, t, pv, ui, rect); - let mut out = Shown::default(); + let mut out = Shown { picture: show_preview(app, t, pv, ui, rect), ..Shown::default() }; if pv.committing.is_some() { // The moving pixels stay without the box until the commit job lands. return out; @@ -125,14 +134,19 @@ pub struct SessionShown { pub shown: bool, /// The snap lines of the box's drag. pub snapped: Vec, + /// The preview's shapes (the moving pixels, then the layers above them), which the canvas adds to its picture + /// slot after the document's picture. + pub picture: Vec, } /// The moving pixels as the session maps them (warped, skewed or styled), then the layers above /// them, both in the canvas's picture, under the grid, guides and controls. Nothing is shown for the Frame tool's transform. -fn show_preview(app: &PhotocraftApp, t: &FreeTransform, pv: &OpenPreview, ui: &mut egui::Ui, rect: egui::Rect) { +fn show_preview(app: &PhotocraftApp, t: &FreeTransform, pv: &OpenPreview, ui: &mut egui::Ui, rect: egui::Rect) -> Vec { if crate::frame_tool::frame_transform(t) { - return; + return Vec::new(); } + // Painted in place after this mark, then taken out for the picture slot. + let mark = PaintSlot::reserve(ui.painter()); let display = preview_display(app, ui.ctx()); let boxed = t.session.phase() == TransformPhase::Box; // The layers that get the styled preview stay PhotoCraft's: a visible layer with a style. @@ -150,8 +164,7 @@ fn show_preview(app: &PhotocraftApp, t: &FreeTransform, pv: &OpenPreview, ui: &m .opacity(pv.opacity) .nearest(t.session.interpolation() == Interpolation::NearestNeighbor) .clip(canvas) - .dragging(t.session.dragging()) - .picture(); + .dragging(t.session.dragging()); if let Some(display) = display.as_ref() { preview = preview.display(display); } @@ -162,8 +175,9 @@ fn show_preview(app: &PhotocraftApp, t: &FreeTransform, pv: &OpenPreview, ui: &m if let Some(above) = &pv.above && let Some(frame) = above.frame() { - RasterDisplay::new("", above).mapped(frame, 1).picture().show_at(ui, rect); + RasterDisplay::new("", above).mapped(frame, 1).show_at(ui, rect); } + mark.take_after(ui.ctx()) } /// What the box draws for the styled layer at `zoom`, as the framework's styled preview builds it: the composite and its diff --git a/crates/ui-egui/src/tools/type_tool.rs b/crates/ui-egui/src/tools/type_tool.rs index 1e41deb6e7..4738f4a510 100644 --- a/crates/ui-egui/src/tools/type_tool.rs +++ b/crates/ui-egui/src/tools/type_tool.rs @@ -35,6 +35,7 @@ use defaults::apply; use defaults::{default_style_params, default_styles, shown_scale}; pub use defaults::{foreground_changed, open_color_picker}; pub(crate) use defaults::{formatting_params, target, target_text}; +pub(crate) use editing::commit_before_selecting; pub use editing::{cancel, commit, commit_with, edit_active, edit_at, end_if_left}; #[cfg(test)] pub(crate) use editing::{step_char_metric, toggle_char_style, toggle_hyphenate}; @@ -129,3 +130,6 @@ mod locked_layer_alert_tests; mod ime_tests; #[cfg(test)] mod mask_escape_tests; + +#[cfg(test)] +mod unchanged_edit_history_tests; diff --git a/crates/ui-egui/src/tools/type_tool/editing.rs b/crates/ui-egui/src/tools/type_tool/editing.rs index ca3edbdca8..936d9fc497 100644 --- a/crates/ui-egui/src/tools/type_tool/editing.rs +++ b/crates/ui-egui/src/tools/type_tool/editing.rs @@ -89,7 +89,9 @@ pub fn edit_at(app: &mut PhotocraftApp, ctx: &egui::Context, x: f64, y: f64) -> } /// Alt+←/→: kern the pair before the caret by `by` (1/1000 em). No pair (caret at a text or line -/// edge): nothing happens, like Photoshop. Not coalesced: one history step per press. +/// edge): nothing happens, like Photoshop. One history step per press: the press takes a fresh +/// key of its own ([`session_step_key`]) rather than no key, so it stays its own state and still +/// says which session opened it (#12050). pub(super) fn kern_pair(app: &mut PhotocraftApp, id: LayerId, caret: usize, by: f32) { let Some(text) = current_text(app, id) else { return }; let before = caret.checked_sub(1).and_then(|i| text.chars().nth(i)); @@ -98,7 +100,11 @@ pub(super) fn kern_pair(app: &mut PhotocraftApp, id: LayerId, caret: usize, by: return; } crate::type_transform::finish(app); - let _ = app.run("type.edit", json!({"layer": id.0, "kernPair": {"at": caret, "by": by}})); + let mut p = json!({"layer": id.0, "kernPair": {"at": caret, "by": by}}); + if let Some(session) = app.ui.text_edit.as_ref().map(|ed| ed.session.clone()) { + p["coalesce"] = json!(session_step_key(app, &session)); + } + let _ = app.run("type.edit", p); } /// Whether the toggle is on for a character style. @@ -162,6 +168,7 @@ fn set_style(app: &mut PhotocraftApp, ed: &TextEdit, range: (usize, usize), mut crate::type_transform::finish(app); p["layer"] = json!(ed.layer); p["range"] = json!([range.0, range.1]); + p["coalesce"] = json!(session_step_key(app, &ed.session)); if let Err(e) = app.run("type.setStyle", p) { app.ui.status = e; app.ui.status_error = true; @@ -224,24 +231,42 @@ pub fn commit(app: &mut PhotocraftApp) { /// result, since a Type Mask always replaces the selection (#12073); the parameter stays so its /// callers don't change. pub fn commit_with(app: &mut PhotocraftApp, _mods: egui::Modifiers) { + commit_ending(app, true); +} + +/// The commit a Layers panel row click makes before it selects `selected` (#5584): a click on +/// another layer's row is a layer switch (#6483), so an unchanged session records nothing (#12050); +/// a click on the edited layer's own row ends the edit like any other commit. A multi-row selection +/// names all its rows, so it is a switch too unless the edited layer is one of them. +pub(crate) fn commit_before_selecting(app: &mut PhotocraftApp, selected: &[u64]) { + let switches = app.ui.text_edit.as_ref().is_some_and(|ed| !selected.is_empty() && !selected.contains(&ed.layer)); + commit_ending(app, !switches); +} + +/// [`commit_with`]'s body. `by_user`: the user ended the edit (a commit gesture), rather than a +/// switch to another layer or document taking the work over, which records nothing for an +/// unchanged session (#12050). +fn commit_ending(app: &mut PhotocraftApp, by_user: bool) { app.ui.type_insertion_style = None; // A box drag in progress keeps the box it reached, as when every move was applied. crate::type_box_preview::flush(app); crate::type_font_preview::clear(app); let current = app.session.active_index(); let Some(home) = app.ui.text_edit.as_ref().map(|ed| edit_home(app, ed)) else { - return commit_here(app); + return commit_here(app, by_user); }; match home { Some(home) if Some(home) != current => { // An edit left in a background document commits there, in its own history (#6483). + // Another document is active, so a document switch ended the edit: an unchanged + // session records nothing there, even though its own document is active now. app.session.set_active(home); - commit_here(app); + commit_here(app, false); if let Some(i) = current { app.session.set_active(i); } } - Some(_) => commit_here(app), + Some(_) => commit_here(app, by_user), // Its document closed: there is nothing to commit into, and the layer id may name a // layer of another document. None => { @@ -261,7 +286,11 @@ pub(super) fn edit_home(app: &PhotocraftApp, ed: &TextEdit) -> Option { } /// [`commit_with`] in the active document, which is the edit's own. -fn commit_here(app: &mut PhotocraftApp) { +fn commit_here(app: &mut PhotocraftApp, by_user: bool) { + // Read before the tool and the layer move on below: #12050 measures the commits the user + // makes, and an unchanged edit that ends because a tool switch or another layer took the + // work over (#6483) keeps today's behaviour of recording nothing. + let ends_an_edit = by_user && user_ends_the_edit(app); if app.ui.tool.is_type() { crate::type_transform::finish(app); } @@ -321,9 +350,51 @@ fn commit_here(app: &mut PhotocraftApp) { } else if ed.created { let name = photocraft_engine::type_cmds::layer_name(&text); let _ = app.run("type.edit", json!({"layer": ed.layer, "name": name, "coalesce": ed.session})); + } else if ends_an_edit && worked_on_layer(app, &ed) && !session_recorded(app, &ed) { + // Ending an edit of an existing layer is a step of its own even when the session changed + // nothing (#12050), so the History list shows the edit the user just ended. The Cancel + // button ends through `cancel`, which never runs this. + let _ = app.run("type.edit", json!({"layer": ed.layer, "coalesce": ed.session})); } } +/// A coalesce key for one deliberate step inside a typing session: the ⇧⌘ style keys, the ⌥ +/// metric steps and Alt+←/→ kerning are one history step per press, so each press takes a fresh +/// key and no two presses share a state. The key still names the session, which is how +/// [`session_recorded`] knows the session already opened a state and must not add an empty one +/// when the edit ends (#12050). +fn session_step_key(app: &mut PhotocraftApp, session: &str) -> String { + format!("{session}-{}", app.ui.alloc_id()) +} + +/// Has this session opened a history state of its own? Its typing carries the session's key, and +/// its one-step-per-press keys ([`session_step_key`]) carry that key with a press number, so the +/// state they leave names the session that made it. Ending such a session adds nothing: the undo +/// step the user just made is already there, and an empty state behind it would be a History row +/// that undoes nothing. A state left by an *earlier* session carries that session's key, so a +/// later unchanged edit of the same layer still records its own (#12050). +fn session_recorded(app: &PhotocraftApp, ed: &TextEdit) -> bool { + let pressed = format!("{}-", ed.session); + app.session.active().is_some_and(|st| st.coalesce.as_deref().is_some_and(|k| k == ed.session || k.starts_with(pressed.as_str()))) +} + +/// Is a Type tool still the tool holding this session? The frame commits the edit when a tool +/// switch takes the work on (#6483), also between the Type tools and the Type Mask tools; that is +/// not an edit of the layer, so #12050's state is not opened for it. +fn user_ends_the_edit(app: &PhotocraftApp) -> bool { + app.ui.tool.is_type() && app.ui.text_edit.as_ref().is_some_and(|ed| ed.mask == app.ui.tool.is_type_mask()) +} + +/// Is the session's layer still the one worked on? Selecting another layer or document commits the +/// session (#6483); #12050 does not measure that, so it records nothing. A background document's +/// edit is checked in its own document, where [`commit_ending`] has just made it active, so a +/// document switch cannot be told from an in-place commit here: [`commit_ending`] already found the +/// switch and passes `by_user` false, which is what keeps the unchanged edit from recording there +/// (#12050 review c4502824764). +fn worked_on_layer(app: &PhotocraftApp, ed: &TextEdit) -> bool { + app.session.active().is_some_and(|st| st.active_layer == Some(LayerId(ed.layer))) +} + /// Commit the edit once its layer is no longer the one worked on (#6483): another layer became /// active (a Layers panel menu, the canvas layer picker, automation) or another document did (a /// tab, File ▸ New/Open). Photoshop commits then; left open, the session took single-key diff --git a/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs b/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs index dcc72c211d..8b47bc69d3 100644 --- a/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs @@ -115,7 +115,8 @@ fn undo_to(h: &mut H, steps: usize) { let _ = h.run_ok(); } -/// Picks `font` in the first family field: open it, type the name, Enter, as `accept` says. +/// Picks `font` in the first family field: open it, type the name, then accept it as `accept` says +/// (Enter, ArrowDown then Enter, a click on its row, or a hover). fn choose(h: &mut H, font: &str, accept: &str) { h.query_all_by_label("Font family").next().unwrap().click(); h.run(); @@ -123,6 +124,11 @@ fn choose(h: &mut H, font: &str, accept: &str) { h.run(); match accept { "enter" => h.key_press(Key::Enter), + "arrow-enter" => { + h.key_press(Key::ArrowDown); + h.run(); + h.key_press(Key::Enter); + } "click" => h.get_by_role_and_label(egui::accesskit::Role::TreeItem, font).click(), "hover" => h.get_by_role_and_label(egui::accesskit::Role::TreeItem, font).hover(), _ => panic!("unknown acceptance"), @@ -139,22 +145,40 @@ fn checkmark(h: &mut H) { #[test] fn caret_font_choices_style_only_subsequent_typing_including_ime() { // One app: each case's text layer goes with Undo before the next case makes its own. + // Every acceptance, as each reaches the caret's pending style by its own route through the + // family field (ArrowDown applies its row once per step). One original font, as it only decides + // which font is chosen, and the carets at both ends. let mut h = document(); let base = past_len(&h); - for original in 0..2 { + let original = 0; + for accept in ["enter", "click", "arrow-enter"] { for text in ["abcdef", "AéB👩‍💻", "ab\ncdé"] { - let n = text.chars().count(); - for caret in [0, n / 2, n] { + for caret in [0, text.chars().count()] { + let label = (accept, text, caret); undo_to(&mut h, base); let id = text_layer(&mut h, original, text); select(&mut h, [caret, caret]); h.run(); let before = saved(&h, id); let steps = h.state().session.active().unwrap().history.entries().len(); - let font = FONTS[1 - original]; - choose(&mut h, font, "enter"); - assert_eq!(saved(&h, id), before, "a font choice at a caret never restyles existing characters"); - assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps); + let requested = FONTS[1 - original]; + choose(&mut h, requested, accept); + // ArrowDown steps to the row below the typed match, which depends on the installed fonts + // ("JetBrains Mono NL" where it is installed), so the pending font is the row it accepted. + let font = h + .state() + .ui + .type_insertion_style + .as_ref() + .map(|s| s.style.font_family.clone()) + .unwrap_or_else(|| panic!("a pending font at the caret: {label:?}")); + let font = font.as_str(); + assert!(font.starts_with(requested) && font != FONTS[original], "the accepted row matches the typed name: {font} {label:?}"); + if accept != "arrow-enter" { + assert_eq!(font, requested, "{label:?}"); + } + assert_eq!(saved(&h, id), before, "a font choice at a caret never restyles existing characters: {label:?}"); + assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps, "{label:?}"); crate::type_font_preview::set(h.state_mut(), font.into()); assert!(crate::type_font_preview::display_doc(h.state_mut(), 0).is_none()); // Two preedit replacements and the final commit keep the pending font. @@ -169,11 +193,15 @@ fn caret_font_choices_style_only_subsequent_typing_including_ime() { h.run(); let mut expected = families(&before); expected.splice(caret..caret, std::iter::repeat_n(font.to_string(), 3)); - assert_eq!(families(&saved(&h, id)), expected); + assert_eq!(families(&saved(&h, id)), expected, "{label:?}"); + let mut expected_text: Vec = text.chars().collect(); + expected_text.splice(caret..caret, "éXZ".chars()); let typed = saved(&h, id); + assert_eq!(typed["text"], expected_text.into_iter().collect::(), "the IME and typed text land at the caret: {label:?}"); + assert!(h.state().ui.type_insertion_style.is_some(), "the pending font is still set before the commit: {label:?}"); checkmark(&mut h); - assert_eq!(saved(&h, id), typed); - assert!(h.state().ui.type_insertion_style.is_none()); + assert_eq!(saved(&h, id), typed, "{label:?}"); + assert!(h.state().ui.type_insertion_style.is_none(), "the commit clears the pending font: {label:?}"); } } } diff --git a/crates/ui-egui/src/tools/type_tool/unchanged_edit_history_tests.rs b/crates/ui-egui/src/tools/type_tool/unchanged_edit_history_tests.rs new file mode 100644 index 0000000000..fe61d5b98a --- /dev/null +++ b/crates/ui-egui/src/tools/type_tool/unchanged_edit_history_tests.rs @@ -0,0 +1,318 @@ +//! BUG-TYPE-TOOL-UNCHANGED-EDIT-NO-HISTORY-STATE (#12050): ending a text edit that changed +//! nothing still adds one `Edit Type` history state. +//! +//! Measured in the reference application: click into an existing text layer, change nothing and +//! end the edit with Escape (when it commits), Ctrl+Enter, the Commit button or a click on the +//! canvas outside the text: one **Edit Type Layer** state is added and the layer is unchanged. +//! The Cancel button discards the session and adds no state. An edit that did change something +//! still gives one state, not two. + +use craft::behavior::SelectionChange; +use craft::layers::ui::panel::{LayerSelect, LayersEvent}; +use photocraft_doc::{LayerContent, LayerId}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; + +/// A 400x200 document with one committed type layer: that layer active and the Type tool picked. +fn app() -> (Box, LayerId) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + app.sync_views(); + let id = LayerId(app.run("type.create", json!({"text": "Hello", "size": 24, "x": 40, "y": 100})).unwrap()["layer"].as_u64().unwrap()); + app.run("layer.select", json!({"layer": id.0})).unwrap(); + app.ui.tool = Tool::Type; + (app, id) +} + +fn history(app: &PhotocraftApp) -> Vec { + app.session.active().unwrap().history.entries() +} + +fn text_of(app: &PhotocraftApp, id: LayerId) -> String { + let LayerContent::Text(t) = &app.session.active().unwrap().doc.layer(id).unwrap().content else { + panic!("the layer is not a type layer"); + }; + t.text.clone() +} + +/// [`text_of`] in document `doc`, active or not. +fn text_of_in(app: &PhotocraftApp, doc: usize, id: LayerId) -> String { + let LayerContent::Text(t) = &app.session.documents()[doc].doc.layer(id).unwrap().content else { + panic!("the layer is not a type layer"); + }; + t.text.clone() +} + +fn first_size(app: &PhotocraftApp, id: LayerId) -> f32 { + let LayerContent::Text(t) = &app.session.active().unwrap().doc.layer(id).unwrap().content else { return 0.0 }; + t.char_runs().first().map(|r| r.style.size_pt).unwrap_or_default() +} + +/// Click into the existing layer: an edit session with nothing changed yet. +fn click_into(app: &mut PhotocraftApp, id: LayerId) { + let ctx = crate::canvas::testing::ctx(app); + crate::type_tool::edit_active(app, &ctx).unwrap(); + let ed = app.ui.text_edit.as_ref().expect("the edit session is open"); + assert_eq!(ed.layer, id.0, "the session edits the layer"); + assert!(!ed.created, "it is an existing layer"); +} + +/// The Layers panel selecting several rows at once (its Shift-click range): one pass of panel +/// events, which sends `layer.select` with a `layers` list rather than a single `layer`. +fn select_rows(app: &mut PhotocraftApp, ids: &[LayerId]) { + let ctx = app.ctx().clone(); + let event = LayersEvent::Select(LayerSelect::new(SelectionChange::Set(ids.to_vec()), None)); + crate::panels::layers_events::apply_layers_events(app, &ctx, vec![event]); +} + +/// What ending the session with `how` left behind: exactly one state, named like any other edit +/// of an existing type layer, on an unchanged layer. +fn ended(app: &PhotocraftApp, id: LayerId, before: &[String], how: &str) { + let after = history(app); + assert!(app.ui.text_edit.is_none(), "{how}: the session ended"); + assert_eq!(after.len(), before.len() + 1, "{how}: exactly one new history state, in {after:?}"); + assert_eq!(after.last().map(String::as_str), Some("Edit Type"), "{how}: the name other edits of an existing type layer carry"); + assert_eq!(text_of(app, id), "Hello", "{how}: the layer is unchanged"); +} + +/// Escape (with Preferences > Type > Use Escape to Commit on, the default), the Commit button and +/// Ctrl+Enter all end the session through `commit` / `commit_with`. +#[test] +fn an_unchanged_edit_records_one_edit_type_state_on_every_commit_path() { + // How each gesture ends the session: Escape runs the plain `commit`, the Commit button and + // Ctrl+Enter pass their held modifiers to `commit_with`. + for (how, mods) in [("Escape (Use Escape to Commit)", None), ("Commit button", Some(egui::Modifiers::NONE)), ("Ctrl+Enter", Some(egui::Modifiers::COMMAND))] + { + let (mut app, id) = app(); + click_into(&mut app, id); + let before = history(&app); + match mods { + None => crate::type_tool::commit(&mut app), + Some(m) => crate::type_tool::commit_with(&mut app, m), + } + ended(&app, id, &before, how); + } +} + +/// A click on the canvas outside the text commits the session, and records it too. +#[test] +fn a_click_outside_the_text_records_one_edit_type_state() { + let (mut app, id) = app(); + click_into(&mut app, id); + let before = history(&app); + // Far from the glyphs and from the box: the editor commits on this background press (#15449 + // pipeline: the canvas press ends the session, the tool only sees that it ended). + super::mask_replace_selection_tests::click(&mut app, 380.0, 20.0, egui::Modifiers::NONE); + ended(&app, id, &before, "click outside the text"); +} + +/// The Cancel button discards the session and adds no history state. +#[test] +fn cancel_still_adds_no_history_state() { + let (mut app, id) = app(); + click_into(&mut app, id); + let before = history(&app); + crate::type_tool::cancel(&mut app); + assert!(app.ui.text_edit.is_none()); + assert_eq!(history(&app), before, "Cancel adds nothing"); + assert_eq!(text_of(&app, id), "Hello"); +} + +/// An edit that did change something gives one state, not two: the commit joins the state the +/// session already opened instead of adding an empty one of its own. +#[test] +fn a_changed_edit_still_gives_one_state_not_two() { + let (mut app, id) = app(); + click_into(&mut app, id); + let before = history(&app); + super::host::type_text(&mut app, "x"); + assert_eq!(text_of(&app, id), "x", "the session changed the text"); + assert_eq!(history(&app).len(), before.len() + 1, "typing opened the session's state"); + crate::type_tool::commit(&mut app); + let after = history(&app); + assert_eq!(after.len(), before.len() + 1, "ending it adds no second state, in {after:?}"); + assert_eq!(after.last().map(String::as_str), Some("Edit Type")); +} + +/// Undo of the state an unchanged edit left behind takes the document back to where it was. +#[test] +fn undoing_the_state_of_an_unchanged_edit_leaves_the_document_as_it_was() { + let (mut app, id) = app(); + let (text, size) = (text_of(&app, id), first_size(&app, id)); + click_into(&mut app, id); + let before = history(&app); + crate::type_tool::commit(&mut app); + assert_eq!(history(&app).len(), before.len() + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(text_of(&app, id), text, "the text is what it was"); + assert_eq!(first_size(&app, id), size, "the style is what it was"); +} + +/// Alt+left/right makes Kerning its own step, deliberately not coalesced with the typing session. +/// Ending that session must leave the one `Kerning` state: an empty `Edit Type` state behind it +/// would be a History row that undoes nothing (#12050 review, c4502824768). +#[test] +fn a_kerned_session_ends_with_its_own_step_and_no_empty_one() { + let (mut app, id) = app(); + click_into(&mut app, id); + // A caret between two characters: what Alt+left/right needs. + if let Some(ed) = app.ui.text_edit.as_mut() { + (ed.caret, ed.anchor) = (2, 2); + } + let before = history(&app); + super::editing::kern_pair(&mut app, id, 2, 20.0); + let kerned = history(&app); + assert_eq!(kerned.len(), before.len() + 1, "the kerning is its own step, in {kerned:?}"); + assert_eq!(kerned.last().map(String::as_str), Some("Kerning")); + crate::type_tool::commit(&mut app); + assert_eq!(history(&app), kerned, "ending the session adds no state of its own"); +} + +/// The ⇧⌘ style keys are one step per press for the same reason; the commit must not add an empty +/// state after them either. +#[test] +fn a_styled_session_ends_with_its_own_step_and_no_empty_one() { + let (mut app, id) = app(); + click_into(&mut app, id); + let before = history(&app); + super::toggle_char_style(&mut app, super::CharToggle::FauxBold); + let styled = history(&app); + assert_eq!(styled.len(), before.len() + 1, "the style key is its own step, in {styled:?}"); + crate::type_tool::commit(&mut app); + assert_eq!(history(&app), styled, "ending the session adds no state of its own"); +} + +/// The "this session already stepped" marker must belong to the session: a *later* unchanged edit +/// of the same layer still records its own state, even when the state before it came from an +/// earlier session's un-coalesced step. +#[test] +fn an_unchanged_edit_still_records_after_an_earlier_session_stepped() { + let (mut app, id) = app(); + click_into(&mut app, id); + if let Some(ed) = app.ui.text_edit.as_mut() { + (ed.caret, ed.anchor) = (2, 2); + } + super::editing::kern_pair(&mut app, id, 2, 20.0); + crate::type_tool::commit(&mut app); + let before = history(&app); + click_into(&mut app, id); + crate::type_tool::commit(&mut app); + let after = history(&app); + assert_eq!(after.len(), before.len() + 1, "the second, unchanged session records, in {after:?}"); + assert_eq!(after.last().map(String::as_str), Some("Edit Type")); + assert_eq!(text_of(&app, id), "Hello"); +} + +/// Not measured in #12050, so it keeps today's behaviour: an unchanged session ended because +/// another layer took the focus records nothing. +#[test] +fn an_unchanged_edit_ended_by_another_layer_records_nothing() { + let (mut app, id) = app(); + // Made before the session opens, so its own history step is not counted. + let other = LayerId(app.run("layer.new.layer", json!({"name": "Pixels"})).unwrap()["layer"].as_u64().unwrap()); + app.run("layer.select", json!({"layer": id.0})).unwrap(); + click_into(&mut app, id); + let before = history(&app); + app.run("layer.select", json!({"layer": other.0})).unwrap(); + super::end_if_left(&mut app); + assert!(app.ui.text_edit.is_none(), "selecting another layer ends the session"); + assert_eq!(app.session.active().unwrap().active_layer, Some(other)); + assert_eq!(history(&app), before, "and adds no state to the edited layer's document"); + assert_eq!(text_of(&app, id), "Hello"); +} + +/// Also not measured, so unchanged: switching tools commits the session, and an unchanged one +/// still adds nothing. +#[test] +fn an_unchanged_edit_ended_by_another_tool_records_nothing() { + let (mut app, id) = app(); + click_into(&mut app, id); + let before = history(&app); + app.ui.tool = Tool::Move; + crate::type_tool::commit(&mut app); + assert!(app.ui.text_edit.is_none()); + assert_eq!(history(&app), before, "the tool switch is not an edit of the layer"); + assert_eq!(text_of(&app, id), "Hello"); +} + +/// A Layers panel click on another layer's row commits before it selects that layer (#5584), so +/// both of the tool's checks still see the edited layer: the panel says it is a layer switch, and +/// an unchanged session records nothing, as when the layer is selected first. +#[test] +fn an_unchanged_edit_ended_by_a_layers_panel_click_on_another_layer_records_nothing() { + let (mut app, id) = app(); + let other = LayerId(app.run("layer.new.layer", json!({"name": "Pixels"})).unwrap()["layer"].as_u64().unwrap()); + app.run("layer.select", json!({"layer": id.0})).unwrap(); + click_into(&mut app, id); + let before = history(&app); + // The panel's order: commit first, then select. + crate::type_tool::commit_before_selecting(&mut app, &[other.0]); + app.run("layer.select", json!({"layer": other.0})).unwrap(); + assert!(app.ui.text_edit.is_none(), "the row click ends the session"); + assert_eq!(history(&app), before, "a layer switch adds no state"); + assert_eq!(text_of(&app, id), "Hello"); +} + +/// A Layers panel click on the edited layer's own row ends the edit like a commit (#5584), so it +/// records the state. +#[test] +fn a_layers_panel_click_on_the_edited_layers_row_records_one_state() { + let (mut app, id) = app(); + click_into(&mut app, id); + let before = history(&app); + crate::type_tool::commit_before_selecting(&mut app, &[id.0]); + ended(&app, id, &before, "click on the edited layer's row"); +} + +/// A Shift-click range selects several rows at once, so the panel sends `layer.select` with a +/// `layers` list instead of a single `layer`. While layer A is being edited, a range of other +/// rows excludes A and leaves A inactive, so it is a layer switch (#6483) and an unchanged +/// session records nothing - as the single-row click on another layer's row does. +#[test] +fn an_unchanged_edit_ended_by_a_multi_layer_selection_that_excludes_the_edited_layer_records_nothing() { + let (mut app, id) = app(); + let b = LayerId(app.run("layer.new.layer", json!({"name": "B"})).unwrap()["layer"].as_u64().unwrap()); + let c = LayerId(app.run("layer.new.layer", json!({"name": "C"})).unwrap()["layer"].as_u64().unwrap()); + app.run("layer.select", json!({"layer": id.0})).unwrap(); + click_into(&mut app, id); + let before = history(&app); + select_rows(&mut app, &[b, c]); + assert!(app.ui.text_edit.is_none(), "the multi-layer selection ends the session"); + assert_eq!(app.session.active().unwrap().active_layer, Some(c), "and the last row of the range becomes active"); + assert_eq!(history(&app), before, "a selection that excludes the edited layer is a switch: no state"); + assert_eq!(text_of(&app, id), "Hello"); +} + +/// The neighbour of that case: a range that names the edited layer among its rows keeps the row +/// click a commit (#5584), so it records the state. Guard test, it pins the boundary. +#[test] +fn a_multi_layer_selection_that_includes_the_edited_layer_records_one_state() { + let (mut app, id) = app(); + let b = LayerId(app.run("layer.new.layer", json!({"name": "B"})).unwrap()["layer"].as_u64().unwrap()); + app.run("layer.select", json!({"layer": id.0})).unwrap(); + click_into(&mut app, id); + let before = history(&app); + select_rows(&mut app, &[b, id]); + assert_eq!(app.session.active().unwrap().active_layer, Some(id), "the edited layer stays active in the range"); + ended(&app, id, &before, "multi-layer selection that includes the edited layer"); +} + +/// Another document becoming active ends the edit in its own document (#6483), which is made +/// active again for the commit: that is a document switch, and an unchanged session records +/// nothing there. +#[test] +fn an_unchanged_edit_ended_by_another_document_records_nothing() { + let (mut app, id) = app(); + click_into(&mut app, id); + let home = app.session.active_index().unwrap(); + let before = history(&app); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + assert_ne!(app.session.active_index(), Some(home), "the new document is active"); + super::end_if_left(&mut app); + assert!(app.ui.text_edit.is_none(), "the document switch ends the session"); + assert_ne!(app.session.active_index(), Some(home), "the new document stays active"); + assert_eq!(app.session.documents()[home].history.entries(), before, "no state in the edited layer's document"); + assert_eq!(text_of_in(&app, home, id), "Hello"); +} diff --git a/crates/ui-egui/tests/it/free_transform_preview_canvas.rs b/crates/ui-egui/tests/it/free_transform_preview_canvas.rs new file mode 100644 index 0000000000..f5890874b7 --- /dev/null +++ b/crates/ui-egui/tests/it/free_transform_preview_canvas.rs @@ -0,0 +1,180 @@ +//! #15546: while Free Transform is open, the canvas shows the layer being transformed inside its box. +//! +//! The canvas hides that layer from the document's picture and draws it as the transform preview. The preview +//! joins the canvas's picture slot, and the document's picture is prepared after the canvas controls, so a preview +//! added with the controls lay under the document: only the layers below showed inside the box. These tests drive +//! the real app offscreen on wgpu, on the GPU canvas and on the CPU one, start Free Transform on a red layer over a +//! white background, and look at the rendered pixels inside the box, before and during a drag that moves it. +//! Skips when no GPU adapter exists (like `drag_preview_canvas.rs`). + +use craft::behavior::kurbo::Point; +use egui::{Modifiers, PointerButton, Pos2}; +use photocraft_geom::Rect; +use photocraft_ui_egui::PhotocraftApp; +use photocraft_ui_egui::control::{ControlRequest, handle}; +use serde_json::{Value, json}; + +type Harness = egui_kittest::Harness<'static, Box>; + +/// The red square on the layer, in document pixels: x 100..200, y 100..200 of a 400 × 300 document. +fn square() -> Rect { + Rect::new(100, 100, 200, 200) +} + +fn harness(gpu_canvas: bool) -> Option { + // Only a panic before the app callback runs (no adapter, no render state) is a skip; one from the app's own setup + // is a failure. + let entered = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let flag = entered.clone(); + let built = std::panic::catch_unwind(move || { + egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 640.0)).with_pixels_per_point(1.0).with_max_steps(64).wgpu().build_eframe(move |cc| { + flag.store(true, std::sync::atomic::Ordering::SeqCst); + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Default::default()); + if gpu_canvas && let Some(rs) = cc.wgpu_render_state.as_ref() { + app.set_wgpu(rs.clone()); + } + app + }) + }); + match built { + Ok(h) => Some(h), + Err(panic) if entered.load(std::sync::atomic::Ordering::SeqCst) => std::panic::resume_unwind(panic), + Err(_) => { + eprintln!("skipping: no GPU adapter"); + None + } + } +} + +fn control(h: &mut Harness, method: &str, params: Value) { + let ctx = h.ctx.clone(); + let (req, _rx) = ControlRequest::new(method, params); + handle(h.state_mut(), &ctx, &req); + h.run_steps(3); +} + +/// A white 400 × 300 document at 100 % with a layer holding the red square, active, and the Move tool. +fn setup(h: &mut Harness) { + { + let app = h.state_mut(); + app.run("file.new", json!({"width": 400, "height": 300, "background": "white"})).expect("new"); + app.run("layer.new.layer", json!({})).expect("new layer"); + app.session + .edit("paint", |doc, active| { + let id = active.expect("the new layer is active"); + let surface = doc.layer_mut(id).and_then(|l| l.surface_mut()).expect("a raster layer"); + surface.fill_rect(square(), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .expect("paint"); + app.sync_views(); + app.ui.extras.rulers = false; + } + control(h, "ui.set", json!({"tool": "move", "zoom": 1.0, "center": [200, 150]})); + h.run_steps(3); +} + +/// Screen point (egui points, one physical pixel each here) of document point `(x, y)`. +fn screen(h: &Harness, x: f64, y: f64) -> Pos2 { + photocraft_ui_egui::canvas::active_view(h.state()).expect("an active document view").to_screen(Point::new(x, y)) +} + +fn pointer_move(h: &mut Harness, at: Pos2) { + h.event(egui::Event::PointerMoved(at)); + h.step(); +} + +fn button(h: &mut Harness, at: Pos2, pressed: bool) { + h.event(egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.step(); +} + +/// The rendered frame's RGB at document point `(x, y)`. +fn rgb_at(h: &mut Harness, x: f64, y: f64) -> [u8; 3] { + let p = screen(h, x, y); + let img = h.render().expect("render"); + let px = img.get_pixel(p.x.floor() as u32, p.y.floor() as u32); + [px[0], px[1], px[2]] +} + +fn is_red(c: [u8; 3]) -> bool { + c[0] > 200 && c[1] < 60 && c[2] < 60 +} + +fn is_white(c: [u8; 3]) -> bool { + c.iter().all(|&v| v > 230) +} + +fn shows_the_layer_inside_the_box(gpu_canvas: bool) { + let _gpu = photocraft_testkit::gpu_lock(); + let Some(mut h) = harness(gpu_canvas) else { return }; + setup(&mut h); + assert!(is_red(rgb_at(&mut h, 150.5, 150.5)), "the layer shows before the transform"); + + control(&mut h, "ui.menu.invoke", json!({"id": "edit.freeTransform"})); + assert!(h.state().ui.transform.is_some(), "Free Transform is open"); + let inside = rgb_at(&mut h, 150.5, 150.5); + assert!(is_red(inside), "the layer shows inside the box once Free Transform opens, not the background: {inside:?}"); + + // Drag the box 60 px right from its middle and hold: the preview follows the pointer. The samples sit off the + // middle row, where the smart guide of the centred box is drawn. + let (from, to) = (screen(&h, 150.0, 150.0), screen(&h, 210.0, 150.0)); + pointer_move(&mut h, from); + button(&mut h, from, true); + for i in 1..=6 { + pointer_move(&mut h, from + (to - from) * (i as f32 / 6.0)); + } + let moved = rgb_at(&mut h, 230.5, 130.5); + assert!(is_red(moved), "the moved square shows where the drag took it: {moved:?}"); + let vacated = rgb_at(&mut h, 120.5, 130.5); + assert!(is_white(vacated), "the place the square left shows the background: {vacated:?}"); + button(&mut h, to, false); + let released = rgb_at(&mut h, 230.5, 130.5); + assert!(is_red(released), "the moved square still shows after the release: {released:?}"); +} + +#[test] +fn free_transform_shows_the_layer_inside_its_box_on_the_gpu_canvas() { + shows_the_layer_inside_the_box(true); +} + +#[test] +fn free_transform_shows_the_layer_inside_its_box_on_the_cpu_canvas() { + shows_the_layer_inside_the_box(false); +} + +/// Escape after a move puts the square back in the frame that cancels: the cancelled preview's moving pixels are not +/// painted over the restored document where the box had taken them. +fn cancelling_shows_no_moved_pixels(gpu_canvas: bool) { + let _gpu = photocraft_testkit::gpu_lock(); + let Some(mut h) = harness(gpu_canvas) else { return }; + setup(&mut h); + control(&mut h, "ui.menu.invoke", json!({"id": "edit.freeTransform"})); + let (from, to) = (screen(&h, 150.0, 150.0), screen(&h, 210.0, 150.0)); + pointer_move(&mut h, from); + button(&mut h, from, true); + for i in 1..=6 { + pointer_move(&mut h, from + (to - from) * (i as f32 / 6.0)); + } + button(&mut h, to, false); + assert!(is_red(rgb_at(&mut h, 230.5, 130.5)), "the box moved the square"); + + h.event(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); + h.step(); + assert!(h.state().ui.transform.is_none(), "Escape ended Free Transform"); + let moved = rgb_at(&mut h, 230.5, 130.5); + assert!(is_white(moved), "the cancelling frame shows no moved pixels: {moved:?}"); + let back = rgb_at(&mut h, 150.5, 130.5); + assert!(is_red(back), "the square is back in its place: {back:?}"); +} + +#[test] +fn cancelling_free_transform_shows_no_moved_pixels_on_the_gpu_canvas() { + cancelling_shows_no_moved_pixels(true); +} + +#[test] +fn cancelling_free_transform_shows_no_moved_pixels_on_the_cpu_canvas() { + cancelling_shows_no_moved_pixels(false); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 1755a9a086..10b331e735 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -14,6 +14,7 @@ mod crop_task_bar; mod display_names; mod eraser_reset_defaults; mod flatpak_updates; +mod free_transform_preview_canvas; mod gpu_device_loss; mod healing_reset_tip; // The interactive bench's `#[cfg(test)]` reporting tests: CI runs `--tests`, never examples. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 4aed18c1c4..22225621a7 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -126,13 +126,13 @@ The transport is the framework's control server (`craft::automation::server` in - Gradient Overlay color stops use `colorPicker {parent, effect, field: "stops", stop: index}`; the stop must exist. - `ui.dialog.open {kind:"colorPicker", textStyle:{kind:"character"|"paragraph", id:u32}}` opens the shared Color Picker for an explicitly enabled Color attribute in Style Options. It opens the matching style panel/editor after validation; inherited colors must first be enabled through the existing style command. The picker reports its bound document/revision/style under `__textStyleColor` in `ui.inspect`. Changes preview in an isolated document; OK runs the existing style `set` command once, Cancel changes nothing. Document edits/switches or closed/changed Style Options discard the picker. `textStyle` cannot be combined with `parent`, `effect`, `field` or `target`. - - Every dialog is hosted: `ui.inspect`'s `dialogs` lists them in stack order (top last) with a decimal-string `id`, and `ui.dialog.set`, `ui.dialog.confirm`, `ui.dialog.cancel` and `ui.dialog.apply` take that id as `dialog`, or `"top"` for the top one (the shell's workspace and pixel-aspect dialogs and the unsaved-changes prompt are listed like any other; the prompt's `ui.dialog.confirm` takes a `choice`). OK runs the dialog's command and keeps the dialog open if it fails. Camera Raw and the other full-window workspaces are hosted dialogs too: `{ui: …}` requests and `ui.dialog.set` field keys drive them (see Camera Raw below) + - Every dialog is hosted: `ui.inspect`'s `dialogs` lists them in stack order (top last) with a decimal-string `id`, and `ui.dialog.set`, `ui.dialog.confirm`, `ui.dialog.cancel` and `ui.dialog.apply` take that id as `dialog`, or `"top"` for the top one (the shell's workspace and pixel-aspect dialogs are listed like any other). A menu item that opens a dialog replies `{"dialog": ""}` with the id it is listed under. Two dialogs have a fixed id instead: the unsaved-changes prompt is `"discard"` (below), and Keyboard Shortcuts and Menus (Edit › Keyboard Shortcuts, Edit › Menus) is `"shortcuts"`, listed first while it is open (it draws beneath the other dialogs); `ui.dialog.cancel {"dialog": "shortcuts"}` closes it without saving, as its Cancel does, and its changes go through `edit.keyboardShortcuts` params rather than `ui.dialog.set` or `ui.dialog.confirm`, which refuse it; `"top"` never names it. OK runs the dialog's command and keeps the dialog open if it fails. Camera Raw and the other full-window workspaces are hosted dialogs too: `{ui: …}` requests and `ui.dialog.set` field keys drive them (see Camera Raw below) - The unsaved-changes prompt (closing a document, Revert, quitting with unsaved work) is listed in `ui.inspect`'s `dialogs` with the id `"discard"` while it is up: `fields` gives the waiting `command` (`file.close`, `file.exit`…), the `document` it asks about, how many are `remaining`, and its `choices`. `ui.dialog.confirm` takes `{"dialog": "discard", "choice": "save" | "saveAll" | "dontSave" | "dontSaveAll" | "cancel"}` (default `save`; Revert takes `dontSave` or `cancel`) and answers it as the window's buttons do, one document at a time. `saveAll` and `dontSaveAll` tick "Apply to All": they answer for every document still to ask about, and are listed in `choices` only while more than one is left. A document whose save is cancelled or fails is asked about again; `ui.dialog.cancel` with `{"dialog": "discard"}` cancels it. Save of an untitled document opens the save dialog first, so the reply's `fileDialog` is true and the prompt stays open until that is answered. - A save dialog's answer that PhotoCraft changes, by giving a name without an extension the suggested file's or by lowercasing the extension (Preferences › File Handling › Lowercase Extension), opens a replace prompt when a file exists under the changed name: a dialog with `__replaceSaved`, `message`, `detail` and `path` (the file the save would replace). `ui.dialog.confirm` writes the file; `ui.dialog.cancel` ends the save without writing, as Cancel in the save dialog does. The file dialog counts as open until the prompt is answered. A name that differs only in letter case and reaches the same file (Windows and macOS by default) does not open it. - Layer Style (`layerStyle {effect?}` opens on that effect kind): the fields hold the dialog's whole state, so agents read and drive it like a user. `effects` lists every effect instance in the layer's order as `{id, kind, on, params, fx}` (`fx` is the effect snapshot the dialog loaded; OK edits that snapshot with `params`, so anything the dialog doesn't model survives). `selected` picks the page (`blendingOptions` or an instance id), `preview` (default on) gates the live canvas preview, `p:blendingOptions` edits blend mode/opacity/fill opacity, and `patternList` names the usable patterns. OK replaces the layer's effects in one step (`layer.layerStyle.replace`); Cancel discards. "New Style…" saves the pending state via `style.presets.new {effects}`, a swatch click applies a style preset, and Make/Reset Default use `layer.layerStyle.makeDefault` / `layer.layerStyle.defaultFor` - Gradient Overlay exposes `params.method` (`smooth`, `perceptual`, `linear`, `classic`). `custom` denotes an existing curve without a recorded method and preserves it. Choosing a method retains all recorded source colour stops. If no source record exists (including baked PSD imports), choosing a method rebuilds from the two end colours, matching legacy command behaviour; the old curve stays unchanged until that choice. Later endpoint edits rebuild the colour curve using the recorded method. The source stops, smoothness and method survive dialog reopening, undo/redo and native `.pcraft` saves. Saving a style preset through "New Style…" may lose the multi-stop source curve: it passes only params to `style.presets.new`, and `effect_from_params` rebuilds the effect from the default gradient. PSD export continues to write the baked appearance; reopening that PSD shows Custom because editable interpolation metadata is not exported yet. Opacity interpolation and the multi-stop editor are separate work. - Gradient Overlay's `params.offset` is the gradient's centre as a fraction of the layer's bounds (`[x, y]`, `[0, 0]` centred, as the renderer takes it). With the dialog on a Gradient Overlay page, a drag on the image moves it by the pointer's movement over the layer's size, as a drag on a shadow page moves the shadow (#10763). - - Preferences (`ui.menu.invoke {id: "edit.preferences.interface"}`) exposes the sections in its `values` field. Apply (`ui.dialog.apply`) and OK (`ui.dialog.confirm`) on Preferences are refused over control because automation denies whole-preferences updates and filesystem-bearing preference sections. A refused `ui.dialog.apply` returns an error and keeps the dialog open; a refused `ui.dialog.confirm` returns an error but closes and removes the dialog. `ui.dialog.cancel` closes the dialog without saving. Individual safe preferences can instead be changed with `engine.execute` using `prefs.set` (e.g. `{"command": "prefs.set", "params": {"path": "interface.showTooltips", "value": false}}`). Settings marked for the next launch still require a restart. + - Preferences (`ui.menu.invoke {id: "edit.preferences.interface"}`, which replies with the id `ui.inspect` lists the window under, its `key` being `preferences`) exposes the sections in its `values` field. Apply (`ui.dialog.apply`) and OK (`ui.dialog.confirm`) on Preferences are refused over control because automation denies whole-preferences updates and filesystem-bearing preference sections. A refused `ui.dialog.apply` returns an error and keeps the dialog open; a refused `ui.dialog.confirm` returns an error but closes and removes the dialog. `ui.dialog.cancel` closes the dialog without saving. Individual safe preferences can instead be changed with `engine.execute` using `prefs.set` (e.g. `{"command": "prefs.set", "params": {"path": "interface.showTooltips", "value": false}}`). Settings marked for the next launch still require a restart. - Select › Select and Mask… (`ui.menu.invoke {id: "select.selectAndMask"}`, Ctrl+Alt+R) opens Photoshop's workspace; `ui.inspect` reports it as `distort.selectAndMask`. Drive it with `ui.menu.invoke {id: "select.selectAndMask", params: {ui: {…}}}`: `tool` (`quick|refineEdge|brush|object|lasso|polygonalLasso|hand|zoom`), `mode` (`add|subtract`), `size`, `hardness`, `sampleAllLayers`, `hideView` (true shows the image without the view, as holding X does), `stroke: {points: [[x,y],…], alt?}` (a drag with the current tool in document px: Object Selection takes a click or the rectangle's corners, the lassos the polygon), `selectSubject`, `clearSelection`, `invert`, the settings (`view`, `opacity`, `showEdge`, `showOriginal`, `realTimeRefinement`, `highQualityPreview`, `overlayColor`, `indicates`, `radius`, `smartRadius`, `smooth`, `feather`, `contrast`, `shiftEdge`, `decontaminate`, `amount`, `output`, `remember`), `undo`, `redo`, `reset`, `waitPreview`, `commit` (OK: `select.refineEdge` with the workspace's `edits` and `refineStrokes`, one history step) and `cancel`. The reply describes the workspace (`edits`, `strokes`, `selectedProxyPixels`, `previewReady`, …). - Edit › Fill… (`ui.menu.invoke {id: "edit.fill"}`, Shift+F5, Shift+Backspace) opens the Fill dialog; its fields are `edit.fill`'s params (`contents`, `color`, `pattern`, `colorAdaptation`, `mode`, `opacity`, `preserveTransparency`), and OK remembers them in the preferences (`dialogs["edit.fill"]`). - Image › Adjustments › Levels… (`ui.menu.invoke {id: "image.adjustments.levels"}`): `__clipping` (`"shadows"` or `"highlights"`; `null` turns it off) shows Photoshop's clipping display on the canvas instead of the preview, what the black or white Input slider clips. The app sets it while Alt and the mouse button are held on one of those sliders; it never reaches OK. The display shows only for RGB and Grayscale documents whose target is a raster layer's pixels, on the main canvas. Other targets (CMYK or Lab documents, a channel, mask or Quick Mask target, a non-pixel layer, a Smart Filter) accept the value and keep the normal preview. @@ -336,7 +336,7 @@ when it starts); see [Without `--control`](#without---control-preferences--integ | `prefs.set` | `{"path":"cursors.painting","value":"precise"}` or `{"values":{"unitsAndRulers.rulers":"cm","guidesGridAndSlices.gridColor":"#ff8800"}}`. Values are validated (choices, ranges, `#rrggbb` colours, shortcut syntax); a batch applies all or nothing. A section path takes an object and merges it key by key | | `prefs.reset` | `{"path":"performance"}` (a section or key); no path resets everything. An individual `shortcuts.` or `menus.colors.` reset removes the override and returns `null`, including when it is already absent | | `edit.preferences.
` | the section's values; in the app (no params) it opens the Preferences dialog on that section | -| `edit.keyboardShortcuts` | `{"set":{"edit.fill":"Cmd+Shift+F"},"reset":true\|["id",…],"removeConflicts":true,"filter":"blur","list":false,"importKys":"<.kys XML>"}`: returns overrides, matching commands and conflicts. A shortcut moved to another command is removed from its old owner unless `removeConflicts` is false. `""` removes a shortcut, `null` restores the default. The held temporary tools are bindable too: `tools.temporary.hand` (Space; also repositions a selection being drawn), `tools.temporary.zoomIn` (Cmd+Space), `tools.temporary.zoomOut` (Alt+Space; Alt added to a held Zoom In, Cmd+Alt+Space, zooms out too), `tools.temporary.erase` (`` ` ``; with the Brush or Pencil, a stroke started while it is held is in Clear mode, `paint.stroke`/`paint.pencil` `"mode": "clear"`, erasing with that tool's brush); they list with `"hold": true`. ⌘ (Ctrl off the Mac) held alone is the Move tool with the painting, retouching and other non-selection tools, as in Photoshop; it is a modifier, not a binding. `importKys` applies a Photoshop `.kys` set (the file's XML text, at most 4 MiB): rows are matched to commands by our id (`pc-id`, in sets PhotoCraft exported) or else by menu label, a key equal to the default restores it, keys also given in `set` win, and the result gains `import` (`name`, `imported`, `set`, `unknown`, `unreadable`, `alternates`, `toolKeys`, `windows`). A set saved by Photoshop on Windows (no ⌘ or Opt anywhere, Ctrl used) reads Ctrl as the primary modifier, so `Ctrl+L` is the `Cmd+L` default (`windows: true`). Tool keys are matched to tools by `pc-id` or name (a tool's own letter keeps its Shift cycling); `import.tools` lists the keys given. In the app it opens Keyboard Shortcuts and Menus, whose Import Shortcuts… button loads a `.kys` set into the dialog (opening or dropping a `.kys`, or Photoshop's live `Keyboard Shortcuts.psp`, does the same). On a desktop with Photoshop installed, the first launch that has no shortcut overrides yet asks whether to import the newest install's live set (Import / Don't Import; `ui.inspect` shows it as `kysOffer`); the answer is recorded in the preferences as `dialogs.photoshopShortcuts`, so it is asked once. **Sets** (Edit › Keyboard Shortcuts › Set): `useSet` loads a saved set's bindings (`""` or `"PhotoCraft Defaults"`: the defaults) before the call's other changes; then `saveSet` saves the bindings as they end up under a name and uses it, `deleteSet` removes one (the bindings stay), `sets` replaces every saved set (`{"": {"shortcuts": {…}, "alternateShortcuts": {…}}}`, the dialog's OK) and `activeSet` names the set in use without loading it. Names are trimmed, 1–64 characters, at most 64 sets. Every reply has `sets`, `activeSet` (`""` for the defaults), `defaultsName` and `modified` (the bindings differ from the set in use). `exportKys: true` adds `kys`, the bindings of every bindable command and tool as a `.kys` file (Photoshop's macOS key spelling; each row carries our id as `pc-id`, so the file imports back exactly); `summarize: true` (or `{"mac": false}`) adds `html`, Photoshop's Summarize page. A bad parameter anywhere in the call, an export path that can't be written included, changes nothing. **Headless parity:** the shell's commands (View › Zoom In, the panels; `photocraft_engine::shell_commands::SHELL_COMMANDS`) and the tools (`tools.select.`, listed with `"tool": true`) are bindable, listed, imported, exported and checked for conflicts without the UI; tools may share a key (they cycle with Shift, so a shared letter is no conflict), while a command given a tool's key takes it from the tools. Keys the system takes first (Alt+Tab, Alt+F4, Ctrl+Alt+Delete everywhere but the Mac, plus Ctrl+Esc and Ctrl+Shift+Esc on Windows and Ctrl+Alt+F1–F12 on Linux; ⌘Tab, ⌘`, ⌘⌥Esc on the Mac) are refused, and left out of an imported set (`import.reserved`). Files: `importKys: {"path": …}` reads a `.kys`, `exportKys: {"path": …}` and `summarize: {"path": …}` write the file (the reply has `kysPath` / `htmlPath`); automation (MCP) refuses these paths, as it does `actions.save`'s | +| `edit.keyboardShortcuts` | `{"set":{"edit.fill":"Cmd+Shift+F"},"reset":true\|["id",…],"removeConflicts":true,"filter":"blur","list":false,"importKys":"<.kys XML>"}`: returns overrides, matching commands and conflicts. A shortcut moved to another command is removed from its old owner unless `removeConflicts` is false. `""` removes a shortcut, `null` restores the default. The held temporary tools are bindable too: `tools.temporary.hand` (Space; also repositions a selection being drawn), `tools.temporary.zoomIn` (Cmd+Space), `tools.temporary.zoomOut` (Alt+Space; Alt added to a held Zoom In, Cmd+Alt+Space, zooms out too), `tools.temporary.erase` (`` ` ``; with the Brush or Pencil, a stroke started while it is held is in Clear mode, `paint.stroke`/`paint.pencil` `"mode": "clear"`, erasing with that tool's brush); they list with `"hold": true`. ⌘ (Ctrl off the Mac) held alone is the Move tool with the painting, retouching and other non-selection tools, as in Photoshop; it is a modifier, not a binding. `importKys` applies a Photoshop `.kys` set (the file's XML text, at most 4 MiB): rows are matched to commands by our id (`pc-id`, in sets PhotoCraft exported) or else by menu label, a key equal to the default restores it, keys also given in `set` win, and the result gains `import` (`name`, `imported`, `set`, `unknown`, `unreadable`, `alternates`, `toolKeys`, `windows`). A set saved by Photoshop on Windows (no ⌘ or Opt anywhere, Ctrl used) reads Ctrl as the primary modifier, so `Ctrl+L` is the `Cmd+L` default (`windows: true`). Tool keys are matched to tools by `pc-id` or name (a tool's own letter keeps its Shift cycling); `import.tools` lists the keys given. In the app it opens Keyboard Shortcuts and Menus (`ui.menu.invoke` replies `{"dialog": "shortcuts"}`, the id `ui.inspect` lists it under and `ui.dialog.cancel` closes it by), whose Import Shortcuts… button loads a `.kys` set into the dialog (opening or dropping a `.kys`, or Photoshop's live `Keyboard Shortcuts.psp`, does the same). On a desktop with Photoshop installed, the first launch that has no shortcut overrides yet asks whether to import the newest install's live set (Import / Don't Import; `ui.inspect` shows it as `kysOffer`); the answer is recorded in the preferences as `dialogs.photoshopShortcuts`, so it is asked once. **Sets** (Edit › Keyboard Shortcuts › Set): `useSet` loads a saved set's bindings (`""` or `"PhotoCraft Defaults"`: the defaults) before the call's other changes; then `saveSet` saves the bindings as they end up under a name and uses it, `deleteSet` removes one (the bindings stay), `sets` replaces every saved set (`{"": {"shortcuts": {…}, "alternateShortcuts": {…}}}`, the dialog's OK) and `activeSet` names the set in use without loading it. Names are trimmed, 1–64 characters, at most 64 sets. Every reply has `sets`, `activeSet` (`""` for the defaults), `defaultsName` and `modified` (the bindings differ from the set in use). `exportKys: true` adds `kys`, the bindings of every bindable command and tool as a `.kys` file (Photoshop's macOS key spelling; each row carries our id as `pc-id`, so the file imports back exactly); `summarize: true` (or `{"mac": false}`) adds `html`, Photoshop's Summarize page. A bad parameter anywhere in the call, an export path that can't be written included, changes nothing. **Headless parity:** the shell's commands (View › Zoom In, the panels; `photocraft_engine::shell_commands::SHELL_COMMANDS`) and the tools (`tools.select.`, listed with `"tool": true`) are bindable, listed, imported, exported and checked for conflicts without the UI; tools may share a key (they cycle with Shift, so a shared letter is no conflict), while a command given a tool's key takes it from the tools. Keys the system takes first (Alt+Tab, Alt+F4, Ctrl+Alt+Delete everywhere but the Mac, plus Ctrl+Esc and Ctrl+Shift+Esc on Windows and Ctrl+Alt+F1–F12 on Linux; ⌘Tab, ⌘`, ⌘⌥Esc on the Mac) are refused, and left out of an imported set (`import.reserved`). Files: `importKys: {"path": …}` reads a `.kys`, `exportKys: {"path": …}` and `summarize: {"path": …}` write the file (the reply has `kysPath` / `htmlPath`); automation (MCP) refuses these paths, as it does `actions.save`'s | | `edit.menus` / `edit.toolbar` | `{"hide":["edit.fade"],"show":[…],"color":{"edit.fill":"red"},"reset":false}` / `{"hidden":["Sponge"],"order":[…]}` | | `edit.colorSettings` | `{"workingRgb":"display-p3","workingCmyk":"coated-cmyk","workingGray":"sgray","policyRgb":"preserve\|convert\|off",…,"askOnMismatch":true,"intent":"perceptual","bpc":true}`; honoured when opening files (`file.openAs`, the app's File › Open) and by Image › Mode and "working" profile specs. `color.profileMismatch {"action":"preserve\|convert\|discard\|assignWorking"}` answers the mismatch prompt | diff --git a/scripts/engine_split/table_fragments.py b/scripts/engine_split/table_fragments.py new file mode 100644 index 0000000000..e711217873 --- /dev/null +++ b/scripts/engine_split/table_fragments.py @@ -0,0 +1,332 @@ +#!/usr/bin/env python3 +"""Move a branch's edits of the old inline command table into the table fragments. + +Before the table was split, `crates/engine/src/cmd.rs` held every core command in one `vec![...]` +inside `fn build()`. The entries now live in `crates/engine/src/cmd/table//.rs`, and +`cmd/command_ids.txt` pins the registry order. A branch that edited the old table carries its +edits in `cmd.rs`. This script applies them to the fragments: + + python3 scripts/engine_split/table_fragments.py --base --head + +Run it in a checkout of the new main (or of the branch rebased onto it, with its `cmd.rs` hunks +for the old table dropped). Per command id, compared between BASE and HEAD: + changed the entry in its fragment is replaced by HEAD's text (if the fragment still has + BASE's text; otherwise it is reported as a CONFLICT and left alone); + added the entry goes after its predecessor's entry, in the predecessor's fragment, and its id + goes after the predecessor's id in command_ids.txt; + removed the entry and its id are deleted (if the fragment still has BASE's text). +The adjustment table and its loop (`ADJ`, between the `vec![...]` and the `v.extend(...)` list) are +three-way merged into table/image/adjustments.rs. Any other change inside `build()` (the module +table list, the test-only command) is reported as UNHANDLED: edit `SPECS` in cmd.rs by hand. +Entries are compared without comments and whitespace, so rustfmt does not matter. Names a new +entry uses from cmd.rs are added to its fragment's `use crate::cmd::{..}` list. Run +`cargo fmt --all` afterwards. Running the script twice gives the same result. CONFLICT, UNHANDLED, +UNPLACED, MISSING and DUPLICATE lines mean exit status 1; resolve those by hand. +Edits outside `build()` (imports in cmd.rs, helper fns, test modules) are not touched. +""" +import argparse, os, re, subprocess, sys, tempfile + +CMD = "crates/engine/src/cmd.rs" +TABLE = "crates/engine/src/cmd/table" +IDS = "crates/engine/src/cmd/command_ids.txt" +ID_RE = re.compile(r'"([a-zA-Z]+\.[A-Za-z0-9.]+)"') + + +def skip(text, i): + """Index after the comment, string or char literal starting at i, or None.""" + if text.startswith("//", i): + j = text.find("\n", i) + return len(text) if j < 0 else j + m = re.match(r'r(#*)"', text[i:]) + if m and (i == 0 or not (text[i - 1].isalnum() or text[i - 1] == "_")): + end = text.index('"' + m.group(1), i + len(m.group(0))) + return end + 1 + len(m.group(1)) + if text[i] == '"': + i += 1 + while text[i] != '"': + i += 2 if text[i] == "\\" else 1 + return i + 1 + if text[i] == "'": + m = re.match(r"'(\\.[^']*|[^\\'])'", text[i:]) + if m: + return i + len(m.group(0)) + return None + + +def split_entries(body): + """The top-level comma-separated entries of a `vec![...]` body.""" + entries, depth, start, i = [], 0, 0, 0 + while i < len(body): + j = skip(body, i) + if j is not None: + i = j + continue + c = body[i] + if c in "([{": + depth += 1 + elif c in ")]}": + depth -= 1 + elif c == "," and depth == 0: + entries.append(body[start : i + 1]) + start = i + 1 + i += 1 + if body[start:].strip(): + entries.append(body[start:]) + return entries + + +def entry_id(entry): + code = "\n".join(l for l in entry.splitlines() if not l.strip().startswith("//")) + m = ID_RE.search(code) + return m.group(1) if m else None + + +def git_show(ref, path): + return subprocess.run(["git", "show", f"{ref}:{path}"], capture_output=True, text=True, check=True).stdout + + +class Fragments: + """Every `vec![...]` of the fragment files, with its entries.""" + + def __init__(self): + self.files = {} + for d, _, names in os.walk(TABLE): + for n in names: + if n.endswith(".rs") and os.path.dirname(os.path.join(d, n)) != TABLE: + p = os.path.join(d, n) + if "vec![" in open(p).read(): + self.files[p] = open(p).read() + + def find(self, cid): + """(path, entry text) of the entry for a command id, or None.""" + for p, t in self.files.items(): + for e in self.entries(t): + if entry_id(e) == cid: + return p, e + return None + + @staticmethod + def spans(t): + """(start, end) of each vec! body in a fragment file.""" + out, pos = [], 0 + while True: + k = t.find("vec![", pos) + if k < 0: + return out + s, depth, i = k + 5, 1, k + 5 + while depth: + j = skip(t, i) + if j is not None: + i = j + continue + depth += t[i] == "[" + depth -= t[i] == "]" + i += 1 + out.append((s, i - 1)) + pos = i + + def entries(self, t): + return [e for s, f in self.spans(t) for e in split_entries(t[s:f])] + + def replace(self, path, old, new): + t = self.files[path] + assert t.count(old) == 1, (path, "entry not unique") + self.files[path] = t.replace(old, new) + + def insert_after(self, path, old, new): + self.replace(path, old, old + new) + + def delete(self, path, old): + self.replace(path, old, "") + + def save(self): + for p, t in self.files.items(): + open(p, "w").write(t) + + +def tidy(e): + """Entry text as a fragment stores it: starts at its own line, ends with a comma.""" + e = e.strip("\n") + return e if e.rstrip().endswith(",") else e.rstrip() + "," + + +def norm(e): + """Entry text without comments and whitespace, and without trailing commas, for comparing.""" + out, i = [], 0 + while i < len(e): + j = skip(e, i) + if j is None: + out.append(e[i]) + i += 1 + elif e.startswith("//", i): + i = j + else: + out.append(e[i:j]) + i = j + s = re.sub(r"\s+", "", "".join(out)) + return re.sub(r",(?=[)\]}])", "", s).rstrip(",") + + +def words(e): + """Identifiers an entry uses as bare names (not paths, fields or inside literals).""" + out, i = [], 0 + while i < len(e): + j = skip(e, i) + if j is None: + out.append(e[i]) + i += 1 + else: + out.append(" ") + i = j + return set(re.findall(r"(? bool { /// Entries ending in `*` are prefixes. pub const UI_CRATES: &[&str] = &["egui", "eframe", "winit", "egui_kittest", "craft-ui", "rfd", "bevy*"]; +/// Facade crates that are a UI toolkit dependency only with some of their features (#15467): `craft` carries the +/// whole craft UI framework behind `ui` (and the features that turn it on), while lower layers use its non-UI parts +/// (imaging, fonts, keymap, settings). `keymap-egui` adds the keymap's egui key conversions, which bring egui itself. +/// Feature names ending in `*` are prefixes. +pub const UI_FEATURES: &[(&str, &[&str])] = &[("craft", &["ui", "ui-*", "screen-testing", "keymap-egui"])]; + /// First layer allowed to use UI crates. pub const UI_MIN_LAYER: u8 = 6; @@ -113,11 +119,17 @@ pub fn classify(pkg: &str) -> Option { TABLE.iter().find(|(n, _)| *n == s).map(|(_, c)| *c) } -fn is_ui_crate(name: &str) -> bool { - UI_CRATES.iter().any(|p| match p.strip_suffix('*') { +fn matches_pattern(name: &str, pattern: &str) -> bool { + match pattern.strip_suffix('*') { Some(prefix) => name.starts_with(prefix), - None => name == *p, - }) + None => name == pattern, + } +} + +/// Whether `dep` brings a UI toolkit: a crate in [`UI_CRATES`], or a [`UI_FEATURES`] facade with one of its UI features. +fn is_ui_dep(dep: &Dep) -> bool { + UI_CRATES.iter().any(|p| matches_pattern(&dep.name, p)) + || UI_FEATURES.iter().any(|(krate, features)| dep.name == *krate && dep.features.iter().any(|f| features.iter().any(|p| matches_pattern(f, p)))) } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -133,6 +145,8 @@ pub struct Dep { pub kind: DepKind, /// `true` if the dependency is a workspace member. pub workspace: bool, + /// The features the dependency is declared with (including the ones inherited from the workspace). + pub features: Vec, } #[derive(Debug, Clone)] @@ -215,7 +229,7 @@ pub fn check(crates: &[Crate]) -> Vec { } } } - } else if layer < UI_MIN_LAYER && is_ui_crate(&d.name) { + } else if layer < UI_MIN_LAYER && is_ui_dep(d) { out.push(Violation::UiBelowL6 { krate: c.name.clone(), dep: d.name.clone(), layer }); } } @@ -241,7 +255,12 @@ pub fn from_metadata(meta: &Value) -> Result, String> { _ => DepKind::Normal, }; let workspace = members.contains(&dname.as_str()) || d["path"].is_string(); - deps.push(Dep { name: dname, kind, workspace }); + let mut features: Vec = d["features"].as_array().into_iter().flatten().filter_map(|f| f.as_str().map(str::to_owned)).collect(); + // The package's own `[features]` can turn on a dependency's features (`default = ["craft/ui"]`), named by + // the dependency's key, which is its rename when it has one. Any of them may be on, so all count. + let key = d["rename"].as_str().unwrap_or(&dname); + features.extend(forwarded_features(&p["features"], key)); + deps.push(Dep { name: dname, kind, workspace, features }); } out.push(Crate { name, deps }); } @@ -249,6 +268,15 @@ pub fn from_metadata(meta: &Value) -> Result, String> { Ok(out) } +/// The features of dependency `key` that the package's `[features]` table (`features` in `cargo metadata`) turns on: +/// `key/feat` and `key?/feat` entries. +fn forwarded_features<'a>(table: &'a Value, key: &'a str) -> impl Iterator + 'a { + table.as_object().into_iter().flat_map(|t| t.values()).filter_map(Value::as_array).flatten().filter_map(Value::as_str).filter_map(move |entry| { + let (dep, feature) = entry.split_once('/')?; + (dep.strip_suffix('?').unwrap_or(dep) == key).then(|| feature.to_owned()) + }) +} + pub fn describe(class: Option) -> String { match class { Some(Class::Layer(l)) => format!("L{l}"), @@ -264,7 +292,7 @@ mod tests { use super::*; fn c(name: &str, deps: &[(&str, DepKind, bool)]) -> Crate { - Crate { name: name.into(), deps: deps.iter().map(|(n, k, w)| Dep { name: (*n).into(), kind: *k, workspace: *w }).collect() } + Crate { name: name.into(), deps: deps.iter().map(|(n, k, w)| Dep { name: (*n).into(), kind: *k, workspace: *w, features: Vec::new() }).collect() } } use DepKind::*; @@ -350,6 +378,71 @@ mod tests { assert!(check(&[c("photocraft-platform", &[("winit", Normal, false)])]).is_empty()); } + fn with_features(name: &str, dep: &str, kind: DepKind, features: &[&str]) -> Crate { + let features = features.iter().map(|f| (*f).to_owned()).collect(); + Crate { name: name.into(), deps: vec![Dep { name: dep.into(), kind, workspace: false, features }] } + } + + #[test] + fn craft_facade_with_ui_features_flagged_below_l6() { + // #15467: the facade's UI features bring the whole craft UI framework. + for features in [&["ui"][..], &["imaging", "ui-app"], &["screen-testing"]] { + let v = check(&[with_features("photocraft-engine", "craft", Normal, features)]); + assert!(matches!(&v[..], [Violation::UiBelowL6 { layer: 5, dep, .. }] if dep == "craft"), "{features:?}"); + let v = check(&[with_features("photocraft-text", "craft", Dev, features)]); + assert!(matches!(v[..], [Violation::UiBelowL6 { layer: 2, .. }]), "dev {features:?}"); + } + // Its non-UI parts stay usable below L6 (what text, io and engine use today), and L6 may use it all. + for features in [&[][..], &["imaging"], &["font-catalog", "font-manager"], &["automation", "color-ui", "keymap", "platform", "settings"]] { + assert!(check(&[with_features("photocraft-engine", "craft", Normal, features)]).is_empty(), "{features:?}"); + } + assert!(check(&[with_features("photocraft-ui-egui", "craft", Normal, &["ui", "screen-testing"])]).is_empty()); + // Only the facade is judged by its features. + assert!(check(&[with_features("photocraft-engine", "craft-imaging", Normal, &["ui"])]).is_empty()); + } + + #[test] + fn metadata_reads_dependency_features() { + let meta: Value = serde_json::from_str( + r#"{"packages":[{"name":"photocraft-engine","dependencies":[ + {"name":"craft","kind":null,"features":["keymap","ui"]}]}]}"#, + ) + .unwrap(); + let g = from_metadata(&meta).unwrap(); + assert_eq!(g[0].deps[0].features, ["keymap", "ui"]); + assert!(matches!(check(&g)[..], [Violation::UiBelowL6 { .. }])); + } + + /// The keymap's egui conversions bring egui; the plain keymap does not. + #[test] + fn keymap_egui_is_a_ui_feature() { + assert!(matches!(check(&[with_features("photocraft-engine", "craft", Normal, &["keymap-egui"])])[..], [Violation::UiBelowL6 { .. }])); + assert!(check(&[with_features("photocraft-engine", "craft", Normal, &["keymap"])]).is_empty()); + } + + /// A UI feature turned on by the package's own `[features]` (also through a renamed dependency) counts; other + /// forwarded features don't. + #[test] + fn metadata_reads_features_forwarded_by_the_package() { + let meta = |features: &str, rename: &str| -> Value { + serde_json::from_str(&format!( + r#"{{"packages":[{{"name":"photocraft-engine","features":{features},"dependencies":[ + {{"name":"craft","kind":null,"features":["keymap"]{rename}}}]}}]}}"# + )) + .unwrap() + }; + for (features, rename) in [(r#"{"default":["craft/ui"]}"#, ""), (r#"{"gui":["c?/ui"]}"#, r#","rename":"c""#)] { + let g = from_metadata(&meta(features, rename)).unwrap(); + assert!(matches!(check(&g)[..], [Violation::UiBelowL6 { .. }]), "{features}"); + } + for (features, rename) in + [(r#"{"default":["craft/imaging"]}"#, ""), (r#"{"gui":["other/ui","dep:craft"]}"#, ""), (r#"{"gui":["craft/ui"]}"#, r#","rename":"c""#)] + { + let g = from_metadata(&meta(features, rename)).unwrap(); + assert!(check(&g).is_empty(), "{features} {rename}: {:?}", check(&g)); + } + } + #[test] fn unregistered_crate_is_error() { let v = check(&[c("photocraft-mystery", &[])]);