mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge remote-tracking branch 'upstream/main' into perf-15709b
This commit is contained in:
commit
c5a3dffb9b
141 files changed
+8068
-1796
No files matched your search
Generated
+111
-111
@@ -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"
|
||||
+34
-34
@@ -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" }
|
||||
|
||||
@@ -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<f32> {
|
||||
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<f32> {
|
||||
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<f32> {
|
||||
|
||||
/// 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<u32, StampError> {
|
||||
dest_pixels(p)?;
|
||||
if p.src_w == 0 || p.src_h == 0 {
|
||||
@@ -653,9 +671,10 @@ pub fn stamp(p: &mut StampParams<'_>) -> Result<u32, StampError> {
|
||||
let tiles = tile_grid(p.dest_w, p.dest_h, p.dest_origin, p.tile);
|
||||
let mut written = 0u32;
|
||||
let dabs: Vec<Dab> = 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<u32, StampError> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
mod tolerance_tests;
|
||||
@@ -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,
|
||||
|
||||
@@ -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<f32> {
|
||||
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<f32> {
|
||||
image(|x| if x < W / 2 { [255, 0, 0] } else { [60, 180, 80] })
|
||||
}
|
||||
|
||||
fn image(rgb: impl Fn(usize) -> [u8; 3]) -> Vec<f32> {
|
||||
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<f32> {
|
||||
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<Dab> = [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");
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<Map> {
|
||||
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<f32> = (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
|
||||
|
||||
@@ -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<Vec<[f32; 4]>> = 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);
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+144
-1221
File diff suppressed because it is too large.
Load diff
@@ -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" {
|
||||
|
||||
@@ -659,10 +659,126 @@ pub fn artboard_document(doc: &Document, id: LayerId) -> Result<Option<Document>
|
||||
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 <board>" 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<Layer> {
|
||||
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<Vec<Document>> {
|
||||
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<Vec<Document>> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<CommandSpec> {
|
||||
"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 "<prefix><artboard name>.<format>" 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 <board>\" layer; artboard: Artboard Content Only),"artboards":[id]? (default all),"quality":0..12?} → {files} (one "<prefix><artboard name>.<format>" 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)]
|
||||
|
||||
@@ -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})");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -980,9 +980,9 @@ fn name_param(p: &Value, cmd: &str) -> Result<String> {
|
||||
|
||||
/// 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<Value> {
|
||||
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<Value> {
|
||||
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());
|
||||
|
||||
@@ -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}");
|
||||
|
||||
@@ -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<Value> {
|
||||
};
|
||||
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<String>, 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<BrushPreset>, Vec<BrushPreset>) = 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<String>, 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<String>, 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<BrushPreset>, Vec<BrushPreset>) = 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<String>, 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<Value> {
|
||||
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<BrushPreset>, Vec<BrushPreset>) = 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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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();
|
||||
|
||||
@@ -7,7 +7,7 @@ fn names(s: &Session, g: &str) -> Vec<String> {
|
||||
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<String> = 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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<f32> {
|
||||
let d = s.active().unwrap();
|
||||
layer(s).surface().unwrap().read_region(d.doc.bounds())
|
||||
}
|
||||
|
||||
fn px(s: &Session, x: i32, y: i32) -> Vec<f32> {
|
||||
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<f32> {
|
||||
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:?}");
|
||||
}
|
||||
}
|
||||
@@ -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<f32> {
|
||||
let d = s.active().unwrap();
|
||||
layer(s).surface().unwrap().read_region(d.doc.bounds())
|
||||
}
|
||||
|
||||
fn px(s: &Session, x: i32, y: i32) -> Vec<f32> {
|
||||
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<Item = Value> {
|
||||
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:?}");
|
||||
}
|
||||
@@ -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<f32> {
|
||||
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<f32> = 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");
|
||||
}
|
||||
@@ -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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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::<String>()).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()
|
||||
}
|
||||
@@ -314,9 +314,9 @@ fn export_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// 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;
|
||||
}
|
||||
|
||||
@@ -114,7 +114,7 @@ pub(super) fn preset_manager(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
"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<Value> {
|
||||
"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),
|
||||
};
|
||||
|
||||
@@ -86,19 +86,40 @@ fn parse(st: &DocState, p: &Value, cmd: &str) -> Result<Option<HistorySource>> {
|
||||
/// 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<Arc<Document>> {
|
||||
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<std::result::Result<Arc<Document>, 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
|
||||
|
||||
@@ -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<String>) -> EngineError {
|
||||
EngineError::BadParams { cmd: CMD.into(), msg: msg.into() }
|
||||
}
|
||||
@@ -224,12 +255,15 @@ fn perspective_crop(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<CommandSpec> {
|
||||
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,
|
||||
|
||||
@@ -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<Layer>) -> 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<Layer>, 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<LayerRecord>, 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<LayerRecord> {
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -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<Value> {
|
||||
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();
|
||||
|
||||
@@ -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<String>) -> EngineError {
|
||||
@@ -413,9 +411,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
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,
|
||||
},
|
||||
|
||||
@@ -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<photocraft_doc::LayerId>, 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<photocraft_doc::LayerId>, p: &Value) -> Result<photocraft_raster::Surface> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
}
|
||||
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;
|
||||
@@ -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}");
|
||||
}
|
||||
@@ -700,7 +700,7 @@ pub fn preview(s: &Session, p: &Value) -> Result<ContentAwarePreview> {
|
||||
}
|
||||
|
||||
/// 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<ContentAwarePreview> {
|
||||
pub(crate) fn preview_with_pixel_budget(s: &Session, p: &Value, max_pixels: u64) -> Result<ContentAwarePreview> {
|
||||
let captured = crate::channel_cmds::inject_target(s, CMD, p.clone());
|
||||
let p = &captured;
|
||||
let plan = plan(s, p, PREVIEW_MARGIN)?;
|
||||
|
||||
@@ -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::<Vec<_>>();
|
||||
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 = [
|
||||
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -0,0 +1,9 @@
|
||||
use crate::cmd::{CommandSpec, can_redo, can_undo, json};
|
||||
|
||||
/// Edit menu: Undo and Redo.
|
||||
pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
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()))),
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
use crate::cmd::{CommandSpec, EngineError, Value, bad, has_doc};
|
||||
|
||||
/// File menu: Close.
|
||||
pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
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)
|
||||
}
|
||||
)]
|
||||
}
|
||||
@@ -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<CommandSpec> {
|
||||
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,
|
||||
},
|
||||
]
|
||||
}
|
||||
@@ -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<CommandSpec> {
|
||||
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)
|
||||
}
|
||||
),
|
||||
]
|
||||
}
|
||||
@@ -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<CommandSpec> {
|
||||
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)
|
||||
}),
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
pub(crate) mod adjustments;
|
||||
pub(crate) mod image_menu;
|
||||
@@ -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<CommandSpec> {
|
||||
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
|
||||
}
|
||||
@@ -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<CommandSpec> {
|
||||
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)
|
||||
}
|
||||
)]
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub(crate) mod edit_menu;
|
||||
pub(crate) mod image_menu;
|
||||
pub(crate) mod layer_menu;
|
||||
@@ -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<CommandSpec> {
|
||||
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)
|
||||
}
|
||||
)]
|
||||
}
|
||||
@@ -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<Value> {
|
||||
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<CommandSpec> {
|
||||
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)
|
||||
}),
|
||||
]
|
||||
}
|
||||
@@ -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<CommandSpec> {
|
||||
[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<CommandSpec> {
|
||||
[adjustments(), placement()].into_iter().flatten().collect()
|
||||
}
|
||||
|
||||
/// New layers and groups, and grouping the selected layers.
|
||||
fn creation() -> Vec<CommandSpec> {
|
||||
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<CommandSpec> {
|
||||
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<CommandSpec> {
|
||||
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<CommandSpec> {
|
||||
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<CommandSpec> {
|
||||
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<CommandSpec> {
|
||||
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<CommandSpec> {
|
||||
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<CommandSpec> {
|
||||
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<CommandSpec> {
|
||||
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<Value> {
|
||||
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<Vec<LayerId>> {
|
||||
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<Option<f32>> {
|
||||
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<f32>, fill: Option<f32>) -> 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<BlendMode> {
|
||||
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<String, Value>) -> 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(())
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
pub(crate) mod edit_menu;
|
||||
pub(crate) mod stroke;
|
||||
@@ -0,0 +1,14 @@
|
||||
use crate::cmd::{CommandSpec, has_pixel_or_channel};
|
||||
|
||||
/// Edit menu: Fill.
|
||||
pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
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
|
||||
)]
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
use crate::cmd::{CommandSpec, has_paintable};
|
||||
|
||||
/// Painting: the stroke command.
|
||||
pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
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
|
||||
)]
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
pub(crate) mod file_menu;
|
||||
pub(crate) mod layer_menu;
|
||||
@@ -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<CommandSpec> {
|
||||
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 }))
|
||||
}
|
||||
),
|
||||
]
|
||||
}
|
||||
@@ -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<CommandSpec> {
|
||||
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<String, Value> = ["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 }))
|
||||
}
|
||||
)]
|
||||
}
|
||||
@@ -278,11 +278,35 @@ fn apply_data_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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;
|
||||
@@ -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<f32> {
|
||||
doc(s).layer(id).unwrap().surface().unwrap().pixel(32, 24)
|
||||
}
|
||||
|
||||
fn history(s: &Session) -> (usize, Option<String>) {
|
||||
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);
|
||||
}
|
||||
@@ -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<photocraft_paint::BrushPreset>,
|
||||
pub presets: Arc<Vec<photocraft_paint::BrushPreset>>,
|
||||
/// 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,
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<R>(&mut self, f: impl FnOnce(&mut Preferences) -> R) -> R {
|
||||
let r = self.prefs.edit(f);
|
||||
|
||||
@@ -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<Vec<BrushPreset>>) {
|
||||
// User presets by group, in first-appearance order.
|
||||
let mut order: Vec<(String, Vec<usize>)> = 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<Vec<String>> = 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<String, usize> = 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
|
||||
|
||||
@@ -52,6 +52,20 @@ fn user(s: &Session) -> Vec<BrushPreset> {
|
||||
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::<Vec<_>>();
|
||||
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];
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
@@ -1553,8 +1553,9 @@ fn bevel_part(p: vec2<i32>, 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; }
|
||||
|
||||
@@ -1703,6 +1703,10 @@ fn effect_cases() -> Vec<(&'static str, Vec<Effect>)> {
|
||||
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<Effect>)> {
|
||||
),
|
||||
("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))))]),
|
||||
|
||||
@@ -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<Vec<u8>> {
|
||||
(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
|
||||
|
||||
@@ -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)),
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<u8>) -> Vec<u8> {
|
||||
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<_>>(), 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.
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<StrokePoint> = (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]
|
||||
|
||||
@@ -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<StrokePoint>,
|
||||
last_input: Option<StrokePoint>,
|
||||
/// 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<StrokePoint>) {
|
||||
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;
|
||||
@@ -438,8 +438,10 @@ impl Texture {
|
||||
}
|
||||
}
|
||||
|
||||
/// The built-in preset set, in display order (grouped by [`GROUPS`]).
|
||||
pub fn builtin() -> Vec<BrushPreset> {
|
||||
#[cfg(test)]
|
||||
static BUILTIN_INITIALIZATIONS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
|
||||
fn build_builtin() -> Vec<BrushPreset> {
|
||||
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<BrushPreset> {
|
||||
v
|
||||
}
|
||||
|
||||
/// An owned copy of the built-in preset set, in display order (grouped by [`GROUPS`]).
|
||||
pub fn builtin() -> Vec<BrushPreset> {
|
||||
builtin_shared().as_ref().clone()
|
||||
}
|
||||
|
||||
/// The built-in set shared by new sessions until one is edited.
|
||||
pub fn builtin_shared() -> std::sync::Arc<Vec<BrushPreset>> {
|
||||
static BUILTIN: std::sync::OnceLock<std::sync::Arc<Vec<BrushPreset>>> = 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();
|
||||
|
||||
@@ -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<StrokePoint> {
|
||||
(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<f64> = [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");
|
||||
}
|
||||
@@ -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<TileCoord, Arc<Tile>>,
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
@@ -222,7 +222,7 @@ impl TranslateSteps {
|
||||
let tiles: Vec<(TileCoord, Arc<Tile>)> =
|
||||
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(),
|
||||
|
||||
@@ -334,3 +334,6 @@ impl eframe::App for Box<PhotocraftApp> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod clipboard_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod apply_data_set_alert_tests;
|
||||
@@ -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<PhotocraftApp> {
|
||||
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<String> {
|
||||
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));
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<Overrides>,
|
||||
/// The preferences revision `overrides` and `catalog` were last built at.
|
||||
overrides_rev: Option<u64>,
|
||||
/// 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<AppCatalog>,
|
||||
/// 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<craft::keymap::CommandDef>,
|
||||
catalog_actions: Vec<String>,
|
||||
catalog_rows_rev: Option<u64>,
|
||||
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<Arc<dyn Files>>,
|
||||
@@ -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>, 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<AppCatalog>, 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<String>, rows: Vec<craft::keymap::CommandDef>) {
|
||||
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<fn(&PhotocraftApp) -> 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<Option<KeptStates>>,
|
||||
/// How many times each source computed its states, for the count trials.
|
||||
#[cfg(test)]
|
||||
pub(crate) runs: Vec<usize>,
|
||||
}
|
||||
|
||||
/// 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<Tables>);
|
||||
#[derive(Default)]
|
||||
struct Tables {
|
||||
tables: BTreeMap<String, toml::Table>,
|
||||
/// 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<String, Value>,
|
||||
/// The sections a component wrote since the last sync.
|
||||
written: BTreeSet<String>,
|
||||
/// 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<String, u64>,
|
||||
/// 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<String, Value> = 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<String> = 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() {
|
||||
|
||||
@@ -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<PhotocraftApp> {
|
||||
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<Option<usize>> {
|
||||
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<usize>], after: &[Option<usize>]) -> Vec<usize> {
|
||||
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");
|
||||
}
|
||||
@@ -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<PhotocraftApp>>;
|
||||
|
||||
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<PhotocraftApp>| 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<Value> {
|
||||
let form = h.state().framework.dialogs.get_by_id::<HostedParamDialog>(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<String> = 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);
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
_ => {}
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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<PhotocraftApp>>, 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");
|
||||
}
|
||||
|
||||
|
||||
@@ -477,6 +477,8 @@ pub(crate) struct BodyShown {
|
||||
pub(crate) crop: Option<CropShown>,
|
||||
/// The snap lines of the open Free Transform's box, which its canvas tool hands to the host.
|
||||
pub(crate) transform_snapped: Vec<SnapLine>,
|
||||
/// The open Free Transform's preview, which the body adds to the canvas's picture slot after the document.
|
||||
pub(crate) transform_picture: Vec<egui::Shape>,
|
||||
}
|
||||
|
||||
/// Borrows a family tool as the host's `dyn`.
|
||||
@@ -513,7 +515,7 @@ fn with_rig<R>(
|
||||
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 };
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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<Value> = 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));
|
||||
|
||||
@@ -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<PhotocraftApp>, egui::Context, std::rc::Rc<std
|
||||
fn answer_save(app: &mut PhotocraftApp, ctx: &egui::Context, synthetic: bool) -> 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<PhotocraftApp>, 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");
|
||||
}
|
||||
@@ -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<PhotocraftApp>> {
|
||||
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}");
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
@@ -159,6 +159,9 @@ pub(crate) struct SourceInit {
|
||||
pub(crate) ctx: egui::Context,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
type BeforePreviewPublish = Arc<dyn Fn(u64, &CameraRaw) + Send + Sync>;
|
||||
|
||||
/// 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<AtomicUsize>,
|
||||
/// 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<Option<BeforePreviewPublish>>,
|
||||
/// 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) {
|
||||
|
||||
@@ -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<bool>, std::sync::Condvar)>,
|
||||
timed_out: Arc<std::sync::atomic::AtomicBool>,
|
||||
}
|
||||
|
||||
#[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<u64>) {
|
||||
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]
|
||||
|
||||
@@ -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<craft::ui::dialog::DialogId> {
|
||||
app.framework.dialogs.get::<UnsavedChangesDialog>().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)> {
|
||||
|
||||
@@ -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())),
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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))
|
||||
})
|
||||
|
||||
Loaded 100 of 141 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user