mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-27 21:29:35 +00:00
Merge main into fix/overprint-preview-canvas
This commit is contained in:
Generated
+118
-34
@@ -1035,7 +1035,15 @@ source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db39
|
||||
[[package]]
|
||||
name = "craft-dds"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-dds"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
@@ -1060,12 +1068,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-eps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec#cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=068e079c7be4b100a8a6b305b31ac881e069727e#068e079c7be4b100a8a6b305b31ac881e069727e"
|
||||
|
||||
[[package]]
|
||||
name = "craft-eps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec#cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec"
|
||||
|
||||
[[package]]
|
||||
name = "craft-font-catalog"
|
||||
@@ -1128,12 +1136,39 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3"
|
||||
dependencies = [
|
||||
"craft-dds",
|
||||
"craft-jpeg",
|
||||
"craft-metadata",
|
||||
"craft-tiff",
|
||||
"craft-dds 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)",
|
||||
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)",
|
||||
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)",
|
||||
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)",
|
||||
"crc32fast",
|
||||
"exr",
|
||||
"flate2",
|
||||
"half",
|
||||
"hayro-jpeg2000",
|
||||
"image",
|
||||
"image-webp",
|
||||
"jpeg-encoder",
|
||||
"png 0.18.1",
|
||||
"rayon",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"tiff",
|
||||
"zune-core",
|
||||
"zune-jpeg",
|
||||
"zune-jpegxl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3"
|
||||
dependencies = [
|
||||
"craft-dds 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)",
|
||||
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)",
|
||||
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)",
|
||||
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)",
|
||||
"crc32fast",
|
||||
"exr",
|
||||
"flate2",
|
||||
@@ -1155,7 +1190,15 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1184,11 +1227,23 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3"
|
||||
dependencies = [
|
||||
"brotli-decompressor 6.3.2",
|
||||
"chrono",
|
||||
"craft-tiff",
|
||||
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)",
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3"
|
||||
dependencies = [
|
||||
"brotli-decompressor 6.3.2",
|
||||
"chrono",
|
||||
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)",
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
]
|
||||
@@ -1298,10 +1353,10 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-svg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"craft-xml",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)",
|
||||
"data-url",
|
||||
"flate2",
|
||||
"gif",
|
||||
@@ -1316,6 +1371,24 @@ dependencies = [
|
||||
"vectorcraft-pathops 0.18.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
@@ -1414,6 +1487,16 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
@@ -6689,7 +6772,7 @@ name = "vectorcraft-affinity"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-affinity",
|
||||
"craft-image-codecs",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)",
|
||||
"crc32fast",
|
||||
"proptest",
|
||||
"vectorcraft-affinity",
|
||||
@@ -6719,7 +6802,7 @@ name = "vectorcraft-cad"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-dxf",
|
||||
"craft-image-codecs",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)",
|
||||
"craft-plotter",
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -6774,7 +6857,7 @@ name = "vectorcraft-doc"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-image-codecs",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)",
|
||||
"craft-stream-codecs",
|
||||
"flate2",
|
||||
"image",
|
||||
@@ -6794,7 +6877,7 @@ dependencies = [
|
||||
name = "vectorcraft-effects"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)",
|
||||
"craft-svg",
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -6819,11 +6902,11 @@ dependencies = [
|
||||
"chrono",
|
||||
"craft-cdr",
|
||||
"craft-docpath",
|
||||
"craft-image-codecs",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)",
|
||||
"craft-jxl",
|
||||
"craft-proof",
|
||||
"craft-stream-codecs",
|
||||
"craft-xml",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)",
|
||||
"crc32fast",
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
@@ -6876,8 +6959,8 @@ dependencies = [
|
||||
name = "vectorcraft-eps"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-eps 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)",
|
||||
"craft-image-codecs",
|
||||
"craft-eps 0.1.0 (git+https://github.com/storytold/craft-libs?rev=068e079c7be4b100a8a6b305b31ac881e069727e)",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)",
|
||||
"craft-pdf",
|
||||
"craft-ps",
|
||||
"craft-stream-codecs",
|
||||
@@ -6957,7 +7040,7 @@ dependencies = [
|
||||
name = "vectorcraft-mcp"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)",
|
||||
"image",
|
||||
"log",
|
||||
"proptest",
|
||||
@@ -6977,7 +7060,7 @@ dependencies = [
|
||||
name = "vectorcraft-metafile"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)",
|
||||
"craft-metafile",
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -7018,10 +7101,10 @@ version = "0.24.1"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"chrono",
|
||||
"craft-image-codecs",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)",
|
||||
"craft-pdf",
|
||||
"craft-stream-codecs",
|
||||
"craft-xml",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)",
|
||||
"flate2",
|
||||
"getrandom 0.4.3",
|
||||
"image",
|
||||
@@ -7053,9 +7136,10 @@ dependencies = [
|
||||
name = "vectorcraft-plugins"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)",
|
||||
"craft-vectorcraft-format",
|
||||
"log",
|
||||
"rustix 1.1.6",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
@@ -7074,10 +7158,10 @@ name = "vectorcraft-render"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-gif",
|
||||
"craft-image-codecs",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)",
|
||||
"craft-psd",
|
||||
"craft-stream-codecs",
|
||||
"craft-tiff",
|
||||
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)",
|
||||
"flate2",
|
||||
"image",
|
||||
"jpeg-encoder",
|
||||
@@ -7113,7 +7197,7 @@ name = "vectorcraft-svg"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-docpath",
|
||||
"craft-image-codecs",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)",
|
||||
"craft-mime",
|
||||
"craft-svg",
|
||||
"data-url",
|
||||
@@ -7143,7 +7227,7 @@ dependencies = [
|
||||
name = "vectorcraft-testkit"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)",
|
||||
"fax",
|
||||
"kurbo 0.13.1",
|
||||
"proptest",
|
||||
@@ -7194,7 +7278,7 @@ dependencies = [
|
||||
name = "vectorcraft-tools"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)",
|
||||
"kurbo 0.13.1",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -7211,7 +7295,7 @@ dependencies = [
|
||||
name = "vectorcraft-trace"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)",
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
"serde",
|
||||
@@ -7226,7 +7310,7 @@ version = "0.24.1"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"chrono",
|
||||
"craft-image-codecs",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)",
|
||||
"craft-keymap",
|
||||
"craft-ui",
|
||||
"craft-update",
|
||||
|
||||
+3
-3
@@ -30,17 +30,17 @@ craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "d7c96
|
||||
# Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778).
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "9b28b56bc7207ef7ce806f37df72cb94c0ad5c37" }
|
||||
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["tree"] }
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
|
||||
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "068e079c7be4b100a8a6b305b31ac881e069727e" }
|
||||
# DXF tags, reader and writer (craft-libs#778, #926, #927).
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec", default-features = false, features = ["read", "write"] }
|
||||
|
||||
@@ -170,6 +170,12 @@ fn fit(size: [f32; 2], room: [f32; 2]) -> [f32; 2] {
|
||||
std::array::from_fn(|i| size[i].min(room[i]).max(MIN_SIZE[i].min(room[i])).max(1.0))
|
||||
}
|
||||
|
||||
/// The smallest size a window of `size` points may take: [`MIN_SIZE`], lowered to `size` in each
|
||||
/// dimension where [`fit`] made the window smaller than that to fit a small work area.
|
||||
fn min_size(size: [f32; 2]) -> [f32; 2] {
|
||||
std::array::from_fn(|i| MIN_SIZE[i].min(size[i]))
|
||||
}
|
||||
|
||||
/// Whether to list the monitors again: on the first frame, when the UI zoom changed, and at most
|
||||
/// every [`MONITORS_EVERY`] seconds while the app draws. `listed` holds the last list's time and zoom.
|
||||
pub fn monitors_due(listed: Option<(f64, f32)>, now: f64, zoom: f32) -> bool {
|
||||
@@ -302,6 +308,12 @@ pub fn restore(window: &winit::window::Window, saved: Option<WindowGeometry>) ->
|
||||
if let Some([x, y]) = g.pos {
|
||||
window.set_outer_position(PhysicalPosition::new(x, y));
|
||||
}
|
||||
// The native minimum (`MIN_SIZE`, set in `native_options`) would keep the window bigger than a
|
||||
// size fitted to a small work area, so it is lowered to that size first.
|
||||
let min = min_size(g.size);
|
||||
if min != MIN_SIZE {
|
||||
window.set_min_inner_size(Some(LogicalSize::new(min[0], min[1])));
|
||||
}
|
||||
// Returns the new size when it applies at once; either way the window gets it.
|
||||
let _ = window.request_inner_size(LogicalSize::new(g.size[0], g.size[1]));
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
@@ -444,6 +456,21 @@ mod tests {
|
||||
assert_eq!(monitor(0, 0, 1920, 1080, 1.0).less_frame([16, 39]).work, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_fitted_below_the_smallest_size_lowers_the_minimum_to_its_size() {
|
||||
// 1366 × 768 at 150% with a 48-pixel taskbar along the bottom: a work area 480 points high.
|
||||
let areas = [WorkArea { monitor: [0, 0, 1366, 768], work: [0, 0, 1366, 720] }];
|
||||
let m = [monitor(0, 0, 1366, 768, 1.5).with_work_area(&areas)];
|
||||
let g = place(saved(Some([0, 0]), [900.0, 500.0], false), &m, Some(0));
|
||||
assert_eq!(g.size, [900.0, 480.0]);
|
||||
// The minimum height drops to the fitted 480 points; the width keeps the normal minimum.
|
||||
assert_eq!(min_size(g.size), [800.0, 480.0]);
|
||||
// A window with room for the smallest size keeps the normal minimum.
|
||||
let big = [monitor(0, 0, 1920, 1080, 1.0)];
|
||||
assert_eq!(min_size(place(saved(Some([0, 0]), [1000.0, 700.0], false), &big, Some(0)).size), MIN_SIZE);
|
||||
assert_eq!(min_size([1.0, 1.0]), [1.0, 1.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn macos_screen_rects_turn_into_winits_top_left_pixels() {
|
||||
// A 1512 × 982 point primary screen at 2× with a 37-point menu bar and an 80-point Dock,
|
||||
|
||||
@@ -13,6 +13,8 @@ workspace = true
|
||||
spine-count = []
|
||||
# `vectorcraft_doc::symbols_read` for other crates' tests (dev-dependencies only).
|
||||
symbol-read-count = []
|
||||
# `vectorcraft_doc::locked_artboard_measures` for other crates' tests (dev-dependencies only).
|
||||
locked-artboard-count = []
|
||||
|
||||
[dependencies]
|
||||
vectorcraft-geom = { workspace = true }
|
||||
|
||||
@@ -174,6 +174,21 @@ impl ArtboardSide {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "locked-artboard-count"))]
|
||||
thread_local! {
|
||||
/// How many objects [`LockedArtboards::overlaps`] has measured on this thread.
|
||||
static LOCKED_ARTBOARD_MEASURES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many objects [`LockedArtboards::overlaps`] has measured on this thread, for other crates'
|
||||
/// tests that count how often art is measured to find what a locked artboard holds (the
|
||||
/// `locked-artboard-count` feature, dev-dependencies only).
|
||||
#[cfg(any(test, feature = "locked-artboard-count"))]
|
||||
#[doc(hidden)]
|
||||
pub fn locked_artboard_measures() -> usize {
|
||||
LOCKED_ARTBOARD_MEASURES.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
/// A document's locked artboards ([`Document::locked_artboards`]).
|
||||
pub struct LockedArtboards<'a> {
|
||||
pub(crate) rects: Vec<Rect>,
|
||||
@@ -210,6 +225,8 @@ impl LockedArtboards<'_> {
|
||||
if let Some(held) = self.held.borrow().get(&n.id) {
|
||||
return *held;
|
||||
}
|
||||
#[cfg(any(test, feature = "locked-artboard-count"))]
|
||||
LOCKED_ARTBOARD_MEASURES.with(|c| c.set(c.get() + 1));
|
||||
let held =
|
||||
n.visual_bounds_with(&self.symbols).is_some_and(|b| self.rects.iter().any(|r| b.x0 < r.x1 && b.x1 > r.x0 && b.y0 < r.y1 && b.y1 > r.y0));
|
||||
self.held.borrow_mut().insert(n.id, held);
|
||||
|
||||
+20
-3
@@ -1162,9 +1162,15 @@ impl Lerp {
|
||||
&& let (Some(qa), Some(qb)) = (a.image_corners(), b.image_corners())
|
||||
{
|
||||
let near = if t < 0.5 { qa } else { qb };
|
||||
if n.set_image_corners([0, 1, 2, 3].map(|i| qa[i].lerp(qb[i], t))).is_err() {
|
||||
// The nearer key's corners passed the same check when it was distorted.
|
||||
let _ = n.set_image_corners(near);
|
||||
if n.set_image_corners([0, 1, 2, 3].map(|i| qa[i].lerp(qb[i], t))).is_err() && n.set_image_corners(near).is_err() {
|
||||
// Corners from a transform that collapses the image fail the check too: the
|
||||
// step is then placed as the nearer key is.
|
||||
if let (NodeKind::Image(o), NodeKind::Image(k)) = (&mut n.kind, &base.kind) {
|
||||
o.xf = k.xf;
|
||||
}
|
||||
if n.extras().image_quad != base.extras().image_quad {
|
||||
n.extras_mut().image_quad = base.extras().image_quad.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
n.extras_mut().mask = None;
|
||||
@@ -2343,6 +2349,17 @@ mod tests {
|
||||
let near = (if t < 0.5 { &a } else { b }).image_corners().unwrap();
|
||||
assert!(got.iter().zip(near).all(|(g, w)| g.distance(w) < 1e-9), "{t}: {got:?} against {near:?}");
|
||||
}
|
||||
// Toward an image whose transform has no height, neither the step's corners nor the
|
||||
// nearer key's pass the check: the step is placed as that key is.
|
||||
let mut flat = image([(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]);
|
||||
let collapsed = Affine::new([-3.0, 0.0, 0.0, 0.0, 100.0, 0.0]);
|
||||
if let NodeKind::Image(im) = &mut flat.kind {
|
||||
im.xf = collapsed;
|
||||
}
|
||||
let step = Lerp::new(&a, &flat, (None, None)).at(0.5);
|
||||
let NodeKind::Image(im) = &step.kind else { panic!("an image") };
|
||||
assert_eq!(im.xf, collapsed);
|
||||
assert!(!step.is_distorted_image() && step.extras().image_quad.is_none());
|
||||
}
|
||||
|
||||
fn key(x: f64) -> Arc<Node> {
|
||||
|
||||
@@ -551,13 +551,19 @@ impl Document {
|
||||
}
|
||||
|
||||
/// Insert `node` into `parent` at `index` (clamped; `usize::MAX` = top). In a layer, art goes
|
||||
/// below the layer's ruler guides and a ruler guide among them ([`Node::insert_index`]).
|
||||
/// below the layer's ruler guides and a ruler guide among them ([`Node::insert_index`]). A
|
||||
/// node that is or holds a dimension (a pasted one) sets [`Document::dimensions`].
|
||||
pub fn insert(&mut self, parent: Option<NodeId>, index: usize, node: Node) -> Result<NodeId, DocError> {
|
||||
fn holds_dimension(n: &Node) -> bool {
|
||||
n.extras().dimension.is_some() || n.children().into_iter().flatten().any(|c| holds_dimension(c))
|
||||
}
|
||||
let id = node.id;
|
||||
self.check_ruler_guide_place(&node, parent)?;
|
||||
let dimension = !self.dimensions && holds_dimension(&node);
|
||||
let ch = self.children_mut(parent)?;
|
||||
let i = Node::insert_index(ch, index, &node);
|
||||
ch.insert(i, Arc::new(node));
|
||||
self.dimensions |= dimension;
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
@@ -659,6 +665,21 @@ impl Document {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Put each list of nodes in `items` directly below its anchor, in list order, in one pass over
|
||||
/// the children of each parent. It fails as [`Document::insert_beside`] does.
|
||||
pub fn insert_below(&mut self, items: Vec<(NodeId, Vec<Node>)>) -> Result<(), DocError> {
|
||||
let anchors: Vec<NodeId> = items.iter().map(|(id, _)| *id).collect();
|
||||
let places = self.places(&anchors)?;
|
||||
let mut lists: Vec<Vec<Node>> = items.into_iter().map(|(_, nodes)| nodes).collect();
|
||||
self.edit_children(places, |k, anchor, children| {
|
||||
let nodes = lists.get_mut(k).map(std::mem::take).unwrap_or_default();
|
||||
children.extend(nodes.into_iter().map(Arc::new));
|
||||
children.push(anchor);
|
||||
})?;
|
||||
self.index.clear();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Where each of `ids` is ([`Places`]). Fails with `NoNode` for an id that is not in the tree,
|
||||
/// is listed twice or lies inside another listed node.
|
||||
fn places(&self, ids: &[NodeId]) -> Result<Places, DocError> {
|
||||
|
||||
+241
-20
@@ -78,6 +78,9 @@ pub struct HitOptions {
|
||||
/// Off, the empty part of the frame (away from its edge and its lines of type) takes no
|
||||
/// clicks, so they reach the art behind (#7274).
|
||||
pub area_type_interior: bool,
|
||||
/// The point hit tests ([`hit_test`], [`hit_test_visible`] and [`hit_test_visible_skipping`])
|
||||
/// hit the art on a layer whose Preview is off as painted, not in outline.
|
||||
pub ignore_layer_preview: bool,
|
||||
}
|
||||
|
||||
impl Default for HitOptions {
|
||||
@@ -90,6 +93,7 @@ impl Default for HitOptions {
|
||||
skip_guides: false,
|
||||
clip_outlines: false,
|
||||
area_type_interior: false,
|
||||
ignore_layer_preview: false,
|
||||
scope: None,
|
||||
}
|
||||
}
|
||||
@@ -111,6 +115,36 @@ pub fn set_image_paint(f: ImagePaint) {
|
||||
let _ = IMAGE_PAINT.set(f);
|
||||
}
|
||||
|
||||
/// Adds the geometry and raster effects of a symbol instance's active fill and stroke to the fills
|
||||
/// and strokes that paint in the art it is given, the instance's art in the symbol's coordinates,
|
||||
/// as the canvas adds them to the art it draws. Every object keeps its place in the art, so the
|
||||
/// child indices of [`symbol_part_at`] still lead to it. Effects are evaluated above this crate, so
|
||||
/// the engine registers one with [`set_instance_row_art`].
|
||||
pub type InstanceRowArt = fn(Option<&Document>, &Node, &mut Node);
|
||||
|
||||
static INSTANCE_ROW_ART: OnceLock<InstanceRowArt> = OnceLock::new();
|
||||
|
||||
/// Register how a symbol instance's art takes the effects of the instance's fill and stroke, for
|
||||
/// Direct Selection's parts (the first registration stays).
|
||||
pub fn set_instance_row_art(f: InstanceRowArt) {
|
||||
// Already set: the same engine, registered by another session.
|
||||
let _ = INSTANCE_ROW_ART.set(f);
|
||||
}
|
||||
|
||||
/// Does a symbol instance's active fill or stroke carry a visible geometry effect, which the art it
|
||||
/// places takes on each of its fills and strokes ([`set_instance_row_art`])? Effects are classified
|
||||
/// above this crate, so the engine registers one with [`set_instance_reshapes`].
|
||||
pub type InstanceReshapes = fn(&Node) -> bool;
|
||||
|
||||
static INSTANCE_RESHAPES: OnceLock<InstanceReshapes> = OnceLock::new();
|
||||
|
||||
/// Register how Direct Selection tells whether a symbol instance's fill or stroke effects reshape
|
||||
/// its art (the first registration stays).
|
||||
pub fn set_instance_reshapes(f: InstanceReshapes) {
|
||||
// Already set: the same engine, registered by another session.
|
||||
let _ = INSTANCE_RESHAPES.set(f);
|
||||
}
|
||||
|
||||
/// The shapes that [`ImagePaint`] gives for one object.
|
||||
type Painted = Vec<(BezPath, FillRule, AppearanceItem)>;
|
||||
|
||||
@@ -847,7 +881,7 @@ fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(No
|
||||
continue;
|
||||
}
|
||||
chain.push(layer.id);
|
||||
let opt = if matches!(layer.kind, NodeKind::Layer { preview: false, .. }) { HitOptions { outline: true, ..opt } } else { opt };
|
||||
let opt = if !opt.ignore_layer_preview && previews_off(layer) { HitOptions { outline: true, ..opt } } else { opt };
|
||||
if let Some(h) = hit_children(layer, p, opt, &symbols, skip, &mut chain, editable_only) {
|
||||
return Some(finish(h));
|
||||
}
|
||||
@@ -1211,7 +1245,9 @@ fn hit_children(
|
||||
chain.push(c.id);
|
||||
let hit = plain(i == 0 && clip.is_some(), || match &c.kind {
|
||||
// A sublayer whose Preview is off is clicked in outline, like an outline view.
|
||||
NodeKind::Layer { preview: false, .. } => hit_children(c, p, HitOptions { outline: true, ..opt }, symbols, skip, chain, editable_only),
|
||||
NodeKind::Layer { preview: false, .. } if !opt.ignore_layer_preview => {
|
||||
hit_children(c, p, HitOptions { outline: true, ..opt }, symbols, skip, chain, editable_only)
|
||||
}
|
||||
NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Intertwine { .. } => {
|
||||
hit_children(c, p, opt, symbols, skip, chain, editable_only)
|
||||
}
|
||||
@@ -1325,7 +1361,7 @@ fn art_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, accept: &
|
||||
match &n.kind {
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } | NodeKind::Intertwine { children } => {
|
||||
// A layer with Preview off is clicked in outline, as [`hit_children`] clicks it.
|
||||
let opt = HitOptions { outline: opt.outline || previews_off(n), ..opt };
|
||||
let opt = HitOptions { outline: opt.outline || !opt.ignore_layer_preview && previews_off(n), ..opt };
|
||||
if n.clips()
|
||||
&& let Some(clip) = children.first()
|
||||
{
|
||||
@@ -1569,12 +1605,67 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
/// symbol instance) paint with their geometry effects ([`image_paint`]), the frontmost first: a
|
||||
/// stroke along its shape, a fill inside it except with Selection by Path Only.
|
||||
fn hit_painted(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option<HitKind> {
|
||||
image_paint(Some(symbols.document()), n).iter().rev().find_map(|(bp, rule, item)| match item {
|
||||
painted_hit(&image_paint(Some(symbols.document()), n), p, opt)
|
||||
}
|
||||
|
||||
/// What a click at `p` hits among `painted`, the shapes [`image_paint`] gives, as [`hit_painted`]
|
||||
/// tests them.
|
||||
fn painted_hit(painted: &Painted, p: Point, opt: HitOptions) -> Option<HitKind> {
|
||||
painted.iter().rev().find_map(|(bp, rule, item)| match item {
|
||||
AppearanceItem::Stroke(s) => s.hits(bp, *rule, p, opt.tol).then_some(HitKind::Stroke),
|
||||
AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill),
|
||||
})
|
||||
}
|
||||
|
||||
/// Is `n` a symbol instance whose active fill or stroke has a visible geometry effect, which
|
||||
/// reshapes the art it draws ([`set_instance_reshapes`])? This holds whatever that art is, clip
|
||||
/// groups and type included. Callers ask [`own_effects_art`] first, which takes an instance whose
|
||||
/// own effects change what it draws; an instance whose own effects add only pixels (a drop shadow)
|
||||
/// is tested here. Never with `outline`, where the canvas draws no effects, nor while a
|
||||
/// [`DrawnOff`] guard lives, nor while nothing is registered.
|
||||
fn reshapes_instance_art(n: &Node, outline: bool) -> bool {
|
||||
!outline
|
||||
&& !DRAWN_OFF.get()
|
||||
&& matches!(n.kind, NodeKind::SymbolInstance { .. })
|
||||
&& n.appearance.items.iter().any(|i| !i.effects().is_empty())
|
||||
&& INSTANCE_RESHAPES.get().is_some_and(|f| f(n))
|
||||
}
|
||||
|
||||
/// How many objects `n` holds with its opacity masks' art ([`Node::count_with_masks`]), what
|
||||
/// testing or outlining it takes from the [`ArtWalk`] limit.
|
||||
fn walk_size(n: &Node) -> u64 {
|
||||
u64::try_from(n.count_with_masks()).unwrap_or(u64::MAX)
|
||||
}
|
||||
|
||||
/// The art that symbol instance `n` draws with a visible effect of its own, the effects of its
|
||||
/// fills and strokes and those of its symbol's art all applied, or that type `n` draws with the
|
||||
/// visible effects of its own and of its fills and strokes, as outlined paths ([`set_drawn_art`]).
|
||||
/// `None` for other objects, with `outline`, where the canvas draws no effects, for an instance or
|
||||
/// type without such an effect, while a [`DrawnOff`] guard lives, and when no geometry effect
|
||||
/// changes what it draws. Evaluating the art is work that walking it does not count, so the art
|
||||
/// takes its objects from the [`ArtWalk`] limit of the click or outline under way, and the walk of
|
||||
/// it takes them again. Once the limit is used up, the result is `Some` of an empty group, which
|
||||
/// hits and outlines nothing, and no more art is evaluated.
|
||||
fn own_effects_art(n: &Node, symbols: &SymbolBoxes, outline: bool) -> Option<Node> {
|
||||
let has = match n.kind {
|
||||
NodeKind::SymbolInstance { .. } => n.appearance.effects.iter().any(|e| e.visible),
|
||||
NodeKind::Text(_) => has_own_effects(n),
|
||||
_ => false,
|
||||
};
|
||||
if outline || DRAWN_OFF.get() || !has || DRAWN_ART.get().is_none() {
|
||||
return None;
|
||||
}
|
||||
let nothing = || Some(Node::group(n.id, vec![]));
|
||||
if ArtWalk::used_up() {
|
||||
return nothing();
|
||||
}
|
||||
let art = DRAWN_ART.get()?(symbols, n)?;
|
||||
if !ArtWalk::take(walk_size(&art)) {
|
||||
return nothing();
|
||||
}
|
||||
Some(art)
|
||||
}
|
||||
|
||||
/// Is `p` within `tol` of the type path of `t` (in `n`), what "Type Object Selection by Path
|
||||
/// Only" picks type by: its baselines ([`crate::TextObject::baselines`]), area type's frame and
|
||||
/// type on a path's path, drawn through `n`'s perspective projection if it has one.
|
||||
@@ -1684,6 +1775,41 @@ impl<'a> InstanceArt<'a> {
|
||||
Some(Self { art, map, xf: *xf, boxes })
|
||||
}
|
||||
|
||||
/// [`Self::of`] with the effects of the instance's active fill and stroke added to the fills and
|
||||
/// strokes in the art ([`set_instance_row_art`]), so that each object of it is tested and
|
||||
/// outlined where the canvas draws it. Not with `outline`, where the canvas draws no effects.
|
||||
fn drawn(doc: &'a Document, inst: &Node, outline: bool) -> Option<Self> {
|
||||
let mut art = Self::of(doc, inst)?;
|
||||
#[cfg(test)]
|
||||
ARTS_WALKED.with(|c| c.set(c.get() + 1));
|
||||
if !outline && let Some(f) = INSTANCE_ROW_ART.get() {
|
||||
f(Some(doc), inst, &mut art.art);
|
||||
}
|
||||
Some(art)
|
||||
}
|
||||
|
||||
/// [`Self::drawn`] for symbol instance `inst` in the art of another instance, outside Outline.
|
||||
/// Copying the art and adding the effects to it is work that walking it does not count, so the
|
||||
/// art takes as many objects as placing it makes ([`Self::size`]) from the [`ArtWalk`] limit of
|
||||
/// the click or outline under way before it is copied, as the marquee takes the art it places,
|
||||
/// and the walk of it takes its objects again. `None` once fewer are left.
|
||||
fn nested(doc: &'a Document, inst: &Node) -> Option<Self> {
|
||||
if ArtWalk::used_up() {
|
||||
return None;
|
||||
}
|
||||
let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return None };
|
||||
let boxes = doc.symbol_boxes().quick();
|
||||
let source = boxes.symbol_art(symbol)?;
|
||||
let size = match boxes.slice_map(symbol, *xf) {
|
||||
Some(m) => m.most_placed_with(source, &boxes),
|
||||
None => walk_size(source),
|
||||
};
|
||||
if !ArtWalk::take(size) {
|
||||
return None;
|
||||
}
|
||||
Self::drawn(doc, inst, false)
|
||||
}
|
||||
|
||||
/// The map that the objects inside group or layer `n` are moved by as one piece: `whole`, the
|
||||
/// map of an object around `n` that is moved as one piece, or else the map of the 9-slice cell
|
||||
/// `n` lies in ([`crate::NineSliceMap::one_cell`]). `None` when `n` is placed through the guides
|
||||
@@ -1745,15 +1871,18 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node {
|
||||
/// [`HitOptions::skip_guides`]. Nothing is picked in art that placing through the symbol's 9-slice
|
||||
/// guides could make more than [`crate::MAX_SYMBOL_NODES`] objects of, which the canvas does not
|
||||
/// draw. Art in a layer of the symbol whose Preview is off, and the art of an instance below such a
|
||||
/// layer, is tested in outline ([`HitOptions::outline`]), as the canvas draws it. `None` when `inst` is not a symbol instance or
|
||||
/// no editable object of its art is under `p`.
|
||||
/// layer, is tested in outline ([`HitOptions::outline`]), as the canvas draws it. Elsewhere each
|
||||
/// object is tested where the geometry effects of the instance's active fill and stroke draw it
|
||||
/// ([`InstanceArt::drawn`]), and not where its own shape no longer paints. Live objects in the art
|
||||
/// (blends, envelopes, repeats) are tested without those effects. `None` when `inst` is not a
|
||||
/// symbol instance or no editable object of its art is under `p`.
|
||||
pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option<Vec<u32>> {
|
||||
let _walk = ArtWalk::open();
|
||||
let art = InstanceArt::of(doc, inst)?;
|
||||
let outline = opt.outline || below_preview_off(doc, inst, opt.scope);
|
||||
let art = InstanceArt::drawn(doc, inst, outline)?;
|
||||
let symbols = doc.kept_symbol_boxes();
|
||||
let mut path = vec![];
|
||||
let outline = opt.outline || below_preview_off(doc, inst, opt.scope);
|
||||
let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false };
|
||||
let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false, drawn: true };
|
||||
find.find(&art.art, &mut path, None, outline).map(|_| path)
|
||||
}
|
||||
|
||||
@@ -1766,14 +1895,35 @@ struct FindPart<'a> {
|
||||
/// For [`instance_art_hit`]: locked and template objects of the art count, as the canvas draws
|
||||
/// them, and clipping paths are not picked by their outline.
|
||||
whole_instance: bool,
|
||||
/// For [`symbol_part_at`] and [`drawn_instance_hit`]: the art carries the effects of the
|
||||
/// instance's active fill and stroke ([`InstanceArt::drawn`]).
|
||||
drawn: bool,
|
||||
}
|
||||
|
||||
impl FindPart<'_> {
|
||||
/// What a click at `p` hits on object `n` of the art, placed. [`hit_any`] takes `n` and each
|
||||
/// object it visits inside `n` from the [`ArtWalk`] limit.
|
||||
/// object it visits inside `n` from the [`ArtWalk`] limit. In drawn art, a symbol instance with
|
||||
/// geometry effects of its own, and type whose own effects or fill and stroke effects (its own,
|
||||
/// or those the outer instance adds) reshape it, are hit only where the art they draw is
|
||||
/// ([`own_effects_art`]), and an instance whose fill or stroke has geometry effects that reshape
|
||||
/// its art (its own, or those the outer instance passes on) only where its art is drawn with
|
||||
/// them ([`drawn_instance_hit`]); not anywhere in their bounds. With Type Object Selection by
|
||||
/// Path Only ([`HitOptions::type_path_only`]), type is still picked by its type path.
|
||||
fn hit(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>, opt: HitOptions) -> Option<HitKind> {
|
||||
let placed = self.art.place(n, whole)?;
|
||||
let _charged = ArtWalk::charge();
|
||||
// Type Object Selection by Path Only picks type by its type path, whatever its effects draw.
|
||||
let type_path = opt.type_path_only && matches!(placed.kind, NodeKind::Text(_));
|
||||
if self.drawn && !type_path {
|
||||
if let Some(art) = own_effects_art(&placed, self.symbols, opt.outline) {
|
||||
let _off = DrawnOff::set();
|
||||
let _art_only = ArtOnly::set();
|
||||
return hit_any(&art, self.p, opt, self.symbols);
|
||||
}
|
||||
if reshapes_instance_art(&placed, opt.outline) {
|
||||
return drawn_instance_hit(&placed, self.p, opt, self.symbols);
|
||||
}
|
||||
}
|
||||
hit_any(&placed, self.p, opt, self.symbols)
|
||||
}
|
||||
|
||||
@@ -1787,7 +1937,7 @@ impl FindPart<'_> {
|
||||
if !n.visible || !self.whole_instance && (n.locked || n.is_template()) || self.skips_guide(n) || ArtWalk::used_up() {
|
||||
return None;
|
||||
}
|
||||
let outline = outline || previews_off(n);
|
||||
let outline = outline || !self.opt.ignore_layer_preview && previews_off(n);
|
||||
let opt = HitOptions { outline, ..self.opt };
|
||||
let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return self.hit(n, whole, opt) };
|
||||
if path.len() >= crate::symbol_overrides::MAX_PATH_DEPTH {
|
||||
@@ -1852,7 +2002,26 @@ fn instance_art_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes)
|
||||
ARTS_WALKED.with(|c| c.set(c.get() + 1));
|
||||
let opt = HitOptions { clip_outlines: false, ..opt };
|
||||
let _art_only = ArtOnly::set();
|
||||
FindPart { art: &art, p, opt, symbols, whole_instance: true }.find(&art.art, &mut vec![], None, false)
|
||||
FindPart { art: &art, p, opt, symbols, whole_instance: true, drawn: false }.find(&art.art, &mut vec![], None, false)
|
||||
}
|
||||
|
||||
/// What a click at `p` hits of symbol instance `n`, an object of another instance's drawn art,
|
||||
/// where the canvas draws `n`'s art with the geometry effects of `n`'s active fill and stroke
|
||||
/// ([`InstanceArt::drawn`]): each object of that art where it is drawn, paths, images and type
|
||||
/// alike, and not anywhere in `n`'s box. Locked and template objects of the art count, as in
|
||||
/// [`instance_art_hit`]. `None` for an instance of a missing symbol, of a symbol that holds an
|
||||
/// instance of itself or nests too deep ([`SymbolBoxes::art`]), of art past the 9-slice object
|
||||
/// limit ([`InstanceArt::of`]), and once the click has visited as many objects of symbol art as
|
||||
/// [`ArtWalk`] allows.
|
||||
fn drawn_instance_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option<HitKind> {
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return None };
|
||||
if symbols.art(symbol).is_none() || ArtWalk::used_up() {
|
||||
return None;
|
||||
}
|
||||
let art = InstanceArt::nested(symbols.document(), n)?;
|
||||
let opt = HitOptions { clip_outlines: false, ..opt };
|
||||
let _art_only = ArtOnly::set();
|
||||
FindPart { art: &art, p, opt, symbols, whole_instance: true, drawn: true }.find(&art.art, &mut vec![], None, false)
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
@@ -2002,15 +2171,21 @@ pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option<
|
||||
/// instance (the isolated container [`HitOptions::scope`] and the layers around it apart), the
|
||||
/// outlines are cut to the bounds of the plain clipping paths, without their live effects, as
|
||||
/// [`symbol_part_at`] counts them. The outline is empty when the effects of a clipping path around
|
||||
/// the object leave no region.
|
||||
/// the object leave no region. Elsewhere the outlines follow the geometry effects of the instance's
|
||||
/// active fill and stroke, as [`symbol_part_at`] does. Outlining visits at most as many objects of
|
||||
/// symbol art as one click does ([`ArtWalk`]), the art of the instances nested in the part included,
|
||||
/// and leaves out what is past that limit.
|
||||
pub fn symbol_part_outline_in_view(doc: &Document, inst: &Node, path: &[u32], opt: HitOptions) -> Option<BezPath> {
|
||||
let art = InstanceArt::of(doc, inst)?;
|
||||
let part = crate::symbol_overrides::part(&art.art, path)?;
|
||||
let _walk = ArtWalk::open();
|
||||
let mut outline = opt.outline || below_preview_off(doc, inst, opt.scope);
|
||||
let art = InstanceArt::drawn(doc, inst, outline)?;
|
||||
let part = crate::symbol_overrides::part(&art.art, path)?;
|
||||
let symbols = doc.kept_symbol_boxes();
|
||||
let mut out = BezPath::new();
|
||||
let mut limit = None;
|
||||
let mut whole = None;
|
||||
let mut n = &art.art;
|
||||
let mut mask = false;
|
||||
for &i in path {
|
||||
let children = n.children()?;
|
||||
whole = art.whole(n, whole);
|
||||
@@ -2022,9 +2197,12 @@ pub fn symbol_part_outline_in_view(doc: &Document, inst: &Node, path: &[u32], op
|
||||
let Some(within) = limit_within(&art.place_unclipped(first, whole)?, limit, outline) else { return Some(out) };
|
||||
limit = within;
|
||||
}
|
||||
mask = i == 0 && n.clips();
|
||||
n = children.get(usize::try_from(i).ok()?)?;
|
||||
}
|
||||
outline_within(&art.place(part, whole)?, limit, outline, &mut out);
|
||||
// A clipping path is picked by its own geometry ([`FindPart::find`]), and outlined so.
|
||||
let placed = art.place(part, whole)?;
|
||||
plain(mask, || outline_within(&placed, &symbols, limit, outline, &mut out));
|
||||
Some(out)
|
||||
}
|
||||
|
||||
@@ -2046,9 +2224,42 @@ fn limit_within(clip: &Node, limit: Option<Rect>, outline: bool) -> Option<Optio
|
||||
}
|
||||
}
|
||||
|
||||
/// [`symbol_part_outline_in_view`] for placed object `n`, cut to `limit` when there is one.
|
||||
fn outline_within(n: &Node, limit: Option<Rect>, outline: bool, out: &mut BezPath) {
|
||||
/// [`symbol_part_outline_in_view`] for placed object `n`, cut to `limit` when there is one. A path
|
||||
/// or compound path whose geometry effects reshape it is outlined as the art they draw
|
||||
/// ([`drawn_art`]), a symbol instance with geometry effects of its own and type whose effects
|
||||
/// reshape it as the art they draw ([`own_effects_art`]), and a symbol instance whose fill or
|
||||
/// stroke effects reshape its art as that art drawn with them ([`InstanceArt::drawn`]), as
|
||||
/// [`FindPart`] tests them, except with `outline` and while a [`DrawnOff`] guard lives. Each object
|
||||
/// visited takes one object of the [`ArtWalk`] limit, and nothing more is outlined once the limit
|
||||
/// is used up. A hidden object and what it holds are not outlined, as [`FindPart`] passes over them.
|
||||
fn outline_within(n: &Node, symbols: &SymbolBoxes, limit: Option<Rect>, outline: bool, out: &mut BezPath) {
|
||||
use vectorcraft_geom::kurbo::Shape;
|
||||
if !n.visible || !ArtWalk::take(1) {
|
||||
return;
|
||||
}
|
||||
if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
|
||||
&& let Some(art) = drawn_art(symbols, n, outline)
|
||||
{
|
||||
let _off = DrawnOff::set();
|
||||
art.iter().for_each(|a| outline_within(a, symbols, limit, outline, out));
|
||||
return;
|
||||
}
|
||||
if let Some(art) = own_effects_art(n, symbols, outline) {
|
||||
let _off = DrawnOff::set();
|
||||
outline_within(&art, symbols, limit, outline, out);
|
||||
return;
|
||||
}
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind
|
||||
&& reshapes_instance_art(n, outline)
|
||||
{
|
||||
if symbols.art(symbol).is_some()
|
||||
&& let Some(art) = InstanceArt::nested(symbols.document(), n)
|
||||
&& let Some(placed) = art.place(&art.art, None)
|
||||
{
|
||||
outline_within(&placed, symbols, limit, outline, out);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if let Some(pd) = n.path_data() {
|
||||
match limit {
|
||||
Some(r) => push_cut(out, &pd.to_bezpath(), r),
|
||||
@@ -2060,16 +2271,26 @@ fn outline_within(n: &Node, limit: Option<Rect>, outline: bool, out: &mut BezPat
|
||||
{
|
||||
out.extend(b.to_path(0.1));
|
||||
}
|
||||
// An image is also outlined where its own fills and strokes paint with their effects, as
|
||||
// [`hit_leaf`] picks it there ([`image_paint`]).
|
||||
if !outline && matches!(n.kind, NodeKind::Image(_)) {
|
||||
for (bp, ..) in image_paint(Some(symbols.document()), n).iter() {
|
||||
match limit {
|
||||
Some(r) => push_cut(out, bp, r),
|
||||
None => out.extend(bp.iter()),
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(children) = n.children() else { return };
|
||||
let outline = outline || previews_off(n);
|
||||
if n.clips()
|
||||
&& let Some((first, rest)) = children.split_first()
|
||||
{
|
||||
let Some(inner) = limit_within(first, limit, outline) else { return };
|
||||
rest.iter().for_each(|c| outline_within(c, inner, outline, out));
|
||||
rest.iter().for_each(|c| outline_within(c, symbols, inner, outline, out));
|
||||
return;
|
||||
}
|
||||
children.iter().for_each(|c| outline_within(c, limit, outline, out));
|
||||
children.iter().for_each(|c| outline_within(c, symbols, limit, outline, out));
|
||||
}
|
||||
|
||||
/// The overlap of `a` and `b` (`a` alone without `b`), `None` when they do not overlap.
|
||||
|
||||
+143
-3
@@ -1324,11 +1324,11 @@ fn evaluated_art_is_not_kept_while_a_placed_document_may_show_in_it() {
|
||||
assert_eq!(evaluated(), before + 2);
|
||||
}
|
||||
|
||||
/// For instances of the symbol "Painted", a fill that paints the square from (300, 0) to
|
||||
/// (320, 20); nothing for anything else.
|
||||
/// For instances of the symbols whose names start with "Painted", a fill that paints the square
|
||||
/// from (300, 0) to (320, 20); nothing for anything else.
|
||||
fn painted_far_away(_: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> {
|
||||
match &n.kind {
|
||||
NodeKind::SymbolInstance { symbol, .. } if symbol == "Painted" => {
|
||||
NodeKind::SymbolInstance { symbol, .. } if symbol.starts_with("Painted") => {
|
||||
let square = shapes::rectangle(Rect::new(300.0, 0.0, 320.0, 20.0)).to_bezpath();
|
||||
vec![(square, FillRule::NonZero, AppearanceItem::Fill(crate::FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0)))))]
|
||||
}
|
||||
@@ -1463,6 +1463,7 @@ const SELECTING: HitOptions = HitOptions {
|
||||
skip_guides: false,
|
||||
clip_outlines: true,
|
||||
area_type_interior: false,
|
||||
ignore_layer_preview: false,
|
||||
scope: None,
|
||||
};
|
||||
|
||||
@@ -2830,6 +2831,32 @@ fn a_symbol_instance_is_hit_on_the_stroke_of_its_art_past_its_box() {
|
||||
assert_eq!(at(108.0, HitOptions { outline: true, ..HitOptions::default() }), None, "Outline view");
|
||||
}
|
||||
|
||||
/// A symbol's art on a layer of the symbol whose Preview is off is hit in outline, unless the
|
||||
/// click sets [`HitOptions::ignore_layer_preview`]: then the stroke past the instance's box hits.
|
||||
#[test]
|
||||
fn ignore_layer_preview_reaches_symbol_art_on_a_preview_off_layer() {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
// A 20 pt stroke reaches 10 pt past the 0..100 square.
|
||||
let look = Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 20.0);
|
||||
let square = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), look);
|
||||
let mut layer = Node::layer(d.alloc_id(), "Art", crate::LayerColor::Preset(2));
|
||||
if let NodeKind::Layer { children, preview, .. } = &mut layer.kind {
|
||||
*children = vec![Arc::new(square)];
|
||||
*preview = false;
|
||||
}
|
||||
let art = Node::group(d.alloc_id(), vec![Arc::new(layer)]);
|
||||
d.symbols.push(crate::Symbol { dynamic: false, name: "Stroked".into(), art: Arc::new(art) });
|
||||
let inst = d.alloc_id();
|
||||
let xf = vectorcraft_geom::Affine::IDENTITY;
|
||||
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Stroked".into(), xf })).unwrap();
|
||||
let at = |x: f64, opt: HitOptions| hit_test(&d, Point::new(x, 50.0), opt).map(|h| h.leaf);
|
||||
let painted = HitOptions { ignore_layer_preview: true, ..HitOptions::default() };
|
||||
assert_eq!(at(108.0, HitOptions::default()), None, "Preview off: in outline");
|
||||
assert_eq!(at(108.0, painted), Some(inst), "ignore_layer_preview: on the stroke past the box");
|
||||
assert_eq!(at(116.0, painted), None, "past the stroke");
|
||||
}
|
||||
|
||||
/// Outside a symbol instance's box, an instance nested in its art counts where its own art is, not
|
||||
/// anywhere in its box: a click or a marquee on empty space in the nested box, where a moved
|
||||
/// clipping path shows the art past the outer box, selects nothing, and on art drawn there it
|
||||
@@ -3040,6 +3067,119 @@ fn a_click_counts_the_members_of_an_intertwine_group_in_symbol_art_toward_one_li
|
||||
assert_eq!(with_art_limit(100, || at(140.0)).0, Some(id), "on the squares' paths");
|
||||
}
|
||||
|
||||
/// Whether a symbol instance's fill or stroke effects reshape its art, for these tests: when
|
||||
/// [`painted_far_away`] gives it shapes.
|
||||
fn reshapes_when_painted(n: &Node) -> bool {
|
||||
!painted_far_away(None, n).is_empty()
|
||||
}
|
||||
|
||||
/// An instance of the symbol named `symbol`, not moved, whose fill has a geometry effect:
|
||||
/// [`reshapes_when_painted`] holds for it when the name starts with "Painted", so a part pick and a
|
||||
/// part outline walk its art as drawn with its fill's effects ([`InstanceArt::drawn`]).
|
||||
fn painted_instance_of(d: &mut Document, symbol: &str) -> Arc<Node> {
|
||||
let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: symbol.into(), xf: vectorcraft_geom::Affine::IDENTITY });
|
||||
n.appearance = Appearance::default_art().into();
|
||||
let offset = crate::Effect { id: "path.offsetPath".into(), params: serde_json::json!({"offset": 10}), visible: true };
|
||||
n.appearance.items[0].effects_mut().push(offset);
|
||||
Arc::new(n)
|
||||
}
|
||||
|
||||
/// Five levels of symbols: "Painted 0" is a 1 pt square, and each level above holds 8 instances
|
||||
/// of the level below whose fills have a geometry effect. Returns the id of an instance of
|
||||
/// "Painted 4" on the layer.
|
||||
fn painted_chain(d: &mut Document) -> NodeId {
|
||||
let l = d.layers[0].id;
|
||||
let dot = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art());
|
||||
d.symbols.push(crate::Symbol { dynamic: false, name: "Painted 0".into(), art: Arc::new(dot) });
|
||||
for level in 1..5 {
|
||||
let members = (0..8).map(|_| painted_instance_of(d, &format!("Painted {}", level - 1))).collect();
|
||||
group_symbol(d, &format!("Painted {level}"), members);
|
||||
}
|
||||
let inst = instance_of(d, "Painted 4");
|
||||
let id = inst.id;
|
||||
d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
/// The outline of a part of a dynamic symbol's instance visits at most the art walk's limit of
|
||||
/// objects, though the part is an instance whose art, drawn with its fill's effects, nests
|
||||
/// instances 3 levels deep, 8 at each level. Within the limit every square is outlined.
|
||||
#[test]
|
||||
fn a_parts_outline_walks_nested_reshaped_symbol_instances_within_one_limit() {
|
||||
set_image_paint(painted_far_away);
|
||||
set_instance_reshapes(reshapes_when_painted);
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
let id = painted_chain(&mut d);
|
||||
let n = d.node(id).unwrap();
|
||||
let squares = |o: &BezPath| o.elements().iter().filter(|e| matches!(e, vectorcraft_geom::kurbo::PathEl::MoveTo(_))).count();
|
||||
// Part [0] is an instance of "Painted 3": 8 × 8 × 8 squares.
|
||||
assert_eq!(squares(&symbol_part_outline(&d, n, &[0]).unwrap()), 512, "within the limit");
|
||||
let (outline, _, arts) = with_art_limit(100, || symbol_part_outline(&d, n, &[0]).unwrap());
|
||||
assert!(squares(&outline) < 100, "{} squares outlined", squares(&outline));
|
||||
assert!(arts < 100, "{arts} instances' art walked");
|
||||
}
|
||||
|
||||
/// A part pick in a dynamic symbol's instance visits at most the art walk's limit of objects of
|
||||
/// nested instances whose art, drawn with their fills' effects, is walked: in a chain of nested
|
||||
/// instances, and in instances whose clip groups the click misses, where only the clip group
|
||||
/// itself is tested. A click on the clipped art of a nested instance is still found.
|
||||
#[test]
|
||||
fn a_part_pick_walks_nested_reshaped_symbol_instances_within_one_limit() {
|
||||
set_image_paint(painted_far_away);
|
||||
set_instance_reshapes(reshapes_when_painted);
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
let id = painted_chain(&mut d);
|
||||
let opt = HitOptions::default();
|
||||
let (hit, _, arts) = with_art_limit(100, || symbol_part_at(&d, d.node(id).unwrap(), Point::new(150.0, 50.0), opt));
|
||||
assert_eq!(hit, None);
|
||||
assert!(arts <= 40, "chain: {arts} instances' art walked");
|
||||
// 30 instances of a clip group whose 10 pt clipping path holds 40 squares: 42 objects each.
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
let mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default());
|
||||
let mut members = vec![Arc::new(mask)];
|
||||
members.extend((0..40).map(|_| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art()))));
|
||||
let mut clip = Node::group(d.alloc_id(), members);
|
||||
clip.set_clips(true);
|
||||
d.symbols.push(crate::Symbol { dynamic: false, name: "Painted clip".into(), art: Arc::new(clip) });
|
||||
let members = (0..30).map(|_| painted_instance_of(&mut d, "Painted clip")).collect();
|
||||
group_symbol(&mut d, "Clips", members);
|
||||
let inst = instance_of(&mut d, "Clips");
|
||||
let id = inst.id;
|
||||
d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap();
|
||||
let n = d.node(id).unwrap();
|
||||
let (hit, _, arts) = with_art_limit(300, || symbol_part_at(&d, n, Point::new(150.0, 50.0), opt));
|
||||
assert_eq!(hit, None);
|
||||
assert!(arts <= 8, "clip groups: {arts} instances' art walked");
|
||||
assert_eq!(with_art_limit(300, || symbol_part_at(&d, n, Point::new(2.0, 2.0), opt)).0, Some(vec![29]), "the clipped art");
|
||||
}
|
||||
|
||||
/// The outline of a part of a dynamic symbol's instance leaves out the hidden objects in the art of
|
||||
/// an instance nested in the part whose fill's effects reshape it, as a part pick passes over them.
|
||||
#[test]
|
||||
fn a_parts_outline_leaves_out_hidden_art_of_nested_reshaped_symbol_instances() {
|
||||
use vectorcraft_geom::kurbo::Shape;
|
||||
set_image_paint(painted_far_away);
|
||||
set_instance_reshapes(reshapes_when_painted);
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
let shown = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art());
|
||||
let mut hidden = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(50.0, 50.0, 60.0, 60.0)), Appearance::default_art());
|
||||
hidden.visible = false;
|
||||
group_symbol(&mut d, "Painted hidden", vec![Arc::new(shown), Arc::new(hidden)]);
|
||||
let member = painted_instance_of(&mut d, "Painted hidden");
|
||||
group_symbol(&mut d, "Hides", vec![member]);
|
||||
let inst = instance_of(&mut d, "Hides");
|
||||
let id = inst.id;
|
||||
d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap();
|
||||
let n = d.node(id).unwrap();
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(55.0, 55.0), HitOptions::default()), None, "the hidden square is not picked");
|
||||
let outline = symbol_part_outline(&d, n, &[0]).unwrap();
|
||||
let squares = outline.elements().iter().filter(|e| matches!(e, vectorcraft_geom::kurbo::PathEl::MoveTo(_))).count();
|
||||
assert_eq!(squares, 1, "only the shown square is outlined");
|
||||
assert!(outline.bounding_box().x1 <= 1.0, "the outline reaches {:?}", outline.bounding_box());
|
||||
}
|
||||
|
||||
/// In a dynamic symbol's art that placing through its 9-slice guides could make more than
|
||||
/// [`crate::MAX_SYMBOL_NODES`] objects of, Direct Selection picks and outlines nothing, as the
|
||||
/// canvas draws nothing of it. At the art's natural size the same art is picked.
|
||||
|
||||
@@ -392,6 +392,11 @@ mod tests {
|
||||
assert_eq!(n.image_quad(), None);
|
||||
assert!(distorted_art(&n).is_none());
|
||||
assert_eq!(n.image_corners(), Some(rect_corners(Rect::new(0.0, 0.0, 100.0, 100.0))));
|
||||
// Reading the file drops it, so a later transform can't make it a distortion.
|
||||
let mut back: Node = serde_json::from_value(serde_json::to_value(&n).unwrap()).unwrap();
|
||||
assert!(back.extras().image_quad.is_none());
|
||||
back.transform(Affine::scale_non_uniform(1e6, 1.0), false);
|
||||
assert!(!back.is_distorted_image());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -474,6 +479,50 @@ mod tests {
|
||||
assert_eq!(read.image_quad(), Some(q));
|
||||
}
|
||||
|
||||
/// An entry among the first four that is not a point, or a field that is not a list, drops the
|
||||
/// corners and leaves the rest of the image read; the entries after a bad one are skipped.
|
||||
#[test]
|
||||
fn malformed_corners_a_file_holds_are_dropped_as_it_is_read() {
|
||||
let n = image(100, 100);
|
||||
let plain: Node = serde_json::from_value(serde_json::to_value(&n).unwrap()).unwrap();
|
||||
let bad_entries = [
|
||||
serde_json::json!([[40.0, 0.0], "not a point", [100.0, 100.0], [0.0, 100.0]]),
|
||||
serde_json::json!([[40.0, 0.0], [60.0, 0.0], [100.0, 100.0], {"x": 1}]),
|
||||
serde_json::json!([null, [60.0, 0.0], [100.0, 100.0], [0.0, 100.0]]),
|
||||
serde_json::json!([[40.0, 0.0], [60.0], [100.0, 100.0], [0.0, 100.0], [5.0, 5.0]]),
|
||||
serde_json::json!([[40.0, 0.0], [[1.0, 2.0], 3.0]]),
|
||||
serde_json::json!([[40.0, 0.0], [60.0, 0.0, 1.0], [100.0, 100.0], [0.0, 100.0]]),
|
||||
serde_json::json!([[40.0, 0.0], {"x": 60.0, "y": "0"}, [100.0, 100.0], [0.0, 100.0]]),
|
||||
];
|
||||
let bad_fields = [serde_json::json!("corners"), serde_json::json!(4), serde_json::json!(true), serde_json::json!({"a": [1.0, 2.0]})];
|
||||
for quad in bad_entries.into_iter().chain(bad_fields) {
|
||||
let mut v = serde_json::to_value(&n).unwrap();
|
||||
v["image_quad"] = quad.clone();
|
||||
// File text, so the fields after the corners are read from the same stream.
|
||||
let text = serde_json::to_string(&v).unwrap();
|
||||
let read: Node = serde_json::from_str(&text).unwrap_or_else(|e| panic!("{quad}: {e}"));
|
||||
assert!(read.extras().image_quad.is_none(), "{quad}");
|
||||
assert!(!read.is_distorted_image(), "{quad}");
|
||||
assert_eq!(read, plain, "{quad}");
|
||||
assert_eq!(read.geometric_bounds(), Some(Rect::new(0.0, 0.0, 100.0, 100.0)), "{quad}");
|
||||
}
|
||||
// A point with a repeated coordinate.
|
||||
let mut v = serde_json::to_value(&n).unwrap();
|
||||
v["image_quad"] = serde_json::json!([[40.0, 0.0], "SECOND", [100.0, 100.0], [0.0, 100.0]]);
|
||||
let text = serde_json::to_string(&v).unwrap().replace("\"SECOND\"", r#"{"x":60.0,"y":0.0,"y":1.0}"#);
|
||||
let read: Node = serde_json::from_str(&text).unwrap();
|
||||
assert_eq!(read, plain);
|
||||
// Both forms of a point, whole numbers and unknown fields read as corners, from text and
|
||||
// from a value.
|
||||
let mut v = serde_json::to_value(&n).unwrap();
|
||||
v["image_quad"] = serde_json::json!([[40, 0], {"y": 0.0, "x": 60.0, "z": [1, 2]}, [100.0, 100.0], {"x": 0, "y": 100}]);
|
||||
let q = pts([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
|
||||
let read: Node = serde_json::from_str(&serde_json::to_string(&v).unwrap()).unwrap();
|
||||
assert_eq!(read.image_quad(), Some(q));
|
||||
let read: Node = serde_json::from_value(v).unwrap();
|
||||
assert_eq!(read.image_quad(), Some(q));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refused_corners_change_nothing_and_a_bad_quad_in_a_file_is_ignored() {
|
||||
let mut n = image(10, 10);
|
||||
|
||||
@@ -161,6 +161,9 @@ mod records;
|
||||
mod stored_art;
|
||||
mod units;
|
||||
|
||||
#[cfg(any(test, feature = "locked-artboard-count"))]
|
||||
#[doc(hidden)]
|
||||
pub use artboard::locked_artboard_measures;
|
||||
pub use artboard::{ARTBOARD_GAP, Artboard, ArtboardSide, LockedArtboards, RetiredArtboardId, VIDEO_PIXEL_ASPECT_RANGE, VIDEO_SAFE_INSETS};
|
||||
pub use canvas_range::BeyondCanvas;
|
||||
#[cfg(test)]
|
||||
|
||||
+172
-23
@@ -264,39 +264,188 @@ pub(super) struct NodeWire {
|
||||
}
|
||||
|
||||
/// A distorted image's corners as a file holds them: a list of exactly four points, else none (the
|
||||
/// image is then placed by its transform). At most five points of a longer list are kept while it
|
||||
/// is read.
|
||||
/// image is then placed by its transform). A point is `[x, y]` or `{"x": x, "y": y}`. A value that
|
||||
/// is not a list, or a list with an entry that is not a point, is none too. Values that are not
|
||||
/// taken are skipped as they are read, without being kept in memory, and at most four entries of a
|
||||
/// longer list are decoded.
|
||||
fn image_corners<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<Box<[vectorcraft_geom::Point; 4]>>, D::Error> {
|
||||
use serde::de::{Deserializer, Error, IgnoredAny, MapAccess, SeqAccess, Visitor};
|
||||
use std::fmt::{Formatter, Result as FmtResult};
|
||||
use vectorcraft_geom::Point;
|
||||
|
||||
/// Skips the rest of a list; true when it held another entry.
|
||||
fn rest_of_list<'de, A: SeqAccess<'de>>(mut seq: A) -> Result<bool, A::Error> {
|
||||
let mut more = false;
|
||||
while seq.next_element::<IgnoredAny>()?.is_some() {
|
||||
more = true;
|
||||
}
|
||||
Ok(more)
|
||||
}
|
||||
fn rest_of_map<'de, A: MapAccess<'de>>(mut map: A) -> Result<(), A::Error> {
|
||||
while map.next_entry::<IgnoredAny, IgnoredAny>()?.is_some() {}
|
||||
Ok(())
|
||||
}
|
||||
// The visitors below give none for a value of a kind they do not take.
|
||||
macro_rules! none_for {
|
||||
(scalars) => {
|
||||
fn visit_bool<E: Error>(self, _: bool) -> Result<Self::Value, E> {
|
||||
Ok(None)
|
||||
}
|
||||
fn visit_str<E: Error>(self, _: &str) -> Result<Self::Value, E> {
|
||||
Ok(None)
|
||||
}
|
||||
fn visit_unit<E: Error>(self) -> Result<Self::Value, E> {
|
||||
Ok(None)
|
||||
}
|
||||
fn visit_none<E: Error>(self) -> Result<Self::Value, E> {
|
||||
Ok(None)
|
||||
}
|
||||
};
|
||||
(numbers) => {
|
||||
fn visit_i64<E: Error>(self, _: i64) -> Result<Self::Value, E> {
|
||||
Ok(None)
|
||||
}
|
||||
fn visit_u64<E: Error>(self, _: u64) -> Result<Self::Value, E> {
|
||||
Ok(None)
|
||||
}
|
||||
fn visit_f64<E: Error>(self, _: f64) -> Result<Self::Value, E> {
|
||||
Ok(None)
|
||||
}
|
||||
};
|
||||
(maps $de:lifetime) => {
|
||||
fn visit_map<A: MapAccess<$de>>(self, map: A) -> Result<Self::Value, A::Error> {
|
||||
rest_of_map(map)?;
|
||||
Ok(None)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// A coordinate: a number, else none.
|
||||
struct Coord(Option<f64>);
|
||||
impl<'de> serde::Deserialize<'de> for Coord {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
struct V;
|
||||
impl<'de> Visitor<'de> for V {
|
||||
type Value = Option<f64>;
|
||||
fn expecting(&self, f: &mut Formatter) -> FmtResult {
|
||||
f.write_str("a number")
|
||||
}
|
||||
fn visit_i64<E: Error>(self, v: i64) -> Result<Self::Value, E> {
|
||||
Ok(Some(v as f64))
|
||||
}
|
||||
fn visit_u64<E: Error>(self, v: u64) -> Result<Self::Value, E> {
|
||||
Ok(Some(v as f64))
|
||||
}
|
||||
fn visit_f64<E: Error>(self, v: f64) -> Result<Self::Value, E> {
|
||||
Ok(Some(v))
|
||||
}
|
||||
fn visit_seq<A: SeqAccess<'de>>(self, seq: A) -> Result<Self::Value, A::Error> {
|
||||
rest_of_list(seq)?;
|
||||
Ok(None)
|
||||
}
|
||||
none_for!(scalars);
|
||||
none_for!(maps 'de);
|
||||
}
|
||||
d.deserialize_any(V).map(Coord)
|
||||
}
|
||||
}
|
||||
|
||||
/// The name of a point's field.
|
||||
enum Key {
|
||||
X,
|
||||
Y,
|
||||
Other,
|
||||
}
|
||||
impl<'de> serde::Deserialize<'de> for Key {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
struct V;
|
||||
impl Visitor<'_> for V {
|
||||
type Value = Key;
|
||||
fn expecting(&self, f: &mut Formatter) -> FmtResult {
|
||||
f.write_str("a field name")
|
||||
}
|
||||
fn visit_str<E: Error>(self, v: &str) -> Result<Key, E> {
|
||||
Ok(match v {
|
||||
"x" => Key::X,
|
||||
"y" => Key::Y,
|
||||
_ => Key::Other,
|
||||
})
|
||||
}
|
||||
}
|
||||
d.deserialize_identifier(V)
|
||||
}
|
||||
}
|
||||
|
||||
/// One entry of the list: a point, else none.
|
||||
struct Corner(Option<Point>);
|
||||
impl<'de> serde::Deserialize<'de> for Corner {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
struct V;
|
||||
impl<'de> Visitor<'de> for V {
|
||||
type Value = Option<Point>;
|
||||
fn expecting(&self, f: &mut Formatter) -> FmtResult {
|
||||
f.write_str("a point")
|
||||
}
|
||||
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
|
||||
let x = seq.next_element::<Coord>()?.and_then(|c| c.0);
|
||||
let y = match x {
|
||||
Some(_) => seq.next_element::<Coord>()?.and_then(|c| c.0),
|
||||
None => None,
|
||||
};
|
||||
let more = rest_of_list(seq)?;
|
||||
Ok(x.zip(y).filter(|_| !more).map(|(x, y)| Point::new(x, y)))
|
||||
}
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
|
||||
let (mut x, mut y, mut bad) = (None, None, false);
|
||||
while let Some(key) = map.next_key::<Key>()? {
|
||||
let slot = match key {
|
||||
Key::X => &mut x,
|
||||
Key::Y => &mut y,
|
||||
Key::Other => {
|
||||
map.next_value::<IgnoredAny>()?;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let v = map.next_value::<Coord>()?.0;
|
||||
// A repeated or non-numeric coordinate makes the entry no point.
|
||||
bad |= slot.is_some() || v.is_none();
|
||||
*slot = slot.or(v);
|
||||
}
|
||||
Ok(x.zip(y).filter(|_| !bad).map(|(x, y)| Point::new(x, y)))
|
||||
}
|
||||
none_for!(scalars);
|
||||
none_for!(numbers);
|
||||
}
|
||||
d.deserialize_any(V).map(Corner)
|
||||
}
|
||||
}
|
||||
|
||||
struct Corners;
|
||||
impl<'de> serde::de::Visitor<'de> for Corners {
|
||||
impl<'de> Visitor<'de> for Corners {
|
||||
type Value = Option<Box<[Point; 4]>>;
|
||||
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
fn expecting(&self, f: &mut Formatter) -> FmtResult {
|
||||
f.write_str("a list of points")
|
||||
}
|
||||
fn visit_none<E: serde::de::Error>(self) -> Result<Self::Value, E> {
|
||||
Ok(None)
|
||||
fn visit_some<D: Deserializer<'de>>(self, d: D) -> Result<Self::Value, D::Error> {
|
||||
d.deserialize_any(Corners)
|
||||
}
|
||||
fn visit_unit<E: serde::de::Error>(self) -> Result<Self::Value, E> {
|
||||
Ok(None)
|
||||
}
|
||||
fn visit_some<D: serde::Deserializer<'de>>(self, d: D) -> Result<Self::Value, D::Error> {
|
||||
d.deserialize_seq(Corners)
|
||||
}
|
||||
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
|
||||
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
|
||||
let mut points = Vec::with_capacity(4);
|
||||
while points.len() < 4
|
||||
&& let Some(p) = seq.next_element::<Point>()?
|
||||
{
|
||||
points.push(p);
|
||||
let mut malformed = false;
|
||||
while points.len() < 4 && !malformed {
|
||||
match seq.next_element::<Corner>()? {
|
||||
Some(Corner(Some(p))) => points.push(p),
|
||||
Some(Corner(None)) => malformed = true,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
// A fifth entry drops the field, so the rest is skipped without decoding it.
|
||||
let mut extra = false;
|
||||
while seq.next_element::<serde::de::IgnoredAny>()?.is_some() {
|
||||
extra = true;
|
||||
}
|
||||
Ok(if extra { None } else { <[Point; 4]>::try_from(points).ok().map(Box::new) })
|
||||
// A malformed or fifth entry drops the field, so the rest is skipped without decoding it.
|
||||
let extra = rest_of_list(seq)?;
|
||||
Ok(if extra || malformed { None } else { <[Point; 4]>::try_from(points).ok().map(Box::new) })
|
||||
}
|
||||
none_for!(scalars);
|
||||
none_for!(numbers);
|
||||
none_for!(maps 'de);
|
||||
}
|
||||
d.deserialize_option(Corners)
|
||||
}
|
||||
|
||||
+36
-29
@@ -159,12 +159,8 @@ fn webp(b: &[u8]) -> Option<(f64, f64)> {
|
||||
}
|
||||
|
||||
fn bmp(b: &[u8]) -> Option<(f64, f64)> {
|
||||
// BITMAPINFOHEADER (40 bytes or longer) at 14: pixels per metre at +24 and +28.
|
||||
if le32(b, 14)? < 40 {
|
||||
return None;
|
||||
}
|
||||
let ppm = |at| le32(b, at).filter(|v| (1..=i32::MAX as u32).contains(v)).map(per_metre);
|
||||
Some((ppm(38)?, ppm(42)?))
|
||||
let (x, y) = craft_image_codecs::bmp_probe::pixels_per_meter(b)?;
|
||||
Some((per_metre(x.unsigned_abs()), per_metre(y.unsigned_abs())))
|
||||
}
|
||||
|
||||
/// Pixels per metre for a resolution in pixels per inch (the unit `pHYs` stores).
|
||||
@@ -173,6 +169,7 @@ pub fn pixels_per_metre(ppi: f64) -> u32 {
|
||||
}
|
||||
|
||||
/// PNG CRC-32 (the polynomial ZIP uses) of `parts` read one after another.
|
||||
#[cfg(test)]
|
||||
fn crc32(parts: &[&[u8]]) -> u32 {
|
||||
let mut crc = !0u32;
|
||||
for &b in parts.iter().flat_map(|p| p.iter()) {
|
||||
@@ -186,33 +183,14 @@ fn crc32(parts: &[&[u8]]) -> u32 {
|
||||
|
||||
/// A whole `pHYs` chunk (length, type, data, CRC) declaring `x` × `y` pixels per inch.
|
||||
pub fn phys_chunk(x: f64, y: f64) -> Vec<u8> {
|
||||
let [x, y] = [x, y].map(|v| pixels_per_metre(v).to_be_bytes());
|
||||
// x, y, unit 1 = metre.
|
||||
let data = [x.as_slice(), y.as_slice(), &[1]].concat();
|
||||
let mut out = Vec::with_capacity(21);
|
||||
out.extend_from_slice(&9u32.to_be_bytes());
|
||||
out.extend_from_slice(b"pHYs");
|
||||
out.extend_from_slice(&data);
|
||||
out.extend_from_slice(&crc32(&[b"pHYs", &data]).to_be_bytes());
|
||||
out
|
||||
let ppm = (pixels_per_metre(x).max(1), pixels_per_metre(y).max(1));
|
||||
craft_image_codecs::raw_metadata::png_pixels_per_meter_chunk(ppm).map_or_else(|_| Vec::new(), |chunk| chunk.to_vec())
|
||||
}
|
||||
|
||||
/// `png` with a `pHYs` chunk declaring `ppi` right after the header (any existing one is replaced).
|
||||
pub fn with_png_resolution(png: &[u8], (x, y): (f64, f64)) -> Vec<u8> {
|
||||
let Some(head) = be32(png, 8).and_then(|len| slice(png, 0, 20usize.checked_add(len as usize)?)) else { return png.to_vec() };
|
||||
let chunk = phys_chunk(x, y);
|
||||
let mut out = Vec::with_capacity(png.len() + chunk.len());
|
||||
out.extend_from_slice(head);
|
||||
out.extend_from_slice(&chunk);
|
||||
let mut at = head.len();
|
||||
while let Some(chunk) = be32(png, at).and_then(|len| slice(png, at, 12usize.checked_add(len as usize)?)) {
|
||||
if chunk.get(4..8) != Some(b"pHYs") {
|
||||
out.extend_from_slice(chunk);
|
||||
}
|
||||
at += chunk.len();
|
||||
}
|
||||
out.extend_from_slice(png.get(at..).unwrap_or_default());
|
||||
out
|
||||
let resolution = (pixels_per_metre(x), pixels_per_metre(y));
|
||||
craft_image_codecs::raw_metadata::with_png_pixels_per_meter(png, resolution, png.len().saturating_add(21)).unwrap_or_else(|_| png.to_vec())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -241,6 +219,35 @@ mod tests {
|
||||
assert_eq!(crc32(&[b"IEND"]), 0xAE42_6082);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bmp_resolution_keeps_fractional_axes_and_rounds_near_whole_ppi() {
|
||||
let bmp = bmp_resolution_header(108, 6001, 11811);
|
||||
let (horizontal, vertical) = resolution(&bmp).expect("recorded physical resolution");
|
||||
assert!((horizontal - 152.4254).abs() < 1e-9);
|
||||
assert_eq!(vertical, 300.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bmp_resolution_requires_complete_positive_density_in_range() {
|
||||
let bmp = bmp_resolution_header(40, 3937008, 6001);
|
||||
assert_eq!(resolution(&bmp).map(|(x, _)| x), Some(100_000.0));
|
||||
for len in 0..bmp.len() {
|
||||
assert_eq!(resolution(&bmp[..len]), None, "only {len} header bytes");
|
||||
}
|
||||
for (dib_size, x, y) in [(12, 11811, 11811), (40, -1, 11811), (40, 11811, 0), (40, 1, 11811), (40, 11811, 3937009)] {
|
||||
assert_eq!(resolution(&bmp_resolution_header(dib_size, x, y)), None, "DIB {dib_size}, density {x} by {y}");
|
||||
}
|
||||
}
|
||||
|
||||
fn bmp_resolution_header(dib_size: u32, x: i32, y: i32) -> [u8; 46] {
|
||||
let mut header = [0; 46];
|
||||
header[..2].copy_from_slice(b"BM");
|
||||
header[14..18].copy_from_slice(&dib_size.to_le_bytes());
|
||||
header[38..42].copy_from_slice(&x.to_le_bytes());
|
||||
header[42..46].copy_from_slice(&y.to_le_bytes());
|
||||
header
|
||||
}
|
||||
|
||||
/// RIFF chunk `ty` holding `data`, padded to an even length.
|
||||
fn riff_chunk(ty: &[u8; 4], len: u32, data: &[u8]) -> Vec<u8> {
|
||||
let mut out = [ty.as_slice(), &len.to_le_bytes(), data].concat();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The batched lookups ([`Document::index_paths`], `node_at`, `node_mut_at`, `ancestry_at`) agree
|
||||
//! with the one-id ones on nested trees with missing and duplicated ids, and the edits of many nodes
|
||||
//! ([`Document::remove_many`], `wrap`, `insert_beside`) leave the tree that `remove`, `insert` and
|
||||
//! ([`Document::remove_many`], `wrap`, `insert_beside`, `insert_below`) leave the tree that `remove`, `insert` and
|
||||
//! `move_node` leave one node at a time.
|
||||
use crate::*;
|
||||
use vectorcraft_geom::shapes;
|
||||
@@ -290,6 +290,26 @@ fn insert_beside_matches_inserting_one_at_a_time() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_below_matches_inserting_one_at_a_time() {
|
||||
for seed in 1..40 {
|
||||
let (mut d, mut ids) = tree(seed);
|
||||
let picked = picks(&d, seed);
|
||||
// None to three new nodes for each anchor.
|
||||
let items: Vec<(NodeId, Vec<Node>)> = picked.iter().enumerate().map(|(k, id)| (*id, (0..k % 4).map(|_| square(&mut d)).collect())).collect();
|
||||
ids.extend(items.iter().flat_map(|(_, new)| new.iter().map(|n| n.id)));
|
||||
let (mut a, mut b) = (d.clone(), d.clone());
|
||||
for (id, new) in items.clone() {
|
||||
let (parent, at, _) = a.position(id).unwrap();
|
||||
for (k, n) in new.into_iter().enumerate() {
|
||||
a.insert(parent, at + k, n).unwrap();
|
||||
}
|
||||
}
|
||||
b.insert_below(items).unwrap();
|
||||
same(&a, &b, &ids, &format!("seed {seed}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrap_matches_inserting_a_group_and_moving_the_nodes_into_it_one_at_a_time() {
|
||||
for seed in 1..40 {
|
||||
@@ -331,6 +351,8 @@ fn edits_of_many_refuse_missing_repeated_and_nested_ids() {
|
||||
let items = list.iter().map(|id| (*id, vec![])).collect();
|
||||
assert_eq!(b.insert_beside(items, replace).err(), Some(DocError::NoNode(bad)), "{what}");
|
||||
}
|
||||
let items = list.iter().map(|id| (*id, vec![])).collect();
|
||||
assert_eq!(b.insert_below(items).err(), Some(DocError::NoNode(bad)), "{what}");
|
||||
assert_eq!(serde_json::to_string(&b).ok(), saved, "{what}: the document stays as it was");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -583,9 +583,10 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option<Ou
|
||||
let own_fill = has_visible_fill(group);
|
||||
// A compound shape's area has no paint of its own: the shape's own appearance paints it. The
|
||||
// shape's top painting fill is the area's fill for Remove Unpainted Artwork and for Outline's
|
||||
// strokes, while Divide pieces stay unpainted so that the fill is not drawn twice.
|
||||
// strokes, while Divide pieces stay unpainted so that the fill is not drawn twice. The shape's
|
||||
// strokes stay out: the shape's own appearance already strokes the result.
|
||||
let area_style = group.is_compound_shape().then(|| {
|
||||
let items = group.appearance.items.iter().filter(|i| paints(i)).cloned().collect();
|
||||
let items = top_painting_fill(&group.appearance).cloned().into_iter().collect();
|
||||
Node::path(group.id, PathData::default(), Appearance { items, ..Default::default() })
|
||||
});
|
||||
let style_of = |s: &Node| -> Option<Node> {
|
||||
@@ -644,13 +645,19 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option<Ou
|
||||
// (style source, shape) per stack entry; keys index `sources`.
|
||||
let mut sources: Vec<Node> = vec![];
|
||||
let mut shapes: Vec<po::Shape> = vec![];
|
||||
// Keys of the group operands whose art has no area left at the precision.
|
||||
let mut collapsed: Vec<u64> = vec![];
|
||||
for mut lv in all {
|
||||
if shape_mode && lv.len() > 1 {
|
||||
let parts: Vec<(PathData, FillRule)> = lv.iter().filter_map(geometry).collect();
|
||||
let refs: Vec<(&PathData, FillRule)> = parts.iter().map(|(p, r)| (p, *r)).collect();
|
||||
let key = sources.len() as u64;
|
||||
if let Some(top) = lv.pop() {
|
||||
shapes.push(po::Shape::new(po::unite_all_with(&refs, options.precision), FillRule::NonZero, key));
|
||||
let united = po::unite_all_with(&refs, options.precision);
|
||||
if united.is_empty() && !parts.is_empty() {
|
||||
collapsed.push(key);
|
||||
}
|
||||
shapes.push(po::Shape::new(united, FillRule::NonZero, key));
|
||||
sources.push(top);
|
||||
}
|
||||
} else {
|
||||
@@ -662,6 +669,18 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option<Ou
|
||||
}
|
||||
}
|
||||
}
|
||||
// An operand with no area still takes part: Intersect, and Minus Front or Minus Back when
|
||||
// it is the shape the others are cut from, then leave nothing.
|
||||
let is_collapsed = |s: &po::Shape| collapsed.contains(&s.key);
|
||||
let nothing_left = match op {
|
||||
PathfinderOp::Intersect => shapes.iter().any(is_collapsed),
|
||||
PathfinderOp::MinusFront => shapes.first().is_some_and(is_collapsed),
|
||||
PathfinderOp::MinusBack => shapes.last().is_some_and(is_collapsed),
|
||||
_ => false,
|
||||
};
|
||||
if nothing_left {
|
||||
return Some(vec![]);
|
||||
}
|
||||
shapes.retain(|s| !s.path.is_empty() && s.path.subpaths.iter().all(|sp| sp.anchors.iter().all(|a| a.p.x.is_finite() && a.p.y.is_finite())));
|
||||
if shapes.is_empty() {
|
||||
return Some(vec![]);
|
||||
|
||||
@@ -196,6 +196,49 @@ fn shape_modes_follow_the_pathfinder_panel() {
|
||||
assert_eq!(div.len(), 3);
|
||||
}
|
||||
|
||||
/// An Intersect effect draws nothing when a group member's art has no area left at the effect's
|
||||
/// precision, and so do Minus Back when that group is in front and Subtract when it is at the
|
||||
/// back. Add, and Subtract with the group in front, leave such a member out.
|
||||
#[test]
|
||||
fn intersect_with_a_group_that_collapses_at_its_precision_draws_nothing() {
|
||||
let thin_pair = |width: f64| {
|
||||
let bar = |id: u64, x: f64| {
|
||||
let fill = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0);
|
||||
Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(x, 10.0, x + width, 30.0)), fill))
|
||||
};
|
||||
Node::group(NodeId(5), vec![bar(3, 10.0), bar(4, 50.0)])
|
||||
};
|
||||
let with_precision = |front: Node, effect: &str| {
|
||||
let mut g = square_and(Some(front), effect);
|
||||
g.appearance.effects[0].params = serde_json::json!({"precision": 1.0});
|
||||
g
|
||||
};
|
||||
let int = results(&with_precision(thin_pair(0.5), "pathfinder.intersect"));
|
||||
assert!(int.is_empty(), "{int:#?}");
|
||||
// Bars wider than the precision keep their area.
|
||||
let int = results(&with_precision(thin_pair(2.0), "pathfinder.intersect"));
|
||||
let total: f64 = int.iter().map(|n| area(n)).sum();
|
||||
assert!((total - 80.0).abs() < 1.0, "{total}: {int:#?}");
|
||||
// Add keeps the square alone.
|
||||
let add = results(&with_precision(thin_pair(0.5), "pathfinder.add"));
|
||||
assert_eq!(add.len(), 1);
|
||||
assert!((area(&add[0]) - 10_000.0).abs() < 1.0, "{add:#?}");
|
||||
// Minus Back cuts the square from the empty group in front, and Subtract cuts nothing from
|
||||
// the square.
|
||||
let minus_back = results(&with_precision(thin_pair(0.5), "pathfinder.minusBack"));
|
||||
assert!(minus_back.is_empty(), "{minus_back:#?}");
|
||||
let subtract = results(&with_precision(thin_pair(0.5), "pathfinder.subtract"));
|
||||
assert_eq!(subtract.len(), 1);
|
||||
assert!((area(&subtract[0]) - 10_000.0).abs() < 1.0, "{subtract:#?}");
|
||||
// With the group at the back, Subtract cuts the square from it and leaves nothing.
|
||||
let mut back = with_precision(thin_pair(0.5), "pathfinder.subtract");
|
||||
if let NodeKind::Group { children, .. } = &mut back.kind {
|
||||
children.reverse();
|
||||
}
|
||||
let subtract = results(&back);
|
||||
assert!(subtract.is_empty(), "{subtract:#?}");
|
||||
}
|
||||
|
||||
/// Divide and Outline draw no piece of a member without fill or stroke, the same as when such
|
||||
/// pieces are left out.
|
||||
#[test]
|
||||
@@ -263,6 +306,25 @@ fn outline_strokes_a_compound_shapes_area_in_its_fill() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Outline of a compound shape with no fill gives the edges no paint of their own when Remove
|
||||
/// Unpainted Artwork is off. The shape's own appearance strokes the result, so the shape's stroke
|
||||
/// is not copied onto the edges.
|
||||
#[test]
|
||||
fn outline_of_an_unfilled_compound_shape_adds_no_stroke() {
|
||||
let mut g = compound_shape(ShapeMode::Add);
|
||||
let mut a = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 4.0);
|
||||
if let Some(AppearanceItem::Stroke(s)) = a.items.last_mut() {
|
||||
s.opacity = 0.5;
|
||||
}
|
||||
g.appearance = a.into();
|
||||
g.appearance.effects.push(Effect { id: "pathfinder.outline".into(), params: serde_json::json!({"removeUnpainted": false}), visible: true });
|
||||
let out = pathfinder_children(None, &g, None).unwrap();
|
||||
assert!(!out.is_empty(), "{out:#?}");
|
||||
for n in &out {
|
||||
assert!(!n.appearance.items.iter().any(paints), "{n:#?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// With Remove Unpainted Artwork, Divide keeps the pieces of an unfilled member when its group's
|
||||
/// own visible fill paints them and leaves them out when the group has no fill. Outline leaves out
|
||||
/// the member's segments either way.
|
||||
|
||||
@@ -89,9 +89,9 @@ pub use raster::{
|
||||
without_geometry,
|
||||
};
|
||||
pub use reshape::{
|
||||
SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_copied_row_raster, has_gradient_copies,
|
||||
has_instance_row_raster, has_item_geometry, has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint,
|
||||
instance_as_art, needs_outline, outer_effects, outline_art, outline_text, paint_type_piece, reshape,
|
||||
SYMBOL_ART_MAX_NODES, add_instance_row_effects_to_parts, expand_outlined, follows_image_pixels, gives_image_shape, has_copied_row_raster,
|
||||
has_gradient_copies, has_instance_row_raster, has_item_geometry, has_painted_effects, has_transform_art, has_transform_copies,
|
||||
has_transform_options, image_paint, instance_as_art, needs_outline, outer_effects, outline_art, outline_text, paint_type_piece, reshape,
|
||||
};
|
||||
pub use revolve::{
|
||||
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
|
||||
|
||||
@@ -388,11 +388,23 @@ fn row_effects_of(fx: &[Effect]) -> Vec<Effect> {
|
||||
/// appearance, so the effects never pass round a symbol that holds itself. Without `doc`, no
|
||||
/// instance in the art takes them.
|
||||
pub(crate) fn add_instance_row_effects(doc: Option<&Document>, n: &Node, art: &mut Node) {
|
||||
add_instance_rows(doc, n, art, true);
|
||||
}
|
||||
|
||||
/// [`add_instance_row_effects`] for Direct Selection's parts of a symbol instance's art: live
|
||||
/// objects (blends, envelopes, repeats) are left as they are, without the effects, so that every
|
||||
/// object keeps its place in the art and the child indices that pick a part still lead to it.
|
||||
pub fn add_instance_row_effects_to_parts(doc: Option<&Document>, n: &Node, art: &mut Node) {
|
||||
add_instance_rows(doc, n, art, false);
|
||||
}
|
||||
|
||||
/// [`add_instance_row_effects`], evaluating live objects in the art only with `live`.
|
||||
fn add_instance_rows(doc: Option<&Document>, n: &Node, art: &mut Node, live: bool) {
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return };
|
||||
let fill = active_fill(n).map_or(vec![], |f| row_effects_of(&f.effects));
|
||||
let stroke = active_stroke(n).map_or(vec![], |s| row_effects_of(&s.effects));
|
||||
if !fill.is_empty() || !stroke.is_empty() {
|
||||
add_row_effects(doc, symbol, art, &fill, &stroke);
|
||||
add_row_effects(doc, symbol, art, &fill, &stroke, live);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -413,8 +425,9 @@ fn places_symbol(doc: &Document, from: &str, to: &str, seen: &mut HashSet<String
|
||||
}
|
||||
|
||||
/// [`add_instance_row_effects`] of `fill` and `stroke` to `n` and the art in it, the art of an
|
||||
/// instance of the symbol named `outer`.
|
||||
fn add_row_effects(doc: Option<&Document>, outer: &str, n: &mut Node, fill: &[Effect], stroke: &[Effect]) {
|
||||
/// instance of the symbol named `outer`. Without `live`, live objects are left as they are
|
||||
/// ([`add_instance_row_effects_to_parts`]).
|
||||
fn add_row_effects(doc: Option<&Document>, outer: &str, n: &mut Node, fill: &[Effect], stroke: &[Effect], live: bool) {
|
||||
match &n.kind {
|
||||
NodeKind::Path { clipping: true, .. } | NodeKind::Path { guide: true, .. } | NodeKind::RulerGuide { .. } => return,
|
||||
NodeKind::SymbolInstance { symbol, .. } => {
|
||||
@@ -425,7 +438,12 @@ fn add_row_effects(doc: Option<&Document>, outer: &str, n: &mut Node, fill: &[Ef
|
||||
}
|
||||
return;
|
||||
}
|
||||
_ if vectorcraft_doc::live::is_live(n) => *n = evaluated(doc, n),
|
||||
_ if vectorcraft_doc::live::is_live(n) => {
|
||||
if !live {
|
||||
return;
|
||||
}
|
||||
*n = evaluated(doc, n);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let takes = |i: &AppearanceItem| {
|
||||
@@ -445,7 +463,7 @@ fn add_row_effects(doc: Option<&Document>, outer: &str, n: &mut Node, fill: &[Ef
|
||||
let clips = n.clips();
|
||||
for (i, c) in n.children_mut().into_iter().flatten().enumerate() {
|
||||
if !(clips && i == 0) {
|
||||
add_row_effects(doc, outer, Arc::make_mut(c), fill, stroke);
|
||||
add_row_effects(doc, outer, Arc::make_mut(c), fill, stroke, live);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,7 +67,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Clear Appearance",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind",
|
||||
"{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own; in the contents of a Live Paint group, a face one empty fill and an edge one empty stroke) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind",
|
||||
has_doc,
|
||||
clear_appearance
|
||||
),
|
||||
@@ -76,7 +76,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reduce to Basic Appearance",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)",
|
||||
"{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked; in the contents of a Live Paint group, a face keeps only the fill and an edge only the stroke), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)",
|
||||
has_doc,
|
||||
reduce_basic
|
||||
),
|
||||
@@ -398,15 +398,6 @@ pub(crate) fn aligned(p: &Value, cmd: &str) -> Result<bool> {
|
||||
switch_or(p, "aligned", false, cmd)
|
||||
}
|
||||
|
||||
/// What the appearances of `ids` share, when there are several of them and they all exist.
|
||||
pub(crate) fn shared_stack(d: &vectorcraft_doc::Document, ids: &[NodeId]) -> Option<SharedStack> {
|
||||
if ids.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
let aps: Vec<&Appearance> = ids.iter().map(|id| d.node(*id).map(|n| &*n.appearance)).collect::<Option<_>>()?;
|
||||
Some(SharedStack::of(&aps))
|
||||
}
|
||||
|
||||
/// Do the appearances of `ids` differ (several objects whose stacks aren't all equal)?
|
||||
pub(crate) fn appearances_differ(d: &vectorcraft_doc::Document, ids: &[NodeId]) -> bool {
|
||||
let mut aps = ids.iter().filter_map(|id| d.node(*id)).map(|n| &n.appearance);
|
||||
@@ -529,6 +520,24 @@ pub(crate) fn contents_skipped(s: &Session, p: &Value, fill: bool) -> Result<Has
|
||||
Ok(super::paint::live_paint_parts_skipped(&s.doc()?.doc, &appearance_roots(s, p)?, fill))
|
||||
}
|
||||
|
||||
/// The faces and the edges of the Live Paint groups whose contents `p` targets (`target: "contents"`). A command that
|
||||
/// gives them a whole appearance gives a face only its fill rows and an edge only its stroke rows
|
||||
/// ([`keep_rows_of_kind`]). Both are empty without `target: "contents"`.
|
||||
pub(crate) fn contents_parts(s: &Session, p: &Value) -> Result<(HashSet<NodeId>, HashSet<NodeId>)> {
|
||||
if !targets_contents(p)? {
|
||||
return Ok((HashSet::new(), HashSet::new()));
|
||||
}
|
||||
let (faces, edges, _) = super::paint::live_paint_split(&s.doc()?.doc, &appearance_roots(s, p)?);
|
||||
Ok((faces, edges))
|
||||
}
|
||||
|
||||
/// Remove from `n` its stroke rows (`fill`) or its fill rows: a Live Paint face draws fills and an edge strokes.
|
||||
pub(crate) fn keep_rows_of_kind(n: &mut Node, fill: bool) {
|
||||
if n.appearance.items.iter().any(|it| it.is_fill() != fill) {
|
||||
n.appearance.items.retain(|it| it.is_fill() == fill);
|
||||
}
|
||||
}
|
||||
|
||||
/// The refusal of an appearance edit whose targets are all the art of graph designs drawn in graph series.
|
||||
const DESIGN_ART: &str = "the art of a graph design in a graph series is drawn again from the design: edit the design to change it";
|
||||
|
||||
@@ -1044,12 +1053,17 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
|
||||
|
||||
fn clear_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = require_whole_targets(s, p, "appearance.clear")?;
|
||||
let (faces, edges) = contents_parts(s, p)?;
|
||||
// When every object is cleared already, the document and its undo history stay as they are.
|
||||
let before = s.doc()?.doc.clone();
|
||||
super::overprint::edit_counted(s, "Clear Appearance", |d| {
|
||||
for id in &ids {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
clear(n);
|
||||
// A Live Paint group's face keeps an empty fill and its edge an empty stroke.
|
||||
if faces.contains(id) || edges.contains(id) {
|
||||
keep_rows_of_kind(n, faces.contains(id));
|
||||
}
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
}
|
||||
@@ -1284,6 +1298,7 @@ fn is_group(n: &Node) -> bool {
|
||||
|
||||
fn reduce_basic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = require_whole_targets(s, p, "appearance.reduceToBasic")?;
|
||||
let (faces, edges) = contents_parts(s, p)?;
|
||||
// When every object comes out as it was, the document and its undo history stay as they are.
|
||||
let before = s.doc()?.doc.clone();
|
||||
// The Appearance panel's active row (a row of the first selected object's stack, and in each
|
||||
@@ -1322,6 +1337,10 @@ fn reduce_basic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
st.blend = BlendMode::Normal;
|
||||
n.appearance.items.push(AppearanceItem::Stroke(st));
|
||||
}
|
||||
// A Live Paint group's face keeps only its fill and its edge only its stroke.
|
||||
if faces.contains(id) || edges.contains(id) {
|
||||
keep_rows_of_kind(n, faces.contains(id));
|
||||
}
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
}
|
||||
@@ -1502,19 +1521,16 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut first_at = None;
|
||||
let active = s.active_appearance_item.as_ref().and_then(|a| a.objects.first().copied());
|
||||
let mut active_at = None;
|
||||
// Aligned rows of a mixed selection are copied right above themselves in each object. Rows of a graph design's art,
|
||||
// which is left out, go to `to` in an object whose stack is the same as the art's.
|
||||
// Aligned rows of a mixed selection are copied right above themselves in each object. Aligned rows of objects whose
|
||||
// stacks are the same, and rows of a graph design's art, which is left out, go to `to` as in one stack.
|
||||
let of = design_reference(s, p, C)?;
|
||||
if aligned(p, C)?
|
||||
&& to.is_some()
|
||||
&& (shared_stack(&s.doc()?.doc, &ids).is_some() || (of.is_some() && appearances_differ(&s.doc()?.doc, &with_reference(of, &ids))))
|
||||
{
|
||||
if aligned(p, C)? && to.is_some() && appearances_differ(&s.doc()?.doc, &with_reference(of, &ids)) {
|
||||
return Err(bad(C, "`to` takes the rows of one object's stack, not aligned rows"));
|
||||
}
|
||||
let before = s.doc()?.doc.clone();
|
||||
// With `to`, the art's stack is the same as the object's, so its rows are the object's, each of which must exist.
|
||||
let per =
|
||||
if to.is_some() { items_per_target(&before, &ids, &idx, aligned(p, C)?) } else { rows_per_target(&before, of, &ids, &idx, aligned(p, C)?) };
|
||||
// With `to`, aligned rows are rows of stacks that are all the same (the art's too), so each target takes the same
|
||||
// indices, each of which must exist.
|
||||
let per = if to.is_some() { vec![idx.clone(); ids.len()] } else { rows_per_target(&before, of, &ids, &idx, aligned(p, C)?) };
|
||||
s.edit("Duplicate Item", |d, _| {
|
||||
let mut any = false;
|
||||
// Copies that became the topmost visible row of their kind: the series stores their paint even when the object
|
||||
|
||||
@@ -48,7 +48,7 @@ use dynamic::{symbol_instance_reset, symbol_instance_select_part, symbol_instanc
|
||||
use symbolism::symbol_set_density;
|
||||
use symbols::selected_instances;
|
||||
pub(crate) use symbols::{
|
||||
expand_instances_under, expandable_instances, instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol,
|
||||
Placement, expand_instances_under, expandable_instances, instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol,
|
||||
stored_natural_size,
|
||||
};
|
||||
use symbols::{
|
||||
@@ -234,7 +234,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Place Symbol Instance",
|
||||
[],
|
||||
None,
|
||||
"{name?, x?, y?} place an instance so its registration point is at (x, y) (default: artboard centre; name default: current) → {id}",
|
||||
"{name?, x?, y?} place an instance so its registration point is at (x, y) (default: artboard centre; name default: current), on top of the current layer, or in Draw Behind directly below the bottommost selected object (at the bottom of the current layer with nothing selected) → {id}",
|
||||
has_doc,
|
||||
symbol_place
|
||||
),
|
||||
|
||||
@@ -33,6 +33,40 @@ pub(crate) fn place_xf(at: Point, (w, h): (f64, f64), reg: SymbolRegistration) -
|
||||
Affine::translate(c.to_vec2()) * Affine::scale_non_uniform(w / (2.0 * HALF), h / (2.0 * HALF))
|
||||
}
|
||||
|
||||
/// Where a placed symbol instance goes in the active document, worked out before the edit from
|
||||
/// the drawing mode, the selection and the layer new art goes into.
|
||||
pub(crate) struct Placement {
|
||||
parent: Option<NodeId>,
|
||||
behind: bool,
|
||||
anchor: Option<NodeId>,
|
||||
}
|
||||
|
||||
impl Placement {
|
||||
/// On top of the layer new art goes into; in Draw Behind, directly below the bottommost
|
||||
/// selected object (beside the compound path that holds it), or at the bottom of that layer
|
||||
/// when nothing is selected. An error when that layer is locked or hidden.
|
||||
pub(crate) fn of(s: &Session) -> Result<Self> {
|
||||
let st = s.doc()?;
|
||||
let parent = st.target_parent()?;
|
||||
let behind = s.draw_mode == crate::DrawMode::Behind;
|
||||
let compound_of = |id: NodeId| st.doc.parent_of(id).filter(|p| st.doc.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })));
|
||||
let anchor = behind.then(|| st.selection.in_paint_order(&st.doc).first().copied()).flatten().map(|id| compound_of(id).unwrap_or(id));
|
||||
Ok(Self { parent, behind, anchor })
|
||||
}
|
||||
|
||||
/// Inserts instance `n` where this placement puts it. In a clip group or a clipping layer the
|
||||
/// clipping path stays at the bottom.
|
||||
pub(crate) fn insert(&self, d: &mut Document, n: Node) -> Result<NodeId> {
|
||||
let (parent, index) = match (self.behind, self.anchor.and_then(|a| d.position(a))) {
|
||||
(false, _) => return Ok(d.insert(self.parent, usize::MAX, n)?),
|
||||
(true, Some((par, i, _))) => (par, i),
|
||||
(true, None) => (self.parent, 0),
|
||||
};
|
||||
let floor = usize::from(parent.and_then(|p| d.node(p)).is_some_and(Node::clips));
|
||||
Ok(d.insert(parent, index.max(floor), n)?)
|
||||
}
|
||||
}
|
||||
|
||||
fn registration_param(p: &Value, cmd: &str) -> Result<Option<SymbolRegistration>> {
|
||||
match p.get("registration") {
|
||||
None => Ok(None),
|
||||
@@ -437,10 +471,10 @@ pub(super) fn symbol_place(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let at = Point::new(number_or(p, "x", centre.x, "symbol.place")?, number_or(p, "y", centre.y, "symbol.place")?);
|
||||
let size = natural_size(d, &name);
|
||||
let reg = d.symbol_registration(&name);
|
||||
let parent = s.doc()?.target_parent()?;
|
||||
let spot = Placement::of(s)?;
|
||||
let id = s.edit("Place Symbol Instance", |d, sel| {
|
||||
let id = d.alloc_id();
|
||||
d.insert(parent, usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: name.clone(), xf: place_xf(at, size, reg) }))?;
|
||||
spot.insert(d, Node::new(id, NodeKind::SymbolInstance { symbol: name.clone(), xf: place_xf(at, size, reg) }))?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})?;
|
||||
|
||||
@@ -55,7 +55,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Flare",
|
||||
[],
|
||||
None,
|
||||
"{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: deterministically places every ring along the path, including the first for small seed values, keeping their count and sizes)} → {id}",
|
||||
"{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end, both or neither: one alone is an error; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: deterministically places every ring along the path, including the first for small seed values, keeping their count and sizes)} → {id}",
|
||||
has_doc,
|
||||
super::flare::flare
|
||||
),
|
||||
|
||||
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Update Dimensions",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [dimension ids] (default selection), options?: dimension options, orientation?: aligned|horizontal|vertical (linear dimensions only; the line stays on the side of the points it was on), offset?: pt (as in dimension.create)} restyle, turn or move existing dimensions → {ids}",
|
||||
"{ids?: [dimension ids] (default selection), options?: dimension options, orientation?: aligned|horizontal|vertical (linear dimensions only; the line stays on the side of the points it was on), offset?: pt (as in dimension.create), at?: [x,y] (after offset: puts a linear dimension's line through this point, gives an angular dimension's arc a radius of the point's distance from the vertex, at least 12 pt, or turns a radius or diameter line toward it; what the dimension measures does not change)} restyle, turn or move existing dimensions → {ids}",
|
||||
has_doc,
|
||||
update
|
||||
),
|
||||
@@ -159,6 +159,7 @@ fn update(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(error("Select dimensions to update"));
|
||||
}
|
||||
let o = if p.get("options").is_some() { Some(options(s, p)?) } else { None };
|
||||
let at = if p.get("at").is_some() { Some(point(p, "at")?) } else { None };
|
||||
// Every dimension is checked before anything changes, and an update that changes none of
|
||||
// them records no undo step.
|
||||
let mut next = Vec::with_capacity(ids.len());
|
||||
@@ -178,6 +179,10 @@ fn update(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
dim.offset = distance(p, dim.offset)?;
|
||||
dim.resolve(doc).map_err(error)?;
|
||||
if let Some(at) = at {
|
||||
dim.place(at);
|
||||
dim.resolve(doc).map_err(error)?;
|
||||
}
|
||||
if dim != old {
|
||||
next.push((*id, dim));
|
||||
}
|
||||
|
||||
@@ -231,7 +231,7 @@ fn persp_edit(
|
||||
let d = &s.doc()?.doc;
|
||||
fallback.filter(|_| ids.iter().any(|id| g.attachment_of(d, *id).is_none()))
|
||||
};
|
||||
let kept = if copy && !stores_attachments(&s.doc()?.doc) { crate::cmd::object::preview_copies(s, ids, false)? } else { None };
|
||||
let kept = if copy && !stores_attachments(&s.doc()?.doc) { crate::cmd::object::preview_copies(s, ids, false, false)? } else { None };
|
||||
let edited = s.edit(label, |d, sel| {
|
||||
g.adopt_stored_attachments(d);
|
||||
let targets = match &kept {
|
||||
@@ -502,7 +502,7 @@ pub(super) fn plane_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// lists attachments of its own (`stores_attachments`).
|
||||
let kept = if objects == "copy" && s.in_interaction() && !stores_attachments(&s.doc()?.doc) {
|
||||
let on = on_plane(&s.doc()?.doc);
|
||||
crate::cmd::object::preview_copies(s, &on, false)?
|
||||
crate::cmd::object::preview_copies(s, &on, false, false)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
@@ -120,7 +120,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Smooth",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the smoothing), radius?: pt (12), fidelity?: pt (2.5; kept within 0.000078125 and about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side → {ids, before, after}",
|
||||
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the smoothing), radius?: pt (12; from 0.001 to 1000), fidelity?: pt (2.5; from 0.000078125 to about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom, kept within the range)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side → {ids, before, after}. A radius or fidelity outside its range is refused with an error, and nothing changes",
|
||||
has_selection,
|
||||
smooth_region
|
||||
),
|
||||
@@ -129,7 +129,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Join",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the join), tolerance?: pt (12)} join the open-path endpoints scrubbed over, or trim two crossing open paths whose overhanging ends are scrubbed and join them at the crossing → {id}",
|
||||
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the join), tolerance?: pt (12; from 0.001 to 1000)} join the open-path endpoints scrubbed over, or trim two crossing open paths whose overhanging ends are scrubbed and join them at the crossing → {id}. A tolerance outside 0.001 to 1000 is refused with an error, and nothing changes",
|
||||
has_doc,
|
||||
join_scrub
|
||||
),
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
use vectorcraft_pathops::addons::pathtools as pt;
|
||||
use vectorcraft_pathops::start_nearest;
|
||||
|
||||
use super::common::{dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, subpath_len, target_paths};
|
||||
use super::common::{dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, ranged, subpath_len, target_paths};
|
||||
use super::{
|
||||
Anchor, BezPath, CubicBez, NodeId, ParamCurve, ParamCurveNearest, PathData, Point, Rect, Result, Session, SimplifyOptions, SubPath, Value, json,
|
||||
number_or, po,
|
||||
Anchor, BezPath, CubicBez, NodeId, ParamCurve, ParamCurveNearest, PathData, Point, Rect, Result, Session, SimplifyOptions, SubPath, Value, bad,
|
||||
json, number_or, po,
|
||||
};
|
||||
|
||||
// ---------- Smooth ----------
|
||||
@@ -323,84 +324,6 @@ fn refit_run(anchors: &[Anchor], tol: f64, sigma: f64, free: [bool; 2]) -> Vec<A
|
||||
out.into_vec()
|
||||
}
|
||||
|
||||
/// Distance (points) from an anchor within which a smoothed closed path starts at that anchor
|
||||
/// instead of at a new one split in beside it.
|
||||
const START_SNAP: f64 = 1e-3;
|
||||
|
||||
/// Distance (points) within which two points of a smoothed closed path count as equally near its
|
||||
/// old start.
|
||||
const START_TIE: f64 = 1e-6;
|
||||
|
||||
/// Where `p` lies along the closed `orig` from its first anchor: the segment index and parameter of
|
||||
/// the point of `orig` nearest `p`, the first such point in its order. Sorts after every finite place
|
||||
/// when there is none.
|
||||
fn place_along(orig: &SubPath, p: Point) -> (usize, f64) {
|
||||
let mut best: Option<(f64, usize, f64)> = None;
|
||||
for j in 0..orig.anchors.len() {
|
||||
let hit = orig.segment(j).nearest(p, 1e-9);
|
||||
if hit.distance_sq.is_finite() && hit.t.is_finite() && best.is_none_or(|(d, ..)| hit.distance_sq < d) {
|
||||
best = Some((hit.distance_sq, j, hit.t));
|
||||
}
|
||||
}
|
||||
best.map_or((usize::MAX, f64::INFINITY), |(_, j, t)| (j, t))
|
||||
}
|
||||
|
||||
/// The closed `sp` started at the point on it nearest `start`: at the anchor there, or at a new
|
||||
/// anchor split into the segment there, which leaves the outline as it is. Of points equally near
|
||||
/// `start`, the one earliest along `orig` (the path before smoothing) from its first anchor is used,
|
||||
/// then the first in `sp`'s order. An open `sp`, or one with no segment or no finite nearest point,
|
||||
/// is returned as it is.
|
||||
fn start_nearest(mut sp: SubPath, start: Point, orig: &SubPath) -> SubPath {
|
||||
let n = sp.anchors.len();
|
||||
if !sp.closed || n < 2 {
|
||||
return sp;
|
||||
}
|
||||
// (distance, place along `orig` once a tie needs it, segment of `sp`, parameter)
|
||||
type Best = (f64, Option<(usize, f64)>, usize, f64);
|
||||
let mut best: Option<Best> = None;
|
||||
for i in 0..n {
|
||||
let c = sp.segment(i);
|
||||
let hit = c.nearest(start, 1e-9);
|
||||
if !hit.distance_sq.is_finite() || !hit.t.is_finite() {
|
||||
continue;
|
||||
}
|
||||
let d = hit.distance_sq.sqrt();
|
||||
match &mut best {
|
||||
None => best = Some((d, None, i, hit.t)),
|
||||
Some((bd, bplace, bi, bt)) if (d - *bd).abs() <= START_TIE => {
|
||||
let held = *bplace.get_or_insert_with(|| place_along(orig, sp.segment(*bi).eval(*bt)));
|
||||
let place = place_along(orig, c.eval(hit.t));
|
||||
if place.0 < held.0 || (place.0 == held.0 && place.1 < held.1) {
|
||||
best = Some((d, Some(place), i, hit.t));
|
||||
}
|
||||
}
|
||||
Some((bd, ..)) if d < *bd => best = Some((d, None, i, hit.t)),
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
let Some((_, _, i, t)) = best else { return sp };
|
||||
let c = sp.segment(i);
|
||||
let at = c.eval(t);
|
||||
let first = if at.distance(c.p0) <= START_SNAP {
|
||||
i
|
||||
} else if at.distance(c.p3) <= START_SNAP {
|
||||
(i + 1) % n
|
||||
} else {
|
||||
let mid = if sp.segment_is_line(i) {
|
||||
Anchor::corner(at)
|
||||
} else {
|
||||
let (l, r) = (c.subsegment(0.0..t), c.subsegment(t..1.0));
|
||||
sp.anchors[i].h_out = l.p1;
|
||||
sp.anchors[(i + 1) % n].h_in = r.p2;
|
||||
Anchor::with_handles(at, l.p2, r.p1)
|
||||
};
|
||||
sp.anchors.insert(i + 1, mid);
|
||||
i + 1
|
||||
};
|
||||
sp.anchors.rotate_left(first);
|
||||
sp
|
||||
}
|
||||
|
||||
/// Pieces of curve that one Smooth drag measures against the drag while it searches the segments
|
||||
/// under it ([`reach_samples`]), shared equally by the curved segments that come within its reach,
|
||||
/// each of which gets at least one: enough to search 300,000 pt of curve within the default reach
|
||||
@@ -645,14 +568,28 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f
|
||||
(!same_anchors(&res, &anchors)).then(|| SubPath::new(res, false))
|
||||
}
|
||||
|
||||
/// The segment `c`, which ends in the drag's reach (`near`) and starts outside it, split where it
|
||||
/// enters the reach: the part outside, then the part in reach. `None` when no more than a sliver
|
||||
/// is outside.
|
||||
fn split_at_reach(c: CubicBez, near: &dyn Fn(Point) -> bool) -> Option<(CubicBez, CubicBez)> {
|
||||
/// How much of a segment that ends in the drag's reach is in reach ([`split_at_reach`]).
|
||||
enum Reach {
|
||||
/// All of it, or all but a sliver.
|
||||
Whole,
|
||||
/// No more than a sliver at its end.
|
||||
End,
|
||||
/// The part outside the reach, then the part in reach.
|
||||
Split(CubicBez, CubicBez),
|
||||
}
|
||||
|
||||
/// Share of the tool's reach that the part of a segment in reach must be longer than for
|
||||
/// [`split_at_reach`] to split the segment. VectorCraft's own value.
|
||||
const REACH_SLIVER: f64 = 1.0 / 64.0;
|
||||
|
||||
/// The segment `c`, which ends in the drag's reach (`near`, `radius` points) and starts outside it,
|
||||
/// split where it enters the reach. No more than 2% of its parameter range outside the reach is a
|
||||
/// sliver, and so is a part in reach no longer than [`REACH_SLIVER`] of the reach.
|
||||
fn split_at_reach(c: CubicBez, near: &dyn Fn(Point) -> bool, radius: f64) -> Reach {
|
||||
const STEPS: u32 = 32;
|
||||
let step = 1.0 / f64::from(STEPS);
|
||||
// Back from the end in reach to the first sample outside, then halving to the crossing.
|
||||
let outside = (1..=STEPS).map(|i| 1.0 - f64::from(i) * step).find(|t| !near(c.eval(*t)))?;
|
||||
let Some(outside) = (1..=STEPS).map(|i| 1.0 - f64::from(i) * step).find(|t| !near(c.eval(*t))) else { return Reach::Whole };
|
||||
let (mut lo, mut hi) = (outside, outside + step);
|
||||
for _ in 0..20 {
|
||||
let mid = (lo + hi) / 2.0;
|
||||
@@ -668,7 +605,11 @@ fn split_at_reach(c: CubicBez, near: &dyn Fn(Point) -> bool) -> Option<(CubicBez
|
||||
let s = c.subsegment(range);
|
||||
if straight { CubicBez::new(s.p0, s.p0, s.p3, s.p3) } else { s }
|
||||
};
|
||||
(hi > 0.02).then(|| (part(0.0..hi), part(hi..1.0)))
|
||||
if hi <= 0.02 {
|
||||
return Reach::Whole;
|
||||
}
|
||||
let (far, reach) = (part(0.0..hi), part(hi..1.0));
|
||||
if polygon_len(reach) <= REACH_SLIVER * radius { Reach::End } else { Reach::Split(far, reach) }
|
||||
}
|
||||
|
||||
/// `anchors` with each run of `marked` ones smoothed by a Gaussian of spread `sigma` and refitted
|
||||
@@ -695,25 +636,33 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool
|
||||
}
|
||||
let mut out = anchors.to_vec();
|
||||
for (a, b) in runs.into_iter().rev() {
|
||||
let lo = a.saturating_sub(1);
|
||||
let hi = (b + 1).min(n - 1);
|
||||
let (mut lo, mut hi) = (a.saturating_sub(1), (b + 1).min(n - 1));
|
||||
// How much of the segments leading out of the run is in reach. A segment that is in reach
|
||||
// only at the run's anchor stays out of the piece, so the piece ends at that anchor rather
|
||||
// than in a sliver of a segment, which would leave the refit no direction to end along.
|
||||
let after = if hi > b { split_at_reach(CubicBez::new(out[hi].p, out[hi].h_in, out[b].h_out, out[b].p), near, radius) } else { Reach::Whole };
|
||||
let before = if lo < a { split_at_reach(CubicBez::new(out[lo].p, out[lo].h_out, out[a].h_in, out[a].p), near, radius) } else { Reach::Whole };
|
||||
if matches!(after, Reach::End) {
|
||||
hi = b;
|
||||
}
|
||||
if matches!(before, Reach::End) {
|
||||
lo = a;
|
||||
}
|
||||
if hi == lo {
|
||||
continue;
|
||||
}
|
||||
let mut piece = out[lo..=hi].to_vec();
|
||||
// The anchors outside the reach, kept with the part of their segment that is outside.
|
||||
let (mut head, mut tail) = (None, None);
|
||||
if hi > b
|
||||
if let Reach::Split(far, reach) = after
|
||||
&& let [.., inner, outer] = piece.as_mut_slice()
|
||||
&& let Some((far, reach)) = split_at_reach(CubicBez::new(outer.p, outer.h_in, inner.h_out, inner.p), near)
|
||||
{
|
||||
inner.h_out = reach.p2;
|
||||
tail = Some(Anchor { h_in: far.p1, ..*outer });
|
||||
*outer = Anchor::with_handles(far.p3, reach.p1, far.p2);
|
||||
}
|
||||
if lo < a
|
||||
if let Reach::Split(far, reach) = before
|
||||
&& let [outer, inner, ..] = piece.as_mut_slice()
|
||||
&& let Some((far, reach)) = split_at_reach(CubicBez::new(outer.p, outer.h_out, inner.h_in, inner.p), near)
|
||||
{
|
||||
inner.h_in = reach.p2;
|
||||
head = Some(Anchor { h_out: far.p1, ..*outer });
|
||||
@@ -733,8 +682,12 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool
|
||||
pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.smoothRegion";
|
||||
let pts = points_param(p, "points", C)?;
|
||||
let radius = number_or(p, "radius", 12.0, C)?.max(0.0);
|
||||
let tol = number_or(p, "fidelity", 2.5, C)?.clamp(vectorcraft_tools::draw2::SMOOTH_MIN_TOLERANCE, vectorcraft_tools::draw2::SMOOTH_MAX_TOLERANCE);
|
||||
let radius = ranged(p, "radius", 12.0, vectorcraft_tools::draw2::REACH_RANGE, C)?;
|
||||
let tol = number_or(p, "fidelity", 2.5, C)?;
|
||||
let (lo, hi) = (vectorcraft_tools::draw2::SMOOTH_MIN_TOLERANCE, vectorcraft_tools::draw2::SMOOTH_MAX_TOLERANCE);
|
||||
if !(lo..=hi).contains(&tol) {
|
||||
return Err(bad(C, format!("`fidelity` must be from {lo} to {hi} pt")));
|
||||
}
|
||||
let sigma = radius * SMOOTH_SPREAD;
|
||||
let st = s.doc()?;
|
||||
let mut plan = vec![];
|
||||
@@ -882,7 +835,7 @@ fn trim_join(d: &vectorcraft_doc::Document, ids: &[NodeId], pts: &[Point], tol:
|
||||
pub(super) fn join_scrub(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.joinScrub";
|
||||
let pts = points_param(p, "points", C)?;
|
||||
let tol = number_or(p, "tolerance", 12.0, C)?.max(0.0);
|
||||
let tol = ranged(p, "tolerance", 12.0, vectorcraft_tools::draw2::REACH_RANGE, C)?;
|
||||
let st = s.doc()?;
|
||||
let targets = target_paths(&st.doc, &st.selection, poly_bounds(&pts, tol));
|
||||
// Paths that cross with their ends scrubbed are trimmed there and joined (#5844).
|
||||
@@ -1009,6 +962,8 @@ pub(super) fn join_scrub(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use vectorcraft_pathops::START_SNAP;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A closed ring of four smooth anchors round (100, 100) with radius 50.
|
||||
|
||||
@@ -1828,7 +1828,19 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// Duplicate `roots` directly above each original, transform the copies, select them
|
||||
/// ([`copy_above`]).
|
||||
pub(crate) fn duplicate_in(d: &mut Document, sel: &mut vectorcraft_doc::Selection, roots: &[NodeId], xf: Affine) -> Result<Vec<NodeId>> {
|
||||
let out = copy_above(d, roots, |_, _, c| {
|
||||
duplicate_beside(d, sel, roots, xf, false)
|
||||
}
|
||||
|
||||
/// [`duplicate_in`], with each copy directly below its original when `below` is true
|
||||
/// ([`copy_beside`]).
|
||||
pub(crate) fn duplicate_beside(
|
||||
d: &mut Document,
|
||||
sel: &mut vectorcraft_doc::Selection,
|
||||
roots: &[NodeId],
|
||||
xf: Affine,
|
||||
below: bool,
|
||||
) -> Result<Vec<NodeId>> {
|
||||
let out = copy_beside(d, roots, below, |_, _, c| {
|
||||
c.transform(xf, true);
|
||||
super::object::keep_pixel_aligned(c, true.into());
|
||||
})?;
|
||||
@@ -1841,20 +1853,42 @@ pub(crate) fn duplicate_in(d: &mut Document, sel: &mut vectorcraft_doc::Selectio
|
||||
/// tree as it is. The copies take new ids in the order of `roots`. Roots listed twice, or inside
|
||||
/// another root, are copied one at a time: each copy is made from the document as the copies
|
||||
/// before it left it. Copied type whose layout caches [`Document::reid`] dropped has them again.
|
||||
pub(crate) fn copy_above(d: &mut Document, roots: &[NodeId], mut change: impl FnMut(&mut Document, &Node, &mut Node)) -> Result<Vec<NodeId>> {
|
||||
pub(crate) fn copy_above(d: &mut Document, roots: &[NodeId], change: impl FnMut(&mut Document, &Node, &mut Node)) -> Result<Vec<NodeId>> {
|
||||
copy_beside(d, roots, false, change)
|
||||
}
|
||||
|
||||
/// [`copy_above`], with each copy directly below its original, in the same parent, when `below`
|
||||
/// is true. The clipping path of a clip group or a clipping layer stays the bottom child: its copy
|
||||
/// goes directly above it.
|
||||
pub(crate) fn copy_beside(
|
||||
d: &mut Document,
|
||||
roots: &[NodeId],
|
||||
below: bool,
|
||||
mut change: impl FnMut(&mut Document, &Node, &mut Node),
|
||||
) -> Result<Vec<NodeId>> {
|
||||
let paths = d.index_paths(roots.iter().copied());
|
||||
let mut found: Vec<_> = roots.iter().filter_map(|id| paths.get(id)).collect();
|
||||
found.sort_unstable();
|
||||
// The bottom child of a parent that clips is its clipping path.
|
||||
let clips_at = |d: &Document, up: &[usize], i: usize| i == 0 && !up.is_empty() && d.node_at(up).is_some_and(Node::clips);
|
||||
let out = if found.windows(2).all(|w| !w[1].starts_with(w[0])) {
|
||||
let mut copies = Vec::with_capacity(roots.len());
|
||||
let (mut copies, mut above) = (Vec::with_capacity(roots.len()), vec![]);
|
||||
let mut out = Vec::with_capacity(roots.len());
|
||||
for id in roots {
|
||||
let Some(n) = paths.get(id).and_then(|p| d.node_at(p)).cloned() else { continue };
|
||||
let Some(p) = paths.get(id) else { continue };
|
||||
let Some(n) = d.node_at(p).cloned() else { continue };
|
||||
let mut c = d.reid(&n);
|
||||
change(d, &n, &mut c);
|
||||
copies.push((*id, vec![c]));
|
||||
out.push(c.id);
|
||||
let on_floor = below && p.split_last().is_some_and(|(i, up)| clips_at(d, up, *i));
|
||||
if !below || on_floor { above.push((*id, vec![c])) } else { copies.push((*id, vec![c])) }
|
||||
}
|
||||
if !copies.is_empty() {
|
||||
d.insert_below(copies)?;
|
||||
}
|
||||
if !above.is_empty() {
|
||||
d.insert_beside(above, false)?;
|
||||
}
|
||||
let out: Vec<NodeId> = copies.iter().flat_map(|(_, c)| c.iter().map(|n| n.id)).collect();
|
||||
d.insert_beside(copies, false)?;
|
||||
out
|
||||
} else {
|
||||
let mut out = vec![];
|
||||
@@ -1863,7 +1897,8 @@ pub(crate) fn copy_above(d: &mut Document, roots: &[NodeId], mut change: impl Fn
|
||||
let Some(n) = d.node(*id).cloned() else { continue };
|
||||
let mut c = d.reid(&n);
|
||||
change(d, &n, &mut c);
|
||||
out.push(d.insert(par, idx + 1, c)?);
|
||||
let floor = usize::from(par.and_then(|p| d.node(p)).is_some_and(Node::clips));
|
||||
out.push(d.insert(par, if below { idx.max(floor) } else { idx + 1 }, c)?);
|
||||
}
|
||||
out
|
||||
};
|
||||
|
||||
@@ -97,7 +97,7 @@ fn effect_specs() -> Vec<CommandSpec> {
|
||||
"Expand Appearance",
|
||||
["Object"],
|
||||
None,
|
||||
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}",
|
||||
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places, a visible plain instance outside template layers in a group or layer whose raster effect makes an image of it included) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}",
|
||||
can_expand,
|
||||
expand_appearance
|
||||
),
|
||||
@@ -927,7 +927,8 @@ fn bevel_effect(id: &str) -> bool {
|
||||
/// Options ([`effects::PathfinderEffectOptions`], so an effect saved without them and given their
|
||||
/// defaults is unchanged), each option given equal to the one it stores (a precision that Scale
|
||||
/// Strokes & Effects took past its range evaluates at the bound but is still edited), and every
|
||||
/// other value given equal to the one it has?
|
||||
/// other value given equal to the one it has (a number by its value, so a Soft Mix `mixingRate` of 50
|
||||
/// over a stored 50.0 is unchanged)?
|
||||
fn pathfinder_edit_changes_nothing(e: &Effect, params: &Value) -> bool {
|
||||
if !effects::takes_pathfinder_options(&e.id) {
|
||||
return false;
|
||||
@@ -938,8 +939,12 @@ fn pathfinder_edit_changes_nothing(e: &Effect, params: &Value) -> bool {
|
||||
if let Value::Object(m) = &mut after {
|
||||
m.extend(given.clone());
|
||||
}
|
||||
let others_same = given.iter().filter(|(k, _)| !effects::PATHFINDER_OPTION_KEYS.contains(&k.as_str())).all(|(k, v)| current.get(k) == Some(v));
|
||||
let same_value = |a: &Value, b: &Value| a == b || a.as_f64().is_some_and(|x| b.as_f64() == Some(x));
|
||||
// Two integers compare exactly, and a float compares with any number by value.
|
||||
let same_value = |a: &Value, b: &Value| a == b || ((a.is_f64() || b.is_f64()) && a.as_f64().is_some_and(|x| b.as_f64() == Some(x)));
|
||||
let others_same = given
|
||||
.iter()
|
||||
.filter(|(k, _)| !effects::PATHFINDER_OPTION_KEYS.contains(&k.as_str()))
|
||||
.all(|(k, v)| current.get(k).is_some_and(|c| same_value(c, v)));
|
||||
let stored_same = given
|
||||
.iter()
|
||||
.filter(|(k, _)| effects::PATHFINDER_OPTION_KEYS.contains(&k.as_str()))
|
||||
@@ -1611,27 +1616,72 @@ fn expanded_node(
|
||||
|
||||
/// Does `n`, an object in it, or the art of a symbol placed in it hold a plug-in effect that
|
||||
/// expanding it draws: a visible one, the object's own or a visible fill's or stroke's, on an
|
||||
/// object that expands ([`expandable`]; in a symbol's art, `in_art`, every object does). A symbol's
|
||||
/// object that expands ([`expandable`]; in a symbol's art, `in_art`, every object does), or that the
|
||||
/// image of a group or layer with a raster effect draws ([`rasterizes_plugin_effect`]). A symbol's
|
||||
/// art counts where an instance of it expands. `seen` holds the symbols already looked into.
|
||||
fn holds_plugin_effect(d: &Document, n: &Node, in_art: bool, seen: &mut std::collections::HashSet<String>) -> bool {
|
||||
let plugin = |e: &Effect| e.visible && vectorcraft_plugins::effect::plugin_id(&e.id).is_some();
|
||||
let mut symbols = vec![];
|
||||
let mut holds = false;
|
||||
n.walk(&mut |c| {
|
||||
if !in_art && !expandable(c) {
|
||||
return;
|
||||
}
|
||||
holds |= c.appearance.effects.iter().any(plugin) || c.appearance.items.iter().any(|i| i.visible() && i.effects().iter().any(plugin));
|
||||
holds |= has_own_plugin_effect(c);
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &c.kind {
|
||||
symbols.push(symbol.clone());
|
||||
}
|
||||
});
|
||||
holds
|
||||
|| (!in_art && rasterizes_plugin_effect(d, n, &mut std::collections::HashSet::new()))
|
||||
|| symbols.into_iter().any(|name| {
|
||||
seen.insert(name.clone()) && d.symbols.iter().find(|s| s.name == name).is_some_and(|s| holds_plugin_effect(d, &s.art, true, seen))
|
||||
})
|
||||
}
|
||||
|
||||
/// Does `n` have a visible plug-in effect of its own, or on a visible fill or stroke?
|
||||
fn has_own_plugin_effect(n: &Node) -> bool {
|
||||
let plugin = |e: &Effect| e.visible && vectorcraft_plugins::effect::plugin_id(&e.id).is_some();
|
||||
n.appearance.effects.iter().any(plugin) || n.appearance.items.iter().any(|i| i.visible() && i.effects().iter().any(plugin))
|
||||
}
|
||||
|
||||
/// Does a group or layer in `n` with a raster effect make an image of a visible plug-in effect
|
||||
/// ([`draws_plugin_effect`])? Expansion makes the image of such a group or layer even when it, or
|
||||
/// a group around it, is hidden. A group or layer that paints something and whose raster effects
|
||||
/// are not all shadows and outer glows becomes one image of what it draws, so the groups and layers
|
||||
/// in it make no images of their own; one that paints nothing makes no image, and its members
|
||||
/// expand on their own.
|
||||
fn rasterizes_plugin_effect(d: &Document, n: &Node, seen: &mut std::collections::HashSet<String>) -> bool {
|
||||
let fx = if is_container(n) { rasterfx::raster_fx(n) } else { vec![] };
|
||||
if !fx.is_empty() {
|
||||
if draws_plugin_effect(d, n, seen) {
|
||||
return true;
|
||||
}
|
||||
if !fx.iter().all(effects::RasterFx::is_below) && vectorcraft_render::painted_bounds(d, n).is_some() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
n.children().into_iter().flatten().any(|c| rasterizes_plugin_effect(d, c, seen))
|
||||
}
|
||||
|
||||
/// Does `n`, an object the image of `n` draws in it, or the art of a symbol such an instance places,
|
||||
/// have a visible plug-in effect ([`has_own_plugin_effect`])? The image leaves out a hidden object
|
||||
/// in `n`, a template layer, a guide or a ruler guide, and everything in it, as the renderer does
|
||||
/// with templates skipped. `seen` holds the symbols already looked into.
|
||||
fn draws_plugin_effect(d: &Document, n: &Node, seen: &mut std::collections::HashSet<String>) -> bool {
|
||||
if has_own_plugin_effect(n) {
|
||||
return true;
|
||||
}
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind
|
||||
&& seen.insert(symbol.clone())
|
||||
&& d.symbols.iter().find(|s| s.name == *symbol).is_some_and(|s| draws_plugin_effect(d, &s.art, seen))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
let drawn =
|
||||
|c: &Node| c.visible && !c.is_ruler_guide() && !matches!(c.kind, NodeKind::Layer { template: true, .. } | NodeKind::Path { guide: true, .. });
|
||||
n.children().into_iter().flatten().any(|c| drawn(c) && draws_plugin_effect(d, c, seen))
|
||||
}
|
||||
|
||||
fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let roots = edit_targets(s, p, "effect.expandAppearance")?;
|
||||
// In Safe Mode a plug-in effect draws nothing: expanding it would drop the effect and keep the
|
||||
|
||||
@@ -42,7 +42,7 @@ pub mod jxlread;
|
||||
mod legacy_ai;
|
||||
mod load;
|
||||
mod mesh3d;
|
||||
pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, image_clip, size_note};
|
||||
pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, image_clip, preview_with_clip, size_note};
|
||||
mod heifread;
|
||||
pub mod hpgl;
|
||||
mod jp2read;
|
||||
|
||||
@@ -1370,6 +1370,20 @@ pub(crate) fn image_clip(blob: &ImageBlob) -> Option<vectorcraft_geom::PathData>
|
||||
vectorcraft_geom::path::with_anchor_budget(vectorcraft_geom::path::MAX_READ_ANCHORS, || serde_json::from_slice(json).ok())
|
||||
}
|
||||
|
||||
/// `blob` with its preview keeping the clipping path its PNG or TIFF keeps ([`image_clip`]), in a
|
||||
/// text chunk of the preview PNG as [`png_with_clip`] writes it: a document saved without its
|
||||
/// linked files holds the preview alone, and the Links commands then still know a clip group of
|
||||
/// that path as the file's. Unchanged without a preview or a clipping path.
|
||||
pub(crate) fn preview_with_clip(mut blob: ImageBlob) -> ImageBlob {
|
||||
let Some(proxy) = blob.proxy.clone().filter(|p| !std::sync::Arc::ptr_eq(p, &blob.bytes) && png_clip(p).is_none()) else { return blob };
|
||||
let Some(json) = image_clip(&blob).and_then(|clip| serde_json::to_string(&clip).ok()).filter(|j| j.len() <= MAX_PNG_CLIP) else {
|
||||
return blob;
|
||||
};
|
||||
let png = vectorcraft_render::encode::png::with_text(proxy.to_vec(), &[(CLIP_KEYWORD, json.into())]);
|
||||
blob.proxy = Some(std::sync::Arc::new(png));
|
||||
blob
|
||||
}
|
||||
|
||||
/// An image as a document of its physical size at the resolution it declares (as Place sizes it;
|
||||
/// 72 ppi, 1 px = 1 pt, when it declares none), the image named after the file.
|
||||
pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result<Document> {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -18,6 +18,8 @@ struct L {
|
||||
rect: [i32; 4],
|
||||
/// Red, green, blue and alpha, the same for every pixel.
|
||||
rgba: [u8; 4],
|
||||
/// The alpha of each pixel, in place of `rgba`'s, stored raw.
|
||||
alpha: Option<Vec<u8>>,
|
||||
blend: &'static [u8; 4],
|
||||
opacity: u8,
|
||||
clipped: bool,
|
||||
@@ -40,6 +42,7 @@ fn layer(name: &'static str, rect: [i32; 4], rgba: [u8; 4]) -> L {
|
||||
name,
|
||||
rect,
|
||||
rgba,
|
||||
alpha: None,
|
||||
blend: b"norm",
|
||||
opacity: 255,
|
||||
clipped: false,
|
||||
@@ -96,10 +99,15 @@ fn predict(row: &[u8], depth: u16) -> Vec<u8> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A channel of `n` samples of `v` (in 32 bits, `v` / 255 as a float) at `depth`, raw, zipped
|
||||
/// (with prediction when `zip` is `Some(true)`) or PackBits rows of `width` when `rle`.
|
||||
/// One sample of `v` at `depth` (in 32 bits, `v` / 255 as a float).
|
||||
fn sample_of(v: u8, depth: u16) -> Vec<u8> {
|
||||
if depth == 32 { (f32::from(v) / 255.0).to_be_bytes().to_vec() } else { vec![v; usize::from(depth / 8)] }
|
||||
}
|
||||
|
||||
/// A channel of `n` samples of `v` (see [`sample_of`]) at `depth`, raw, zipped (with prediction
|
||||
/// when `zip` is `Some(true)`) or PackBits rows of `width` when `rle`.
|
||||
fn channel(v: u8, n: usize, width: usize, depth: u16, rle: bool, psb: bool, zip: Option<bool>) -> Vec<u8> {
|
||||
let sample = if depth == 32 { (f32::from(v) / 255.0).to_be_bytes().to_vec() } else { vec![v; usize::from(depth / 8)] };
|
||||
let sample = sample_of(v, depth);
|
||||
let row: Vec<u8> = std::iter::repeat_n(sample.as_slice(), width).flatten().copied().collect();
|
||||
if let Some(predicted) = zip {
|
||||
let rows = n.checked_div(width).unwrap_or(0);
|
||||
@@ -151,11 +159,17 @@ fn layer_info(layers: &[L], depth: u16, rle: bool, psb: bool) -> Vec<u8> {
|
||||
.filter(|_| !l.bare)
|
||||
.map(|&(id, v)| (id, channel(v, w * h, w, depth, rle, psb, l.zip)))
|
||||
.collect();
|
||||
if let (Some(pixels), Some((_, d))) = (&l.alpha, channels.first_mut()) {
|
||||
*d = vec![0, 0];
|
||||
for &p in pixels {
|
||||
d.extend(sample_of(p, depth));
|
||||
}
|
||||
}
|
||||
let mut mask = vec![];
|
||||
if let Some(([mt, ml, mb, mr], default, flags, pixels)) = &l.mask {
|
||||
let mut d = vec![0, 0];
|
||||
for &p in pixels {
|
||||
d.extend(std::iter::repeat_n(p, usize::from(depth / 8)));
|
||||
d.extend(sample_of(p, depth));
|
||||
}
|
||||
channels.push((-2, d));
|
||||
for v in [mt, ml, mb, mr] {
|
||||
@@ -1201,6 +1215,790 @@ fn layers_clipped_to_an_adjustment_layer_show_over_the_canvas() {
|
||||
assert!(r["warnings"].to_string().contains("1 adjustment layer was not applied"), "{r}");
|
||||
}
|
||||
|
||||
/// An adjustment layer of key `key` with `data`, storing no pixels.
|
||||
fn adjustment(name: &'static str, key: &[u8; 4], data: &[u8]) -> L {
|
||||
L { blocks: vec![(*key, data.to_vec())], ..layer(name, [0, 0, 0, 0], [0; 4]) }
|
||||
}
|
||||
|
||||
/// The colors of a 1-pixel-high layer's image, left to right.
|
||||
fn row_of(s: &Session, l: &Node) -> Vec<[u8; 4]> {
|
||||
let px = image_of(s, l).1;
|
||||
(0..px.width()).map(|x| px.get_pixel(x, 0).0).collect()
|
||||
}
|
||||
|
||||
/// Invert, Threshold and Posterize adjustment layers merge with the visible layers below them, which
|
||||
/// they change; the layers above stay apart. Invert turns each value `v` into `255 − v`; Threshold
|
||||
/// at 128 makes a pixel white when its luminance is above 128 and black at or below it; Posterize at
|
||||
/// 4 levels maps each channel to the nearest of 0, 85, 170 and 255.
|
||||
#[test]
|
||||
fn invert_threshold_and_posterize_merge_with_the_layers_below() {
|
||||
let top = layer("Top", [0, 0, 1, 1], [1, 2, 3, 255]);
|
||||
for (depth, psb) in [(8, false), (16, false), (8, true), (16, true)] {
|
||||
let layers = [
|
||||
layer("Dark", [0, 0, 1, 1], [10, 20, 30, 255]),
|
||||
layer("Light", [0, 1, 1, 2], [200, 150, 100, 128]),
|
||||
adjustment("Invert", b"nvrt", &[]),
|
||||
top.clone(),
|
||||
];
|
||||
let (s, r) = open(&file(2, 1, &layers, depth, false, psb), json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Dark + Light + Invert", "Top"], "{depth} {psb}: {r}");
|
||||
assert_eq!(r["warnings"], json!([]), "{depth} {psb}");
|
||||
assert_eq!(row_of(&s, &d.layers[0]), [[245, 235, 225, 255], [55, 105, 155, 128]], "{depth} {psb}: transparency stays");
|
||||
assert_eq!(row_of(&s, &d.layers[1]), [[1, 2, 3, 255]], "{depth} {psb}: the layer above isn't changed");
|
||||
}
|
||||
let grays = [
|
||||
layer("128", [0, 0, 1, 1], [128, 128, 128, 255]),
|
||||
layer("129", [0, 1, 1, 2], [129, 129, 129, 255]),
|
||||
layer("Light", [0, 2, 1, 3], [200, 150, 100, 255]),
|
||||
layer("Dark", [0, 3, 1, 4], [10, 20, 30, 255]),
|
||||
];
|
||||
let layers = [&grays[..], &[adjustment("Threshold", b"thrs", &[0, 128, 0, 0])][..]].concat();
|
||||
let (s, r) = open(&file(4, 1, &layers, 8, false, false), json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["128 + 129 + Light + Dark + Threshold"], "{r}");
|
||||
assert_eq!(row_of(&s, &d.layers[0]), [[0, 0, 0, 255], [255, 255, 255, 255], [255, 255, 255, 255], [0, 0, 0, 255]]);
|
||||
let layers =
|
||||
[layer("A", [0, 0, 1, 1], [42, 43, 128, 255]), layer("B", [0, 1, 1, 2], [212, 213, 0, 255]), adjustment("Posterize", b"post", &[0, 4, 0, 0])];
|
||||
let (s, r) = open(&file(2, 1, &layers, 8, false, false), json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["A + B + Posterize"], "{r}");
|
||||
assert_eq!(row_of(&s, &d.layers[0]), [[0, 85, 170, 255], [170, 255, 0, 255]]);
|
||||
}
|
||||
|
||||
/// An adjustment layer's opacity, layer mask and blend mode decide how much of the adjusted color
|
||||
/// replaces the color below.
|
||||
#[test]
|
||||
fn an_adjustment_layer_takes_its_opacity_mask_and_blend_mode() {
|
||||
let black = || layer("Black", [0, 0, 1, 2], [0, 0, 0, 255]);
|
||||
let half = L { opacity: 128, ..adjustment("Invert", b"nvrt", &[]) };
|
||||
let (s, r) = open(&file(2, 1, &[black(), half], 8, false, false), json!({}));
|
||||
assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[128, 128, 128, 255]; 2], "{r}");
|
||||
// Black in the mask leaves the first pixel as it was; outside, the mask's default (white) applies it.
|
||||
let masked = L { mask: Some(([0, 0, 1, 1], 255, 0, vec![0])), ..adjustment("Invert", b"nvrt", &[]) };
|
||||
let (s, r) = open(&file(2, 1, &[black(), masked], 8, false, false), json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(row_of(&s, &d.layers[0]), [[0, 0, 0, 255], [255, 255, 255, 255]], "{r}");
|
||||
assert!(d.layers[0].extras().mask.is_none(), "the mask is spent on the merge");
|
||||
// A disabled mask applies it everywhere.
|
||||
let off = L { mask: Some(([0, 0, 1, 1], 255, 2, vec![0])), ..adjustment("Invert", b"nvrt", &[]) };
|
||||
let (s, _) = open(&file(2, 1, &[black(), off], 8, false, false), json!({}));
|
||||
assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[255, 255, 255, 255]; 2]);
|
||||
// Multiply: the inverted color (55, 155, 205) multiplies the color below.
|
||||
let multiply = L { blend: b"mul ", ..adjustment("Invert", b"nvrt", &[]) };
|
||||
let (s, _) = open(&file(1, 1, &[layer("Under", [0, 0, 1, 1], [200, 100, 50, 255]), multiply], 8, false, false), json!({}));
|
||||
assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[43, 61, 40, 255]]);
|
||||
// In a mode VectorCraft lacks, the warnings name the mode, as for other layers merged for it.
|
||||
let dodge = L { blend: b"lddg", ..adjustment("Invert", b"nvrt", &[]) };
|
||||
let (s, r) = open(&file(1, 1, &[layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), dodge], 8, false, false), json!({}));
|
||||
assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[255, 255, 255, 255]], "{r}");
|
||||
let merged = "layers in blend modes VectorCraft doesn't have (Linear Dodge) were merged with the layers below them";
|
||||
assert_eq!(r["warnings"], json!([merged]));
|
||||
}
|
||||
|
||||
/// Clipped to a layer, an adjustment layer changes only that layer and the layers clipped to it.
|
||||
#[test]
|
||||
fn a_clipped_adjustment_layer_changes_only_its_base() {
|
||||
let layers = [
|
||||
layer("Other", [0, 1, 1, 2], [10, 10, 10, 255]),
|
||||
layer("Base", [0, 0, 1, 1], [200, 0, 0, 255]),
|
||||
L { clipped: true, ..adjustment("Invert", b"nvrt", &[]) },
|
||||
];
|
||||
let (s, r) = open(&file(2, 1, &layers, 8, false, false), json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Other", "Base + Invert"], "{r}");
|
||||
assert_eq!(r["warnings"], json!([]));
|
||||
assert_eq!((row_of(&s, &d.layers[0]), row_of(&s, &d.layers[1])), (vec![[10, 10, 10, 255]], vec![[55, 255, 255, 255]]));
|
||||
// Over a layer clipped to the same base, and only inside the base's shape.
|
||||
let layers = [
|
||||
layer("Base", [0, 0, 1, 1], [200, 0, 0, 255]),
|
||||
L { clipped: true, ..layer("Photo", [0, 0, 1, 2], [0, 0, 255, 255]) },
|
||||
L { clipped: true, ..adjustment("Invert", b"nvrt", &[]) },
|
||||
];
|
||||
let (s, r) = open(&file(2, 1, &layers, 8, false, false), json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Base + Photo + Invert"], "{r}");
|
||||
assert_eq!(row_of(&s, &d.layers[0]), [[255, 255, 0, 255]]);
|
||||
// Clipped to another adjustment layer, it isn't applied: the layers keep their colors.
|
||||
let layers = [
|
||||
layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]),
|
||||
adjustment("Curves", b"curv", &[0; 4]),
|
||||
L { clipped: true, ..layer("Photo", [0, 0, 1, 1], [0, 0, 255, 255]) },
|
||||
L { clipped: true, ..adjustment("Invert", b"nvrt", &[]) },
|
||||
];
|
||||
let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under", "Curves + Photo"], "{r}");
|
||||
assert_eq!((row_of(&s, &d.layers[0]), row_of(&s, &d.layers[1])), (vec![[10, 20, 30, 255]], vec![[0, 0, 255, 255]]));
|
||||
assert_eq!(r["warnings"], json!(["2 adjustment layers were not applied"]));
|
||||
// Its layer mask isn't read then: one too large to read doesn't stop the file opening.
|
||||
let mut masked = layers;
|
||||
masked[3].mask = Some(([0, 0, 1, 40_000], 0, 0, vec![200]));
|
||||
let (s, r) = open(&file(1, 1, &masked, 8, false, false), json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under", "Curves + Photo"], "{r}");
|
||||
assert_eq!(r["warnings"], json!(["2 adjustment layers were not applied"]));
|
||||
// An Invert layer that a layer drawing nothing is clipped to isn't applied either.
|
||||
let layers = [
|
||||
layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]),
|
||||
adjustment("Invert", b"nvrt", &[]),
|
||||
L { clipped: true, ..layer("Empty", [0, 0, 0, 0], [0; 4]) },
|
||||
];
|
||||
let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under"], "{r}");
|
||||
assert_eq!(row_of(&s, &d.layers[0]), [[10, 20, 30, 255]]);
|
||||
assert_eq!(r["warnings"], json!(["1 adjustment layer was not applied"]));
|
||||
}
|
||||
|
||||
/// A hidden adjustment layer changes nothing and is left out, with or without the hidden layers; one
|
||||
/// with nothing below it, or in an isolated group with nothing below it there, changes nothing.
|
||||
#[test]
|
||||
fn hidden_and_lone_adjustment_layers_change_nothing() {
|
||||
for hidden in [false, true] {
|
||||
let layers = [layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), L { hidden: true, ..adjustment("Invert", b"nvrt", &[]) }];
|
||||
let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({"hiddenLayers": hidden}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!((d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), &r["warnings"]), (vec!["Under"], &json!([HIDDEN_1])), "{hidden}");
|
||||
assert_eq!(row_of(&s, &d.layers[0]), [[10, 20, 30, 255]]);
|
||||
}
|
||||
let (s, r) = open(&file(1, 1, &[adjustment("Invert", b"nvrt", &[]), layer("Top", [0, 0, 1, 1], [10, 20, 30, 255])], 8, false, false), json!({}));
|
||||
assert_eq!((s.doc().unwrap().doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), &r["warnings"]), (vec!["Top"], &json!([])));
|
||||
let layers = [layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), group_end(), adjustment("Invert", b"nvrt", &[]), group("Isolated", b"norm")];
|
||||
let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!((d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), &r["warnings"]), (vec!["Under", "Isolated"], &json!([])));
|
||||
assert_eq!(row_of(&s, &d.layers[0]), [[10, 20, 30, 255]]);
|
||||
}
|
||||
|
||||
/// In a pass-through group with nothing below it in the group, an adjustment layer changes what is
|
||||
/// below the group when the group is merged; when the group comes in as layers, it isn't applied.
|
||||
#[test]
|
||||
fn an_adjustment_layer_in_a_pass_through_group_changes_what_is_below_the_group() {
|
||||
let layers = |dodge: bool| {
|
||||
let mut l = vec![layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), group_end(), adjustment("Invert", b"nvrt", &[]), group("Folder", b"pass")];
|
||||
if dodge {
|
||||
l.push(L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) });
|
||||
}
|
||||
l
|
||||
};
|
||||
let (s, r) = open(&file(1, 1, &layers(true), 8, false, false), json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Folder + Dodge"], "{r}");
|
||||
assert_eq!(row_of(&s, &d.layers[0]), [[245, 235, 225, 255]]);
|
||||
let (s, r) = open(&file(1, 1, &layers(false), 8, false, false), json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under", "Folder"], "{r}");
|
||||
assert_eq!(r["warnings"], json!(["1 adjustment layer was not applied"]));
|
||||
// Two at the bottom of the group both change what is below it, in order: inverted, then
|
||||
// posterized to 4 levels (without the Invert the color would posterize to black).
|
||||
let stacked = [
|
||||
layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]),
|
||||
group_end(),
|
||||
adjustment("Invert", b"nvrt", &[]),
|
||||
adjustment("Posterize", b"post", &[0, 4, 0, 0]),
|
||||
group("Folder", b"pass"),
|
||||
L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) },
|
||||
];
|
||||
let (s, r) = open(&file(1, 1, &stacked, 8, false, false), json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Folder + Dodge"], "{r}");
|
||||
assert_eq!((row_of(&s, &d.layers[0]), r["warnings"].to_string().contains("adjustment")), (vec![[255, 255, 255, 255]], false), "{r}");
|
||||
// One above a layer of the group, with one kept below that layer, is kept too: the group draws
|
||||
// them in order over what is below it.
|
||||
let between = [
|
||||
layer("Under", [0, 0, 1, 2], [10, 20, 30, 255]),
|
||||
group_end(),
|
||||
adjustment("Invert", b"nvrt", &[]),
|
||||
layer("Top", [0, 1, 1, 2], [100, 100, 100, 255]),
|
||||
adjustment("Posterize", b"post", &[0, 4, 0, 0]),
|
||||
group("Folder", b"pass"),
|
||||
L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) },
|
||||
];
|
||||
let (s, r) = open(&file(2, 1, &between, 8, false, false), json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Folder + Dodge"], "{r}");
|
||||
assert_eq!(row_of(&s, &d.layers[0]), [[255, 255, 255, 255], [85, 85, 85, 255]], "{r}");
|
||||
// Another adjustment layer below it in the group draws nothing, so it still changes what is
|
||||
// below the group.
|
||||
let over_curves = [
|
||||
layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]),
|
||||
group_end(),
|
||||
adjustment("Curves", b"curv", &[0; 4]),
|
||||
adjustment("Invert", b"nvrt", &[]),
|
||||
group("Folder", b"pass"),
|
||||
L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) },
|
||||
];
|
||||
let (s, r) = open(&file(1, 1, &over_curves, 8, false, false), json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Folder + Dodge"], "{r}");
|
||||
assert_eq!(row_of(&s, &d.layers[0]), [[245, 235, 225, 255]], "{r}");
|
||||
// One kept in a pass-through group inside the group keeps the ones above it too: inverted, then
|
||||
// posterized to 4 levels.
|
||||
let nested = [
|
||||
layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]),
|
||||
group_end(),
|
||||
group_end(),
|
||||
adjustment("Invert", b"nvrt", &[]),
|
||||
group("Inner", b"pass"),
|
||||
adjustment("Posterize", b"post", &[0, 4, 0, 0]),
|
||||
group("Folder", b"pass"),
|
||||
L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) },
|
||||
];
|
||||
let (s, r) = open(&file(1, 1, &nested, 8, false, false), json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Folder + Dodge"], "{r}");
|
||||
assert_eq!((row_of(&s, &d.layers[0]), r["warnings"].to_string().contains("adjustment")), (vec![[255, 255, 255, 255]], false), "{r}");
|
||||
// Without the merge, the group comes in as layers and both are counted as not applied.
|
||||
let (s, r) = open(&file(1, 1, &nested[..7], 8, false, false), json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under", "Folder"], "{r}");
|
||||
assert_eq!(r["warnings"], json!(["2 adjustment layers were not applied"]));
|
||||
// Merged in the group with a layer in a mode VectorCraft lacks, it has nothing to change.
|
||||
let inside = [
|
||||
layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]),
|
||||
group_end(),
|
||||
adjustment("Invert", b"nvrt", &[]),
|
||||
L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) },
|
||||
group("Folder", b"pass"),
|
||||
];
|
||||
let (s, r) = open(&file(1, 1, &inside, 8, false, false), json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let names: Vec<&str> = d.layers.iter().map(|l| name(l)).collect();
|
||||
let merged = "layers in blend modes VectorCraft doesn't have (Linear Dodge) were merged with the layers below them";
|
||||
assert_eq!((names, &r["warnings"]), (vec!["Under", "Folder"], &json!(["1 adjustment layer was not applied", merged])), "{r}");
|
||||
assert_eq!(row_of(&s, &d.layers[0]), [[10, 20, 30, 255]]);
|
||||
}
|
||||
|
||||
/// The layer of a pass-through group's sublayers whose name ends with `end`.
|
||||
fn sublayer<'d>(folder: &'d Node, end: &str) -> &'d Node {
|
||||
let children = folder.children().map(Vec::as_slice).unwrap_or_default();
|
||||
let names: Vec<&str> = children.iter().map(|c| name(c)).collect();
|
||||
children.iter().find(|c| name(c).ends_with(end)).unwrap_or_else(|| panic!("no sublayer ending with {end} in {names:?}"))
|
||||
}
|
||||
|
||||
/// An adjustment layer that changes nothing, in a hidden pass-through group or at 0 opacity or 0
|
||||
/// fill, keeps no adjustment layer above it in the group from merging with the layers below it:
|
||||
/// the gray 100 posterizes to 85.
|
||||
#[test]
|
||||
fn adjustment_layers_that_change_nothing_hold_none_back() {
|
||||
let invert = |opacity: u8, fill: u8| {
|
||||
let mut l = L { opacity, ..adjustment("Invert", b"nvrt", &[]) };
|
||||
l.blocks.push((*b"iOpa", vec![fill]));
|
||||
l
|
||||
};
|
||||
let cases = [("hidden group", true, invert(255, 255)), ("0 opacity", false, invert(0, 255)), ("0 fill", false, invert(255, 0))];
|
||||
for (what, hidden, invert) in cases {
|
||||
let layers = [
|
||||
group_end(),
|
||||
group_end(),
|
||||
invert,
|
||||
L { hidden, ..group("Inner", b"pass") },
|
||||
layer("Photo", [0, 0, 1, 1], [100, 100, 100, 255]),
|
||||
adjustment("Posterize", b"post", &[0, 4, 0, 0]),
|
||||
group("Folder", b"pass"),
|
||||
];
|
||||
let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({"hiddenLayers": hidden}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Folder"], "{what}: {r}");
|
||||
assert_eq!(row_of(&s, sublayer(&d.layers[0], "Photo + Posterize")), [[85, 85, 85, 255]], "{what}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A layer that stores no pixels draws nothing: an adjustment layer above it in a pass-through group,
|
||||
/// directly or in a pass-through group inside it, still changes what is below the group.
|
||||
#[test]
|
||||
fn an_adjustment_layer_over_layers_that_draw_nothing_changes_what_is_below_the_group() {
|
||||
let empty = || layer("Empty", [0, 0, 0, 0], [0; 4]);
|
||||
let direct = [
|
||||
layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]),
|
||||
group_end(),
|
||||
empty(),
|
||||
adjustment("Invert", b"nvrt", &[]),
|
||||
group("Folder", b"pass"),
|
||||
L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) },
|
||||
];
|
||||
let (s, r) = open(&file(1, 1, &direct, 8, false, false), json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Folder + Dodge"], "{r}");
|
||||
assert_eq!(row_of(&s, &d.layers[0]), [[245, 235, 225, 255]], "{r}");
|
||||
assert!(!r["warnings"].to_string().contains("adjustment"), "{r}");
|
||||
// Inverted in the inner group, then posterized to 4 levels.
|
||||
let nested = [
|
||||
layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]),
|
||||
group_end(),
|
||||
group_end(),
|
||||
empty(),
|
||||
adjustment("Invert", b"nvrt", &[]),
|
||||
group("Inner", b"pass"),
|
||||
adjustment("Posterize", b"post", &[0, 4, 0, 0]),
|
||||
group("Folder", b"pass"),
|
||||
L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) },
|
||||
];
|
||||
let (s, r) = open(&file(1, 1, &nested, 8, false, false), json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Folder + Dodge"], "{r}");
|
||||
assert_eq!(row_of(&s, &d.layers[0]), [[255, 255, 255, 255]], "{r}");
|
||||
assert!(!r["warnings"].to_string().contains("adjustment"), "{r}");
|
||||
// Nor does a group of such layers, in any mode, or a layer at 0 opacity: below them, directly
|
||||
// or in the inner group, Invert and Posterize still change what is below the outer group.
|
||||
let mut no_fill = layer("Clear", [0, 0, 1, 1], [0, 0, 0, 255]);
|
||||
no_fill.blocks.push((*b"iOpa", vec![0]));
|
||||
let photo = || layer("Photo", [0, 0, 1, 1], [0, 0, 255, 255]);
|
||||
let below: [(&str, Vec<L>); 5] = [
|
||||
("empty group", vec![group_end(), empty(), group("Empty", b"norm")]),
|
||||
("empty pass-through group", vec![group_end(), empty(), group("Empty", b"pass")]),
|
||||
("0 opacity", vec![L { opacity: 0, ..layer("Clear", [0, 0, 1, 1], [0, 0, 0, 255]) }]),
|
||||
("0 fill in a group", vec![group_end(), no_fill, group("Empty", b"norm")]),
|
||||
("group clipped to an empty layer", vec![empty(), group_end(), photo(), L { clipped: true, ..group("Clipped", b"norm") }]),
|
||||
];
|
||||
for (what, nothing) in below {
|
||||
let direct = [
|
||||
&[layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), group_end()][..],
|
||||
¬hing,
|
||||
&[adjustment("Invert", b"nvrt", &[]), group("Folder", b"pass"), L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }],
|
||||
]
|
||||
.concat();
|
||||
let (s, r) = open(&file(1, 1, &direct, 8, false, false), json!({}));
|
||||
assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[245, 235, 225, 255]], "{what}: {r}");
|
||||
let nested = [
|
||||
&[layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), group_end(), group_end()][..],
|
||||
¬hing,
|
||||
&[
|
||||
adjustment("Invert", b"nvrt", &[]),
|
||||
group("Inner", b"pass"),
|
||||
adjustment("Posterize", b"post", &[0, 4, 0, 0]),
|
||||
group("Folder", b"pass"),
|
||||
L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) },
|
||||
],
|
||||
]
|
||||
.concat();
|
||||
let (s, r) = open(&file(1, 1, &nested, 8, false, false), json!({}));
|
||||
assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[255, 255, 255, 255]], "{what}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Layers clipped to a layer at 0 fill, or to an adjustment layer, draw: an adjustment layer above
|
||||
/// them in a pass-through group merges with them and is applied.
|
||||
#[test]
|
||||
fn an_adjustment_layer_over_clipped_layers_merges_with_them() {
|
||||
let mut clear = layer("Base", [0, 0, 1, 1], [0, 0, 0, 255]);
|
||||
clear.blocks.push((*b"iOpa", vec![0]));
|
||||
let photo = || L { clipped: true, ..layer("Photo", [0, 0, 1, 1], [0, 0, 255, 255]) };
|
||||
let layers = [
|
||||
group_end(),
|
||||
group_end(),
|
||||
clear,
|
||||
photo(),
|
||||
adjustment("Invert", b"nvrt", &[]),
|
||||
group("Folder", b"pass"),
|
||||
L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) },
|
||||
group("Outer", b"pass"),
|
||||
];
|
||||
let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let merged = "layers in blend modes VectorCraft doesn't have (Linear Dodge) were merged with the layers below them";
|
||||
assert_eq!(r["warnings"], json!([merged]), "{r}");
|
||||
assert_eq!(row_of(&s, sublayer(&d.layers[0], "Dodge")), [[255, 255, 0, 255]], "{r}");
|
||||
// The same with a group at 0 fill as the base.
|
||||
let mut clear_group = group("Base", b"norm");
|
||||
clear_group.blocks.push((*b"iOpa", vec![0]));
|
||||
let layers = [
|
||||
group_end(),
|
||||
group_end(),
|
||||
group_end(),
|
||||
layer("Black", [0, 0, 1, 1], [0, 0, 0, 255]),
|
||||
clear_group,
|
||||
photo(),
|
||||
adjustment("Invert", b"nvrt", &[]),
|
||||
group("Folder", b"pass"),
|
||||
L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) },
|
||||
group("Outer", b"pass"),
|
||||
];
|
||||
let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(r["warnings"], json!([merged]), "{r}");
|
||||
assert_eq!(row_of(&s, sublayer(&d.layers[0], "Dodge")), [[255, 255, 0, 255]], "{r}");
|
||||
// Clipped to an Invert layer, which isn't applied then, the photo shows over the canvas, and
|
||||
// Posterize merges with it: the gray 100 posterizes to 85.
|
||||
let layers = [
|
||||
group_end(),
|
||||
group_end(),
|
||||
adjustment("Invert", b"nvrt", &[]),
|
||||
L { clipped: true, ..layer("Photo", [0, 0, 1, 1], [100, 100, 100, 255]) },
|
||||
group("Folder", b"pass"),
|
||||
adjustment("Posterize", b"post", &[0, 4, 0, 0]),
|
||||
group("Outer", b"pass"),
|
||||
];
|
||||
let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(row_of(&s, sublayer(&d.layers[0], "Posterize")), [[85, 85, 85, 255]], "{r}");
|
||||
}
|
||||
|
||||
/// Invert, Threshold and Posterize data that can't be read is not applied, with a warning: a level
|
||||
/// out of range, data too short, or a second adjustment block on the layer.
|
||||
#[test]
|
||||
fn adjustment_data_that_cant_be_read_isnt_applied() {
|
||||
let mut twice = adjustment("Twice", b"nvrt", &[]);
|
||||
twice.blocks.push((*b"post", vec![0, 4, 0, 0]));
|
||||
let mut apart = adjustment("Apart", b"nvrt", &[]);
|
||||
apart.blocks.extend([(*b"SoCo", vec![]), (*b"post", vec![0, 4, 0, 0])]);
|
||||
let cases = [
|
||||
adjustment("Level 0", b"thrs", &[0, 0, 0, 0]),
|
||||
adjustment("Level 256", b"thrs", &[1, 0, 0, 0]),
|
||||
adjustment("No level", b"thrs", &[]),
|
||||
adjustment("No padding", b"thrs", &[0, 128]),
|
||||
adjustment("No padding", b"post", &[0, 4]),
|
||||
adjustment("1 level", b"post", &[0, 1, 0, 0]),
|
||||
adjustment("256 levels", b"post", &[1, 0, 0, 0]),
|
||||
twice,
|
||||
apart,
|
||||
];
|
||||
for bad in cases {
|
||||
let what = bad.name;
|
||||
let (s, r) = open(&file(1, 1, &[layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), bad], 8, false, false), json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under"], "{what}: {r}");
|
||||
assert_eq!(row_of(&s, &d.layers[0]), [[10, 20, 30, 255]], "{what}");
|
||||
assert_eq!(r["warnings"], json!(["1 adjustment layer was not applied"]), "{what}");
|
||||
}
|
||||
// The highest level and count are read.
|
||||
let under = |c: u8| layer("Under", [0, 0, 1, 1], [c, c, c, 255]);
|
||||
let (s, r) = open(&file(1, 1, &[under(254), adjustment("Max", b"thrs", &[0, 255, 0, 0])], 8, false, false), json!({}));
|
||||
assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[0, 0, 0, 255]], "{r}");
|
||||
let (s, r) = open(&file(1, 1, &[under(7), adjustment("Max", b"post", &[0, 255, 0, 0])], 8, false, false), json!({}));
|
||||
assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[7, 7, 7, 255]], "{r}");
|
||||
}
|
||||
|
||||
/// An adjustment layer whose merge needs more memory than allowed isn't applied: the layers below
|
||||
/// it stay as they are, with a warning.
|
||||
#[test]
|
||||
fn an_adjustment_merge_past_the_memory_allowed_isnt_applied() {
|
||||
let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
|
||||
let layers = [layer("Under", [0, 0, 2, 2], [10, 20, 30, 255]), layer("Beside", [2, 2, 4, 4], [1, 2, 3, 255]), adjustment("Invert", b"nvrt", &[])];
|
||||
let f = file(4, 4, &layers, 8, false, false);
|
||||
// Each 2 × 2 layer fits 128 bytes; the 4 × 4 canvas of both doesn't.
|
||||
let (doc, warnings) = psdlayers::import(&f, false, 128, cms).unwrap().unwrap();
|
||||
assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under", "Beside"]);
|
||||
assert_eq!(warnings, ["1 adjustment layer was not applied"]);
|
||||
let (doc, warnings) = psdlayers::import(&f, false, 1 << 20, cms).unwrap().unwrap();
|
||||
assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Beside + Invert"]);
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
// Clipped: the base's canvas with its shape doesn't fit 300 bytes, so the adjustment is left
|
||||
// out rather than applied to everything below.
|
||||
let layers = [layer("Base", [0, 0, 4, 4], [10, 20, 30, 255]), L { clipped: true, ..adjustment("Invert", b"nvrt", &[]) }];
|
||||
let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 300, cms).unwrap().unwrap();
|
||||
assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Base"]);
|
||||
assert_eq!(warnings, ["1 adjustment layer was not applied"]);
|
||||
// A layer clipped to an Invert layer whose merge doesn't fit comes in unclipped, and the Invert
|
||||
// layer isn't applied to the layers below it.
|
||||
let layers = [
|
||||
layer("Under", [0, 0, 2, 2], [10, 20, 30, 255]),
|
||||
adjustment("Invert", b"nvrt", &[]),
|
||||
L { clipped: true, ..layer("Photo", [0, 0, 4, 4], [1, 2, 3, 255]) },
|
||||
];
|
||||
let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 128, cms).unwrap().unwrap();
|
||||
assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under", "Photo"], "{warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w == "1 adjustment layer was not applied"), "{warnings:?}");
|
||||
}
|
||||
|
||||
/// An adjustment layer whose layer mask is too large for the memory allowed isn't applied, merged
|
||||
/// with the layers below it or clipped to one, and the file still opens with its layers.
|
||||
#[test]
|
||||
fn an_adjustment_mask_past_the_memory_allowed_isnt_applied() {
|
||||
let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
|
||||
// The 100 × 100 mask takes more than 128 bytes; the 1-pixel layer below it doesn't.
|
||||
let masked = |clipped: bool| L { clipped, mask: Some(([0, 0, 100, 100], 255, 0, vec![0; 10_000])), ..adjustment("Invert", b"nvrt", &[]) };
|
||||
for clipped in [false, true] {
|
||||
let f = file(1, 1, &[layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), masked(clipped)], 8, false, false);
|
||||
let (doc, warnings) = psdlayers::import(&f, false, 128, cms).unwrap_or_else(|e| panic!("{clipped}: {e}")).unwrap();
|
||||
assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under"], "{clipped}: {warnings:?}");
|
||||
assert_eq!(warnings, ["1 adjustment layer was not applied"], "{clipped}");
|
||||
// With the memory for it, the mask's black leaves the layer as it was.
|
||||
let (doc, warnings) = psdlayers::import(&f, false, 1 << 20, cms).unwrap().unwrap();
|
||||
assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Invert"], "{clipped}: {warnings:?}");
|
||||
assert!(warnings.is_empty(), "{clipped}: {warnings:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An adjustment layer's mask is read beside the canvases it changes: a 100 × 1 mask fits 256 bytes
|
||||
/// alone, but not beside a 6 × 1 canvas, so the layer isn't applied. With the memory for both, it is.
|
||||
#[test]
|
||||
fn an_adjustment_mask_counts_the_canvas_it_changes() {
|
||||
let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
|
||||
let masked = |clipped: bool| L { clipped, mask: Some(([0, 0, 1, 100], 255, 0, vec![255; 100])), ..adjustment("Invert", b"nvrt", &[]) };
|
||||
for clipped in [false, true] {
|
||||
let f = file(6, 1, &[layer("Under", [0, 0, 1, 6], [10, 20, 30, 255]), masked(clipped)], 8, false, false);
|
||||
let (doc, warnings) = psdlayers::import(&f, false, 256, cms).unwrap_or_else(|e| panic!("{clipped}: {e}")).unwrap();
|
||||
assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under"], "{clipped}: {warnings:?}");
|
||||
assert_eq!(warnings, ["1 adjustment layer was not applied"], "{clipped}");
|
||||
let (doc, warnings) = psdlayers::import(&f, false, 1 << 20, cms).unwrap().unwrap();
|
||||
assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Invert"], "{clipped}: {warnings:?}");
|
||||
assert!(warnings.is_empty(), "{clipped}: {warnings:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An adjustment layer whose mask is too large to read is left out without stopping the clip or the
|
||||
/// merge around it: a layer clipped above it still clips to the base, and a layer in a mode
|
||||
/// VectorCraft lacks above a pass-through group holding it still merges in its mode.
|
||||
#[test]
|
||||
fn an_adjustment_mask_too_large_leaves_the_clip_and_merge_around_it() {
|
||||
let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
|
||||
let masked = |clipped: bool| L { clipped, mask: Some(([0, 0, 100, 100], 255, 0, vec![255; 10_000])), ..adjustment("Invert", b"nvrt", &[]) };
|
||||
let layers = [layer("Base", [0, 0, 1, 1], [200, 0, 0, 255]), masked(true), L { clipped: true, ..layer("Photo", [0, 0, 1, 2], [0, 0, 255, 255]) }];
|
||||
let (doc, warnings) = psdlayers::import(&file(2, 1, &layers, 8, false, false), false, 128, cms).unwrap().unwrap();
|
||||
assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Base + Photo"], "{warnings:?}");
|
||||
assert_eq!(warnings, ["1 adjustment layer was not applied"]);
|
||||
// Gray 100 under Linear Dodge's gray 20 gives gray 120.
|
||||
let layers = [
|
||||
layer("Under", [0, 0, 1, 1], [100, 100, 100, 255]),
|
||||
group_end(),
|
||||
masked(false),
|
||||
group("Folder", b"pass"),
|
||||
L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [20, 20, 20, 255]) },
|
||||
];
|
||||
let (doc, warnings) = psdlayers::import(&file(1, 1, &layers, 8, false, false), false, 128, cms).unwrap().unwrap();
|
||||
assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Folder + Dodge"], "{warnings:?}");
|
||||
let merged = "layers in blend modes VectorCraft doesn't have (Linear Dodge) were merged with the layers below them";
|
||||
assert_eq!(warnings, ["1 adjustment layer was not applied", merged]);
|
||||
let Some([c]) = doc.layers[0].children().map(Vec::as_slice) else { panic!("the merged layer holds one image") };
|
||||
let NodeKind::Image(img) = &c.kind else { panic!("the merged layer holds an image") };
|
||||
let px = craft_image_codecs::decode(&doc.images[&img.key].bytes).unwrap().to_rgba8();
|
||||
assert_eq!(px, [120, 120, 120, 255]);
|
||||
}
|
||||
|
||||
/// A layer merged in a pass-through group for its mode or its knockout takes the adjustment layers
|
||||
/// kept below it with it: an adjustment layer above that group in an outer pass-through group then
|
||||
/// merges with it, and the gray 100 posterizes to 85.
|
||||
#[test]
|
||||
fn an_adjustment_layer_above_a_group_whose_kept_ones_merged_is_applied() {
|
||||
let tops = [
|
||||
("Linear Dodge", vec![L { blend: b"lddg", ..layer("Top", [0, 0, 1, 1], [100, 100, 100, 255]) }]),
|
||||
("knockout", vec![layer("Photo", [0, 0, 1, 1], [50, 50, 50, 255]), knockout(layer("Top", [0, 0, 1, 1], [100, 100, 100, 255]), 1, 255)]),
|
||||
];
|
||||
for (what, top) in tops {
|
||||
let layers = [
|
||||
&[group_end(), group_end(), adjustment("Invert", b"nvrt", &[])][..],
|
||||
&top,
|
||||
&[group("Inner", b"pass"), adjustment("Posterize", b"post", &[0, 4, 0, 0]), group("Folder", b"pass")],
|
||||
]
|
||||
.concat();
|
||||
let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(row_of(&s, sublayer(&d.layers[0], "Posterize")), [[85, 85, 85, 255]], "{what}: {r}");
|
||||
assert!(r["warnings"].to_string().contains("1 adjustment layer was not applied"), "{what}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An adjustment layer in a pass-through group, over a layer drawn below that group in an outer
|
||||
/// pass-through group, isn't kept to change what is below the outer group: a layer merged above
|
||||
/// them for its mode merges it applied, and the import doesn't count it as not applied. The gray
|
||||
/// 100 inverts to 155.
|
||||
#[test]
|
||||
fn an_adjustment_layer_in_a_group_over_a_drawn_layer_merges_applied() {
|
||||
let layers = [
|
||||
group_end(),
|
||||
layer("Photo", [0, 0, 1, 1], [100, 100, 100, 255]),
|
||||
group_end(),
|
||||
adjustment("Invert", b"nvrt", &[]),
|
||||
group("Inner", b"pass"),
|
||||
L { blend: b"lddg", ..layer("Top", [0, 0, 1, 1], [0, 0, 0, 255]) },
|
||||
group("Folder", b"pass"),
|
||||
];
|
||||
let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(row_of(&s, sublayer(&d.layers[0], "Top")), [[155, 155, 155, 255]], "{r}");
|
||||
assert!(!r["warnings"].to_string().contains("adjustment"), "{r}");
|
||||
}
|
||||
|
||||
/// A layer whose pixels are all transparent draws nothing: an adjustment layer above it in a
|
||||
/// pass-through group, directly or in a pass-through group inside it, still changes what is below
|
||||
/// the group.
|
||||
#[test]
|
||||
fn an_adjustment_layer_over_transparent_pixels_changes_what_is_below_the_group() {
|
||||
let clear = || layer("Clear", [0, 0, 1, 1], [50, 50, 50, 0]);
|
||||
let dodge = || L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) };
|
||||
let direct = [
|
||||
layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]),
|
||||
group_end(),
|
||||
clear(),
|
||||
adjustment("Invert", b"nvrt", &[]),
|
||||
group("Folder", b"pass"),
|
||||
dodge(),
|
||||
];
|
||||
let (s, r) = open(&file(1, 1, &direct, 8, false, false), json!({}));
|
||||
assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[245, 235, 225, 255]], "{r}");
|
||||
let nested = [
|
||||
layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]),
|
||||
group_end(),
|
||||
group_end(),
|
||||
clear(),
|
||||
adjustment("Invert", b"nvrt", &[]),
|
||||
group("Inner", b"pass"),
|
||||
adjustment("Posterize", b"post", &[0, 4, 0, 0]),
|
||||
group("Folder", b"pass"),
|
||||
dodge(),
|
||||
];
|
||||
let (s, r) = open(&file(1, 1, &nested, 8, false, false), json!({}));
|
||||
assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[255, 255, 255, 255]], "{r}");
|
||||
}
|
||||
|
||||
/// A layer or group whose layer mask hides all of it draws nothing: an adjustment layer above it in
|
||||
/// a pass-through group still changes what is below the group, and a shallow knockout hidden that
|
||||
/// way merges nothing, so the adjustment layers below it stay kept. A layer's mask hides all of it
|
||||
/// when it hides each of its pixels that isn't fully transparent, and a group's when it hides each
|
||||
/// such pixel of the group's layers, whatever the mask's value elsewhere; a layer hidden that way
|
||||
/// hides the layers clipped to it too. The layers in a pass-through group hidden that way don't
|
||||
/// count as drawing below an adjustment layer above the group.
|
||||
#[test]
|
||||
fn an_adjustment_layer_over_layers_their_masks_hide_changes_what_is_below_the_group() {
|
||||
let black = |l: L| L { mask: Some(([0, 0, 1, 2], 0, 0, vec![0, 0])), ..l };
|
||||
let under = || layer("Under", [0, 0, 1, 2], [10, 20, 30, 255]);
|
||||
let dodge = || L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 2], [0, 0, 0, 255]) };
|
||||
let photo = || layer("Photo", [0, 0, 1, 2], [100, 100, 100, 255]);
|
||||
let inverted = [[245, 235, 225, 255], [245, 235, 225, 255]];
|
||||
let masked_layer = [under(), group_end(), black(photo()), adjustment("Invert", b"nvrt", &[]), group("Folder", b"pass"), dodge()];
|
||||
// A mask over all of the layer's pixels hides it whatever its value outside them.
|
||||
let white_outside = L { mask: Some(([0, 0, 1, 2], 255, 0, vec![0, 0])), ..photo() };
|
||||
let covered_layer = [under(), group_end(), white_outside, adjustment("Invert", b"nvrt", &[]), group("Folder", b"pass"), dodge()];
|
||||
let masked_group = [
|
||||
under(),
|
||||
group_end(),
|
||||
group_end(),
|
||||
photo(),
|
||||
black(group("Inner", b"norm")),
|
||||
adjustment("Invert", b"nvrt", &[]),
|
||||
group("Folder", b"pass"),
|
||||
dodge(),
|
||||
];
|
||||
let knockout_cut = knockout(black(layer("Cut", [0, 0, 1, 1], [0, 0, 255, 255])), 1, 255);
|
||||
let masked_knockout = [
|
||||
under(),
|
||||
group_end(),
|
||||
group_end(),
|
||||
adjustment("Invert", b"nvrt", &[]),
|
||||
layer("Photo", [0, 0, 1, 1], [100, 100, 100, 255]),
|
||||
knockout_cut,
|
||||
group("Inner", b"pass"),
|
||||
adjustment("Posterize", b"post", &[0, 4, 0, 0]),
|
||||
group("Folder", b"pass"),
|
||||
dodge(),
|
||||
];
|
||||
// A knockout whose mask hides each pixel it doesn't leave transparent.
|
||||
let half = L { alpha: Some(vec![255, 0]), mask: Some(([0, 0, 1, 2], 0, 0, vec![0, 255])), ..layer("Cut", [0, 0, 1, 2], [0, 0, 255, 255]) };
|
||||
let mut transparent_knockout = masked_knockout.clone();
|
||||
transparent_knockout[5] = knockout(half, 1, 255);
|
||||
// A pass-through group its mask hides, below Invert in a pass-through group, with a layer drawn
|
||||
// above that group, under Posterize.
|
||||
let masked_pass = [
|
||||
under(),
|
||||
group_end(),
|
||||
group_end(),
|
||||
group_end(),
|
||||
photo(),
|
||||
black(group("Hidden", b"pass")),
|
||||
adjustment("Invert", b"nvrt", &[]),
|
||||
group("Inner", b"pass"),
|
||||
layer("Blue", [0, 0, 1, 1], [0, 0, 100, 255]),
|
||||
adjustment("Posterize", b"post", &[0, 4, 0, 0]),
|
||||
group("Folder", b"pass"),
|
||||
dodge(),
|
||||
];
|
||||
// Invert in a pass-through group its mask hides keeps nothing above that group: Posterize
|
||||
// merges with the layer below it, as with no such group.
|
||||
let masked_invert = [
|
||||
under(),
|
||||
group_end(),
|
||||
group_end(),
|
||||
adjustment("Invert", b"nvrt", &[]),
|
||||
black(group("Hidden", b"pass")),
|
||||
layer("Blue", [0, 0, 1, 1], [0, 0, 100, 255]),
|
||||
adjustment("Posterize", b"post", &[0, 4, 0, 0]),
|
||||
group("Folder", b"pass"),
|
||||
dodge(),
|
||||
];
|
||||
// A mask over only the pixels that aren't fully transparent, white outside it.
|
||||
let corner = |l: L| L { mask: Some(([0, 0, 1, 1], 255, 0, vec![0])), ..l };
|
||||
let half_photo = || L { alpha: Some(vec![255, 0]), ..photo() };
|
||||
let corner_layer = [under(), group_end(), corner(half_photo()), adjustment("Invert", b"nvrt", &[]), group("Folder", b"pass"), dodge()];
|
||||
let corner_group = [
|
||||
under(),
|
||||
group_end(),
|
||||
group_end(),
|
||||
half_photo(),
|
||||
corner(group("Inner", b"norm")),
|
||||
adjustment("Invert", b"nvrt", &[]),
|
||||
group("Folder", b"pass"),
|
||||
dodge(),
|
||||
];
|
||||
// The same mask over a group with a pixel drawn outside it: the group draws there.
|
||||
let drawn_group = [
|
||||
under(),
|
||||
group_end(),
|
||||
group_end(),
|
||||
photo(),
|
||||
corner(group("Inner", b"norm")),
|
||||
adjustment("Invert", b"nvrt", &[]),
|
||||
group("Folder", b"pass"),
|
||||
dodge(),
|
||||
];
|
||||
// A layer its mask hides, with a layer clipped to it.
|
||||
let clipped_base = [
|
||||
under(),
|
||||
group_end(),
|
||||
black(photo()),
|
||||
L { clipped: true, ..layer("Red", [0, 0, 1, 2], [200, 0, 0, 255]) },
|
||||
adjustment("Invert", b"nvrt", &[]),
|
||||
group("Folder", b"pass"),
|
||||
dodge(),
|
||||
];
|
||||
let cases = [
|
||||
("layer", &masked_layer[..], inverted),
|
||||
("covered layer", &covered_layer[..], inverted),
|
||||
("group", &masked_group[..], inverted),
|
||||
("knockout", &masked_knockout[..], [[85, 85, 85, 255], [255, 255, 255, 255]]),
|
||||
("transparent knockout", &transparent_knockout[..], [[85, 85, 85, 255], [255, 255, 255, 255]]),
|
||||
("pass-through group", &masked_pass[..], [[0, 0, 85, 255], [255, 255, 255, 255]]),
|
||||
("adjustment in a pass-through group", &masked_invert[..], [[0, 0, 85, 255], [10, 20, 30, 255]]),
|
||||
("layer covered where it draws", &corner_layer[..], inverted),
|
||||
("group covered where it draws", &corner_group[..], inverted),
|
||||
("group drawn outside its mask", &drawn_group[..], [[10, 20, 30, 255], [155, 155, 155, 255]]),
|
||||
("clipped base", &clipped_base[..], inverted),
|
||||
];
|
||||
let rows = |layers: &[L]| {
|
||||
let (s, _) = open(&file(2, 1, layers, 8, false, false), json!({}));
|
||||
row_of(&s, &s.doc().unwrap().doc.layers[0])
|
||||
};
|
||||
let got: Vec<_> = cases.iter().map(|(what, layers, _)| (*what, rows(layers))).collect();
|
||||
let want: Vec<_> = cases.iter().map(|(what, _, want)| (*what, want.to_vec())).collect();
|
||||
assert_eq!(got, want);
|
||||
}
|
||||
|
||||
/// Damaged Invert, Threshold and Posterize layers, masked and clipped, open without a panic.
|
||||
#[test]
|
||||
fn damaged_adjustment_layers_never_panic() {
|
||||
let layers = [
|
||||
layer("A", [0, 0, 2, 2], [255, 0, 0, 255]),
|
||||
L { mask: Some(([0, 0, 1, 1], 0, 0, vec![200])), ..adjustment("Invert", b"nvrt", &[]) },
|
||||
L { clipped: true, ..adjustment("Threshold", b"thrs", &[0, 128, 0, 0]) },
|
||||
adjustment("Posterize", b"post", &[0, 3, 0, 0]),
|
||||
];
|
||||
let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
|
||||
let good = file(2, 2, &layers, 8, false, false);
|
||||
assert!(psdlayers::import(&good, true, 1 << 30, cms).unwrap().is_some());
|
||||
for i in 0..good.len() {
|
||||
for v in [0, 1, 0x7f, 0x80, 0xff] {
|
||||
let mut f = good.clone();
|
||||
f[i] = v;
|
||||
let _ = psdlayers::import(&f, true, 1 << 30, cms);
|
||||
let _ = psdlayers::import(&f, false, 64, cms);
|
||||
}
|
||||
}
|
||||
for n in 0..good.len() {
|
||||
let _ = psdlayers::import(&good[..n], true, 1 << 30, cms);
|
||||
}
|
||||
}
|
||||
|
||||
/// Each blend mode VectorCraft lacks merges with the layer below by its formula, from the public
|
||||
/// descriptions: <https://helpx.adobe.com/photoshop/desktop/repair-retouch/adjust-light-tone/blending-mode-descriptions.html>
|
||||
/// (Vivid Light, Pin Light, Hard Mix, Darker and Lighter Color) and
|
||||
@@ -1449,6 +2247,12 @@ fn damaged_layers_never_panic() {
|
||||
assert!(psdlayers::import(&file(8, 8, &many[..16], 8, false, false), false, 512, cms).unwrap().is_some());
|
||||
let e = psdlayers::import(&file(8, 8, &many, 8, false, false), false, 512, cms).err();
|
||||
assert!(e.as_deref().is_some_and(|e| e.contains("take more memory to read than allowed")), "{e:?}");
|
||||
// Looking through those layers' transparency for pixels that draw, below an adjustment layer,
|
||||
// takes nothing from the allowance.
|
||||
let mut clear: Vec<L> = (0..16).map(|_| layer("x", [0, 0, 8, 8], [1, 2, 3, 0])).collect();
|
||||
clear.push(adjustment("Invert", b"nvrt", &[]));
|
||||
let opened = psdlayers::import(&file(8, 8, &clear, 8, false, false), false, 512, cms);
|
||||
assert!(opened.as_ref().is_ok_and(Option::is_some), "{:?}", opened.err());
|
||||
}
|
||||
|
||||
/// A layer in a mode VectorCraft lacks above a pass-through group merges with the group's layers
|
||||
|
||||
@@ -602,6 +602,217 @@ fn relink_and_update_follow_the_clipping_path_of_a_linked_psd() {
|
||||
assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared, true, NodeId(image)), "links.update reads the clipping path again");
|
||||
}
|
||||
|
||||
/// links.relink follows the clipping path of a linked PSD file for an image changed by Perspective
|
||||
/// Distort or Free Distort too: the new file's clipping path is mapped through the image's corners,
|
||||
/// a clip group of the old file's clipping path loses it when the new file names none, and a later
|
||||
/// file's clipping path clips it again.
|
||||
#[test]
|
||||
fn relink_follows_the_clipping_path_of_a_distorted_psd() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("psd-relink-distorted");
|
||||
let cut = write_file(&dir, "cut.psd", &red_psd(&triangle_resources()));
|
||||
let square = write_file(&dir, "square.psd", &red_psd(&square_resources()));
|
||||
let plain = write_file(&dir, "plain.psd", &red_psd(&[]));
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"path": cut, "at": [50, 25]})).unwrap();
|
||||
let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap()));
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap();
|
||||
let node = |s: &Session| s.doc().unwrap().doc.node(image).unwrap().clone();
|
||||
assert!(node(&s).is_distorted_image());
|
||||
let corners = node(&s).image_corners().unwrap();
|
||||
// A path's anchors (in the image's pixels) where the image's corners put them.
|
||||
let mapped = |s: &Session, pixels: &[[f64; 2]]| -> Vec<[f64; 2]> {
|
||||
let map = node(s).image_map().unwrap();
|
||||
pixels.iter().map(|[x, y]| map.apply(vectorcraft_geom::Point::new(*x, *y)).unwrap()).map(|p| [p.x, p.y]).collect()
|
||||
};
|
||||
let near =
|
||||
|a: &[[f64; 2]], b: &[[f64; 2]]| a.len() == b.len() && a.iter().zip(b).all(|(p, q)| (p[0] - q[0]).abs() < 1e-6 && (p[1] - q[1]).abs() < 1e-6);
|
||||
let (anchors, even_odd, held) = clip_group(&s.doc().unwrap().doc, group);
|
||||
let triangle = mapped(&s, &[[50.0, 0.0], [100.0, 50.0], [0.0, 50.0]]);
|
||||
assert!(near(&anchors, &triangle) && even_odd && held == image, "{anchors:?} vs {triangle:?}");
|
||||
s.execute("links.relink", &json!({"ids": [image.0], "path": square})).unwrap();
|
||||
let (anchors, even_odd, held) = clip_group(&s.doc().unwrap().doc, group);
|
||||
let squared = mapped(&s, &[[25.0, 12.5], [75.0, 12.5], [75.0, 37.5], [25.0, 37.5]]);
|
||||
assert!(near(&anchors, &squared) && even_odd && held == image, "the new file's clipping path: {anchors:?} vs {squared:?}");
|
||||
assert_eq!(node(&s).image_corners().unwrap(), corners);
|
||||
s.execute("links.relink", &json!({"ids": [image.0], "path": plain})).unwrap();
|
||||
match s.doc().unwrap().doc.node(group).map(|n| &n.kind) {
|
||||
Some(NodeKind::Group { children, clip: false }) => assert_eq!(children.iter().map(|c| c.id).collect::<Vec<_>>(), [image]),
|
||||
other => panic!("a plain group of the image: {other:?}"),
|
||||
}
|
||||
s.execute("links.relink", &json!({"ids": [image.0], "path": cut})).unwrap();
|
||||
let (anchors, _, held) = clip_group(&s.doc().unwrap().doc, group);
|
||||
assert!(near(&anchors, &triangle) && held == image, "clipped again: {anchors:?} vs {triangle:?}");
|
||||
assert!(node(&s).is_distorted_image());
|
||||
assert_eq!(node(&s).image_corners().unwrap(), corners);
|
||||
}
|
||||
|
||||
/// Update Links follows the clipping path of a linked PSD file for an image changed by Perspective
|
||||
/// Distort or Free Distort: the file's new clipping path is drawn through the image's corners, and
|
||||
/// a file without one leaves a plain group.
|
||||
#[test]
|
||||
fn update_links_follows_the_clipping_path_of_a_distorted_psd() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("psd-update-distorted");
|
||||
let cut = write_file(&dir, "cut.psd", &red_psd(&triangle_resources()));
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"path": cut, "at": [50, 25]})).unwrap();
|
||||
let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap()));
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap();
|
||||
let node = |s: &Session| s.doc().unwrap().doc.node(image).unwrap().clone();
|
||||
let corners = node(&s).image_corners().unwrap();
|
||||
let map = node(&s).image_map().unwrap();
|
||||
let squared: Vec<[f64; 2]> = [[25.0, 12.5], [75.0, 12.5], [75.0, 37.5], [25.0, 37.5]]
|
||||
.iter()
|
||||
.map(|[x, y]| map.apply(vectorcraft_geom::Point::new(*x, *y)).unwrap())
|
||||
.map(|p| [p.x, p.y])
|
||||
.collect();
|
||||
std::fs::write(&cut, red_psd(&square_resources())).unwrap();
|
||||
s.execute("links.update", &json!({"ids": [image.0]})).unwrap();
|
||||
let (anchors, even_odd, held) = clip_group(&s.doc().unwrap().doc, group);
|
||||
let near = anchors.len() == squared.len() && anchors.iter().zip(&squared).all(|(p, q)| (p[0] - q[0]).abs() < 1e-6 && (p[1] - q[1]).abs() < 1e-6);
|
||||
assert!(near && even_odd && held == image, "the file's new clipping path: {anchors:?} vs {squared:?}");
|
||||
assert_eq!(node(&s).image_corners().unwrap(), corners);
|
||||
std::fs::write(&cut, red_psd(&[])).unwrap();
|
||||
s.execute("links.update", &json!({"ids": [image.0]})).unwrap();
|
||||
match s.doc().unwrap().doc.node(group).map(|n| &n.kind) {
|
||||
Some(NodeKind::Group { children, clip: false }) => assert_eq!(children.iter().map(|c| c.id).collect::<Vec<_>>(), [image]),
|
||||
other => panic!("a plain group of the image: {other:?}"),
|
||||
}
|
||||
assert_eq!(node(&s).image_corners().unwrap(), corners);
|
||||
}
|
||||
|
||||
/// A document saved without its linked files keeps a linked PSD file's image as a preview, smaller
|
||||
/// than the file. Reopened after the file's clipping path changed, Update Links still knows the
|
||||
/// clip group of the old clipping path as the file's and gives it the new one, for an image changed
|
||||
/// by Perspective Distort or Free Distort and for one that is not.
|
||||
#[test]
|
||||
fn update_links_after_reopening_from_the_preview_replaces_the_files_clipping_path() {
|
||||
let big = |resources: &[u8]| psd(1, 3, (400, 200), 8, 3, &[], resources, &[], &raw(&[&[255; 80000], &[0; 80000], &[0; 80000]]));
|
||||
for distorted in [false, true] {
|
||||
let dir = vectorcraft_testkit::TempDir::new(if distorted { "psd-preview-distorted" } else { "psd-preview" });
|
||||
let cut = write_file(&dir, "cut.psd", &big(&triangle_resources()));
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"path": cut, "at": [200, 100]})).unwrap();
|
||||
let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap()));
|
||||
if distorted {
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[0, 0], [400, 30], [360, 200], [20, 180]]})).unwrap();
|
||||
}
|
||||
let node = |s: &Session| s.doc().unwrap().doc.node(image).unwrap().clone();
|
||||
let corners = node(&s).image_corners().unwrap();
|
||||
let doc_path = dir.join("poster.vectorcraft").to_string_lossy().into_owned();
|
||||
s.execute("document.save", &json!({"path": doc_path})).unwrap();
|
||||
std::fs::write(&cut, big(&square_resources())).unwrap();
|
||||
s.execute("document.open", &json!({"path": doc_path})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let NodeKind::Image(im) = &d.node(image).unwrap().kind else { panic!("an image") };
|
||||
assert!(d.images[&im.key].is_proxy(), "the saved preview shows");
|
||||
let r = s.execute("links.update", &json!({"ids": [image.0]})).unwrap();
|
||||
assert_eq!(r["updated"], json!([image.0]), "{r}");
|
||||
let map = node(&s).image_map().unwrap();
|
||||
let squared: Vec<[f64; 2]> = [[100.0, 50.0], [300.0, 50.0], [300.0, 150.0], [100.0, 150.0]]
|
||||
.iter()
|
||||
.map(|[x, y]| map.apply(vectorcraft_geom::Point::new(*x, *y)).unwrap())
|
||||
.map(|p| [p.x, p.y])
|
||||
.collect();
|
||||
let (anchors, even_odd, held) = clip_group(&s.doc().unwrap().doc, group);
|
||||
let near =
|
||||
anchors.len() == squared.len() && anchors.iter().zip(&squared).all(|(p, q)| (p[0] - q[0]).abs() < 1e-6 && (p[1] - q[1]).abs() < 1e-6);
|
||||
assert!(near && even_odd && held == image, "distorted: {distorted}: {anchors:?} vs {squared:?}");
|
||||
assert_eq!(node(&s).image_corners().unwrap(), corners);
|
||||
}
|
||||
}
|
||||
|
||||
/// Unembed of a distorted image from a PSD file, with a path and with a folder, keeps the clip
|
||||
/// group of the clipping path that file names, drawn through its corners, and so does relinking it
|
||||
/// to the file written. Update Links reads the clipping path the file on disk keeps then, and all
|
||||
/// four corners stay where they were.
|
||||
#[test]
|
||||
fn unembed_keeps_the_clipping_path_of_a_distorted_psd() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("psd-unembed-distorted-clip");
|
||||
// An RGB file is kept as a PNG, a CMYK one as a TIFF.
|
||||
let cmyk = |resources: &[u8]| psd(1, 4, (100, 50), 8, 4, &[], resources, &[], &raw(&[&[0; 5000], &[255; 5000], &[255; 5000], &[0; 5000]]));
|
||||
let files = [("rgb", red_psd(&triangle_resources())), ("cmyk", cmyk(&triangle_resources()))];
|
||||
// The file Unembed writes, as stored, for the same kind of file clipped to the square.
|
||||
let squared_file = |kind: &str| {
|
||||
let file = if kind == "rgb" { red_psd(&square_resources()) } else { cmyk(&square_resources()) };
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": "square.psd", "dataBase64": vectorcraft_format::base64_encode(&file)})).unwrap();
|
||||
let r = s.execute("links.unembed", &json!({"id": r["image"]})).unwrap();
|
||||
vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()
|
||||
};
|
||||
for ((kind, file), folder) in files.iter().flat_map(|f| [(f, false), (f, true)]) {
|
||||
let data = vectorcraft_format::base64_encode(file);
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "at": [50, 25]})).unwrap();
|
||||
let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap()));
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap();
|
||||
let before = clip_group(&s.doc().unwrap().doc, group);
|
||||
let corners = s.doc().unwrap().doc.node(image).unwrap().image_corners().unwrap();
|
||||
// Without an extension the image is written in the format it is stored in.
|
||||
let path = if folder {
|
||||
let out = dir.join(format!("folder-{kind}"));
|
||||
std::fs::create_dir_all(&out).unwrap();
|
||||
let r = s.execute("links.unembed", &json!({"ids": [image.0], "folder": out})).unwrap();
|
||||
r["unembedded"][0]["path"].as_str().unwrap().to_string()
|
||||
} else {
|
||||
let r = s.execute("links.unembed", &json!({"id": image.0, "path": dir.join(format!("written-{kind}"))})).unwrap();
|
||||
r["path"].as_str().unwrap().to_string()
|
||||
};
|
||||
let ext = if *kind == "rgb" { ["png"].as_slice() } else { ["tif", "tiff"].as_slice() };
|
||||
assert!(ext.contains(&super::extension(&path).as_str()), "{kind}: {path}");
|
||||
for step in ["unembed", "relink", "update"] {
|
||||
let mut want = before.0.clone();
|
||||
if step == "relink" {
|
||||
s.execute("links.relink", &json!({"ids": [image.0], "path": path})).unwrap();
|
||||
}
|
||||
if step == "update" {
|
||||
// The file on disk now keeps the square: Update Links reads it from there.
|
||||
std::fs::write(&path, squared_file(kind)).unwrap();
|
||||
let r = s.execute("links.update", &json!({"ids": [image.0]})).unwrap();
|
||||
assert_eq!(r["updated"], json!([image.0]), "{kind}: {r}");
|
||||
let map = s.doc().unwrap().doc.node(image).unwrap().image_map().unwrap();
|
||||
want = [[25.0, 12.5], [75.0, 12.5], [75.0, 37.5], [25.0, 37.5]]
|
||||
.iter()
|
||||
.map(|[x, y]| map.apply(vectorcraft_geom::Point::new(*x, *y)).unwrap())
|
||||
.map(|p| [p.x, p.y])
|
||||
.collect();
|
||||
}
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let NodeKind::Image(im) = &d.node(image).unwrap().kind else { panic!("an image") };
|
||||
assert!(im.link.is_some(), "linked to the file written");
|
||||
assert_eq!(d.node(image).unwrap().image_corners().unwrap(), corners, "{kind}, {step}, folder: {folder}");
|
||||
// The clipping path is drawn through the corners, within rounding.
|
||||
let (anchors, even_odd, held) = clip_group(d, group);
|
||||
let near =
|
||||
anchors.len() == want.len() && anchors.iter().zip(&want).all(|(p, q)| (p[0] - q[0]).abs() < 1e-6 && (p[1] - q[1]).abs() < 1e-6);
|
||||
assert!(near && (even_odd, held) == (before.1, before.2), "{kind}, {step}, folder: {folder}: {anchors:?} vs {want:?}");
|
||||
}
|
||||
}
|
||||
// A path that converts the image writes a file without the clipping path: the clip group
|
||||
// becomes a plain group of the image, as Relink to any file without one leaves it.
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
let data = vectorcraft_format::base64_encode(&red_psd(&triangle_resources()));
|
||||
let r = s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "at": [50, 25]})).unwrap();
|
||||
let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap()));
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap();
|
||||
s.execute("links.unembed", &json!({"id": image.0, "path": dir.join("converted.jpg")})).unwrap();
|
||||
match s.doc().unwrap().doc.node(group).map(|n| &n.kind) {
|
||||
Some(NodeKind::Group { children, clip: false }) => assert_eq!(children.iter().map(|c| c.id).collect::<Vec<_>>(), [image]),
|
||||
other => panic!("a plain group of the image: {other:?}"),
|
||||
}
|
||||
assert!(s.doc().unwrap().doc.node(image).unwrap().is_distorted_image());
|
||||
}
|
||||
|
||||
/// Unembed keeps the clip group of the clipping path an embedded PSD file's image came with, with a
|
||||
/// path and with a folder, and so do relinking to the written file, placing it and opening it.
|
||||
#[test]
|
||||
@@ -652,6 +863,78 @@ fn unembed_keeps_the_clipping_path_of_an_embedded_psd() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Unembed leaves a clipping mask released or edited in the document as it is, with a path and with
|
||||
/// a folder, for a plain image and for a distorted one: no clip group of the file's clipping path is
|
||||
/// put back or nested inside the edited mask. Every case runs, and the test names each one that
|
||||
/// fails.
|
||||
#[test]
|
||||
fn unembed_keeps_a_released_or_edited_clipping_mask() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("psd-unembed-mask");
|
||||
let data = vectorcraft_format::base64_encode(&red_psd(&triangle_resources()));
|
||||
let cases = ["release", "move"]
|
||||
.into_iter()
|
||||
.flat_map(|edit| [false, true].into_iter().flat_map(move |distort| [(edit, distort, false), (edit, distort, true)]));
|
||||
let failed: Vec<_> = cases
|
||||
.filter(|&(edit, distort, folder)| {
|
||||
std::panic::catch_unwind(|| unembed_mask_case(&dir.join(format!("{edit}-{distort}-{folder}")), &data, edit, distort, folder)).is_err()
|
||||
})
|
||||
.collect();
|
||||
assert!(failed.is_empty(), "failed: {failed:?}");
|
||||
}
|
||||
|
||||
/// One case of [`unembed_keeps_a_released_or_edited_clipping_mask`]: the clipping mask of a placed
|
||||
/// PSD file's image released or moved (`edit`), the image or the clip group then distorted with
|
||||
/// `distort`, and the image unembedded into `out`.
|
||||
fn unembed_mask_case(out: &std::path::Path, data: &str, edit: &str, distort: bool, folder: bool) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "at": [50, 25]})).unwrap();
|
||||
let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap()));
|
||||
if edit == "release" {
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
s.execute("object.clippingMask.release", &json!({})).unwrap();
|
||||
} else {
|
||||
let Some(NodeKind::Group { children, .. }) = s.doc().unwrap().doc.node(group).map(|n| &n.kind) else { panic!("a clip group") };
|
||||
let mask = children[0].id;
|
||||
s.execute("select.set", &json!({"ids": [mask.0]})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 10, "dy": 0})).unwrap();
|
||||
}
|
||||
if distort {
|
||||
let target = if edit == "release" { image } else { group };
|
||||
s.execute("select.set", &json!({"ids": [target.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(image).unwrap().is_distorted_image(), "{edit}, folder: {folder}: distorted");
|
||||
}
|
||||
let parent = |s: &Session| s.doc().unwrap().doc.parent_of(image);
|
||||
let before = (parent(&s), parent(&s).and_then(|p| s.doc().unwrap().doc.node(p).cloned()));
|
||||
std::fs::create_dir_all(out).unwrap();
|
||||
if folder {
|
||||
s.execute("links.unembed", &json!({"ids": [image.0], "folder": out})).unwrap();
|
||||
} else {
|
||||
s.execute("links.unembed", &json!({"id": image.0, "path": out.join("cut")})).unwrap();
|
||||
}
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let NodeKind::Image(im) = &d.node(image).unwrap().kind else { panic!("an image") };
|
||||
assert!(im.link.is_some(), "{edit}, folder: {folder}: linked to the file written");
|
||||
assert_eq!(parent(&s), before.0, "{edit}, folder: {folder}: the image stays where it was");
|
||||
let after = before.0.and_then(|p| d.node(p));
|
||||
match (edit, after.map(|n| &n.kind), before.1.as_ref().map(|n| &n.kind)) {
|
||||
// Released: the image is in no clip group, as before.
|
||||
("release", Some(NodeKind::Group { clip, .. }), _) => assert!(!clip, "folder: {folder}: the released mask came back"),
|
||||
("release", _, _) => {}
|
||||
// Moved: the same clip group of the moved path holds just the image.
|
||||
(_, Some(NodeKind::Group { children: a, clip: true }), Some(NodeKind::Group { children: b, clip: true })) => {
|
||||
assert_eq!(a.len(), 2, "{edit}, folder: {folder}: a clip group was nested inside the edited mask");
|
||||
let path = |c: &std::sync::Arc<vectorcraft_doc::Node>| match &c.kind {
|
||||
NodeKind::Path { path, .. } => path.anchors().map(|(_, _, a)| [a.p.x, a.p.y]).collect::<Vec<_>>(),
|
||||
_ => vec![],
|
||||
};
|
||||
assert_eq!((path(&a[0]), a[1].id), (path(&b[0]), image), "{edit}, folder: {folder}: the clipping mask");
|
||||
}
|
||||
other => panic!("{edit}, folder: {folder}: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The PNG a PSD file's merged image is kept as holds the clipping path the file names, and only a
|
||||
/// text chunk within the size limit that reads as a path gives one back.
|
||||
#[test]
|
||||
|
||||
@@ -65,12 +65,14 @@ fn settings_of(p: &Value, cmd: &str) -> Result<Value> {
|
||||
};
|
||||
let rays = count_or(p, "rays", 15, cmd)?.min(50);
|
||||
let rings = count_or(p, "rings", 10, cmd)?.min(50);
|
||||
// The end point is given whole or not at all: a lone `x2` or `y2` is refused.
|
||||
let end = match (p.get("x2").and_then(Value::as_f64), p.get("y2").and_then(Value::as_f64)) {
|
||||
(Some(x), Some(y)) => Point::new(x, y),
|
||||
_ => {
|
||||
(None, None) => {
|
||||
let a = f64_or(p, "direction", 45.0).to_radians();
|
||||
finite_end(c + Vec2::new(a.cos(), -a.sin()) * f64_or(p, "pathLength", 300.0), cmd)?
|
||||
}
|
||||
_ => Point::new(f64_req(p, "x2", cmd)?, f64_req(p, "y2", cmd)?),
|
||||
};
|
||||
let mut v = json!({ "cx": c.x, "cy": c.y, "x2": end.x, "y2": end.y, "rays": rays, "rings": rings, "seed": seed });
|
||||
if let Some(r) = ring_seed {
|
||||
|
||||
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Freeform Point",
|
||||
[],
|
||||
None,
|
||||
"{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its points); the points on a label's characters are not stored → {index}",
|
||||
"{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its points); the points on a label's characters are not stored; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {index}",
|
||||
has_doc,
|
||||
add_point
|
||||
),
|
||||
@@ -28,7 +28,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Freeform Point",
|
||||
[],
|
||||
None,
|
||||
"{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}",
|
||||
"{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {index}",
|
||||
has_doc,
|
||||
set_point
|
||||
),
|
||||
@@ -37,7 +37,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Delete Freeform Point",
|
||||
[],
|
||||
None,
|
||||
"{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go → {index}",
|
||||
"{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {index}",
|
||||
has_doc,
|
||||
delete_point
|
||||
),
|
||||
@@ -46,7 +46,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Freeform Line",
|
||||
[],
|
||||
None,
|
||||
"{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order → {line}",
|
||||
"{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {line}",
|
||||
has_doc,
|
||||
add_line
|
||||
),
|
||||
@@ -55,7 +55,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Split Freeform Line",
|
||||
[],
|
||||
None,
|
||||
"{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it → {index}",
|
||||
"{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {index}",
|
||||
has_doc,
|
||||
split_line
|
||||
),
|
||||
@@ -64,7 +64,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Select Freeform Point",
|
||||
[],
|
||||
None,
|
||||
"{index: point index | null to clear} select a point of the freeform gradient behind the active proxy (the first selected object's): the point the Gradient tool, the Gradient and Color panels and Delete act on → {index}",
|
||||
"{index: point index | null to clear} select a point of the freeform gradient behind the active proxy (the first selected object's; an index is an error while the proxies show the Live Paint Bucket's colors): the point the Gradient tool, the Gradient and Color panels and Delete act on → {index}",
|
||||
has_doc,
|
||||
select_point
|
||||
),
|
||||
@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Freeform Gradient",
|
||||
[],
|
||||
None,
|
||||
"{stroke?: bool (default: the active proxy)} the freeform gradient behind the proxy of the first selected object → {mode: points|lines, points: [{at: [x,y] (document coordinates), color, opacity, spread}], lines: [[index, …]], selected: index|null}",
|
||||
"{stroke?: bool (default: the active proxy)} the freeform gradient behind the proxy of the first selected object (an error while the proxies show the Live Paint Bucket's colors) → {mode: points|lines, points: [{at: [x,y] (document coordinates), color, opacity, spread}], lines: [[index, …]], selected: index|null}",
|
||||
has_doc,
|
||||
get
|
||||
),
|
||||
@@ -81,6 +81,14 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
|
||||
const NOT_FREEFORM: &str = "the paint is not a freeform gradient (apply one with paint.editGradient {kind: \"freeform\"})";
|
||||
const BUCKET_NOT_FREEFORM: &str = "the Live Paint Bucket's colors have no freeform points (give ids, id or item to edit an object's)";
|
||||
const BUCKET_NO_POINTS: &str = "the Live Paint Bucket's colors have no freeform points";
|
||||
|
||||
/// The error of `paint.freeform.get` and `paint.freeform.selectPoint` when the active proxy shows no freeform gradient:
|
||||
/// while the Live Paint Bucket paints, the proxies show its colors, which have none.
|
||||
fn no_proxy_freeform(s: &Session) -> &'static str {
|
||||
if s.bucket_paints() { BUCKET_NO_POINTS } else { NOT_FREEFORM }
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The selected freeform point (`paint.freeform.selectPoint`), while the gradient it was
|
||||
@@ -179,6 +187,14 @@ pub(crate) fn parse_mode(m: &str) -> std::result::Result<FreeformMode, String> {
|
||||
/// as one undo step; returns what it returned for the first. An unplaced gradient gets the
|
||||
/// automatic points it shows first, and the stops follow the points' colours.
|
||||
fn edit<R>(s: &mut Session, p: &Value, cmd: &str, mut f: impl FnMut(&mut Freeform, Space) -> std::result::Result<R, String>) -> Result<R> {
|
||||
// While the Live Paint Bucket paints, the proxies show its colors, which have no freeform points
|
||||
// (paint.freeform.get finds none): an edit that names no target is refused. A bad `aligned` or
|
||||
// `target` is refused first, as it is without the bucket.
|
||||
if super::paint::for_bucket(s, p) {
|
||||
super::appearance::aligned(p, cmd)?;
|
||||
super::appearance::targets_contents(p)?;
|
||||
return Err(bad(cmd, BUCKET_NOT_FREEFORM));
|
||||
}
|
||||
let item = item_target(s, p, cmd)?;
|
||||
let stroke = edits_stroke(s, p, item, !s.fill_active, cmd)?;
|
||||
let item = item.of_kind(s, !stroke);
|
||||
@@ -331,7 +347,7 @@ fn select_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(Value::Null) => None,
|
||||
Some(v) => {
|
||||
let i = v.as_u64().map(index).ok_or_else(|| bad(C, "`index` must be a whole number or null"))?;
|
||||
let (f, _) = s.proxy_freeform(!s.fill_active).ok_or_else(|| bad(C, NOT_FREEFORM))?;
|
||||
let (f, _) = s.proxy_freeform(!s.fill_active).ok_or_else(|| bad(C, no_proxy_freeform(s)))?;
|
||||
check_index(&f, i).map_err(|e| bad(C, e))?;
|
||||
Some(i)
|
||||
}
|
||||
@@ -343,7 +359,7 @@ fn select_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "paint.freeform.get";
|
||||
let stroke = switch_or(p, "stroke", !s.fill_active, C)?;
|
||||
let (f, _) = s.proxy_freeform(stroke).ok_or_else(|| bad(C, NOT_FREEFORM))?;
|
||||
let (f, _) = s.proxy_freeform(stroke).ok_or_else(|| bad(C, no_proxy_freeform(s)))?;
|
||||
let selected = if stroke != s.fill_active { s.selected_freeform_point().filter(|i| *i < f.points.len()) } else { None };
|
||||
let mut v = vectorcraft_tools::params::freeform_json(&f);
|
||||
v["selected"] = json!(selected);
|
||||
|
||||
@@ -3455,6 +3455,145 @@ fn redefining_a_graphic_style_keeps_an_edited_mark_of_a_linked_series_group() {
|
||||
assert!(marks[1..].iter().all(|m| d.node(*m).unwrap().extras().graphic_style == Some(style.id)));
|
||||
}
|
||||
|
||||
/// A column graph whose series 0 group is linked to style "Blue" (as a file can hold it) and whose first path directly
|
||||
/// inside that group is linked to style "Green" and has its look: the session, the graph, the group, series 0's paths,
|
||||
/// and the ids of "Blue" and "Green".
|
||||
fn linked_group_with_a_green_mark() -> (Session, NodeId, NodeId, Vec<NodeId>, u32, u32) {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
let (blue, green) = blue_and_green_styles(&mut s);
|
||||
link_group_and_member(&mut s, group, &blue, marks[0], &green);
|
||||
(s, id, group, marks, blue.id, green.id)
|
||||
}
|
||||
|
||||
/// Graphic styles "Blue" (a blue fill at 50% opacity) and "Green" (a green fill at full opacity), made from one new
|
||||
/// rectangle that is linked to neither.
|
||||
fn blue_and_green_styles(s: &mut Session) -> (vectorcraft_doc::GraphicStyle, vectorcraft_doc::GraphicStyle) {
|
||||
let (rect, _) = blue_style(s, "Blue", false);
|
||||
s.execute("appearance.setItem", &json!({"ids": [rect.0], "index": top_row(s, rect, true), "color": "#00ff00", "opacity": 100})).unwrap();
|
||||
s.execute("graphicStyle.new", &json!({"id": rect.0, "name": "Green"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
(d.graphic_style("Blue").unwrap().clone(), d.graphic_style("Green").unwrap().clone())
|
||||
}
|
||||
|
||||
/// Links `group` to `outer` with its look and `member` to `inner` with its look, as a file can hold them.
|
||||
fn link_group_and_member(
|
||||
s: &mut Session,
|
||||
group: NodeId,
|
||||
outer: &vectorcraft_doc::GraphicStyle,
|
||||
member: NodeId,
|
||||
inner: &vectorcraft_doc::GraphicStyle,
|
||||
) {
|
||||
s.edit("Link", |d, _| {
|
||||
let g = d.node_mut(group).unwrap();
|
||||
g.appearance = outer.appearance.clone().into();
|
||||
g.extras_mut().graphic_style = Some(outer.id);
|
||||
let m = d.node_mut(member).unwrap();
|
||||
m.appearance = inner.appearance.clone().into();
|
||||
m.extras_mut().graphic_style = Some(inner.id);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Asserts that `d` holds what `was` holds for a redefinition of style "Blue": its definition, the link of `group`, the
|
||||
/// look and link of each of `members`, and everything graph `id` stores (series paints and label rows included).
|
||||
fn assert_same_redefine_state(
|
||||
d: &vectorcraft_doc::Document,
|
||||
was: &vectorcraft_doc::Document,
|
||||
id: NodeId,
|
||||
group: NodeId,
|
||||
members: &[NodeId],
|
||||
when: &str,
|
||||
) {
|
||||
assert_eq!(d.graphic_style("Blue"), was.graphic_style("Blue"), "{when}: the definition of Blue");
|
||||
assert_eq!(d.node(group).unwrap().extras().graphic_style, was.node(group).unwrap().extras().graphic_style, "{when}: the group's link");
|
||||
for m in members {
|
||||
let (a, b) = (d.node(*m).unwrap(), was.node(*m).unwrap());
|
||||
assert_eq!((&a.appearance, a.extras().graphic_style), (&b.appearance, b.extras().graphic_style), "{when}: member {m:?}");
|
||||
}
|
||||
assert_eq!(d.node(id).unwrap().extras().graph, was.node(id).unwrap().extras().graph, "{when}: what the graph stores");
|
||||
}
|
||||
|
||||
/// Redefine Graphic Style with another style's look (`from`) on a linked series group leaves a path of the group that is
|
||||
/// linked to that other style linked to it, and restyles and links the group's other paths; one undo takes the
|
||||
/// redefinition back and redo makes it again.
|
||||
#[test]
|
||||
fn redefining_a_graphic_style_from_another_style_keeps_a_mark_linked_to_it() {
|
||||
let (mut s, id, group, marks, blue, green) = linked_group_with_a_green_mark();
|
||||
let own = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.clone();
|
||||
let look = s.doc().unwrap().doc.graphic_style("Green").unwrap().appearance.fill_paint();
|
||||
let was = s.doc().unwrap().doc.clone();
|
||||
s.execute("graphicStyle.redefine", &json!({"name": "Blue", "from": "Green"})).unwrap();
|
||||
let after = s.doc().unwrap().doc.clone();
|
||||
let first = after.node(marks[0]).unwrap();
|
||||
assert_eq!((&first.appearance, first.extras().graphic_style), (&own, Some(green)), "the mark keeps its own style");
|
||||
assert!(marks[1..].iter().all(|m| after.node(*m).unwrap().appearance.fill_paint() == look));
|
||||
assert!(marks[1..].iter().all(|m| after.node(*m).unwrap().extras().graphic_style == Some(blue)));
|
||||
assert_eq!(after.node(group).unwrap().extras().graphic_style, None);
|
||||
assert_eq!(spec(&s, id).series_paints[0].fill, Some(look), "the graph stores the new look");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_same_redefine_state(&s.doc().unwrap().doc, &was, id, group, &marks, "after one undo");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_same_redefine_state(&s.doc().unwrap().doc, &after, id, group, &marks, "after redo");
|
||||
}
|
||||
|
||||
/// Redefine Graphic Style from an object on a linked series group leaves a path of the group that is linked to another
|
||||
/// style as it is, restyles and links the group's other paths; one undo takes the redefinition back and redo makes it
|
||||
/// again.
|
||||
#[test]
|
||||
fn redefining_a_graphic_style_from_an_object_keeps_a_mark_linked_to_another_style() {
|
||||
let (mut s, id, group, marks, blue, green) = linked_group_with_a_green_mark();
|
||||
let own = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.clone();
|
||||
let red = NodeId(s.execute("shape.rectangle", &json!({"x": 700, "y": 700, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("appearance.setItem", &json!({"ids": [red.0], "index": top_row(&s, red, true), "color": "#ff0000", "opacity": 100})).unwrap();
|
||||
let look = s.doc().unwrap().doc.node(red).unwrap().appearance.fill_paint();
|
||||
let was = s.doc().unwrap().doc.clone();
|
||||
s.execute("graphicStyle.redefine", &json!({"name": "Blue", "id": red.0})).unwrap();
|
||||
let after = s.doc().unwrap().doc.clone();
|
||||
let first = after.node(marks[0]).unwrap();
|
||||
assert_eq!((&first.appearance, first.extras().graphic_style), (&own, Some(green)), "the mark keeps its own style");
|
||||
assert!(marks[1..].iter().all(|m| after.node(*m).unwrap().appearance.fill_paint() == look));
|
||||
assert!(marks[1..].iter().all(|m| after.node(*m).unwrap().extras().graphic_style == Some(blue)));
|
||||
assert_eq!(after.node(group).unwrap().extras().graphic_style, None);
|
||||
assert_eq!(spec(&s, id).series_paints[0].fill, Some(look), "the graph stores the new look");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_same_redefine_state(&s.doc().unwrap().doc, &was, id, group, &marks, "after one undo");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_same_redefine_state(&s.doc().unwrap().doc, &after, id, group, &marks, "after redo");
|
||||
}
|
||||
|
||||
/// Redefine Graphic Style on a graph's Legend group linked to the style leaves a label of the group that is linked to
|
||||
/// another style with its look and its link, restyles and links the group's other label, and clears and unlinks the
|
||||
/// group; one undo takes the redefinition back and redo makes it again.
|
||||
#[test]
|
||||
fn redefining_a_graphic_style_keeps_a_legend_label_linked_to_another_style() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let legend = group(s.doc().unwrap().doc.node(id).unwrap(), "Legend").id;
|
||||
let labels = [text_id(&s, id, "Legend", "2024"), text_id(&s, id, "Legend", "2025")];
|
||||
let (blue, green) = blue_and_green_styles(&mut s);
|
||||
link_group_and_member(&mut s, legend, &blue, labels[0], &green);
|
||||
let own = s.doc().unwrap().doc.node(labels[0]).unwrap().appearance.clone();
|
||||
let red = NodeId(s.execute("shape.rectangle", &json!({"x": 700, "y": 700, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("appearance.setItem", &json!({"ids": [red.0], "index": top_row(&s, red, true), "color": "#ff0000", "opacity": 100})).unwrap();
|
||||
let look = s.doc().unwrap().doc.node(red).unwrap().appearance.fill_paint();
|
||||
let was = s.doc().unwrap().doc.clone();
|
||||
s.execute("graphicStyle.redefine", &json!({"name": "Blue", "id": red.0})).unwrap();
|
||||
let after = s.doc().unwrap().doc.clone();
|
||||
let kept = after.node(labels[0]).unwrap();
|
||||
assert_eq!((&kept.appearance, kept.extras().graphic_style), (&own, Some(green.id)), "the label keeps its own style");
|
||||
let other = after.node(labels[1]).unwrap();
|
||||
assert_eq!((other.appearance.fill_paint(), other.extras().graphic_style), (look, Some(blue.id)), "the other label follows");
|
||||
let g = after.node(legend).unwrap();
|
||||
assert_eq!((g.appearance.items.is_empty(), g.extras().graphic_style), (true, None), "the group is cleared and unlinked");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_same_redefine_state(&s.doc().unwrap().doc, &was, id, legend, &labels, "after one undo");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_same_redefine_state(&s.doc().unwrap().doc, &after, id, legend, &labels, "after redo");
|
||||
}
|
||||
|
||||
/// Series `index`'s group: its object opacity and blend mode, and those of each path directly inside it.
|
||||
fn group_transparency(s: &Session, id: NodeId, index: u32) -> ((f32, BlendMode), Vec<(f32, BlendMode)>) {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
@@ -9472,6 +9611,29 @@ fn appearance_commands_given_the_axes_or_legend_group_edit_its_lines_and_labels(
|
||||
}
|
||||
}
|
||||
|
||||
/// Aligned rows copied to `to` given the Legend group, whose labels have the same rows, go to `to` in every label.
|
||||
#[test]
|
||||
fn aligned_copies_given_the_legend_group_go_to_to_when_its_labels_have_the_same_rows() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let labels = |s: &Session| -> Vec<vectorcraft_doc::Appearance> {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
group(&n, "Legend").children().unwrap().iter().map(|c| (*c.appearance).clone()).collect()
|
||||
};
|
||||
let legend = group(s.doc().unwrap().doc.node(id).unwrap(), "Legend").id;
|
||||
s.execute("appearance.addFill", &json!({"ids": [legend.0]})).unwrap();
|
||||
s.execute("appearance.addStroke", &json!({"ids": [legend.0]})).unwrap();
|
||||
let was = labels(&s);
|
||||
assert!(was.len() >= 2 && was.iter().all(|a| *a == was[0]) && was[0].items.len() >= 2, "{was:?}");
|
||||
let top = was[0].items.len() - 1;
|
||||
s.execute("appearance.duplicateItem", &json!({"ids": [legend.0], "index": top, "to": 0, "aligned": true})).unwrap();
|
||||
for a in labels(&s) {
|
||||
assert_eq!(a.items.len(), was[0].items.len() + 1);
|
||||
assert_eq!(a.items[0], was[0].items[top], "the copy is at the bottom");
|
||||
}
|
||||
}
|
||||
|
||||
/// A row index given the Axes group, whose lines and labels have different rows, is refused unless it is `aligned`, a row
|
||||
/// of the backmost member's stack: then the members that share that row change, the labels keep theirs, and the graph
|
||||
/// keeps the change when it is drawn again.
|
||||
|
||||
@@ -332,6 +332,36 @@ fn pasted_type_brings_its_kinsoku_sets() {
|
||||
assert_eq!(style_set(&s), Value::Null);
|
||||
}
|
||||
|
||||
/// Type pasted back after its set was edited breaks its lines by the set as it is now: with B in
|
||||
/// Cannot End Line the first line of `A B C` ends at A, and once the set holds nothing, it ends at B.
|
||||
#[test]
|
||||
fn pasted_type_relayouts_after_its_kinsoku_set_was_edited() {
|
||||
let mut s = session();
|
||||
s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "Tight", "cannotEnd": "B"}]})).unwrap();
|
||||
let create = json!({"x": 10, "y": 10, "text": "A B C", "size": 20, "font": "JetBrains Mono", "area": {"width": 40, "height": 120}});
|
||||
let id = s.execute("text.create", &create).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"kinsoku": "Tight"})).unwrap();
|
||||
let lines = |t: &vectorcraft_doc::TextObject| t.baselines().collect::<Vec<_>>();
|
||||
let first_width = |t: &vectorcraft_doc::TextObject| t.baselines().next().map(|(a, b)| b.x - a.x).unwrap_or_default();
|
||||
let copied = text(&s, id);
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "Tight"}]})).unwrap();
|
||||
// The set's edit lays the type in the document out anew, and its first line takes B.
|
||||
let edited = text(&s, id);
|
||||
assert_eq!(lines(&edited).len(), 2);
|
||||
assert!(first_width(&edited) > first_width(&copied), "{:?} against {:?}", lines(&edited), lines(&copied));
|
||||
|
||||
let v = s.execute("edit.paste", &json!({})).unwrap();
|
||||
let t = text(&s, v["ids"][0].as_u64().unwrap());
|
||||
let now = s.doc().unwrap().doc.kinsoku_sets[0].clone();
|
||||
assert_eq!(t.para_at(0).kinsoku_set.as_deref(), Some(&now));
|
||||
let mut fresh = t.clone();
|
||||
crate::cmd::typecmd::refresh_bounds(&mut fresh);
|
||||
assert_eq!(lines(&t), lines(&fresh), "the pasted type is laid out with the edited set");
|
||||
assert_eq!(first_width(&t), first_width(&edited));
|
||||
}
|
||||
|
||||
/// A pasted set whose name, at the longest a name can be, the document's set with other
|
||||
/// characters already has comes in under a free name that fits: the number takes the place of the
|
||||
/// name's last characters, and a space left at the end of them is dropped. A second paste uses
|
||||
|
||||
@@ -20,7 +20,6 @@ use serde_json::{Map, Value, json};
|
||||
use vectorcraft_color::{Color, GradientPaint, Paint};
|
||||
use vectorcraft_doc::{Appearance, Node, NodeId, TextStyleDef};
|
||||
|
||||
use super::clipboard::SwatchChoices;
|
||||
use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd, color_value, has_doc, ids_param, index_opt, ok, point_param, str_param};
|
||||
use crate::Clipboard;
|
||||
|
||||
@@ -713,7 +712,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Use Library Item",
|
||||
[],
|
||||
None,
|
||||
"{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number; a character style's color linked to a swatch that isn't a global or spot swatch of the document keeps the color it shows, unlinked) and apply it to the selected text, one undo step → {kind, ids?, style?}",
|
||||
"{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused, also when its art links to the document's own color of a name; a global or spot color its art links to whose name the document gives another color comes in numbered, or as the document's numbered copy of the same color, and the pattern links to it) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number; a character style's color linked to a swatch that isn't a global or spot swatch of the document keeps the color it shows, unlinked) and apply it to the selected text, one undo step → {kind, ids?, style?}",
|
||||
has_doc,
|
||||
use_item
|
||||
),
|
||||
@@ -1353,12 +1352,13 @@ fn use_pattern(s: &mut Session, data: &Value, stroke: bool) -> Result<String> {
|
||||
if clip.nodes.is_empty() {
|
||||
return Err(damaged());
|
||||
}
|
||||
let choices = SwatchChoices::default();
|
||||
// The pattern's name in the document, worked out on a copy: nothing to add is no edit.
|
||||
let mut probe = (*s.doc()?.doc).clone();
|
||||
let imported = clip.import_into(&mut probe, &choices, false)?;
|
||||
let renamed = imported.renamed.iter().find(|r| r["kind"] == "pattern" && r["from"] == name.as_str()).and_then(|r| r["to"].as_str());
|
||||
let target = renamed.unwrap_or(&name).to_string();
|
||||
// The pattern's name in the document, worked out on a copy: nothing to add is no edit. A global
|
||||
// or spot color the pattern's art links to keeps the library's color, as Add to Swatches brings
|
||||
// a library pattern's colors.
|
||||
let current = s.doc()?.doc.clone();
|
||||
let (choices, probe, imported) = super::patternlib::probe_import(¤t, &doc, &name, &clip)?;
|
||||
drop(current);
|
||||
let target = super::patternlib::imported_name(&imported, &name);
|
||||
let paint = vectorcraft_doc::pattern::pattern_paint(&target);
|
||||
// A pattern the document holds without a swatch (an imported SVG's) gets one.
|
||||
let has_swatch =
|
||||
|
||||
+145
-59
@@ -33,7 +33,7 @@ use vectorcraft_doc::{
|
||||
Appearance, DataValue, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, PlacedDocument, PlacementOptions,
|
||||
StoredPlace, StoredRoot,
|
||||
};
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes};
|
||||
use vectorcraft_geom::{Affine, FillRule, Homography, PathData, Rect, shapes};
|
||||
|
||||
use super::fileio::{self, RasterImage, absolute_path, file_created, file_stamp, read_file, write_file};
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, ids_param, object_param, str_param, switch_or, text_param};
|
||||
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Update Links",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. Images and placed documents inside symbols, graph designs, patterns, opacity masks and the art of stored brushes have ids of their own, as links.list gives them; those that show the same content as one read again are read again too. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns]}",
|
||||
"{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. Images and placed documents inside symbols, graph designs, patterns, opacity masks and the art of stored brushes have ids of their own, as links.list gives them; those that show the same content as one read again are read again too. An image changed by Perspective Distort or Free Distort keeps its corners, with the file's pixels between them, and its Placement Options do not apply; the clipping path its file names is drawn through the corners, and a clip group of the old file's clipping path gets the new one, or becomes a plain group when the file names none. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns]}",
|
||||
has_doc,
|
||||
update
|
||||
),
|
||||
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Relink",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object linked to the same file as one of them, in the layers, opacity-mask art, symbols, graph designs, patterns and the art of stored brushes) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's)}",
|
||||
"{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object linked to the same file as one of them, in the layers, opacity-mask art, symbols, graph designs, patterns and the art of stored brushes) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. An image changed by Perspective Distort or Free Distort keeps its corners, with the new file's pixels between them, whatever preserve or its Placement Options say, and its clipping is handled as links.update handles it. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's, and, when preserve is given, one naming the distorted images it was not applied to)}",
|
||||
has_doc,
|
||||
relink
|
||||
),
|
||||
@@ -99,7 +99,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Embed Image",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [image or placed document ids] (default: the selected linked ones)} break the links (the Links panel's Break Link): images keep the linked files' pixels in the document; a placed document becomes an editable copy of its art, as placing its file without link gives (its symbols, patterns, swatches and images joining the document). An image whose file can't be found and that shows the saved preview, or a placed document whose file can't be read or changed, stays linked: relink or update it first. An image placed from a DCS file can't be embedded (an error, and nothing changes). One undo step → {embedded: [ids], missing: [ids]}",
|
||||
"{ids?: [image or placed document ids] (default: the selected linked ones)} break the links (the Links panel's Break Link): images keep the linked files' pixels in the document; a placed document becomes an editable copy of its art, as placing its file without link gives (its symbols, patterns, swatches and images joining the document). An image whose file can't be found and that shows the saved preview, or a placed document whose file can't be read or changed, stays linked: relink or update it first. An image placed from a DCS file can't be embedded (an error, and nothing changes). An image changed by Perspective Distort or Free Distort keeps its corners. One undo step → {embedded: [ids], missing: [ids]}",
|
||||
has_doc,
|
||||
embed
|
||||
),
|
||||
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Unembed",
|
||||
[],
|
||||
None,
|
||||
"{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds; written as stored (here and with folder), an image from a PSD or PSB file keeps the clip group of the clipping path that file names, and the file written keeps the path, so Open, Place, Relink and Update Links read the file with that clip group. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds. One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors",
|
||||
"{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path and link the image to it, keeping its bounds (an image changed by Perspective Distort or Free Distort keeps its corners). The image is written as stored (PNG, JPEG, GIF, WebP or TIFF; as PNG when that format is not one of VectorCraft's raster file formats) when path has no extension or names the stored format, and converted when path ends in another of .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp. Written as stored (here and with folder), an image from a PSD or PSB file keeps the clip group of the clipping path that file names, and the file written keeps the path, so Open, Place, Relink and Update Links read the file with that clip group (drawn through a distorted image's corners); a converted file holds no clipping path, and the clip group becomes a plain group. A clipping mask released, edited or made in the document stays as it is, in either case. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds (a distorted image its corners). One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors",
|
||||
has_doc,
|
||||
unembed
|
||||
),
|
||||
@@ -609,13 +609,14 @@ pub(crate) fn kept_unread(bytes: &[u8]) -> bool {
|
||||
/// `blob`, an image [`fileio::raster_image`] read from a file, ready to keep. When `unread` (the
|
||||
/// file is one [`kept_unread`] names), its pixels are decoded once to check that they can be read,
|
||||
/// and a `linked` image's preview is made from that decode ([`ImageBlob::checked_with_proxy`]);
|
||||
/// otherwise a `linked` image gets its preview ([`ImageBlob::with_proxy`]). An error when the
|
||||
/// pixels can't be read.
|
||||
/// otherwise a `linked` image gets its preview ([`ImageBlob::with_proxy`]). The preview keeps the
|
||||
/// clipping path the image keeps ([`fileio::preview_with_clip`]). An error when the pixels can't
|
||||
/// be read.
|
||||
pub(crate) fn readable(blob: ImageBlob, unread: bool, linked: bool) -> Result<ImageBlob> {
|
||||
if !unread {
|
||||
return Ok(if linked { blob.with_proxy() } else { blob });
|
||||
return Ok(if linked { fileio::preview_with_clip(blob.with_proxy()) } else { blob });
|
||||
}
|
||||
blob.checked_with_proxy(linked).ok_or_else(|| EngineError::Other("the image's pixels can't be read".into()))
|
||||
blob.checked_with_proxy(linked).map(fileio::preview_with_clip).ok_or_else(|| EngineError::Other("the image's pixels can't be read".into()))
|
||||
}
|
||||
|
||||
/// [`readable`], and the pixels it decoded are kept in the image store the renderers share
|
||||
@@ -626,6 +627,7 @@ pub(crate) fn readable_and_kept(blob: ImageBlob, unread: bool, linked: bool) ->
|
||||
return readable(blob, unread, linked);
|
||||
}
|
||||
let (blob, pixels) = blob.checked_with_pixels(linked).ok_or_else(|| EngineError::Other("the image's pixels can't be read".into()))?;
|
||||
let blob = fileio::preview_with_clip(blob);
|
||||
if let Some(pixels) = pixels {
|
||||
vectorcraft_render::keep_decoded_image(&blob, pixels);
|
||||
}
|
||||
@@ -792,13 +794,20 @@ fn clip_to(
|
||||
new_xf: Affine,
|
||||
held: Option<(&PathData, FillRule)>,
|
||||
) -> ClipTo {
|
||||
let old = old_clip.filter(|_| held.is_some()).map(|(path, rule)| (path.transformed(old_xf), *rule));
|
||||
let file = img.clip.as_ref().map(|(path, rule)| (path.transformed(new_xf), *rule));
|
||||
placed_clip_to(old.as_ref(), clip, file, held)
|
||||
}
|
||||
|
||||
/// [`clip_to`] with the clipping paths of the old file (`old`) and of the new file (`file`) already
|
||||
/// on the page.
|
||||
fn placed_clip_to(old: Option<&FileClip>, clip: Option<Clip>, file: Option<FileClip>, held: Option<(&PathData, FillRule)>) -> ClipTo {
|
||||
// Whether the clip group holding just the image is the old file's: a clipping path whose fill
|
||||
// rule was changed in the document is not.
|
||||
let file_held = match (old_clip, held) {
|
||||
(Some((old, old_rule)), Some((held, rule))) => rule == *old_rule && same_path(&old.transformed(old_xf), held),
|
||||
let file_held = match (old, held) {
|
||||
(Some((old, old_rule)), Some((held, rule))) => rule == *old_rule && same_path(old, held),
|
||||
_ => false,
|
||||
};
|
||||
let file = img.clip.as_ref().map(|(path, rule)| (path.transformed(new_xf), *rule));
|
||||
if let Some(clip) = clip {
|
||||
let placement = clip_shape(clip);
|
||||
return match file {
|
||||
@@ -1211,21 +1220,75 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_
|
||||
install(d, &[id], read, Some(Preserve::Bounds), None)
|
||||
}
|
||||
|
||||
/// Distorted image `im` shows the file read for `link` (`img`) and keeps its corners and its
|
||||
/// clipping: the new pixels fill them. Its transform is scaled to the new pixel size, so a reader
|
||||
/// that places it by the transform still gives it its old size.
|
||||
fn refill_distorted(im: &mut ImageObject, link: &LinkInfo, img: &RasterImage) {
|
||||
if (img.width, img.height) != (im.width, im.height) && img.width > 0 && img.height > 0 {
|
||||
im.xf *= Affine::scale_non_uniform(f64::from(im.width) / f64::from(img.width), f64::from(im.height) / f64::from(img.height));
|
||||
/// Distorted image `n` shows the file read for `link` (`img`) and keeps its corners: the new pixels
|
||||
/// fill them. Its transform is scaled to the new pixel size, so a reader that places it by the
|
||||
/// transform still gives it its old size. Its Placement Options do not apply. The result is what
|
||||
/// happens to its clip, as [`clip_to`] decides from the clipping path of the clip group holding
|
||||
/// just it (`held`): the clipping paths of its old file (`old_clip`, in its old pixels) and of the
|
||||
/// new file (`img.clip`, else the path kept in its stored PNG or TIFF, as Unembed writes it:
|
||||
/// [`file_clip`]) are mapped to the page through its corners, anchors and handles alike, as a
|
||||
/// distort maps a path's.
|
||||
fn refill_distorted(n: &mut Node, old_clip: Option<&FileClip>, link: &LinkInfo, img: &RasterImage, held: Option<(&PathData, FillRule)>) -> ClipTo {
|
||||
let old = old_clip.filter(|_| held.is_some()).and_then(|(path, rule)| Some((warped(path, &n.image_map()?)?, *rule)));
|
||||
if let NodeKind::Image(im) = &mut n.kind {
|
||||
if (img.width, img.height) != (im.width, im.height) && img.width > 0 && img.height > 0 {
|
||||
im.xf *= Affine::scale_non_uniform(f64::from(im.width) / f64::from(img.width), f64::from(im.height) / f64::from(img.height));
|
||||
}
|
||||
(im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, Some(link.clone()));
|
||||
}
|
||||
(im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, Some(link.clone()));
|
||||
let file = img.clip.clone().or_else(|| file_clip(&img.blob)).and_then(|(path, rule)| Some((warped(&path, &n.image_map()?)?, rule)));
|
||||
placed_clip_to(old.as_ref(), None, file, held)
|
||||
}
|
||||
|
||||
/// `path` with its anchors and handles mapped through `map` as a distort maps a path's points
|
||||
/// (`xform::Projective::apply`): a point on the map's horizon is mapped as if a billionth in front
|
||||
/// of it, and one past it to the far side. `None` when a point maps to no finite page point.
|
||||
fn warped(path: &PathData, map: &Homography) -> Option<PathData> {
|
||||
let [[a, b, c], [d, e, f], [g, h, i]] = map.0;
|
||||
let apply = |p: vectorcraft_geom::Point| {
|
||||
let w = g * p.x + h * p.y + i;
|
||||
let w = if w.abs() < 1e-9 { 1e-9_f64.copysign(w) } else { w };
|
||||
let q = vectorcraft_geom::Point::new((a * p.x + b * p.y + c) / w, (d * p.x + e * p.y + f) / w);
|
||||
q.is_finite().then_some(q)
|
||||
};
|
||||
let mut out = path.clone();
|
||||
for sp in &mut out.subpaths {
|
||||
for anchor in &mut sp.anchors {
|
||||
(anchor.p, anchor.h_in, anchor.h_out) = (apply(anchor.p)?, apply(anchor.h_in)?, apply(anchor.h_out)?);
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Image objects `ids` (in the layers or outside them) show the file read for `link` (`img`), each
|
||||
/// placed as its Placement Options say (`force`: as that Preserve choice says, whatever they say);
|
||||
/// with `also` (a file's path and the content shown), so do the images outside the layer tree that
|
||||
/// show that content.
|
||||
fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Option<Preserve>, also: Option<(&str, &str)>) -> Result<()> {
|
||||
fn install(d: &mut Document, ids: &[NodeId], read: FileRead, force: Option<Preserve>, also: Option<(&str, &str)>) -> Result<()> {
|
||||
install_with(d, ids, read, force, also, false)
|
||||
}
|
||||
|
||||
/// What Unembed (`unembed`) does with the clip `to` of an image whose clip group holding just it
|
||||
/// has a clipping path (`held`): a clipping mask released, edited or made in the document stays as
|
||||
/// it is, and only a clip group of the old file's own clipping path follows the file written.
|
||||
fn unembed_clip(to: ClipTo, held: bool) -> ClipTo {
|
||||
match to {
|
||||
ClipTo::Nest(_) => ClipTo::Keep,
|
||||
ClipTo::File(_) if !held => ClipTo::Keep,
|
||||
to => to,
|
||||
}
|
||||
}
|
||||
|
||||
/// As [`install`]; with `unembed`, each clip goes through [`unembed_clip`].
|
||||
fn install_with(
|
||||
d: &mut Document,
|
||||
ids: &[NodeId],
|
||||
(link, img): FileRead,
|
||||
force: Option<Preserve>,
|
||||
also: Option<(&str, &str)>,
|
||||
unembed: bool,
|
||||
) -> Result<()> {
|
||||
let keep = |to: ClipTo, held: bool| if unembed { unembed_clip(to, held) } else { to };
|
||||
let new_pt = super::place::pt_per_px(img.ppi);
|
||||
let mut clips = vec![];
|
||||
let nested = nested_ids(d, ids);
|
||||
@@ -1245,12 +1308,15 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio
|
||||
let mut make = |n: &Node, held: Option<(&PathData, FillRule)>| {
|
||||
let mut n = n.clone();
|
||||
let mut clip = ClipTo::Keep;
|
||||
let distorted = n.is_distorted_image();
|
||||
if n.is_distorted_image() {
|
||||
let old_clip = match &n.kind {
|
||||
NodeKind::Image(im) => old.get(&im.key).and_then(|(_, clip)| clip.clone()),
|
||||
_ => None,
|
||||
};
|
||||
let clip = refill_distorted(&mut n, old_clip.as_ref(), &link, &img, held);
|
||||
return (n, keep(clip, held.is_some()));
|
||||
}
|
||||
if let NodeKind::Image(im) = &mut n.kind {
|
||||
if distorted {
|
||||
refill_distorted(im, &link, &img);
|
||||
return (n, clip);
|
||||
}
|
||||
let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement };
|
||||
let size = |w: u32, h: u32| (w as f64, h as f64);
|
||||
let (old_pt, old_clip) = match old.get(&im.key) {
|
||||
@@ -1258,7 +1324,7 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio
|
||||
None => (super::place::pt_per_px(None), None),
|
||||
};
|
||||
let (xf, c) = placed_xf(im.xf, size(im.width, im.height), old_pt, size(img.width, img.height), new_pt, o);
|
||||
clip = clip_to(im.xf, old_clip, c, &img, xf, held);
|
||||
clip = keep(clip_to(im.xf, old_clip, c, &img, xf, held), held.is_some());
|
||||
(im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone()));
|
||||
}
|
||||
(n, clip)
|
||||
@@ -1267,10 +1333,14 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio
|
||||
}
|
||||
for id in ids {
|
||||
if d.node(*id).is_some_and(Node::is_distorted_image) {
|
||||
if let Some(n) = d.node_mut(*id)
|
||||
&& let NodeKind::Image(im) = &mut n.kind
|
||||
{
|
||||
refill_distorted(im, &link, &img);
|
||||
let old_clip = match d.node(*id).map(|n| &n.kind) {
|
||||
Some(NodeKind::Image(im)) => d.images.get(&im.key).and_then(file_clip),
|
||||
_ => None,
|
||||
};
|
||||
let held = clip_path_of(d, *id).map(|(path, rule)| (path.clone(), rule));
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
let clip = refill_distorted(n, old_clip.as_ref(), &link, &img, held.as_ref().map(|(path, rule)| (path, *rule)));
|
||||
clips.push((*id, keep(clip, held.is_some())));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -1281,7 +1351,8 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio
|
||||
// Placement Options' clip, else the clipping path of a DCS file (read again with its
|
||||
// plates) or of a PSD or PSB file.
|
||||
let old_clip = d.images.get(&im.key).and_then(file_clip);
|
||||
clips.push((*id, clip_to(im.xf, old_clip.as_ref(), clip, &img, xf, clip_path_of(d, *id))));
|
||||
let held = clip_path_of(d, *id);
|
||||
clips.push((*id, keep(clip_to(im.xf, old_clip.as_ref(), clip, &img, xf, held), held.is_some())));
|
||||
if let Some(n) = d.node_mut(*id)
|
||||
&& let NodeKind::Image(im) = &mut n.kind
|
||||
{
|
||||
@@ -1625,7 +1696,7 @@ fn resolve_links(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_e
|
||||
store_image(d, &g.key, blob, true);
|
||||
} else if let Some(b) = d.images.get(&g.key).filter(|b| b.proxy.is_none()) {
|
||||
// Linked before links kept a preview.
|
||||
let b = b.clone().with_proxy();
|
||||
let b = fileio::preview_with_clip(b.clone().with_proxy());
|
||||
d.images.insert(g.key.clone(), b);
|
||||
}
|
||||
// Found away from its path, or read again: the link follows.
|
||||
@@ -2091,9 +2162,6 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
// Whether the images were found as the missing links (nothing selected, a folder given) rather
|
||||
// than named or selected.
|
||||
let mut found_missing = false;
|
||||
let mut ids: Vec<NodeId> = match (&each, ids_param(p, "ids", C)?) {
|
||||
(Some(each), _) => each.iter().flat_map(|(ids, _)| ids.iter().copied()).collect(),
|
||||
(None, Some(ids)) => ids,
|
||||
@@ -2101,7 +2169,6 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let selected: Vec<NodeId> = st.selection.objects.iter().copied().filter(|id| image(id).is_some()).collect();
|
||||
match folder_param {
|
||||
Some(_) if selected.is_empty() => {
|
||||
found_missing = true;
|
||||
groups(&st.doc, None).into_iter().filter(|g| probe(g, LinkBase::of(st)).0 == Status::Missing).flat_map(|g| g.ids).collect()
|
||||
}
|
||||
_ => selected,
|
||||
@@ -2114,11 +2181,6 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if ids.is_empty() {
|
||||
return Err(bad(C, "select the images to relink, or pass ids"));
|
||||
}
|
||||
// A named or selected distorted image is refused before a folder is searched, whether or not
|
||||
// its file is found there.
|
||||
if !found_missing && let Some(id) = ids.iter().find(|id| stored(&doc, **id).is_some_and(Node::is_distorted_image)) {
|
||||
return Err(super::xform::distorted_image_error(C, *id));
|
||||
}
|
||||
// All Instances: the other stored objects linked to the same files, each once.
|
||||
if scope == Scope::All {
|
||||
let paths: BTreeSet<&str> = ids.iter().filter_map(|id| image(id).flatten()).map(|l| l.path.as_str()).collect();
|
||||
@@ -2163,11 +2225,6 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
(None, None, None) => return Err(bad(C, "give path (a file) or folder")),
|
||||
}
|
||||
// A new file's placement options place a plain image: a distorted one is left as it is.
|
||||
let distorted = files.iter().flat_map(|(ids, _)| ids).find(|id| stored(&doc, **id).is_some_and(Node::is_distorted_image));
|
||||
if let Some(id) = distorted {
|
||||
return Err(super::xform::distorted_image_error(C, *id));
|
||||
}
|
||||
// Every file is read and checked before any is copied.
|
||||
let mut checked = vec![];
|
||||
for (ids, path) in files {
|
||||
@@ -2227,8 +2284,10 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
let relinked: Vec<u64> = reads.iter().flat_map(|(ids, _)| ids_json(ids)).collect();
|
||||
let unpreserved = preserve.and_then(|_| unpreserved_note(&doc, &reads));
|
||||
drop(doc);
|
||||
let warnings = spot_swatch_notes(&s.doc()?.doc, reads.iter().map(|(_, read)| read));
|
||||
let mut warnings = spot_swatch_notes(&s.doc()?.doc, reads.iter().map(|(_, read)| read));
|
||||
warnings.extend(unpreserved);
|
||||
if !reads.is_empty() {
|
||||
s.edit("Relink", |d, _| editing_brush_art(d, |d| reads.into_iter().try_for_each(|(ids, read)| install_read(d, &ids, read, preserve, None))))?;
|
||||
}
|
||||
@@ -2251,6 +2310,23 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The warning that Relink's `preserve` was not applied to the images of `reads` changed by
|
||||
/// Perspective Distort or Free Distort, which keep their corners, naming them; `None` when there
|
||||
/// are none.
|
||||
fn unpreserved_note(doc: &Document, reads: &[(Vec<NodeId>, Read)]) -> Option<String> {
|
||||
let ids: Vec<String> = reads
|
||||
.iter()
|
||||
.filter(|(_, read)| matches!(read, Read::Image(_)))
|
||||
.flat_map(|(ids, _)| ids)
|
||||
.filter(|id| stored(doc, **id).is_some_and(Node::is_distorted_image))
|
||||
.map(|id| id.0.to_string())
|
||||
.collect();
|
||||
let images = if ids.len() == 1 { "image" } else { "images" };
|
||||
(!ids.is_empty()).then(|| {
|
||||
format!("preserve was not applied to {images} {}: an image changed by Perspective Distort or Free Distort keeps its corners", ids.join(", "))
|
||||
})
|
||||
}
|
||||
|
||||
/// `links.relink {scope: "missingInFolder"}`: the other missing links of `st` (not `given`; only
|
||||
/// images when `images_only`, as copy takes), each added to `files` with the file of its name in
|
||||
/// the folder of the first file there; names not there go to `not_found`.
|
||||
@@ -2630,9 +2706,6 @@ fn embed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if ids.is_empty() {
|
||||
return Err(bad(C, "select the linked images or placed documents, or pass ids"));
|
||||
}
|
||||
if let Some(id) = ids.iter().find(|id| stored(&doc, **id).is_some_and(Node::is_distorted_image)) {
|
||||
return Err(super::xform::distorted_image_error(C, *id));
|
||||
}
|
||||
// A DCS file's plates print from its file.
|
||||
let separated = |id: &NodeId| match kind(id) {
|
||||
Some(NodeKind::Image(im)) => st.doc.images.get(&im.key).is_some_and(ImageBlob::is_separated),
|
||||
@@ -2761,11 +2834,8 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if im.link.is_some() {
|
||||
return Err(bad(C, format!("image {} is linked already", id.0)));
|
||||
}
|
||||
if n.is_distorted_image() {
|
||||
return Err(super::xform::distorted_image_error(C, id));
|
||||
}
|
||||
let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?;
|
||||
// As stored (PNG, JPEG, GIF, WebP), unless the path names another format.
|
||||
// As stored (PNG, JPEG, GIF, WebP, or TIFF for an image that keeps CMYK inks), unless the path names another format.
|
||||
let stored = stored_extension(blob);
|
||||
let path = str_param(p, "path");
|
||||
let ext = match path.map(fileio::extension) {
|
||||
@@ -2785,7 +2855,7 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
write_file(&path, &bytes)?;
|
||||
let read = (link_info(&path, &bytes), img);
|
||||
drop(doc);
|
||||
s.edit("Unembed", |d, _| editing_brush_art(d, |d| install(d, &[id], read, Some(Preserve::Bounds), None)))?;
|
||||
s.edit("Unembed", |d, _| editing_brush_art(d, |d| install_with(d, &[id], read, Some(Preserve::Bounds), None, true)))?;
|
||||
Ok(json!({ "id": id.0, "path": path }))
|
||||
}
|
||||
|
||||
@@ -2815,9 +2885,6 @@ fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option<Vec<NodeId>>) -> Re
|
||||
skipped.push(id);
|
||||
continue;
|
||||
}
|
||||
if n.is_distorted_image() {
|
||||
return Err(super::xform::distorted_image_error(C, id));
|
||||
}
|
||||
let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?;
|
||||
embedded.push((id, n.display_name(), blob));
|
||||
}
|
||||
@@ -2855,7 +2922,7 @@ fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option<Vec<NodeId>>) -> Re
|
||||
drop(doc);
|
||||
let done: Vec<Value> = reads.iter().map(|(id, (l, _))| json!({ "id": id.0, "path": l.path })).collect();
|
||||
let edited = s.edit("Unembed", |d, _| {
|
||||
editing_brush_art(d, |d| reads.into_iter().try_for_each(|(id, read)| install(d, &[id], read, Some(Preserve::Bounds), None)))
|
||||
editing_brush_art(d, |d| reads.into_iter().try_for_each(|(id, read)| install_with(d, &[id], read, Some(Preserve::Bounds), None, true)))
|
||||
});
|
||||
if let Err(e) = edited {
|
||||
remove_written(&written);
|
||||
@@ -3137,4 +3204,23 @@ mod tests {
|
||||
let long = unembed_stem(&"é".repeat(200));
|
||||
assert!(long.len() <= 150 && long.chars().all(|c| c == 'é'), "{}", long.len());
|
||||
}
|
||||
|
||||
/// A clipping path mapped through a distorted image's corners keeps the points that lie on or
|
||||
/// past the map's horizon, each mapped as a distort maps a path's point.
|
||||
#[test]
|
||||
fn points_past_the_horizon_are_mapped_as_a_distort_maps_them() {
|
||||
use vectorcraft_geom::{Anchor, Point, SubPath};
|
||||
// w = 1 + x / 100: the horizon is the line x = -100.
|
||||
let map = Homography([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.01, 0.0, 1.0]]);
|
||||
let (at, handle, on) = (Point::new(0.0, 0.0), Point::new(-200.0, 0.0), Point::new(-100.0, 5.0));
|
||||
assert!(map.apply(handle).is_none() && map.apply(on).is_none());
|
||||
let path = PathData::new(vec![SubPath::new(vec![Anchor::smooth(at, handle), Anchor::corner(on)], false)]);
|
||||
let out = warped(&path, &map).expect("a path");
|
||||
let (first, second) = (out.subpaths[0].anchors[0], out.subpaths[0].anchors[1]);
|
||||
assert_eq!((first.p, first.h_in), (at, Point::new(200.0 / 3.0, 0.0)));
|
||||
// w = -1: the handle maps to the far side.
|
||||
assert_eq!(first.h_out, Point::new(200.0, 0.0));
|
||||
// w = 0 is taken as a billionth.
|
||||
assert!(second.p.is_finite() && (second.p.x.abs() - 1e11).abs() < 1.0 && (second.p.y.abs() - 5e9).abs() < 1.0, "{:?}", second.p);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ use vectorcraft_geom::shapes::CornerKind;
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Point, Rect, Vec2};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::edit::{duplicate_in, outermost, selected_roots, selected_roots_to_transform};
|
||||
use super::edit::{duplicate_beside, outermost, selected_roots, selected_roots_to_transform};
|
||||
use super::opacitymask::percent;
|
||||
use super::{
|
||||
CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, f64_or, f64_req, has_doc, has_multi, has_selection,
|
||||
|
||||
@@ -16,7 +16,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Transform",
|
||||
[],
|
||||
None,
|
||||
"{matrix: [a,b,c,d,e,f], copy?: bool, ids?, strokes?: bool, corners?: bool, typeAreas?: bool, anchors?: bool, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), releaseOutside?: bool, interpolate?: bool (with anchors and a matrix that only moves them: the handles of each segment with one moved end are re-mapped, as path.moveAnchors's; default: prefs interpolateControlPoints)} apply an affine to the selection (or ids); anchors (without ids or copy): paths with anchors selected with Direct Selection have only those anchors and their handles transformed, as the Transform tools and object.move/rotate/scale/reflect/shear do (default: the whole objects); strokes/corners: Scale Strokes & Effects / Scale Corners (default: the preferences); typeAreas: area type among them (not type inside a group) reshapes its frame by the matrix and its text reflows at its size, as a bounding-box handle drag does (default: the type transforms too); releaseOutside (without copy or anchors): a Shaper Group's original shape that ends wholly outside the bounds the group's original shapes had before takes shaper.releaseSource in the same undo step, named Remove from Shaper Group, as the Selection tool's moves in Construction mode do",
|
||||
"{matrix: [a,b,c,d,e,f], copy?: bool, ids?, strokes?: bool, corners?: bool, typeAreas?: bool, anchors?: bool, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), releaseOutside?: bool, interpolate?: bool (with anchors and a matrix that only moves them: the handles of each segment with one moved end are re-mapped, as path.moveAnchors's; default: prefs interpolateControlPoints), drawBehind?: bool (with copy: in Draw Behind, view.drawMode, each copy goes directly below its original instead of above it, as the Selection and Direct Selection tools' Alt-drags send; default false)} apply an affine to the selection (or ids); anchors (without ids or copy): paths with anchors selected with Direct Selection have only those anchors and their handles transformed, as the Transform tools and object.move/rotate/scale/reflect/shear do (default: the whole objects); strokes/corners: Scale Strokes & Effects / Scale Corners (default: the preferences); typeAreas: area type among them (not type inside a group) reshapes its frame by the matrix and its text reflows at its size, as a bounding-box handle drag does (default: the type transforms too); releaseOutside (without copy or anchors): a Shaper Group's original shape that ends wholly outside the bounds the group's original shapes had before takes shaper.releaseSource in the same undo step, named Remove from Shaper Group, as the Selection tool's moves in Construction mode do",
|
||||
has_doc,
|
||||
transform
|
||||
),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::align::choice;
|
||||
use super::{
|
||||
Affine, Arc, Document, EngineError, LastTransform, Node, NodeId, NodeKind, OrientedBox, Point, Rect, Result, Scaling, Session, Value, Vec2, bad,
|
||||
bool_or, check_numbers, check_switches, duplicate_in, effects, f64_or, f64_req, ids_param, json, matrix_param, ok, outermost, point_param,
|
||||
bool_or, check_numbers, check_switches, duplicate_beside, effects, f64_or, f64_req, ids_param, json, matrix_param, ok, outermost, point_param,
|
||||
selected_roots_to_transform,
|
||||
};
|
||||
|
||||
@@ -91,12 +91,22 @@ pub(crate) fn transform_node(n: &mut Node, xf: Affine, sc: Scaling, objects: boo
|
||||
/// `anchors` (`ids` being the selection): with anchors selected with Direct Selection and no
|
||||
/// copy, only those anchors transform, their handles with them, and the objects selected whole.
|
||||
pub(crate) fn apply_transform(s: &mut Session, label: &str, ids: Vec<NodeId>, xf: Affine, p: &Value, anchors: bool) -> Result<Value> {
|
||||
apply_transform_moving_guides(s, label, ids, xf, p, anchors, None)
|
||||
apply_transform_moving_guides(s, label, ids, xf, p, anchors, Placing::default())
|
||||
}
|
||||
|
||||
/// [`apply_transform`], with the selected ruler guides moved by `guides` instead of by the
|
||||
/// Where [`apply_transform_moving_guides`] puts the selected ruler guides and the copies.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct Placing {
|
||||
/// The selected ruler guides move by this instead of by the transform's translation.
|
||||
guides: Option<Vec2>,
|
||||
/// Each copy goes directly below its original instead of above it.
|
||||
below: bool,
|
||||
}
|
||||
|
||||
/// [`apply_transform`], with the selected ruler guides moved by `placing.guides` instead of by the
|
||||
/// translation `xf` when given (a nudge along a turned Constrain Angle moves the art along it and
|
||||
/// the guides along the page's axes).
|
||||
/// the guides along the page's axes), and with each copy directly below its original with
|
||||
/// `placing.below`.
|
||||
fn apply_transform_moving_guides(
|
||||
s: &mut Session,
|
||||
label: &str,
|
||||
@@ -104,8 +114,9 @@ fn apply_transform_moving_guides(
|
||||
xf: Affine,
|
||||
p: &Value,
|
||||
anchors: bool,
|
||||
guides: Option<Vec2>,
|
||||
placing: Placing,
|
||||
) -> Result<Value> {
|
||||
let Placing { guides, below } = placing;
|
||||
let copy = bool_or(p, "copy", false);
|
||||
let areas = bool_or(p, "typeAreas", false);
|
||||
let objects = transforms_objects(p);
|
||||
@@ -138,7 +149,7 @@ fn apply_transform_moving_guides(
|
||||
} else if none || (!copy && xf == Affine::IDENTITY) {
|
||||
if copy { vec![] } else { ids }
|
||||
} else {
|
||||
let kept = if copy { preview_copies(s, &ids, with_guides)? } else { None };
|
||||
let kept = if copy { preview_copies(s, &ids, with_guides, below)? } else { None };
|
||||
s.edit(label, |d, sel| {
|
||||
let targets = match &kept {
|
||||
// The document becomes the snapshot with the kept copies, untransformed, and the
|
||||
@@ -155,7 +166,7 @@ fn apply_transform_moving_guides(
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let new_ids = duplicate_in(d, sel, &ids, Affine::IDENTITY)?;
|
||||
let new_ids = duplicate_beside(d, sel, &ids, Affine::IDENTITY, below)?;
|
||||
if let Some(copies) = guide_copies {
|
||||
sel.guides = copies.iter().map(|g| d.add_ruler_guide(g)).collect();
|
||||
}
|
||||
@@ -212,11 +223,12 @@ fn apply_transform_moving_guides(
|
||||
/// Returns the copies of `roots` for a transform or a perspective edit with `copy` in an interaction
|
||||
/// whose document is still its snapshot, as in a preview ([`Session::preview`] puts the snapshot
|
||||
/// back first). These are the copies the interaction keeps when they were made of that snapshot for
|
||||
/// the same `roots`; otherwise this copies `roots` with [`duplicate_in`] in a clone of the snapshot,
|
||||
/// untransformed, and the interaction keeps that clone. It returns `None` outside an interaction,
|
||||
/// the same `roots` on the same side (`below`: directly below each original); otherwise this copies
|
||||
/// `roots` with [`duplicate_beside`] in a clone of the snapshot, untransformed, and the interaction
|
||||
/// keeps that clone. It returns `None` outside an interaction,
|
||||
/// and when the document is no longer the snapshot, as for a command run in a typing session or a
|
||||
/// script batch after an earlier edit there: the command then copies the current document.
|
||||
pub(crate) fn preview_copies(s: &mut Session, roots: &[NodeId], with_guides: bool) -> Result<Option<Arc<crate::PreviewCopies>>> {
|
||||
pub(crate) fn preview_copies(s: &mut Session, roots: &[NodeId], with_guides: bool, below: bool) -> Result<Option<Arc<crate::PreviewCopies>>> {
|
||||
let st = s.doc_mut()?;
|
||||
let Some(it) = &mut st.interaction else { return Ok(None) };
|
||||
if !Arc::ptr_eq(&st.doc, &it.doc) {
|
||||
@@ -226,19 +238,20 @@ pub(crate) fn preview_copies(s: &mut Session, roots: &[NodeId], with_guides: boo
|
||||
if let Some(k) = &it.copies
|
||||
&& Arc::ptr_eq(&k.from, &it.doc)
|
||||
&& k.roots == roots
|
||||
&& k.below == below
|
||||
&& (k.selection.guides.is_empty() != has_guide_copies)
|
||||
{
|
||||
return Ok(Some(k.clone()));
|
||||
}
|
||||
let mut doc = it.doc.clone();
|
||||
let mut selection = st.selection.clone();
|
||||
let ids = duplicate_in(Arc::make_mut(&mut doc), &mut selection, roots, Affine::IDENTITY)?;
|
||||
let ids = duplicate_beside(Arc::make_mut(&mut doc), &mut selection, roots, Affine::IDENTITY, below)?;
|
||||
if has_guide_copies {
|
||||
let d = Arc::make_mut(&mut doc);
|
||||
let copies: Vec<_> = st.selection.guides.iter().filter_map(|&i| d.ruler_guide(i)).collect();
|
||||
selection.guides = copies.iter().map(|g| d.add_ruler_guide(g)).collect();
|
||||
}
|
||||
let k = Arc::new(crate::PreviewCopies { from: it.doc.clone(), roots: roots.to_vec(), doc, selection, ids });
|
||||
let k = Arc::new(crate::PreviewCopies { from: it.doc.clone(), roots: roots.to_vec(), below, doc, selection, ids });
|
||||
it.copies = Some(k.clone());
|
||||
Ok(Some(k))
|
||||
}
|
||||
@@ -256,7 +269,9 @@ fn resize_type_area(n: &mut Node, xf: Affine) -> bool {
|
||||
|
||||
pub(super) fn transform(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_switches(p, &TRANSFORM_SWITCHES, "object.transform")?;
|
||||
check_switches(p, &["anchors", "releaseOutside", "interpolate"], "object.transform")?;
|
||||
check_switches(p, &["anchors", "releaseOutside", "interpolate", "drawBehind"], "object.transform")?;
|
||||
// An Alt-drag copy in Draw Behind goes directly below its original.
|
||||
let below = bool_or(p, "drawBehind", false) && bool_or(p, "copy", false) && s.draw_mode == crate::DrawMode::Behind;
|
||||
let m = matrix_param(p, "matrix").ok_or_else(|| bad("object.transform", "missing matrix [a,b,c,d,e,f]"))?;
|
||||
// An object selected in a symbol instance's art stays where the symbol puts it: the selection
|
||||
// is left as it is, and the reply's warning goes to the status bar.
|
||||
@@ -280,7 +295,7 @@ pub(super) fn transform(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if grouped {
|
||||
s.begin_named_undo_group(None);
|
||||
}
|
||||
let r = apply_transform(s, "Transform", ids, m, p, anchors);
|
||||
let r = apply_transform_moving_guides(s, "Transform", ids, m, p, anchors, Placing { guides: None, below });
|
||||
let released = match &r {
|
||||
Ok(_) if !moved.is_empty() => crate::cmd::shaper::release_outside(s, &moved),
|
||||
_ => Ok(false),
|
||||
@@ -358,7 +373,7 @@ pub(super) fn nudge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return ok();
|
||||
}
|
||||
}
|
||||
apply_transform_moving_guides(s, "Move", ids, Affine::translate((dx, dy)), p, true, Some(Vec2::new(gx, gy)))
|
||||
apply_transform_moving_guides(s, "Move", ids, Affine::translate((dx, dy)), p, true, Placing { guides: Some(Vec2::new(gx, gy)), below: false })
|
||||
}
|
||||
|
||||
pub(super) fn about(o: Point, a: Affine) -> Affine {
|
||||
|
||||
@@ -373,16 +373,25 @@ impl DocState {
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `t` the Live Paint Bucket, or a tool armed to switch back to it after its pick?
|
||||
fn works_for_bucket(t: &dyn vectorcraft_tools::Tool) -> bool {
|
||||
t.id() == LIVE_PAINT_BUCKET || t.returns_to() == Some(LIVE_PAINT_BUCKET)
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Did the Live Paint Bucket, or the Eyedropper armed for it, lend the active tool (a Cmd+click)?
|
||||
pub(crate) fn lent_by_bucket(&self) -> bool {
|
||||
self.lender.as_deref().is_some_and(works_for_bucket)
|
||||
}
|
||||
|
||||
/// Do the fill and stroke proxies, and the paint commands that name no objects, stand for the
|
||||
/// colors the Live Paint Bucket paints with? They do while the bucket is the active tool, while
|
||||
/// a Cmd+click with the bucket uses the Selection tool, and while the Eyedropper samples into a
|
||||
/// stop of the bucket's gradient for the Gradient panel's eyedropper, up to and including the
|
||||
/// sample its click takes before it switches back to the bucket.
|
||||
pub fn bucket_paints(&self) -> bool {
|
||||
let for_bucket = |t: &dyn vectorcraft_tools::Tool| t.id() == LIVE_PAINT_BUCKET || t.returns_to() == Some(LIVE_PAINT_BUCKET);
|
||||
// A Cmd+click lends the Selection tool to the bucket, or to the Eyedropper armed for it.
|
||||
self.back_to_bucket || for_bucket(self.tool.as_ref()) || self.lender.as_deref().is_some_and(for_bucket)
|
||||
self.back_to_bucket || works_for_bucket(self.tool.as_ref()) || self.lent_by_bucket()
|
||||
}
|
||||
|
||||
/// The tool the active tool's armed one-shot pick switches back to after its click
|
||||
|
||||
@@ -199,14 +199,11 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
|
||||
// ---------- helpers ----------
|
||||
|
||||
/// Number param that also accepts strings like `"10 pt"`.
|
||||
/// Number param that also accepts a string when all of it is a number (`"10"`, not `"10abc"`).
|
||||
pub(crate) fn num_param(p: &Value, key: &str) -> Option<f64> {
|
||||
match p.get(key)? {
|
||||
Value::Number(n) => n.as_f64(),
|
||||
Value::String(s) => {
|
||||
let t: String = s.trim().chars().take_while(|c| c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E')).collect();
|
||||
t.parse().ok()
|
||||
}
|
||||
Value::String(s) => whole_number(s),
|
||||
_ => None,
|
||||
}
|
||||
.filter(|v: &f64| v.is_finite())
|
||||
|
||||
@@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Replace Pattern Art",
|
||||
[],
|
||||
None,
|
||||
"{name, ids?} make copies of the selected art the tile art of pattern `name`, as Alt-dragging (Option-dragging on macOS) art onto its swatch in the Swatches panel does; the pattern keeps its name, swatch, tile and options (with Size Tile to Art on, the tile fits the new art), every fill and stroke painted with it draws the new tile, and the art stays on the canvas, selected; one undo step, none when the art matches the tile art already; refused while a pattern is edited, with nothing selected, and for art painted with the pattern itself → {name}",
|
||||
"{name, ids?} make copies of the selected art the tile art of pattern `name`, as Alt-dragging (Option-dragging on macOS) art onto its swatch in the Swatches panel does; the pattern keeps its name, swatch, tile and options (with Size Tile to Art on, the tile fits the new art), every fill and stroke painted with it draws the new tile, and the art stays on the canvas, selected; one undo step, none when the art matches the tile art already; refused while a pattern is edited, with nothing selected, for an id that names no object, and for art painted with the pattern itself → {name}",
|
||||
can_replace_pattern_art,
|
||||
pattern_replace_art
|
||||
),
|
||||
@@ -244,10 +244,15 @@ fn ids_json(ids: &[NodeId]) -> Value {
|
||||
json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() })
|
||||
}
|
||||
|
||||
/// The outermost objects among `ids` (layers left out), else the selected ones. An id that names
|
||||
/// no object is an error, so the command never acts on the other ids alone.
|
||||
fn roots(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
match ids_param(p, "ids", cmd)? {
|
||||
Some(ids) => {
|
||||
let st = s.doc()?;
|
||||
if let Some(id) = ids.iter().find(|id| st.doc.node(**id).is_none()) {
|
||||
return Err(bad(cmd, format!("no such object id {}", id.0)));
|
||||
}
|
||||
let mut sel = Selection::default();
|
||||
sel.set(ids.iter().copied().filter(|id| st.doc.node(*id).is_some_and(|n| !n.is_layer())));
|
||||
Ok(outermost(&st.doc, sel.in_paint_order(&st.doc)))
|
||||
|
||||
@@ -85,15 +85,29 @@ pub fn swatch_source(w: &Swatch) -> Option<Arc<Document>> {
|
||||
library_doc(b.id).filter(|d| d.pattern(pattern).is_some())
|
||||
}
|
||||
|
||||
/// Swatches as (the swatch's name in a library, its name in a document).
|
||||
pub(crate) type SwatchNames = Vec<(String, String)>;
|
||||
|
||||
/// Add pattern `name` of library `lib` to `d` with the resources its art uses, as pasting art
|
||||
/// painted with it does: the same pattern there already is used, and a name another pattern or
|
||||
/// swatch has gets a number → the pattern's name in `d`, and the swatches the import added for
|
||||
/// the pattern's art: (the swatch's name in `lib`, its name in `d`), pattern swatches left out.
|
||||
/// the pattern's art: (the swatch's name in `lib`, its name in `d`), pattern swatches left out,
|
||||
/// and the swatches `d` had that the art took under another name than its own, in the same form.
|
||||
/// A global or spot color whose name `d` gives another color comes in under a free name, as Add
|
||||
/// to Swatches adds such a color, so that the pattern keeps the library's colors.
|
||||
pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<(String, Vec<(String, String)>)> {
|
||||
/// to Swatches adds such a color, so that the pattern keeps the library's colors. Those colors
|
||||
/// merge instead when that reuses a pattern of `d` that keeping them would add again
|
||||
/// ([`probe_import`]).
|
||||
pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<(String, SwatchNames, SwatchNames)> {
|
||||
let gathered = gather(lib, name);
|
||||
let had: std::collections::HashSet<String> = d.swatches_iter().map(|w| w.name.clone()).collect();
|
||||
let imported = gather(lib, name).import_into(d, &SwatchChoices::add_all(), false)?;
|
||||
// Without a color to merge or a pattern to reuse, the document is not copied.
|
||||
let imported = if !gathered.swatches.is_empty() && has_candidate(d, lib, name) {
|
||||
let (_, probed, imported) = probe_import(d, lib, name, &gathered)?;
|
||||
*d = probed;
|
||||
imported
|
||||
} else {
|
||||
gathered.import_into(d, &SwatchChoices::add_all(), false)?
|
||||
};
|
||||
let from = |to: &str| {
|
||||
let renamed = imported.renamed.iter().find(|r| r["kind"] == "swatch" && r["to"] == to).and_then(|r| r["from"].as_str());
|
||||
renamed.unwrap_or(to).to_string()
|
||||
@@ -103,7 +117,14 @@ pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<(St
|
||||
.filter(|w| !had.contains(&w.name) && !matches!(w.paint, Paint::Pattern { .. }))
|
||||
.map(|w| (from(&w.name), w.name.clone()))
|
||||
.collect();
|
||||
Ok((imported_name(&imported, name), added))
|
||||
let reused = imported
|
||||
.renamed
|
||||
.iter()
|
||||
.filter(|r| r["kind"] == "swatch")
|
||||
.filter_map(|r| Some((r["from"].as_str()?.to_string(), r["to"].as_str()?.to_string())))
|
||||
.filter(|(_, to)| had.contains(to))
|
||||
.collect();
|
||||
Ok((imported_name(&imported, name), added, reused))
|
||||
}
|
||||
|
||||
/// Pattern `name` of `lib` with the resources its art uses, as an object painted with it is copied.
|
||||
@@ -112,17 +133,29 @@ fn gather(lib: &Document, name: &str) -> Clipboard {
|
||||
Clipboard::gather(lib, vec![user])
|
||||
}
|
||||
|
||||
/// The names in `lib` of the swatches that pattern `name` of `lib` brings with its art.
|
||||
pub(crate) fn brought_names(lib: &Document, name: &str) -> std::collections::HashSet<String> {
|
||||
gather(lib, name).swatches.into_iter().map(|w| w.name).collect()
|
||||
}
|
||||
|
||||
/// The names in `lib` of pattern `name` and of the patterns its art brings.
|
||||
pub(crate) fn brought_patterns(lib: &Document, name: &str) -> std::collections::HashSet<String> {
|
||||
gather(lib, name).patterns.into_iter().map(|p| p.name).collect()
|
||||
}
|
||||
|
||||
/// The name pattern `name` has in the document `imported` went into.
|
||||
fn imported_name(imported: &Imported, name: &str) -> String {
|
||||
pub(crate) fn imported_name(imported: &Imported, name: &str) -> String {
|
||||
let renamed = imported.renamed.iter().find(|r| r["kind"] == "pattern" && r["from"] == name).and_then(|r| r["to"].as_str());
|
||||
renamed.unwrap_or(name).to_string()
|
||||
}
|
||||
|
||||
/// The pattern of `d` that [`import`] of pattern `name` of library `lib` would use without adding
|
||||
/// anything to `d` → its name in `d`. A pattern whose art uses no other resource is compared as
|
||||
/// [`existing_pattern`] does. One whose art uses other resources, such as a pattern it is painted
|
||||
/// with, is imported into a copy of `d`, so that those resources are compared too.
|
||||
pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Option<String> {
|
||||
/// anything to `d` → its name in `d`, and the swatches of `d` that the art takes under another
|
||||
/// name than its own, as [`import`] lists them. A pattern whose art uses no other resource is
|
||||
/// compared as [`existing_pattern`] does. One whose art uses other resources, such as a pattern it
|
||||
/// is painted with, is imported into a copy of `d` as [`probe_import`] does, so that those
|
||||
/// resources are compared too.
|
||||
pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Option<(String, SwatchNames)> {
|
||||
let gathered = gather(lib, name);
|
||||
let only_pattern = gathered.patterns.len() == 1
|
||||
&& gathered.symbols.is_empty()
|
||||
@@ -131,23 +164,58 @@ pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Optio
|
||||
&& gathered.char_styles.is_empty()
|
||||
&& gathered.para_styles.is_empty()
|
||||
&& gathered.brushes.is_empty()
|
||||
&& gathered.images.is_empty();
|
||||
&& gathered.images.is_empty()
|
||||
&& gathered.graph_designs.is_empty();
|
||||
if only_pattern {
|
||||
return existing_pattern(d, lib, name);
|
||||
return existing_pattern(d, lib, name).map(|target| (target, vec![]));
|
||||
}
|
||||
// Importing reuses only a pattern under that name or a numbered copy of it with the same tile
|
||||
// options and as many art objects; without one, the document is not copied.
|
||||
let def = lib.pattern(name)?;
|
||||
// Without a pattern to reuse, the document is not copied.
|
||||
if !has_candidate(d, lib, name) {
|
||||
return None;
|
||||
}
|
||||
let (_, _, imported) = probe_import(d, lib, name, &gathered).ok()?;
|
||||
if imported.added != 0 {
|
||||
return None;
|
||||
}
|
||||
let took = imported
|
||||
.renamed
|
||||
.iter()
|
||||
.filter(|r| r["kind"] == "swatch")
|
||||
.filter_map(|r| Some((r["from"].as_str()?.to_string(), r["to"].as_str()?.to_string())))
|
||||
.filter(|(_, to)| d.swatches_iter().any(|w| w.name == *to))
|
||||
.collect();
|
||||
Some((imported_name(&imported, name), took))
|
||||
}
|
||||
|
||||
/// Whether `d` has a pattern that importing pattern `name` of `lib` can reuse: one under that name
|
||||
/// or a numbered copy of it with the same tile options and as many art objects.
|
||||
pub(crate) fn has_candidate(d: &Document, lib: &Document, name: &str) -> bool {
|
||||
let Some(def) = lib.pattern(name) else { return false };
|
||||
let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() };
|
||||
let copy = |n: &str| {
|
||||
n == name || n.strip_prefix(name).and_then(|r| r.strip_prefix(' ')).is_some_and(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
|
||||
};
|
||||
if !d.patterns.iter().any(|p| copy(&p.name) && p.art.len() == def.art.len() && bare(p) == bare(def)) {
|
||||
return None;
|
||||
d.patterns.iter().any(|p| copy(&p.name) && p.art.len() == def.art.len() && bare(p) == bare(def))
|
||||
}
|
||||
|
||||
/// Import `gathered`, which paints with pattern `name` of `lib`, into a copy of `d` → the swatch
|
||||
/// choices used, the copy and what the import did. A global or spot color whose name `d` gives
|
||||
/// another color comes in under a free name (Add). Those colors merge instead when Add would add
|
||||
/// the pattern again while merging reuses a pattern of `d`: such a pattern has its art linked to
|
||||
/// the document's own colors of those names, as pasting with Merge, or adding it from a library
|
||||
/// before, leaves it.
|
||||
pub(crate) fn probe_import(d: &Document, lib: &Document, name: &str, gathered: &Clipboard) -> Result<(SwatchChoices, Document, Imported)> {
|
||||
let reused = |i: &Imported| d.pattern(&imported_name(i, name)).is_some();
|
||||
let mut with_add = d.clone();
|
||||
let added = gathered.import_into(&mut with_add, &SwatchChoices::add_all(), false)?;
|
||||
if !reused(&added) && added.renamed.iter().any(|r| r["kind"] == "swatch") && has_candidate(d, lib, name) {
|
||||
let mut merged = d.clone();
|
||||
let found = gathered.import_into(&mut merged, &SwatchChoices::default(), false)?;
|
||||
if reused(&found) {
|
||||
return Ok((SwatchChoices::default(), merged, found));
|
||||
}
|
||||
}
|
||||
let mut probe = d.clone();
|
||||
let imported = gathered.import_into(&mut probe, &SwatchChoices::add_all(), false).ok()?;
|
||||
(imported.added == 0).then(|| imported_name(&imported, name))
|
||||
Ok((SwatchChoices::add_all(), with_add, added))
|
||||
}
|
||||
|
||||
/// The pattern of `d` that is pattern `name` of library `lib`: the same tile options and art under
|
||||
|
||||
@@ -1188,8 +1188,8 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let doc = super::links::with_brush_art(&st.doc);
|
||||
let n = doc.stored_node(id).map(|(n, _)| &**n).ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::Image(im) = &n.kind else { return Err(bad(C, format!("object {} is not an image", id.0))) };
|
||||
// Effective resolution, taken at the middle of a distorted image.
|
||||
let ppi = effective_ppi(vectorcraft_doc::image_quad::nearest_affine(n).unwrap_or(im.xf));
|
||||
// Effective resolution at the middle of a distorted image.
|
||||
let xf = vectorcraft_doc::image_quad::nearest_affine(n).unwrap_or(im.xf);
|
||||
let size = n.geometric_bounds().unwrap_or_default();
|
||||
// A linked file outside the read roots of the caller asking now is left unnamed, as in Link Info.
|
||||
let doc_path = super::links::LinkBase::of(st).doc;
|
||||
@@ -1201,7 +1201,7 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"colorMode": st.doc.images.get(&im.key).map_or("RGB", |b| color_mode(&b.bytes)),
|
||||
"pixelWidth": im.width,
|
||||
"pixelHeight": im.height,
|
||||
"ppi": ppi,
|
||||
"ppi": effective_ppi(xf),
|
||||
"width": size.width(),
|
||||
"height": size.height(),
|
||||
}))
|
||||
|
||||
@@ -1044,7 +1044,7 @@ fn load_folder(s: &Session, folder: &str) -> Value {
|
||||
if r.disabled_changed {
|
||||
s.store_disabled_plugins_in(&turn);
|
||||
}
|
||||
json!({"folder": folder, "loaded": r.loaded, "failed": r.failed.iter().map(|(f, e)| json!({"file": f, "error": e})).collect::<Vec<_>>()})
|
||||
json!({"folder": folder, "loaded": r.loaded, "failed": r.failed.iter().map(|(f, e)| json!({"file": f, "error": e})).collect::<Vec<_>>(), "leftOut": r.left_out})
|
||||
}
|
||||
Err(e) => json!({"folder": folder, "error": e.to_string()}),
|
||||
}
|
||||
@@ -1270,7 +1270,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"List Plug-ins",
|
||||
[],
|
||||
None,
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}]} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
|
||||
always,
|
||||
list
|
||||
),
|
||||
@@ -1333,7 +1333,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reload Plug-ins",
|
||||
["Object", "Plug-ins"],
|
||||
None,
|
||||
"{path?: a folder (default: the Additional Plug-ins Folder preference)} install every *.wasm in it (desktop; a bad module, and one disabled with plugin.setEnabled, is reported and skipped, and so are a heavy filter and a plug-in that lists permissions the user hasn't granted this very module, its bytes included; an error in Safe Mode) → {folder, loaded: [id], failed: [{file, error}]}",
|
||||
"{path?: a folder (default: the Additional Plug-ins Folder preference)} install every *.wasm in it, the first 1,000 by file name (desktop; a bad module, one that isn't a regular file, and one disabled with plugin.setEnabled, is reported and skipped, and so are a heavy filter and a plug-in that lists permissions the user hasn't granted this very module, its bytes included; an error in Safe Mode) → {folder, loaded: [id], failed: [{file, error}], leftOut: the count of *.wasm files past the first 1,000, not tried}",
|
||||
always,
|
||||
reload
|
||||
),
|
||||
|
||||
@@ -89,11 +89,13 @@ fn check(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
continue;
|
||||
};
|
||||
let bounds = doc.node(source).and_then(|n| vectorcraft_render::painted_bounds(&doc, n));
|
||||
// A distorted image is measured at its middle, as Link Info measures it.
|
||||
let xf = doc.node(source).and_then(vectorcraft_doc::image_quad::nearest_affine).unwrap_or(im.xf);
|
||||
let ppi = context
|
||||
.pages
|
||||
.iter()
|
||||
.filter(|(area, _)| bounds.is_some_and(|b| area.intersect(b).area() > 0.0))
|
||||
.map(|(_, to_page)| super::place::effective_ppi(*to_page * im.xf))
|
||||
.map(|(_, to_page)| super::place::effective_ppi(*to_page * xf))
|
||||
.reduce(|[a, b], [c, d]| [a.min(c), b.min(d)]);
|
||||
let Some(ppi) = ppi else {
|
||||
resolution_unchecked += 1;
|
||||
|
||||
+754
-109
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
@@ -31,7 +31,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Apply Graphic Style",
|
||||
["Window", "Graphic Styles"],
|
||||
None,
|
||||
"{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows (with `add`: of the kinds of row the style shows) and, without `add`, its object opacity and blend mode for every label or line of its kind. With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}",
|
||||
"{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. In the contents of a Live Paint group, each face takes only the style's fills and each edge only its strokes, and neither is linked. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows (with `add`: of the kinds of row the style shows) and, without `add`, its object opacity and blend mode for every label or line of its kind. With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}",
|
||||
has_doc,
|
||||
style_apply
|
||||
),
|
||||
@@ -76,7 +76,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Redefine Graphic Style",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{name?, id?} | {name, from} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it; a graph's Axes or Legend group: its topmost line or label); the objects still linked to it update, and that object becomes linked. With `from`, the style takes the look of the style named `from` (its fills, strokes, effects, opacity, blend mode, isolate and knockout) and keeps its own name and place; `from` and the objects linked to it stay as they are, `from` naming the style itself or a style with the same look changes nothing, and `from` with `id` is an error. The art of a graph design in a series keeps its look and is unlinked, as the source or as a linked object. A linked graph series group passes the style to the paths directly in it, a linked Axes group to its lines and labels and a linked Legend group to its labels, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {name}",
|
||||
"{name?, id?} | {name, from} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it; a graph's Axes or Legend group: its topmost line or label); the objects still linked to it update, and that object becomes linked. With `from`, the style takes the look of the style named `from` (its fills, strokes, effects, opacity, blend mode, isolate and knockout) and keeps its own name and place; `from` and the objects linked to it stay as they are, `from` naming the style itself or a style with the same look changes nothing, and `from` with `id` is an error. The art of a graph design in a series keeps its look and is unlinked, as the source or as a linked object. A linked graph series group passes the style to the paths directly in it, a linked Axes group to its lines and labels and a linked Legend group to its labels, other than the source, paths linked to the style whose look was edited and members linked to another style, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {name}",
|
||||
has_doc,
|
||||
style_redefine
|
||||
),
|
||||
@@ -351,6 +351,9 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// The series groups their paths stand for: a style that replaces the appearance clears what they hold themselves,
|
||||
// and a style added on top unlinks them.
|
||||
let groups = super::appearance::stood_for(&own, &ids);
|
||||
// In the contents of a Live Paint group, a face takes the style's fills and an edge its strokes.
|
||||
let (faces, edges) = super::appearance::contents_parts(s, p)?;
|
||||
let part = |id: &NodeId| (faces.contains(id) || edges.contains(id)).then(|| faces.contains(id));
|
||||
if ids.is_empty() {
|
||||
if p.get("ids").is_some() || p.get("id").is_some() {
|
||||
return Err(bad("graphicStyle.apply", "no such objects"));
|
||||
@@ -361,13 +364,20 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Ok(json!({ "newArt": true }));
|
||||
}
|
||||
let before = s.doc()?.doc.clone();
|
||||
s.edit("Apply Graphic Style", |d, _| {
|
||||
// An apply that changes nothing (a fill-only style added to edges only) records no undo step.
|
||||
super::overprint::edit_counted(s, "Apply Graphic Style", |d| {
|
||||
if add {
|
||||
let g = d.graphic_styles[i].clone();
|
||||
for id in &ids {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
let ap = g.appearance_on(n).into_owned();
|
||||
n.appearance.items.extend(ap.items);
|
||||
let kind = part(id);
|
||||
let rows: Vec<_> = ap.items.into_iter().filter(|it| kind.is_none_or(|fill| it.is_fill() == fill)).collect();
|
||||
// A face or edge the style adds nothing to keeps its appearance and its link.
|
||||
if kind.is_some() && rows.is_empty() && ap.effects.is_empty() {
|
||||
continue;
|
||||
}
|
||||
n.appearance.items.extend(rows);
|
||||
n.appearance.effects.extend(ap.effects);
|
||||
n.extras_mut().graphic_style = None;
|
||||
}
|
||||
@@ -387,13 +397,18 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut shared = None;
|
||||
for id in &ids {
|
||||
apply_style(d, *id, &g, &mut shared, chars);
|
||||
// A face or edge that keeps only the rows of its kind no longer has the style's look, so it is not linked.
|
||||
if let (Some(fill), Some(n)) = (part(id), d.node_mut(*id)) {
|
||||
super::appearance::keep_rows_of_kind(n, fill);
|
||||
n.extras_mut().graphic_style = None;
|
||||
}
|
||||
}
|
||||
super::appearance::clear_stood_for(d, &groups);
|
||||
super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, true);
|
||||
// A label or graph line keeps its new rows for its kind.
|
||||
super::graph::capture_label_rows(d, &ids);
|
||||
}
|
||||
Ok(())
|
||||
Ok(usize::from(*d != *before))
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
@@ -539,10 +554,13 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
linked.into_iter().partition(|nid| !super::graph::is_design_art(d, *nid) && d.node(*nid).is_some_and(|n| in_sync(n, &old)));
|
||||
set_link(d, &edited, None);
|
||||
// A linked graph series group passes the style to the paths directly inside it, so the graph stores it, and
|
||||
// goes back to the empty appearance the graph draws it with. The source and the edited paths keep their look.
|
||||
// goes back to the empty appearance the graph draws it with; a linked Axes or Legend group does the same with its
|
||||
// lines and labels. The source and the edited paths keep their look, and a member linked to another style keeps
|
||||
// its look and its link.
|
||||
let mut follow_marks = super::graph::series_group_marks(d, &follow);
|
||||
let edited: HashSet<NodeId> = edited.into_iter().collect();
|
||||
follow_marks.retain(|nid| Some(*nid) != src && !edited.contains(nid));
|
||||
let takes_style = |nid: NodeId| d.node(nid).is_some_and(|n| n.extras().graphic_style.is_none_or(|g| g == id));
|
||||
follow_marks.retain(|nid| Some(*nid) != src && !edited.contains(nid) && takes_style(*nid));
|
||||
super::appearance::clear_stood_for(d, &super::appearance::stood_for(&follow, &follow_marks));
|
||||
let g = d.graphic_styles[i].clone();
|
||||
let mut shared = None;
|
||||
|
||||
@@ -49,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add to Swatches",
|
||||
["Window", "Swatch Libraries"],
|
||||
None,
|
||||
"{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"). A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, and the pattern links to it → {library, added: [names in the document], existing: [names already there], applied?: name}",
|
||||
"{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint, and for a color the same process, global or spot kind, or a numbered copy of that name with the same color when the name has another color there) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"); a tint or gradient whose global or spot color comes in under a numbered name, or is in the document as such a numbered copy, links to that copy; a global or spot color it links to that the document lacks comes in with it. A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, also when its art links to the document's own color of a name, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, skipping the names of the library's other swatches, and the pattern links to it → {library, added: [names in the document, the colors patterns, tints and gradients brought included], existing: [names already there], applied?: name}",
|
||||
has_doc,
|
||||
add
|
||||
),
|
||||
@@ -1011,6 +1011,154 @@ fn free_in(taken: &mut HashSet<String>, base: &str) -> String {
|
||||
name
|
||||
}
|
||||
|
||||
/// [`free_in`] for a library swatch's copy: a numbered name also skips the names `reserved` says
|
||||
/// the library's other swatches have, so that a later add finds the copy as this swatch's.
|
||||
fn free_copy_in(taken: &mut HashSet<String>, base: &str, reserved: impl Fn(&str) -> bool) -> String {
|
||||
let name = if taken.contains(base) {
|
||||
(2..).map(|i| format!("{base} {i}")).find(|n| !taken.contains(n) && !reserved(n)).unwrap_or_else(|| base.to_string())
|
||||
} else {
|
||||
base.to_string()
|
||||
};
|
||||
taken.insert(name.clone());
|
||||
name
|
||||
}
|
||||
|
||||
/// [`patternlib::import`] of pattern `pattern` of `src` into `d`, keeping the library's numbered
|
||||
/// swatch names (the keys of `names`, such as "Ink 2") that `d` does not use for the library's own
|
||||
/// swatches of those names, so that a color the art brings under a numbered name does not take one
|
||||
/// of them. While the import runs, a placeholder swatch holds each such name the art does not
|
||||
/// bring, and a copy of the library's color holds each one the art brings, which the art then
|
||||
/// takes. The placeholders are removed before it returns, and so is a copy the art did not take;
|
||||
/// a copy the art took is listed with the colors the import brought. Names of the patterns the
|
||||
/// import brings are not held.
|
||||
fn import_holding(
|
||||
d: &mut vectorcraft_doc::Document,
|
||||
src: &vectorcraft_doc::Document,
|
||||
pattern: &str,
|
||||
names: &HashMap<&str, &Swatch>,
|
||||
) -> Result<(String, patternlib::SwatchNames, patternlib::SwatchNames)> {
|
||||
let numbered = |n: &str| n.rsplit_once(' ').is_some_and(|(_, k)| !k.is_empty() && k.bytes().all(|b| b.is_ascii_digit()));
|
||||
let taken = taken_names(d);
|
||||
let mut free: Vec<&str> = names.keys().copied().filter(|n| numbered(n) && !taken.contains(*n)).collect();
|
||||
free.sort_unstable();
|
||||
let (mut held, mut copies): (Vec<Swatch>, Vec<Swatch>) = (vec![], vec![]);
|
||||
if !free.is_empty() {
|
||||
let brings = patternlib::brought_names(src, pattern);
|
||||
let patterns = patternlib::brought_patterns(src, pattern);
|
||||
for n in free.into_iter().filter(|n| !patterns.contains(*n)) {
|
||||
if !brings.contains(n) {
|
||||
held.push(Swatch { name: n.to_string(), paint: Paint::None, global: false, spot: false });
|
||||
} else if let Some(w) = names.get(n).filter(|w| w.paint.color().is_some() && linked_names(&w.paint).is_empty()) {
|
||||
copies.push((*w).clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
let start = d.swatches.len();
|
||||
d.swatches.extend(held.iter().chain(&copies).cloned());
|
||||
let imported = patternlib::import(d, src, pattern);
|
||||
let used = |n: &str| {
|
||||
imported
|
||||
.as_ref()
|
||||
.is_ok_and(|(_, colors, took)| !colors.iter().any(|(from, _)| from == n) && !took.iter().any(|(from, to)| from == n && to != n))
|
||||
};
|
||||
let used: HashSet<String> = copies.iter().map(|w| w.name.clone()).filter(|n| used(n)).collect();
|
||||
let mut i = 0;
|
||||
d.swatches.retain(|w| {
|
||||
i += 1;
|
||||
let ours = held.iter().chain(&copies).any(|h| h.name == w.name && h.paint == w.paint);
|
||||
!(i > start && ours && !used.contains(&w.name))
|
||||
});
|
||||
let (target, mut colors, mut took) = imported?;
|
||||
took.retain(|(from, _)| !used.contains(from));
|
||||
colors.extend(copies.into_iter().map(|w| w.name).filter(|n| used.contains(n)).map(|n| (n.clone(), n)));
|
||||
Ok((target, colors, took))
|
||||
}
|
||||
|
||||
/// Link the swatches of `d` that `pending` names (document name, library swatch) to their colors
|
||||
/// under the names `links` gives them, for each whose colors `links` names now. Those leave
|
||||
/// `pending` and are returned.
|
||||
fn settle<'a>(
|
||||
d: &mut vectorcraft_doc::Document,
|
||||
pending: &mut Vec<(String, &'a Swatch)>,
|
||||
links: &HashMap<String, String>,
|
||||
) -> Vec<(String, &'a Swatch)> {
|
||||
let mut done = vec![];
|
||||
pending.retain(|(name, w)| {
|
||||
let all = all_linked(&w.paint, links);
|
||||
if all {
|
||||
done.push((name.clone(), *w));
|
||||
}
|
||||
!all
|
||||
});
|
||||
relink_in(d, &done, links);
|
||||
done
|
||||
}
|
||||
|
||||
/// Give the swatches of `d` that `list` names (document name, library swatch) the library swatch's
|
||||
/// paint with its colors linked to the names `links` gives them, in one pass over the document's
|
||||
/// swatches.
|
||||
fn relink_in(d: &mut vectorcraft_doc::Document, list: &[(String, &Swatch)], links: &HashMap<String, String>) {
|
||||
if list.is_empty() {
|
||||
return;
|
||||
}
|
||||
let paints: HashMap<&str, Paint> = list.iter().map(|(name, w)| (name.as_str(), relinked(&w.paint, links))).collect();
|
||||
for x in d.swatches_iter_mut() {
|
||||
if let Some(paint) = paints.get(x.name.as_str()) {
|
||||
x.paint = paint.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether paint `a` shows what paint `b` shows: the same color, or the same gradient with the
|
||||
/// colors its stops show, whichever swatches those colors link to.
|
||||
fn shows(a: &Paint, b: &Paint) -> bool {
|
||||
let unlinked = |p: &Paint| match p {
|
||||
Paint::Gradient(g) => {
|
||||
let mut g = g.clone();
|
||||
g.swatch = None;
|
||||
g.gradient.stops.iter_mut().for_each(|s| s.swatch = None);
|
||||
Paint::Gradient(g)
|
||||
}
|
||||
other => other.clone(),
|
||||
};
|
||||
match (a.color(), b.color()) {
|
||||
(Some(x), Some(y)) => x == y,
|
||||
_ => unlinked(a) == unlinked(b),
|
||||
}
|
||||
}
|
||||
|
||||
/// The names of the swatches the colors of paint `p` link to: a tint's base color, or the colors
|
||||
/// of a gradient's stops.
|
||||
fn linked_names(p: &Paint) -> Vec<&str> {
|
||||
match p {
|
||||
Paint::Solid { swatch: Some(b), .. } => vec![b.as_str()],
|
||||
Paint::Gradient(g) => g.gradient.stops.iter().filter_map(|s| s.swatch.as_deref()).collect(),
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// Paint `p` with each link to a swatch that `links` names changed to the name it maps to.
|
||||
fn relinked(p: &Paint, links: &HashMap<String, String>) -> Paint {
|
||||
let mut out = p.clone();
|
||||
let swap = |name: &mut String| {
|
||||
if let Some(to) = links.get(name.as_str()) {
|
||||
*name = to.clone();
|
||||
}
|
||||
};
|
||||
match &mut out {
|
||||
Paint::Solid { swatch: Some(b), .. } => swap(b),
|
||||
Paint::Gradient(g) => g.gradient.stops.iter_mut().filter_map(|s| s.swatch.as_mut()).for_each(swap),
|
||||
_ => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether `links` names every swatch the colors of paint `p` link to, the built-in Registration
|
||||
/// swatch aside (every document has it under its own name).
|
||||
fn all_linked(p: &Paint, links: &HashMap<String, String>) -> bool {
|
||||
linked_names(p).iter().all(|n| *n == REGISTRATION || links.contains_key(*n))
|
||||
}
|
||||
|
||||
fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "swatch.library.add";
|
||||
let (info, lib) = library_param(s, p, C)?;
|
||||
@@ -1030,34 +1178,207 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// The document's swatches by name (the first of a name wins, as in `Document::swatch`), looked
|
||||
// up once so that a large palette takes linear time.
|
||||
let mut by_name: std::collections::HashMap<&str, &Swatch> = std::collections::HashMap::new();
|
||||
// The document's numbered copies ("Ink 2") by the name they are numbered after, in order.
|
||||
let mut copies: HashMap<&str, Vec<&Swatch>> = HashMap::new();
|
||||
for w in d.swatches_iter() {
|
||||
by_name.entry(w.name.as_str()).or_insert(w);
|
||||
let std::collections::hash_map::Entry::Vacant(e) = by_name.entry(w.name.as_str()) else { continue };
|
||||
e.insert(w);
|
||||
if let Some((base, n)) = w.name.rsplit_once(' ')
|
||||
&& !n.is_empty()
|
||||
&& n.bytes().all(|b| b.is_ascii_digit())
|
||||
{
|
||||
copies.entry(base).or_default().push(w);
|
||||
}
|
||||
}
|
||||
let there = |w: &Swatch| match (&w.paint, &patterns) {
|
||||
(Paint::Pattern { pattern, .. }, Some(src)) => {
|
||||
patternlib::present_pattern(d, src, pattern).and_then(|target| library_pattern_swatch(d, w, &target))
|
||||
}
|
||||
_ => match by_name.get(w.name.as_str()) {
|
||||
Some(x) => x.paint == w.paint,
|
||||
None => w.name == REGISTRATION && d.swatch(&w.name).is_some_and(|x| x.paint == w.paint),
|
||||
}
|
||||
.then(|| w.name.clone()),
|
||||
// The library's swatches by name (the first of a name wins), looked up once.
|
||||
let mut lib_by_name: HashMap<&str, &Swatch> = HashMap::new();
|
||||
for w in lib.swatches.iter().chain(lib.groups.iter().flat_map(|g| &g.swatches)) {
|
||||
lib_by_name.entry(w.name.as_str()).or_insert(w);
|
||||
}
|
||||
let group_names: HashSet<&str> = d.swatch_groups.iter().map(|g| g.name.as_str()).collect();
|
||||
// A color whose name the document gives another color, or a color group, is the numbered copy
|
||||
// of it that an earlier add or a pattern's art brought in, when that copy is the same color. A
|
||||
// numbered copy whose name the library gives a swatch of the same paint stands for that swatch
|
||||
// alone, as adding that swatch finds it under its own name. Paints are compared with their
|
||||
// colors linked as `links` says ([`relinked`]).
|
||||
let same_kind = |x: &Swatch, w: &Swatch| x.global == w.global && x.spot == w.spot;
|
||||
// A color is the same swatch only as the same kind: a library global color is not the
|
||||
// document's process color of the same name and paint, which a tint cannot link to.
|
||||
let same_color_kind = |x: &Swatch, w: &Swatch| w.paint.color().is_none() || same_kind(x, w);
|
||||
let numbered = |w: &Swatch, paint: &Paint, links: &HashMap<String, String>| {
|
||||
let c = copies.get(w.name.as_str())?;
|
||||
let own = |x: &Swatch| lib_by_name.get(x.name.as_str()).is_some_and(|l| relinked(&l.paint, links) == x.paint && same_color_kind(x, l));
|
||||
let found = c.iter().find(|x| !own(x) && x.paint == *paint && same_kind(x, w));
|
||||
found.map(|x| x.name.clone())
|
||||
};
|
||||
let unlinked = HashMap::new();
|
||||
// Whether a library global or spot color that paint `p` links to has no place in `links`
|
||||
// while the document gives its name another swatch, which such a link would find instead.
|
||||
let misplaced = |p: &Paint, links: &HashMap<String, String>| {
|
||||
linked_names(p)
|
||||
.into_iter()
|
||||
.any(|n| !links.contains_key(n) && by_name.contains_key(n) && lib_by_name.get(n).is_some_and(|b| b.global || b.spot))
|
||||
};
|
||||
let picked_names: HashSet<&str> = picked.iter().map(|(_, w)| w.name.as_str()).collect();
|
||||
// The picked patterns the document already has, each probed once: library pattern name → its
|
||||
// name in the document and the colors of the document its art takes under other names.
|
||||
let mut present: HashMap<&str, Option<(String, patternlib::SwatchNames)>> = HashMap::new();
|
||||
if let Some(src) = &patterns {
|
||||
for (_, w) in &picked {
|
||||
let Paint::Pattern { pattern, .. } = &w.paint else { continue };
|
||||
present.entry(pattern.as_str()).or_insert_with(|| patternlib::present_pattern(d, src, pattern));
|
||||
}
|
||||
}
|
||||
// Whether the document's swatch `x` of the name of library swatch `w` is `w` with its colors
|
||||
// linked to swatches of the document → the library's global and spot colors to bring back,
|
||||
// those this call picks included.
|
||||
// `x` shows `w`'s paint with each color linked to: the name `links` gives it; its own name when
|
||||
// that is the document's color of the library color's paint and kind; or, for a library color
|
||||
// the document has under no name, that color's own name, which then comes in under it.
|
||||
// Registration and colors the library does not have keep their names.
|
||||
let fit = |x: &Swatch, w: &Swatch, links: &HashMap<String, String>| -> Option<Vec<String>> {
|
||||
let (ours, theirs) = (linked_names(&w.paint), linked_names(&x.paint));
|
||||
if ours.len() != theirs.len() {
|
||||
return None;
|
||||
}
|
||||
let map: HashMap<String, String> = ours.iter().zip(&theirs).map(|(l, t)| (l.to_string(), t.to_string())).collect();
|
||||
if relinked(&w.paint, &map) != x.paint {
|
||||
return None;
|
||||
}
|
||||
let mut restore = vec![];
|
||||
for (&l, &t) in ours.iter().zip(&theirs) {
|
||||
let ok = match (links.get(l), lib_by_name.get(l).filter(|b| b.global || b.spot)) {
|
||||
(Some(to), _) => to == t,
|
||||
(None, None) => l == t,
|
||||
(None, Some(b)) => match by_name.get(t) {
|
||||
Some(y) => l == t && y.paint == b.paint && same_kind(y, b),
|
||||
None if l == t && !group_names.contains(t) => {
|
||||
restore.push(l.to_string());
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
},
|
||||
};
|
||||
if !ok {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(restore)
|
||||
};
|
||||
// `paint` is `w`'s paint with the colors it links to as `links` has them in the document → the
|
||||
// name of the document's swatch, and the library colors to bring back for it ([`fit`]).
|
||||
let there = |w: &Swatch, paint: &Paint, links: &HashMap<String, String>| -> Option<(String, Vec<String>)> {
|
||||
if let (Paint::Pattern { pattern, .. }, Some(_)) = (&w.paint, &patterns) {
|
||||
let (target, _) = present.get(pattern.as_str())?.as_ref()?;
|
||||
return library_pattern_swatch(d, w, target).map(|n| (n, vec![]));
|
||||
}
|
||||
if let Some(restore) = by_name.get(w.name.as_str()).filter(|x| same_color_kind(x, w)).and_then(|x| fit(x, w, links)) {
|
||||
return Some((w.name.clone(), restore));
|
||||
}
|
||||
if misplaced(&w.paint, links) {
|
||||
return None;
|
||||
}
|
||||
let found = match by_name.get(w.name.as_str()) {
|
||||
Some(_) => numbered(w, paint, links),
|
||||
None if group_names.contains(w.name.as_str()) => numbered(w, paint, links),
|
||||
None => (w.name == REGISTRATION && d.swatch(&w.name).is_some_and(|x| x.paint == *paint)).then(|| w.name.clone()),
|
||||
};
|
||||
// A numbered copy brings back the colors it links to that the document deleted, as a
|
||||
// swatch of `w`'s own name does.
|
||||
found.map(|n| {
|
||||
let back = by_name.get(n.as_str()).and_then(|x| fit(x, w, links)).unwrap_or_default();
|
||||
(n, back)
|
||||
})
|
||||
};
|
||||
// The global or spot color of the document that library color `b` is: its own name, or the
|
||||
// numbered copy of it that adding `b` would find. While no color or color group has its name,
|
||||
// a numbered copy is looked for only when this call does not add `b` under its own name.
|
||||
let base_in_doc = |b: &Swatch| match by_name.get(b.name.as_str()) {
|
||||
Some(x) if x.paint == b.paint && same_kind(x, b) => Some(b.name.clone()),
|
||||
Some(_) => numbered(b, &b.paint, &unlinked),
|
||||
None if group_names.contains(b.name.as_str()) || !picked_names.contains(b.name.as_str()) => numbered(b, &b.paint, &unlinked),
|
||||
None => None,
|
||||
};
|
||||
// The library's global and spot colors that the picked tints and gradients link to, with the
|
||||
// name each has in the document: library name → document name. Each is looked up for itself,
|
||||
// whether or not this call picks it, once.
|
||||
let mut base_names: HashMap<String, String> = HashMap::new();
|
||||
let mut looked_up: HashSet<&str> = HashSet::new();
|
||||
for (_, w) in &picked {
|
||||
for base in linked_names(&w.paint) {
|
||||
if !looked_up.insert(base) {
|
||||
continue;
|
||||
}
|
||||
if let Some(n) = lib_by_name.get(base).filter(|b| b.global || b.spot).and_then(|b| base_in_doc(b)) {
|
||||
base_names.insert(base.to_string(), n);
|
||||
}
|
||||
}
|
||||
}
|
||||
// A color that the art of a picked pattern the document holds takes under another name (a
|
||||
// numbered copy that the library also names) is the one the picked tints and gradients link
|
||||
// to, as when the pattern came in, unless this call adds the color itself. The colors the art
|
||||
// takes are those of an import into a copy of the document, which adds nothing.
|
||||
if looked_up.iter().any(|n| !base_names.contains_key(*n)) {
|
||||
for (_, w) in &picked {
|
||||
let Paint::Pattern { pattern, .. } = &w.paint else { continue };
|
||||
let Some(Some((_, took))) = present.get(pattern.as_str()) else { continue };
|
||||
for (from, to) in took.iter().cloned() {
|
||||
let fits = |b: &&Swatch| by_name.get(to.as_str()).is_some_and(|x| (x.global || x.spot) && x.paint == b.paint && same_kind(x, b));
|
||||
if looked_up.contains(from.as_str()) && !picked_names.contains(from.as_str()) && lib_by_name.get(from.as_str()).is_some_and(fits) {
|
||||
base_names.entry(from).or_insert(to);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Library name → the name of the document's swatch.
|
||||
let mut existing: Vec<(String, String)> = vec![];
|
||||
let mut fresh = vec![];
|
||||
// The library colors that the document's tints and gradients found here link to by name while
|
||||
// the document has no swatch of that name (one deleted without unlinking them): they come back
|
||||
// under their own names.
|
||||
let mut restore: Vec<String> = vec![];
|
||||
// Those that this call picks: they are added first, so that they keep their names, which the
|
||||
// art of a pattern added before them could otherwise take.
|
||||
let mut reserved: HashSet<String> = HashSet::new();
|
||||
for &(group, w) in &picked {
|
||||
match there(w) {
|
||||
Some(name) => existing.push((w.name.clone(), name)),
|
||||
// A tint or gradient is compared with its colors linked to the names they have here.
|
||||
let paint = relinked(&w.paint, &base_names);
|
||||
match there(w, &paint, &base_names) {
|
||||
Some((name, back)) => {
|
||||
existing.push((w.name.clone(), name));
|
||||
for n in back {
|
||||
if picked_names.contains(n.as_str()) {
|
||||
reserved.insert(n);
|
||||
} else if !restore.contains(&n) {
|
||||
restore.push(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
None => fresh.push((group, w)),
|
||||
}
|
||||
}
|
||||
if !reserved.is_empty() {
|
||||
let (first, rest): (Vec<_>, Vec<_>) = fresh.into_iter().partition(|(_, w)| reserved.contains(&w.name));
|
||||
fresh = first;
|
||||
fresh.extend(rest);
|
||||
}
|
||||
let undo_before = s.doc()?.history.undo.len();
|
||||
// Library name → the name it got in the document.
|
||||
let added: Vec<(String, String)> = if fresh.is_empty() {
|
||||
// Library name → the name it got in the document. The colors the patterns brought that no
|
||||
// library swatch of this call stands for are added too; they are listed after the others and
|
||||
// are never the one `apply` paints with.
|
||||
let mut brought_alone: Vec<(String, String)> = vec![];
|
||||
// Library name → the name of the document's global or spot color for it, which the tints and
|
||||
// gradients added here link to: one that is global or spot as the library color is.
|
||||
let base_of = |l: &str, n: &str| {
|
||||
let (Some(w), Some(x)) = (lib_by_name.get(l), by_name.get(n)) else { return false };
|
||||
(x.global || x.spot) && same_kind(x, w)
|
||||
};
|
||||
let mut links: HashMap<String, String> = existing.iter().filter(|(l, n)| base_of(l, n)).cloned().collect();
|
||||
links.extend(base_names);
|
||||
let added: Vec<(String, String)> = if fresh.is_empty() && restore.is_empty() {
|
||||
vec![]
|
||||
} else {
|
||||
let (added, reused) = s.edit("Add to Swatches", |d, _| {
|
||||
let (added, reused, brought) = s.edit("Add to Swatches", |d, _| {
|
||||
let mut out = vec![];
|
||||
// Library pattern swatches that stand for a swatch added earlier in this call.
|
||||
let mut reused = vec![];
|
||||
@@ -1069,13 +1390,81 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// The swatches the patterns imported in this call brought with their art: (library
|
||||
// name, document name).
|
||||
let mut brought: Vec<(String, String)> = vec![];
|
||||
// The colors to bring back come first, under their own names, which no swatch or color
|
||||
// group of the document has; the tints and gradients added here link to them too.
|
||||
for n in &restore {
|
||||
let Some(b) = lib_by_name.get(n.as_str()) else { continue };
|
||||
let name = free_in(&mut taken, &b.name);
|
||||
d.swatches.push(Swatch { name: name.clone(), ..(*b).clone() });
|
||||
links.insert(n.clone(), name.clone());
|
||||
brought.push((n.clone(), name));
|
||||
}
|
||||
// The swatches added here with a link `links` did not name yet: (document name, library
|
||||
// swatch).
|
||||
let mut pending: Vec<(String, &Swatch)> = vec![];
|
||||
for (group, w) in fresh {
|
||||
let (name, sw) = if let (Paint::Pattern { pattern, .. }, Some(src)) = (&w.paint, &patterns) {
|
||||
// The pattern comes with its swatch; a pattern the document has without one
|
||||
// gets one. The swatch a pattern that comes in brings is named after the pattern:
|
||||
// it takes the library swatch's name and color group instead.
|
||||
// The tints and gradients added so far link to their colors first, so that the
|
||||
// pattern's art finds them. A color they wait for that the pattern's art brings
|
||||
// is named by importing the pattern into a copy first.
|
||||
let brings = if pending.is_empty() { Default::default() } else { patternlib::brought_names(src, pattern) };
|
||||
let waited = |n: &&str| !links.contains_key(*n) && brings.contains(*n);
|
||||
// A global or spot color the pattern brought, or took from the document under
|
||||
// a numbered name: library name → document name. A color this call picks is
|
||||
// added under its own name instead of the one the pattern took. A library global
|
||||
// or spot color is only a document color of its paint and kind, as for `base_of`.
|
||||
let colors_of = |d: &vectorcraft_doc::Document, colors: &[(String, String)], took: &[(String, String)]| {
|
||||
let mut out: HashMap<String, String> = HashMap::new();
|
||||
for (from, to) in colors.iter().chain(took.iter().filter(|(from, _)| !picked_names.contains(from.as_str()))) {
|
||||
let library = lib_by_name.get(from.as_str()).filter(|b| b.global || b.spot);
|
||||
let fits = |x: &Swatch| (x.global || x.spot) && library.is_none_or(|b| x.paint == b.paint && same_kind(x, b));
|
||||
if d.swatch(to).is_some_and(fits) {
|
||||
out.entry(from.clone()).or_insert_with(|| to.clone());
|
||||
}
|
||||
}
|
||||
out
|
||||
};
|
||||
// The names learned from the copy, which the import into the document confirms.
|
||||
let mut learned = vec![];
|
||||
if pending.iter().any(|(_, w)| linked_names(&w.paint).iter().any(waited)) {
|
||||
let mut probe = d.clone();
|
||||
let (_, colors, took) = import_holding(&mut probe, src, pattern, &lib_by_name)?;
|
||||
for (from, to) in colors_of(&probe, &colors, &took) {
|
||||
if let std::collections::hash_map::Entry::Vacant(e) = links.entry(from.clone()) {
|
||||
e.insert(to);
|
||||
learned.push(from);
|
||||
}
|
||||
}
|
||||
}
|
||||
let settled = settle(d, &mut pending, &links);
|
||||
let had = taken_names(d);
|
||||
let (target, colors) = patternlib::import(d, src, pattern)?;
|
||||
let (target, colors, took) = import_holding(d, src, pattern, &lib_by_name)?;
|
||||
// Those colors are the ones the library's tints of them link to, unless the
|
||||
// document already has one for them. A name the copy gave that the import
|
||||
// into the document did not give is replaced, and the tints linked to it are
|
||||
// linked again.
|
||||
let mut found = colors_of(d, &colors, &took);
|
||||
let mut changed = false;
|
||||
for from in learned {
|
||||
let real = found.remove(&from);
|
||||
if real.as_ref() != links.get(&from) {
|
||||
changed = true;
|
||||
match real {
|
||||
Some(to) => links.insert(from, to),
|
||||
None => links.remove(&from),
|
||||
};
|
||||
}
|
||||
}
|
||||
for (from, to) in found {
|
||||
links.entry(from).or_insert(to);
|
||||
}
|
||||
if changed {
|
||||
relink_in(d, &settled, &links);
|
||||
pending.extend(settled.into_iter().filter(|(_, w)| !all_linked(&w.paint, &links)));
|
||||
}
|
||||
brought.extend(colors);
|
||||
if let Some(name) = library_pattern_swatch(d, w, &target).filter(|n| had.contains(n)) {
|
||||
reused.push((w.name.clone(), name));
|
||||
@@ -1101,8 +1490,29 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(name.clone(), Swatch { name, paint, global: false, spot: false })
|
||||
} else {
|
||||
// A color a pattern added earlier in this call brought with its art is that
|
||||
// swatch: it moves to the library swatch's place.
|
||||
let at = brought.iter().position(|(from, _)| *from == w.name);
|
||||
// swatch when it shows the library swatch's color: it moves to the library
|
||||
// swatch's place, when its colors link where the library swatch's do: to the
|
||||
// names `links` gives them, not elsewhere for a color this call has yet to add,
|
||||
// and otherwise to a color of the library color's paint and process, global or spot kind,
|
||||
// or under the same name when the library has no such swatch (Registration).
|
||||
let fits = |x: &Paint| {
|
||||
let (ours, theirs) = (linked_names(&w.paint), linked_names(x));
|
||||
ours.len() == theirs.len()
|
||||
&& ours.iter().zip(&theirs).all(|(l, t)| match links.get(*l) {
|
||||
Some(to) => to == t,
|
||||
None => {
|
||||
!picked_names.contains(l)
|
||||
&& match lib_by_name.get(*l) {
|
||||
Some(b) => d.swatch(t).is_some_and(|x| x.paint == b.paint && same_kind(x, b)),
|
||||
None => l == t,
|
||||
}
|
||||
}
|
||||
})
|
||||
};
|
||||
let same = |to: &str| {
|
||||
d.swatch(to).is_some_and(|x| shows(&x.paint, &w.paint) && x.global == w.global && x.spot == w.spot && fits(&x.paint))
|
||||
};
|
||||
let at = brought.iter().position(|(from, to)| *from == w.name && same(to));
|
||||
let moved = at.map(|i| brought.swap_remove(i).1).and_then(|n| {
|
||||
let i = d.swatches.iter().position(|x| x.name == n)?;
|
||||
Some(d.swatches.remove(i))
|
||||
@@ -1110,11 +1520,23 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
match moved {
|
||||
Some(sw) => (sw.name.clone(), sw),
|
||||
None => {
|
||||
let name = free_in(&mut taken, &w.name);
|
||||
(name.clone(), Swatch { name, ..(*w).clone() })
|
||||
// A numbered copy skips the names of the library's other swatches,
|
||||
// which a later add looks up as theirs.
|
||||
let name = free_copy_in(&mut taken, &w.name, |n| lib_by_name.contains_key(n));
|
||||
// A tint or gradient links to its colors under the names they have in
|
||||
// the document; a color that comes in later in this call is linked
|
||||
// when it has come in.
|
||||
let paint = relinked(&w.paint, &links);
|
||||
if !all_linked(&w.paint, &links) {
|
||||
pending.push((name.clone(), w));
|
||||
}
|
||||
(name.clone(), Swatch { name, paint, ..(*w).clone() })
|
||||
}
|
||||
}
|
||||
};
|
||||
if sw.global || sw.spot {
|
||||
links.insert(w.name.clone(), name.clone());
|
||||
}
|
||||
match group {
|
||||
Some(g) => {
|
||||
let found = placed.iter().find(|(n, _)| *n == g).map(|&(_, i)| i);
|
||||
@@ -1135,13 +1557,37 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
out.push((w.name.clone(), name));
|
||||
}
|
||||
Ok((out, reused))
|
||||
// A library global or spot color that a tint or gradient added here links to, which the
|
||||
// document does not have and nothing in this call brought, comes in with it, as pasting
|
||||
// art painted with the tint brings its color. It is listed with the colors patterns
|
||||
// brought.
|
||||
let mut wanted: Vec<&str> = vec![];
|
||||
let mut seen: HashSet<&str> = HashSet::new();
|
||||
for (_, w) in &pending {
|
||||
for n in linked_names(&w.paint) {
|
||||
if n != REGISTRATION && !links.contains_key(n) && seen.insert(n) {
|
||||
wanted.push(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
for n in wanted {
|
||||
let Some(b) = lib_by_name.get(n).filter(|b| b.global || b.spot) else { continue };
|
||||
let name = free_copy_in(&mut taken, &b.name, |x| lib_by_name.contains_key(x));
|
||||
d.swatches.push(Swatch { name: name.clone(), ..(*b).clone() });
|
||||
links.insert(n.to_string(), name.clone());
|
||||
brought.push((n.to_string(), name));
|
||||
}
|
||||
relink_in(d, &pending, &links);
|
||||
Ok((out, reused, brought))
|
||||
})?;
|
||||
existing.extend(reused);
|
||||
brought_alone = brought;
|
||||
added
|
||||
};
|
||||
let names = |list: &[(String, String)]| list.iter().map(|(_, n)| n.clone()).collect::<Vec<_>>();
|
||||
let mut out = json!({"library": shown_library_id(s, &info.id), "added": names(&added), "existing": names(&existing)});
|
||||
let mut added_names = names(&added);
|
||||
added_names.extend(names(&brought_alone));
|
||||
let mut out = json!({"library": shown_library_id(s, &info.id), "added": added_names, "existing": names(&existing)});
|
||||
if let (Some(cmd), Some((_, first))) = (apply, picked.first()) {
|
||||
let name = added.iter().chain(&existing).find(|(l, _)| *l == first.name).map_or(first.name.clone(), |(_, n)| n.clone());
|
||||
s.execute(cmd, &json!({"swatch": name, "focus": focus}))?;
|
||||
|
||||
@@ -15,7 +15,7 @@ use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Symbol, SymbolNineSlice};
|
||||
use vectorcraft_geom::{Affine, Anchor, AnchorKind, PathData, Point, Rect, SubPath, shapes};
|
||||
|
||||
use super::brushsym::{CURRENT_SYMBOL, natural_size, normalize, place_xf, set_natural_size};
|
||||
use super::brushsym::{CURRENT_SYMBOL, Placement, natural_size, normalize, place_xf, set_natural_size};
|
||||
use super::clipboard::Clipboard;
|
||||
use super::clipboard::resources::SwatchChoices;
|
||||
use super::swatch::str_list;
|
||||
@@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add to Symbols",
|
||||
["Window", "Symbol Libraries"],
|
||||
None,
|
||||
"{library: id or name, name? | names?: [symbol names in the library] (default: all of it), place?: false (also place an instance of the first one, its registration point at x, y: default the first artboard's centre), x?, y?, swatchConflict? (as edit.paste)} copy library symbols into the document's Symbols as one undo step (with the place), with their Symbol Options and the resources they use (the symbols they nest, patterns, swatches, brushes, graphic styles, images). A symbol the document already has (same name and art) isn't added again; a name another symbol has gets a number (\"Star 2\"). The first one becomes the current symbol → {library, names: [each symbol's name in the document], added: [names added], existing: [names already there], placed?: id}",
|
||||
"{library: id or name, name? | names?: [symbol names in the library] (default: all of it), place?: false (also place an instance of the first one, its registration point at x, y: default the first artboard's centre, in the stacking order symbol.place gives it, Draw Behind included), x?, y?, swatchConflict? (as edit.paste)} copy library symbols into the document's Symbols as one undo step (with the place), with their Symbol Options and the resources they use (the symbols they nest, patterns, swatches, brushes, graphic styles, images). A symbol the document already has (same name and art) isn't added again; a name another symbol has gets a number (\"Star 2\"). The first one becomes the current symbol → {library, names: [each symbol's name in the document], added: [names added], existing: [names already there], placed?: id}",
|
||||
has_doc,
|
||||
add
|
||||
),
|
||||
@@ -59,7 +59,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Place Symbol Instance",
|
||||
[],
|
||||
None,
|
||||
"{sourceDocument: uid, name: a symbol of that document, x?, y?} place an instance of a symbol of another open document so its registration point is at (x, y) (default: the first artboard's center), as a symbol dragged from that document's Symbols panel onto the canvas is placed. The symbol, the symbols it nests and the resources they use are added as a drop of art from that document adds them, in the same undo step as the instance: a symbol the active document already has with the same name, art and Symbol Options is used, and one with the same name but other art or Symbol Options gets a number (\"Leaf 2\"); each symbol added takes its Symbol Options along. When sourceDocument is the active document, its own symbol is placed, as symbol.place places it. An error, with no edit, when that document is no longer open or has no symbol `name` → {id, name: the symbol's name in the active document}",
|
||||
"{sourceDocument: uid, name: a symbol of that document, x?, y?} place an instance of a symbol of another open document so its registration point is at (x, y) (default: the first artboard's center), in the stacking order symbol.place gives it (Draw Behind included), as a symbol dragged from that document's Symbols panel onto the canvas is placed. The symbol, the symbols it nests and the resources they use are added as a drop of art from that document adds them, in the same undo step as the instance: a symbol the active document already has with the same name, art and Symbol Options is used, and one with the same name but other art or Symbol Options gets a number (\"Leaf 2\"); each symbol added takes its Symbol Options along. When sourceDocument is the active document, its own symbol is placed, as symbol.place places it. An error, with no edit, when that document is no longer open or has no symbol `name` → {id, name: the symbol's name in the active document}",
|
||||
has_doc,
|
||||
place_from_document
|
||||
),
|
||||
@@ -816,7 +816,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let doc_names: Vec<String> = picked.iter().map(|n| target(&imported.renamed, n)).collect();
|
||||
let centre = st.doc.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO);
|
||||
let at = if place { Some(Point::new(number_or(p, "x", centre.x, C)?, number_or(p, "y", centre.y, C)?)) } else { None };
|
||||
let parent = if place { st.target_parent()? } else { None };
|
||||
let spot = if place { Some(Placement::of(s)?) } else { None };
|
||||
let mut out = json!({ "library": shown_library_id(s, &info.id) });
|
||||
if imported.added > 0 || place {
|
||||
let placed = s.edit("Add to Symbols", |d, sel| {
|
||||
@@ -830,10 +830,10 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let Some(first) = doc_names.first() else { return Ok(None) };
|
||||
d.unknown.insert(CURRENT_SYMBOL.into(), json!(first));
|
||||
let Some(at) = at else { return Ok(None) };
|
||||
let (Some(at), Some(spot)) = (at, &spot) else { return Ok(None) };
|
||||
let xf = place_xf(at, natural_size(d, first), d.symbol_registration(first));
|
||||
let id = d.alloc_id();
|
||||
d.insert(parent, usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: first.clone(), xf }))?;
|
||||
spot.insert(d, Node::new(id, NodeKind::SymbolInstance { symbol: first.clone(), xf }))?;
|
||||
sel.set([id]);
|
||||
Ok(Some(id))
|
||||
})?;
|
||||
@@ -860,7 +860,7 @@ fn place_from_document(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let centre = st.doc.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO);
|
||||
let at = Point::new(number_or(p, "x", centre.x, C)?, number_or(p, "y", centre.y, C)?);
|
||||
let parent = st.target_parent()?;
|
||||
let spot = Placement::of(s)?;
|
||||
let same = uid == st.uid;
|
||||
let src = s.documents().iter().find(|d| d.uid == uid).map(|d| Arc::clone(&d.doc));
|
||||
let src = src.ok_or_else(|| bad(C, "the document the symbol came from is no longer open"))?;
|
||||
@@ -883,7 +883,7 @@ fn place_from_document(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let xf = place_xf(at, natural_size(d, &placed), d.symbol_registration(&placed));
|
||||
let id = d.alloc_id();
|
||||
d.insert(parent, usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: placed.clone(), xf }))?;
|
||||
spot.insert(d, Node::new(id, NodeKind::SymbolInstance { symbol: placed.clone(), xf }))?;
|
||||
sel.set([id]);
|
||||
Ok((id, placed))
|
||||
})?;
|
||||
|
||||
@@ -11,8 +11,8 @@ use super::menucmds::whole_or;
|
||||
use super::stroke::StrokeChange;
|
||||
use super::typecmd::refresh_bounds;
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, has_doc, has_selection, index,
|
||||
number_or, object_param, point_param, str_param, switch_or, targets, text_param,
|
||||
CommandSpec, EngineError, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, finite_numbers, has_doc, has_selection,
|
||||
index, number_or, object_param, str_param, switch_or, targets, text_param,
|
||||
};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -85,7 +85,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Area / Path Type",
|
||||
[],
|
||||
None,
|
||||
"{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point), size?: pt 0.1..1296 (outside it: an error), font?, style?, color?, keepModel? (as text.create), fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (area: as text.areaOptions; default autoHeight when the autoSizeAreaType preference is on), placeholder?: bool (placeholder text instead, as text.create), justify?, leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id, bounds: {x, y, width, height} (as text.create), overflow?: [id] (the text doesn't fit; left out when it fits)}",
|
||||
"{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point; anything but two numbers: an error), size?: pt 0.1..1296 (outside it: an error), font?, style?, color?, keepModel? (as text.create), fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (area: as text.areaOptions; default autoHeight when the autoSizeAreaType preference is on), placeholder?: bool (placeholder text instead, as text.create), justify?, leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id, bounds: {x, y, width, height} (as text.create), overflow?: [id] (the text doesn't fit; left out when it fits)}",
|
||||
has_doc,
|
||||
create_in_path
|
||||
),
|
||||
@@ -255,9 +255,15 @@ fn byte_param(p: &Value, k: &str) -> Option<usize> {
|
||||
/// The byte offset that `p` gives for `k`, or `default` when `p` leaves it out or gives null. Any
|
||||
/// other value that is not a whole number of at least 0, such as `"2"`, `-1` or `1.5`, is an error.
|
||||
fn offset_or(p: &Value, k: &str, default: usize, cmd: &str) -> Result<usize> {
|
||||
Ok(offset_given(p, k, cmd)?.unwrap_or(default))
|
||||
}
|
||||
|
||||
/// The byte offset that `p` gives for `k`, or `None` when `p` leaves it out or gives null. Any
|
||||
/// other value that is not a whole number of at least 0, such as `"2"`, `-1` or `1.5`, is an error.
|
||||
fn offset_given(p: &Value, k: &str, cmd: &str) -> Result<Option<usize>> {
|
||||
match p.get(k) {
|
||||
None | Some(Value::Null) => Ok(default),
|
||||
Some(_) => Ok(index(whole_or(p, k, 0, cmd)?)),
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(_) => Ok(Some(index(whole_or(p, k, 0, cmd)?))),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -280,7 +286,7 @@ pub(crate) fn edit_range(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => Some(serde_json::from_value(v.clone()).map_err(|e| bad(C, format!("bad `runs`: {e}")))?),
|
||||
};
|
||||
let insert = str_param(p, "insert").unwrap_or("").to_string();
|
||||
let insert = text_param(p, "insert", C)?.unwrap_or("").to_string();
|
||||
let clear = clear_param(s, p, id, C)?;
|
||||
let caret = s.edit("Typing", |d, _| {
|
||||
for other in &clear {
|
||||
@@ -1313,8 +1319,7 @@ pub fn effective_kerning(db: &vectorcraft_text::FontDb, t: &TextObject, lay: &ve
|
||||
/// The character at byte `start` of `p` in text object `t`, its bytes and its font's face. An error
|
||||
/// when there is no character there, it is an inline graphic, or its font is not available.
|
||||
fn glyph_target(t: &TextObject, p: &Value, c: &str) -> Result<(char, std::ops::Range<usize>, std::sync::Arc<vectorcraft_text::FontFace>)> {
|
||||
check_numbers(p, &["start"], c)?;
|
||||
let start = byte_param(p, "start").ok_or_else(|| bad(c, "missing `start` (the byte offset of a character)"))?;
|
||||
let start = offset_given(p, "start", c)?.ok_or_else(|| bad(c, "missing `start` (the byte offset of a character)"))?;
|
||||
let mut at = 0;
|
||||
for run in &t.runs {
|
||||
let end = at + run.text.len();
|
||||
@@ -1558,8 +1563,7 @@ fn glyph_alternates(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn touch_type(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.touchType";
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?;
|
||||
check_numbers(p, &["start"], C)?;
|
||||
let start = byte_param(p, "start").ok_or_else(|| bad(C, "missing `start` (the byte offset of a character)"))?;
|
||||
let start = offset_given(p, "start", C)?.ok_or_else(|| bad(C, "missing `start` (the byte offset of a character)"))?;
|
||||
if !["dx", "dy", "hScale", "vScale", "rotation"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
|
||||
return Err(bad(C, "nothing to change: give dx, dy, hScale, vScale or rotation"));
|
||||
}
|
||||
@@ -1797,7 +1801,7 @@ fn touch_type(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.createInPath";
|
||||
let pid = object_param(p, "path", C)?.ok_or_else(|| bad(C, "missing `path` (a path object id)"))?;
|
||||
let on_path = match str_param(p, "mode").unwrap_or("area") {
|
||||
let on_path = match text_param(p, "mode", C)?.unwrap_or("area") {
|
||||
"area" => false,
|
||||
"onPath" | "path" => true,
|
||||
o => return Err(bad(C, format!("mode must be area|onPath, got {o}"))),
|
||||
@@ -1815,8 +1819,12 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_switches(p, &["vertical", "placeholder"], C)?;
|
||||
super::color_param(p, "color", C)?;
|
||||
let style = super::create::new_type_style(s, p, C)?;
|
||||
let text = str_param(p, "text").unwrap_or("").to_string();
|
||||
let start = match point_param(p, "at") {
|
||||
let text = text_param(p, "text", C)?.unwrap_or("").to_string();
|
||||
let at = match p.get("at").filter(|v| !v.is_null()) {
|
||||
None => None,
|
||||
Some(v) => Some(finite_numbers::<2>(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(C, "`at` must be a point: [x, y]"))?),
|
||||
};
|
||||
let start = match at {
|
||||
Some(at) if on_path => vectorcraft_geom::ArcPath::new(path).fraction_at(at).unwrap_or(0.0),
|
||||
_ => 0.0,
|
||||
};
|
||||
|
||||
@@ -13,7 +13,7 @@ use super::edit::selected_roots;
|
||||
use super::pathops::{length_given, number_given, shape_node};
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, bad, check_numbers, cmd, color_value, f64_req, has_doc, has_selection, index, index_opt, number_or,
|
||||
object_param, ok, str_param, switch_or, targets, text_param,
|
||||
object_param, ok, switch_or, targets, text_param,
|
||||
};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -873,7 +873,7 @@ pub(crate) fn style_chars(t: &mut TextObject, range: Option<TextRange>, mut f: i
|
||||
}
|
||||
|
||||
fn set_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let text = str_param(p, "text").ok_or_else(|| bad("text.setText", "missing `text`"))?.to_string();
|
||||
let text = text_param(p, "text", "text.setText")?.ok_or_else(|| bad("text.setText", "missing `text`"))?.to_string();
|
||||
let ids = text_targets(s, p, "text.setText")?;
|
||||
// The text the type already has is no undo step.
|
||||
edit_if_nodes_changed(s, "Typing", &ids, |d| {
|
||||
|
||||
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Save for Web",
|
||||
[],
|
||||
None,
|
||||
"{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries, its transparent colors taking one slot together; a new reduction without colorTable clears it and deleted), shifted?: {\"#source\": \"#rrggbb\"…} (each source color is written as the color given, wherever it is in the image; kept when reducing as a locked color is, before the locked ones, while one palette slot is left for the reduction; at most 256; a source the table does not hold shifts nothing; a color shifted to itself is removed; a shifted color is not web-shifted, and a transparent one stays transparent; GIF lossy moves no pixel into or out of a shifted color)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/<slice name>.<ext>), output?: images (default)|html (an HTML page placing the image or slices, <stem>.html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself",
|
||||
"{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries, its transparent colors taking one slot together (the transparent pixels' slot when there are any), its shifted and then its locked colors kept first; a new reduction without colorTable clears it and deleted), shifted?: {\"#source\": \"#rrggbb\"…} (each source color is written as the color given, wherever it is in the image; kept when reducing as a locked color is, before the locked ones, while one palette slot is left for the reduction; at most 256; a source the table does not hold shifts nothing; a color shifted to itself is removed; a shifted color is not web-shifted, and a transparent one stays transparent; GIF lossy moves no pixel into or out of a shifted color)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/<slice name>.<ext>), output?: images (default)|html (an HTML page placing the image or slices, <stem>.html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself",
|
||||
has_doc,
|
||||
export
|
||||
),
|
||||
@@ -800,11 +800,18 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
|
||||
transparency: s.transparency,
|
||||
matte,
|
||||
};
|
||||
let mut ix = reduced(rgba, w, h, s, &o, &kept)?;
|
||||
let (mut ix, dropped) = reduced(rgba, w, h, s, &o, &kept)?;
|
||||
// Map to transparent works on the colours the reduction made.
|
||||
let before = ix.palette.clone();
|
||||
let clear = ix.transparent.map(usize::from);
|
||||
let mapped: Vec<[u8; 3]> = before.iter().enumerate().filter(|(i, c)| Some(*i) != clear && to_clear.contains(c)).map(|(_, c)| *c).collect();
|
||||
let mut mapped: Vec<[u8; 3]> = before.iter().enumerate().filter(|(i, c)| Some(*i) != clear && to_clear.contains(c)).map(|(_, c)| *c).collect();
|
||||
// The colors mapped to transparent that did not fit in a fixed palette and whose pixels became
|
||||
// transparent.
|
||||
for c in dropped {
|
||||
if !mapped.contains(&c) {
|
||||
mapped.push(c);
|
||||
}
|
||||
}
|
||||
let remap = web::to_transparent(&mut ix, |i| Some(i) != clear && before.get(i).is_some_and(|c| to_clear.contains(c)));
|
||||
let mut sources = ix.palette.clone();
|
||||
for (old, new) in remap.iter().enumerate() {
|
||||
@@ -868,8 +875,17 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
|
||||
/// color table's fixed one, without the deleted colors. The pixels of a deleted color take the
|
||||
/// nearest color left, with `o`'s dither. A deletion has to leave a color that is not mapped to
|
||||
/// transparent. A fixed palette keeps its colors mapped to transparent, which take one slot of
|
||||
/// `colors` together, and its first opaque colors that fit in the rest.
|
||||
fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, locked: &[[u8; 3]]) -> std::result::Result<Indexed, String> {
|
||||
/// `colors` together (the transparent pixels' slot when there are any), and the opaque colors that
|
||||
/// fit in the rest: the `locked` ones first, in their order, then the others in palette order. Also returns the
|
||||
/// colors mapped to transparent that did not fit and whose pixels became transparent.
|
||||
fn reduced(
|
||||
rgba: &[u8],
|
||||
w: u32,
|
||||
h: u32,
|
||||
s: &WebSettings,
|
||||
o: &PaletteOptions,
|
||||
locked: &[[u8; 3]],
|
||||
) -> std::result::Result<(Indexed, Vec<[u8; 3]>), String> {
|
||||
let table = &s.color_table;
|
||||
let deleted = ColorTable::colors(&table.deleted, "deleted")?;
|
||||
let custom = ColorTable::colors(&table.custom_palette, "customPalette")?;
|
||||
@@ -880,13 +896,13 @@ fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, loc
|
||||
let clear = ix.transparent.map(usize::from);
|
||||
let gone = |i: usize, c: &[u8; 3]| Some(i) != clear && deleted.contains(c);
|
||||
if !ix.palette.iter().enumerate().any(|(i, c)| gone(i, c)) {
|
||||
return Ok(ix);
|
||||
return Ok((ix, vec![]));
|
||||
}
|
||||
let left: Vec<[u8; 3]> = ix.palette.iter().enumerate().filter(|&(i, c)| Some(i) != clear && !deleted.contains(c)).map(|(_, c)| *c).collect();
|
||||
if left.is_empty() || !opaque_left(&left) {
|
||||
return Err(KEEP_ONE.into());
|
||||
}
|
||||
return Ok(quantize::quantize_to(rgba, w, h, o, &left));
|
||||
return Ok((quantize::quantize_to(rgba, w, h, o, &left), vec![]));
|
||||
}
|
||||
// A fixed palette holds at most `colors` entries, the transparent one included.
|
||||
let has_clear = s.transparency && rgba.as_chunks::<4>().0.iter().any(|p| p[3] < 128);
|
||||
@@ -901,32 +917,46 @@ fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, loc
|
||||
return Err(KEEP_ONE.into());
|
||||
}
|
||||
// The colors mapped to transparent all become the one transparent entry, so together they take
|
||||
// one slot, and the opaque colors fill the rest in palette order. When no pixel takes one of
|
||||
// them and no pixel is transparent, that slot goes to the next opaque color instead.
|
||||
let kept = fixed_palette(&left, &to_clear, s.colors, has_clear, true);
|
||||
// one slot, and the opaque colors fill the rest. With transparent pixels that slot is theirs, so
|
||||
// the colors mapped to transparent take no entry of their own and their pixels take the
|
||||
// transparent pixels' entry. Without them, when no pixel takes one of those colors, the slot
|
||||
// goes to the next opaque color instead.
|
||||
let kept = fixed_palette(&left, &to_clear, locked, s.colors, has_clear, !has_clear);
|
||||
let mut ix = quantize::quantize_to(rgba, w, h, o, &kept);
|
||||
clear_dropped(&mut ix, rgba, o, &kept, &left, &to_clear);
|
||||
let dropped = clear_dropped(&mut ix, rgba, o, &kept, &left, &to_clear);
|
||||
if !has_clear && !ix.palette.iter().any(|c| to_clear.contains(c)) && left.iter().any(|c| to_clear.contains(c)) {
|
||||
return Ok(quantize::quantize_to(rgba, w, h, o, &fixed_palette(&left, &to_clear, s.colors, has_clear, false)));
|
||||
return Ok((quantize::quantize_to(rgba, w, h, o, &fixed_palette(&left, &to_clear, locked, s.colors, has_clear, false)), vec![]));
|
||||
}
|
||||
Ok(ix)
|
||||
Ok((ix, dropped))
|
||||
}
|
||||
|
||||
/// The entries of the fixed palette `left` that fit in `colors`. With `clear`, the colors in
|
||||
/// `to_clear` are kept and take one slot together; without it they are left out. The list holds
|
||||
/// at most 256 entries, less one when `has_clear` (the transparent pixels' entry).
|
||||
fn fixed_palette(left: &[[u8; 3]], to_clear: &[[u8; 3]], colors: u16, has_clear: bool, clear: bool) -> Vec<[u8; 3]> {
|
||||
/// The entries of the fixed palette `left` that fit in `colors`, in palette order. The opaque
|
||||
/// colors in `locked` are kept first, in the order `locked` lists them (the colors shifted by hand
|
||||
/// before the locked ones), then the other opaque colors in palette order. With `clear`,
|
||||
/// the colors in `to_clear` are kept and take one slot together; without it they are left out. The
|
||||
/// list holds at most 256 entries, less one when `has_clear` (the transparent pixels' entry).
|
||||
fn fixed_palette(left: &[[u8; 3]], to_clear: &[[u8; 3]], locked: &[[u8; 3]], colors: u16, has_clear: bool, clear: bool) -> Vec<[u8; 3]> {
|
||||
let any_clear = clear && left.iter().any(|c| to_clear.contains(c));
|
||||
let total = 256 - usize::from(has_clear);
|
||||
let mut room = (usize::from(colors.clamp(2, 256)) - usize::from(has_clear || any_clear)).min(total - usize::from(any_clear));
|
||||
let opaque = left.iter().filter(|c| !to_clear.contains(c)).count().min(room);
|
||||
let mut clear_room = if clear { total - opaque } else { 0 };
|
||||
let room = (usize::from(colors.clamp(2, 256)) - usize::from(has_clear || any_clear)).min(total - usize::from(any_clear));
|
||||
let opaque = |c: &&[u8; 3]| !to_clear.contains(c);
|
||||
let mut first: Vec<[u8; 3]> = vec![];
|
||||
for c in locked.iter().filter(opaque).filter(|c| left.contains(c)) {
|
||||
if first.len() < room && !first.contains(c) {
|
||||
first.push(*c);
|
||||
}
|
||||
}
|
||||
let rest = room - first.len();
|
||||
let others: Vec<[u8; 3]> = left.iter().filter(opaque).filter(|c| !locked.contains(c)).take(rest).copied().collect();
|
||||
let mut clear_room = if clear { total - first.len() - others.len() } else { 0 };
|
||||
left.iter()
|
||||
.copied()
|
||||
.filter(|c| {
|
||||
let slots = if to_clear.contains(c) { &mut clear_room } else { &mut room };
|
||||
let keep = *slots > 0;
|
||||
*slots = slots.saturating_sub(1);
|
||||
if !to_clear.contains(c) {
|
||||
return first.contains(c) || others.contains(c);
|
||||
}
|
||||
let keep = clear_room > 0;
|
||||
clear_room = clear_room.saturating_sub(1);
|
||||
keep
|
||||
})
|
||||
.collect()
|
||||
@@ -935,32 +965,39 @@ fn fixed_palette(left: &[[u8; 3]], to_clear: &[[u8; 3]], colors: u16, has_clear:
|
||||
/// Makes transparent the pixels of `ix` whose nearest color is a color of `left` mapped to
|
||||
/// transparent (`to_clear`) that does not fit in the fixed palette `kept`. Such a pixel takes the
|
||||
/// transparent entry, or an entry mapped to transparent, which Map to Transparent clears later.
|
||||
fn clear_dropped(ix: &mut Indexed, rgba: &[u8], o: &PaletteOptions, kept: &[[u8; 3]], left: &[[u8; 3]], to_clear: &[[u8; 3]]) {
|
||||
/// Returns those colors that a pixel took.
|
||||
fn clear_dropped(ix: &mut Indexed, rgba: &[u8], o: &PaletteOptions, kept: &[[u8; 3]], left: &[[u8; 3]], to_clear: &[[u8; 3]]) -> Vec<[u8; 3]> {
|
||||
let dropped: Vec<[u8; 3]> = left.iter().filter(|c| to_clear.contains(c) && !kept.contains(c)).copied().collect();
|
||||
if dropped.is_empty() {
|
||||
return;
|
||||
return vec![];
|
||||
}
|
||||
let all: Vec<[u8; 3]> = kept.iter().chain(&dropped).copied().collect();
|
||||
let near = quantize::nearest_entries(rgba, o, &all);
|
||||
if !near.iter().any(|n| n.is_some_and(|n| n >= kept.len())) {
|
||||
return;
|
||||
}
|
||||
let entry = match ix.transparent.or_else(|| ix.palette.iter().position(|c| to_clear.contains(c)).and_then(|i| u8::try_from(i).ok())) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
// A kept color mapped to transparent that no pixel took; at most 255 entries are used then.
|
||||
let (Some(c), Ok(i)) = (kept.iter().find(|c| to_clear.contains(c)), u8::try_from(ix.palette.len())) else {
|
||||
return;
|
||||
};
|
||||
ix.palette.push(*c);
|
||||
i
|
||||
let Indexed { palette, transparent, indices, .. } = ix;
|
||||
// The entry such pixels take, looked up at the first of them.
|
||||
let mut entry: Option<Option<u8>> = None;
|
||||
let mut taken = vec![false; dropped.len()];
|
||||
let mut pixel = 0;
|
||||
quantize::nearest_entries(rgba, o, &all, |n| {
|
||||
if let Some(d) = n.and_then(|n| n.checked_sub(kept.len())) {
|
||||
let e = *entry.get_or_insert_with(|| {
|
||||
transparent.or_else(|| palette.iter().position(|c| to_clear.contains(c)).and_then(|i| u8::try_from(i).ok())).or_else(|| {
|
||||
// A kept color mapped to transparent that no pixel took; at most 255 entries are used then.
|
||||
let c = kept.iter().find(|c| to_clear.contains(c))?;
|
||||
let i = u8::try_from(palette.len()).ok()?;
|
||||
palette.push(*c);
|
||||
Some(i)
|
||||
})
|
||||
});
|
||||
if let (Some(e), Some(v)) = (e, indices.get_mut(pixel)) {
|
||||
*v = e;
|
||||
if let Some(t) = taken.get_mut(d) {
|
||||
*t = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
for (v, n) in ix.indices.iter_mut().zip(&near) {
|
||||
if n.is_some_and(|n| n >= kept.len()) {
|
||||
*v = entry;
|
||||
}
|
||||
}
|
||||
pixel += 1;
|
||||
});
|
||||
dropped.into_iter().zip(taken).filter(|(_, t)| *t).map(|(c, _)| c).collect()
|
||||
}
|
||||
|
||||
/// An optimised image as straight RGBA → `(pixels, width, height)` (the dialog's preview).
|
||||
|
||||
@@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Sample Color",
|
||||
[],
|
||||
None,
|
||||
"{color (#rrggbbaa and #rgba are refused), stroke?: bool (default: whichever proxy is active), ids?, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default, and so does a sample without ids while the Live Paint Bucket is the active tool, `stop` included); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it",
|
||||
"{color (#rrggbbaa and #rgba are refused), stroke?: bool (default: whichever proxy is active), ids?, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default, and so does a sample without ids while the Live Paint Bucket is the active tool, `stop` included); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); with `stop` and objects in `ids`, whatever tool is active, the stops come from the topmost fill (or stroke) of the first object that paint.editGradient edits for those ids (a compound path for its member); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it",
|
||||
has_doc,
|
||||
sample_color
|
||||
),
|
||||
@@ -529,9 +529,15 @@ fn sample_color(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(v) => {
|
||||
let i = v.as_u64().map(index).ok_or_else(|| bad(C, "`stop` must be a stop index"))?;
|
||||
let color = super::paint::new_color(s, p, color_value(c).ok_or_else(|| bad(C, format!("bad color {c}")))?);
|
||||
let (fill, stroke_paint) = s.proxy_paints();
|
||||
let Paint::Gradient(g) = (if stroke { stroke_paint } else { fill }) else {
|
||||
return Err(bad(C, "the paint behind the proxy is not a gradient"));
|
||||
let (paint, source) = match given_stop_paint(s, p, stroke)? {
|
||||
Some(paint) => (paint, "the paint of the first object in `ids`"),
|
||||
None => {
|
||||
let (fill, stroke_paint) = s.proxy_paints();
|
||||
(if stroke { stroke_paint } else { fill }, "the paint behind the proxy")
|
||||
}
|
||||
};
|
||||
let Paint::Gradient(g) = paint else {
|
||||
return Err(bad(C, format!("{source} is not a gradient")));
|
||||
};
|
||||
let mut stops = g.gradient.stops;
|
||||
let n = stops.len();
|
||||
@@ -550,6 +556,24 @@ fn sample_color(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// The paint whose gradient `paint.sampleColor` recolors a stop of when `p` gives `stop` and
|
||||
/// objects in `ids`: the fill (or stroke, `stroke`) of the first object `paint.editGradient` edits
|
||||
/// for those ids (a compound path for its member, a group's painted objects, not the art of a graph
|
||||
/// design in a series). None without `stop` or without objects in `ids`: the gradient behind the
|
||||
/// proxy is used.
|
||||
fn given_stop_paint(s: &Session, p: &Value, stroke: bool) -> Result<Option<Paint>> {
|
||||
const C: &str = "paint.sampleColor";
|
||||
if p.get("stop").is_none_or(Value::is_null) || p.get("ids").and_then(Value::as_array).is_none_or(Vec::is_empty) {
|
||||
return Ok(None);
|
||||
}
|
||||
let q = json!({ "ids": p.get("ids"), "stroke": stroke });
|
||||
let item = super::appearance::item_target(s, &q, C)?.of_kind(s, !stroke);
|
||||
let ids = super::appearance::drop_design_art_rows(s, item.targets_for(s, &q, !stroke)?, item, !stroke, C)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let Some(n) = ids.first().and_then(|id| d.node(*id)) else { return Ok(None) };
|
||||
Ok(Some(super::paint::proxy_paint(n, stroke, None)))
|
||||
}
|
||||
|
||||
// ---------- artboards ----------
|
||||
|
||||
fn artboard_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -782,15 +782,17 @@ impl ScriptScope {
|
||||
self.allows(&real.join(rest))
|
||||
}
|
||||
|
||||
/// What the file or folder at `path` is, located as [`ScriptScope::locate`] locates it.
|
||||
/// What the file or folder at `path` is, located as [`ScriptScope::locate`] locates it. Whether
|
||||
/// it is hidden is a link's own, and the rest is what the link leads to.
|
||||
pub(crate) fn stat(&self, path: &Path) -> Result<ScriptEntry, ScriptRead> {
|
||||
let real = self.locate(path)?;
|
||||
let meta = std::fs::metadata(&real).map_err(|e| ScriptRead::Failed(e.to_string()))?;
|
||||
let link = std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink());
|
||||
let own = std::fs::symlink_metadata(path).ok().filter(|m| m.file_type().is_symlink());
|
||||
let link = own.is_some();
|
||||
#[cfg(windows)]
|
||||
let hidden = std::os::windows::fs::MetadataExt::file_attributes(&meta) & 2 != 0;
|
||||
let hidden = std::os::windows::fs::MetadataExt::file_attributes(own.as_ref().unwrap_or(&meta)) & 2 != 0;
|
||||
#[cfg(not(windows))]
|
||||
let hidden = real.file_name().is_some_and(|n| n.to_string_lossy().starts_with('.'));
|
||||
let hidden = if link { path.file_name() } else { real.file_name() }.is_some_and(|n| n.to_string_lossy().starts_with('.'));
|
||||
Ok(ScriptEntry {
|
||||
dir: meta.is_dir(),
|
||||
file: meta.is_file(),
|
||||
|
||||
@@ -55,6 +55,8 @@ pub(crate) struct PreviewCopies {
|
||||
pub(crate) from: Arc<Document>,
|
||||
/// The transform or perspective edit copied these objects.
|
||||
pub(crate) roots: Vec<NodeId>,
|
||||
/// Each copy is directly below its original, not above it.
|
||||
pub(crate) below: bool,
|
||||
/// This is `from` with the copies added, untransformed.
|
||||
pub(crate) doc: Arc<Document>,
|
||||
/// This is the selection after copying, with the copies selected.
|
||||
|
||||
@@ -75,8 +75,9 @@ pub struct Session {
|
||||
/// back as it was at the release ([`Session::pointer`]).
|
||||
pub(crate) lender: Option<Box<dyn Tool>>,
|
||||
/// Set while tool actions that end by switching back to the Live Paint Bucket are applied (the
|
||||
/// Eyedropper's sample into a stop of the bucket's gradient): their paint commands change the
|
||||
/// colors the bucket paints with ([`Session::bucket_paints`]).
|
||||
/// Eyedropper's sample into a stop of the bucket's gradient), and while a tool the bucket lent
|
||||
/// is deactivated as it goes back: their paint commands change the colors the bucket paints
|
||||
/// with ([`Session::bucket_paints`]).
|
||||
pub(crate) back_to_bucket: bool,
|
||||
/// Pointer and key input that came while the tool computed an edit on another thread, each with
|
||||
/// its number and view, made in order once the edit is applied.
|
||||
|
||||
@@ -67,8 +67,15 @@
|
||||
//! file and once more for each such object. `write` joins its values only for an open file and
|
||||
//! only up to twice [`MAX_FILE_BYTES`] UTF-16 code units. Each file written is named in the
|
||||
//! report's `written` (at most [`super::MAX_WRITTEN`]), also after a run that failed.
|
||||
//! - Hidden settings, aliases and `execute` are not available: they return `false` and set `error`.
|
||||
//! `execute` is counted in the report's `fileExecutes`.
|
||||
//! - On Unix, where a name that starts with a dot is hidden, setting `hidden` renames the file in
|
||||
//! its folder, adding one dot or taking its leading dots off, under the rules for `rename`: the
|
||||
//! old and the new name must both be places the script may write, and a name in use is refused.
|
||||
//! `createAlias` makes a symbolic link at the object's path, a place the script may write where
|
||||
//! nothing is, that leads to the real path of a file the script may read. `hidden` and `alias`
|
||||
//! tell of a link itself, and setting `hidden`, `rename` and `remove` change the link, never what
|
||||
//! it leads to. On other systems both set `error` and change nothing.
|
||||
//! - `execute` is not available: it returns `false`, sets `error`, and is counted in the report's
|
||||
//! `fileExecutes`.
|
||||
//! - In a wasm build every lookup fails with [`NO_WEB`].
|
||||
|
||||
use std::collections::HashMap;
|
||||
@@ -118,6 +125,7 @@ pub(crate) const WRITE_FAILED: &str = "Script file could not be written";
|
||||
pub(crate) const NOT_EMPTY: &str = "Script folder is not empty";
|
||||
pub(crate) const NAME_TAKEN: &str = "Script file name is already in use";
|
||||
pub(crate) const BAD_NAME: &str = "Script file name must be a name without a folder";
|
||||
#[cfg(not(unix))]
|
||||
pub(crate) const NO_ALIAS: &str = "Script files cannot make aliases";
|
||||
pub(crate) const NO_HIDDEN: &str = "Script file hidden setting cannot be changed";
|
||||
pub(crate) const PROTECTED: &str = "Script file access to the app's own folders is not allowed";
|
||||
@@ -1883,44 +1891,41 @@ fn remove(host: &Host, a: &[Data]) -> Result<Data, HostError> {
|
||||
/// `rename(path, name)`: the file or folder named `name` in the same folder; → `{fs}`, its new path.
|
||||
fn rename(host: &Host, a: &[Data]) -> Result<Data, HostError> {
|
||||
let (path, name) = (arg_text(a, 0), arg_text(a, 1));
|
||||
let mut disk = host.disk.borrow_mut();
|
||||
Ok(match rename_in(&mut disk, &path, &name) {
|
||||
Ok(new) => Data::Object(vec![("fs".into(), Data::String(new))]),
|
||||
Err(m) => error(m),
|
||||
})
|
||||
}
|
||||
|
||||
/// Renames the file or folder at `path`, a link itself, to `name` in the same folder. → its new
|
||||
/// path.
|
||||
fn rename_in(disk: &mut Disk, path: &str, name: &str) -> Result<String, &'static str> {
|
||||
let bad = name.is_empty() || name == "." || name == ".." || name.contains('/') || (WINDOWS && (name.contains('\\') || name.contains(':')));
|
||||
if bad || name.contains('\0') {
|
||||
return Ok(error(BAD_NAME));
|
||||
return Err(BAD_NAME);
|
||||
}
|
||||
let Some(new) = Path::new(&path).parent().map(|p| p.join(&name).to_string_lossy().into_owned()) else { return Ok(error(ACCESS_DENIED)) };
|
||||
let mut disk = host.disk.borrow_mut();
|
||||
let (from, to) = match (disk.target(&path, false), disk.target(&new, false)) {
|
||||
(Ok(f), Ok(t)) => (f, t),
|
||||
(Err(m), _) | (_, Err(m)) => return Ok(error(m)),
|
||||
};
|
||||
let Ok(was) = std::fs::symlink_metadata(&from) else { return Ok(error(NOT_FOUND)) };
|
||||
let new = Path::new(path).parent().map(|p| p.join(name).to_string_lossy().into_owned()).ok_or(ACCESS_DENIED)?;
|
||||
let (from, to) = (disk.target(path, false)?, disk.target(&new, false)?);
|
||||
let was = std::fs::symlink_metadata(&from).map_err(|_| NOT_FOUND)?;
|
||||
// A folder that holds the settings folder is not moved, also when its name is given in another
|
||||
// case where case does not matter.
|
||||
let holds = |f: &Path| std::fs::canonicalize(&from).map_or(true, |kept| crate::file_access::path_inside(f, &kept));
|
||||
if was.is_dir() && disk.fenced.as_deref().is_some_and(holds) {
|
||||
return Ok(error(ACCESS_DENIED));
|
||||
return Err(ACCESS_DENIED);
|
||||
}
|
||||
// A name that differs in case alone may name the same file, which then takes the new name.
|
||||
if let Ok(there) = std::fs::symlink_metadata(&to)
|
||||
&& !(from.to_string_lossy().eq_ignore_ascii_case(&to.to_string_lossy()) && same_file((&from, &was), (&to, &there)))
|
||||
{
|
||||
return Ok(error(NAME_TAKEN));
|
||||
return Err(NAME_TAKEN);
|
||||
}
|
||||
// Open objects hold real paths with the names the file system keeps, and `from` keeps the last
|
||||
// name as given, which where case does not matter can differ in case: they are matched by the
|
||||
// kept name. A link is renamed itself, and no object holds a path through it. When the kept
|
||||
// name cannot be learned, nothing is renamed, so no object goes on under the old path's rules.
|
||||
let kept = if was.file_type().is_symlink() {
|
||||
from.clone()
|
||||
} else {
|
||||
match std::fs::canonicalize(&from) {
|
||||
Ok(kept) => kept,
|
||||
Err(_) => return Ok(error(WRITE_FAILED)),
|
||||
}
|
||||
};
|
||||
if std::fs::rename(&from, &to).is_err() {
|
||||
return Ok(error(WRITE_FAILED));
|
||||
}
|
||||
let kept = if was.file_type().is_symlink() { from.clone() } else { std::fs::canonicalize(&from).map_err(|_| WRITE_FAILED)? };
|
||||
std::fs::rename(&from, &to).map_err(|_| WRITE_FAILED)?;
|
||||
// Open objects of the file, or of files in the folder, write to the new path, and the rules for
|
||||
// reading apply to them there.
|
||||
let moved = |p: &mut Option<std::path::PathBuf>| {
|
||||
@@ -1935,7 +1940,102 @@ fn rename(host: &Host, a: &[Data]) -> Result<Data, HostError> {
|
||||
// The old path no longer holds the file, so the report names it as well as the new one.
|
||||
disk.wrote(&from);
|
||||
disk.wrote(&to);
|
||||
Ok(Data::Object(vec![("fs".into(), Data::String(new))]))
|
||||
Ok(new)
|
||||
}
|
||||
|
||||
/// `setHidden(path, hidden)`: on Unix, where a name that starts with a dot is hidden, the file or
|
||||
/// link at `path` (a link itself, never what it leads to) renamed with one dot added or its leading
|
||||
/// dots taken off; → `{fs}`, its path. A file already as asked keeps its name. A name that would be
|
||||
/// left empty, a folder, and every system that is not Unix give `{error}`.
|
||||
fn set_hidden(host: &Host, a: &[Data]) -> Result<Data, HostError> {
|
||||
let (path, on) = (arg_text(a, 0), matches!(a.get(1), Some(Data::Bool(true))));
|
||||
let mut disk = host.disk.borrow_mut();
|
||||
let at = match disk.target(&path, false) {
|
||||
Ok(t) => t,
|
||||
Err(m) => return Ok(error(m)),
|
||||
};
|
||||
if !cfg!(unix) {
|
||||
return Ok(error(NO_HIDDEN));
|
||||
}
|
||||
match std::fs::symlink_metadata(&at) {
|
||||
Err(_) => return Ok(error(NOT_FOUND)),
|
||||
Ok(m) if m.is_dir() => return Ok(error(NOT_REGULAR)),
|
||||
Ok(_) => {}
|
||||
}
|
||||
let Some(name) = Path::new(&path).file_name().map(|n| n.to_string_lossy().into_owned()) else { return Ok(error(ACCESS_DENIED)) };
|
||||
if name.starts_with('.') == on {
|
||||
return Ok(Data::Object(vec![("fs".into(), Data::String(path))]));
|
||||
}
|
||||
let new = if on { format!(".{name}") } else { name.trim_start_matches('.').to_string() };
|
||||
if new.is_empty() {
|
||||
return Ok(error(NO_HIDDEN));
|
||||
}
|
||||
Ok(match rename_in(&mut disk, &path, &new) {
|
||||
Ok(fs) => Data::Object(vec![("fs".into(), Data::String(fs))]),
|
||||
Err(m) => error(m),
|
||||
})
|
||||
}
|
||||
|
||||
/// `createAlias(path, target)`: on Unix a symbolic link at `path` that leads to the real path of the
|
||||
/// file `target`. `path` must be a place the script may write where nothing is, not even a link
|
||||
/// that leads nowhere, and `target` a file the script may read. Every system that is not Unix gives
|
||||
/// `{error}`.
|
||||
fn create_alias(host: &Host, a: &[Data]) -> Result<Data, HostError> {
|
||||
let (path, to) = (arg_text(a, 0), arg_text(a, 1));
|
||||
let mut disk = host.disk.borrow_mut();
|
||||
let at = match disk.target(&path, false) {
|
||||
Ok(t) => t,
|
||||
Err(m) => return Ok(error(m)),
|
||||
};
|
||||
if std::fs::symlink_metadata(&at).is_ok() {
|
||||
return Ok(error(NAME_TAKEN));
|
||||
}
|
||||
if to.is_empty() {
|
||||
return Ok(error(NOT_FOUND));
|
||||
}
|
||||
let real = match disk.stat(&to) {
|
||||
Ok(Some(e)) if e.file => disk.checked(&to).ok().and_then(|p| disk.scope.locate(p).ok()),
|
||||
Ok(Some(_)) => return Ok(error(NOT_REGULAR)),
|
||||
Ok(None) => return Ok(error(NOT_FOUND)),
|
||||
Err(m) => return Ok(error(m)),
|
||||
};
|
||||
let Some(real) = real else { return Ok(error(ACCESS_DENIED)) };
|
||||
#[cfg(test)]
|
||||
if let Some(hook) = BEFORE_ALIAS_LINK.with(|h| h.borrow_mut().take()) {
|
||||
hook(&at);
|
||||
}
|
||||
Ok(make_link(&mut disk, &at, &real))
|
||||
}
|
||||
|
||||
/// A symbolic link at the real path `at` that leads to the real path `real`. → `true`, or `{error}`.
|
||||
#[cfg(unix)]
|
||||
fn make_link(disk: &mut Disk, at: &Path, real: &Path) -> Data {
|
||||
// Making the link fails when something took its place since it was looked up.
|
||||
if std::os::unix::fs::symlink(real, at).is_err() {
|
||||
return error(WRITE_FAILED);
|
||||
}
|
||||
// A link put in place of a folder above it since it was looked up may have taken the new link
|
||||
// elsewhere: that link is removed again, when it is still the one made here.
|
||||
let placed = at.parent().is_some_and(|p| std::fs::canonicalize(p).is_ok_and(|c| c == p));
|
||||
let ours = std::fs::read_link(at).is_ok_and(|l| l == real);
|
||||
if !placed {
|
||||
if ours {
|
||||
let _ = std::fs::remove_file(at);
|
||||
}
|
||||
return error(ACCESS_DENIED);
|
||||
}
|
||||
// Something else at `at` replaced the new link since it was made: it is left alone.
|
||||
if !ours {
|
||||
return error(WRITE_FAILED);
|
||||
}
|
||||
disk.wrote(at);
|
||||
Data::Bool(true)
|
||||
}
|
||||
|
||||
/// Every system that is not Unix: `{error}` with [`NO_ALIAS`].
|
||||
#[cfg(not(unix))]
|
||||
fn make_link(_: &mut Disk, _: &Path, _: &Path) -> Data {
|
||||
error(NO_ALIAS)
|
||||
}
|
||||
|
||||
/// Do the paths `a` and `b`, with their metadata, name one file? On Unix by device and inode; on
|
||||
@@ -2309,13 +2409,8 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr
|
||||
}))
|
||||
};
|
||||
let value = |s: &str| HostItem::Value(Data::String(s.to_string()));
|
||||
let text = HostItem::Object(vec![
|
||||
("notOpen".into(), value(NOT_OPEN)),
|
||||
("badMode".into(), value(BAD_MODE)),
|
||||
("noAlias".into(), value(NO_ALIAS)),
|
||||
("noHidden".into(), value(NO_HIDDEN)),
|
||||
("tooLarge".into(), value(TOO_LARGE)),
|
||||
]);
|
||||
let text =
|
||||
HostItem::Object(vec![("notOpen".into(), value(NOT_OPEN)), ("badMode".into(), value(BAD_MODE)), ("tooLarge".into(), value(TOO_LARGE))]);
|
||||
let system = if WINDOWS {
|
||||
"Windows"
|
||||
} else if cfg!(target_os = "macos") {
|
||||
@@ -2357,6 +2452,8 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr
|
||||
("create".into(), call(link, create)),
|
||||
("setLength".into(), call(link, set_length)),
|
||||
("setReadonly".into(), call(link, set_readonly)),
|
||||
("setHidden".into(), call(link, set_hidden)),
|
||||
("createAlias".into(), call(link, create_alias)),
|
||||
("pick".into(), call(link, pick)),
|
||||
];
|
||||
realm.define_file_classes(items)
|
||||
@@ -2367,9 +2464,16 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr
|
||||
#[cfg(test)]
|
||||
pub(crate) type CopyHook = Box<dyn FnOnce(&Path, &Path)>;
|
||||
|
||||
/// Tests: what the next `createAlias` does with the real path of its link.
|
||||
#[cfg(test)]
|
||||
pub(crate) type AliasHook = Box<dyn FnOnce(&Path)>;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
pub(crate) static BEFORE_COPY_READ: std::cell::RefCell<Option<CopyHook>> = const { std::cell::RefCell::new(None) };
|
||||
/// Tests: what the next `createAlias` does with the real path of its link, after looking it up
|
||||
/// and before making the link.
|
||||
pub(crate) static BEFORE_ALIAS_LINK: std::cell::RefCell<Option<AliasHook>> = const { std::cell::RefCell::new(None) };
|
||||
/// Tests: while set, the bytes `flush` writes fail after the file was opened for them.
|
||||
pub(crate) static FLUSH_WRITE_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
@@ -24,6 +24,10 @@ impl Session {
|
||||
});
|
||||
// Clicks find an image's own fills and strokes where their effects draw them.
|
||||
vectorcraft_doc::hit::set_image_paint(vectorcraft_render::effects::image_paint);
|
||||
// Direct Selection picks and outlines the parts of a dynamic symbol's instance where the
|
||||
// effects of the instance's fill and stroke draw them.
|
||||
vectorcraft_doc::hit::set_instance_row_art(vectorcraft_render::effects::add_instance_row_effects_to_parts);
|
||||
vectorcraft_doc::hit::set_instance_reshapes(vectorcraft_render::effects::has_item_geometry);
|
||||
// Clicks inside a clip group fall in the region its clipping path's effects give it.
|
||||
vectorcraft_doc::hit::set_clip_region(vectorcraft_render::effects::reshaped_clip_outline);
|
||||
// Clicks and marquees find paths, compound paths, groups and layers where their geometry
|
||||
|
||||
@@ -433,11 +433,12 @@ impl Session {
|
||||
let m = cmd::matrix_param(&preview.1, "matrix");
|
||||
if let Some(m) = m {
|
||||
// The options are the last preview's params with the values it noted, without the
|
||||
// matrix and the ids.
|
||||
// matrix, the ids and `drawBehind` (Transform Again puts its copies above).
|
||||
let mut options = preview.1.clone();
|
||||
if let Some(o) = options.as_object_mut() {
|
||||
o.remove("matrix");
|
||||
o.remove("ids");
|
||||
o.remove("drawBehind");
|
||||
}
|
||||
st.last_transform = Some(LastTransform::Matrix(m, options));
|
||||
st.last_perspective = None;
|
||||
|
||||
@@ -112,6 +112,7 @@ mod live;
|
||||
mod livecorners;
|
||||
mod maskview;
|
||||
pub(super) mod menucmds;
|
||||
mod mesh_picks;
|
||||
mod nativefile;
|
||||
mod newart;
|
||||
mod newdoc;
|
||||
@@ -3491,6 +3492,65 @@ fn flare_counts_are_whole_numbers() {
|
||||
assert!(s.execute("shape.flare", &json!({"cx": 100, "cy": 100, "rays": 2.5})).is_err());
|
||||
}
|
||||
|
||||
/// `shape.flare` given only one of `x2` and `y2`, the other left out or null, refuses the call
|
||||
/// naming the missing one, draws nothing and adds no undo step.
|
||||
#[test]
|
||||
fn flare_requires_both_endpoint_coordinates() {
|
||||
let mut s = session();
|
||||
let state = |s: &Session| {
|
||||
let st = s.doc().unwrap();
|
||||
(st.doc.node_count(), st.history.undo.len(), st.history.redo.len())
|
||||
};
|
||||
let before = state(&s);
|
||||
for (p, key) in [
|
||||
(json!({"cx": 100, "cy": 100, "x2": 300}), "y2"),
|
||||
(json!({"cx": 100, "cy": 100, "x2": 300, "y2": null}), "y2"),
|
||||
(json!({"cx": 100, "cy": 100, "y2": 300}), "x2"),
|
||||
(json!({"cx": 100, "cy": 100, "x2": null, "y2": 300}), "x2"),
|
||||
] {
|
||||
let err = s.execute("shape.flare", &p).expect_err(&p.to_string()).to_string();
|
||||
assert_eq!(err, format!("invalid parameters for `shape.flare`: missing number `{key}`"), "{p}");
|
||||
assert_eq!(state(&s), before, "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `shape.flare` with neither `x2` nor `y2` (left out or null) places the rings' end point from
|
||||
/// `pathLength` and `direction`; with both it uses them.
|
||||
#[test]
|
||||
fn flare_omitted_or_null_endpoint_coordinates_use_path_fallback() {
|
||||
let mut s = session();
|
||||
let mut end = |p: serde_json::Value| {
|
||||
let id = NodeId(s.execute("shape.flare", &p).unwrap()["id"].as_u64().unwrap());
|
||||
let spec = flare_settings(&s.doc().unwrap().doc, id).expect("a flare");
|
||||
Point::new(spec.params["x2"].as_f64().unwrap(), spec.params["y2"].as_f64().unwrap())
|
||||
};
|
||||
for p in [
|
||||
json!({"cx": 100, "cy": 100, "pathLength": 200, "direction": 0}),
|
||||
json!({"cx": 100, "cy": 100, "pathLength": 200, "direction": 0, "x2": null}),
|
||||
json!({"cx": 100, "cy": 100, "pathLength": 200, "direction": 0, "y2": null}),
|
||||
json!({"cx": 100, "cy": 100, "pathLength": 200, "direction": 0, "x2": null, "y2": null}),
|
||||
] {
|
||||
let e = end(p.clone());
|
||||
assert!((e.x - 300.0).abs() < 1e-9 && (e.y - 100.0).abs() < 1e-9, "{p}: {e:?}");
|
||||
}
|
||||
assert_eq!(end(json!({"cx": 100, "cy": 100, "pathLength": 200, "direction": 0, "x2": 40, "y2": 70})), Point::new(40.0, 70.0));
|
||||
}
|
||||
|
||||
/// Settings a file holds with only one of `x2` and `y2` are not a flare's: the group stays as art,
|
||||
/// but is not a flare that can be edited.
|
||||
#[test]
|
||||
fn flare_settings_with_a_lone_endpoint_coordinate_are_not_a_flare() {
|
||||
let mut s = session();
|
||||
let id = NodeId(s.execute("shape.flare", &json!({"cx": 100, "cy": 100, "rings": 2})).unwrap()["id"].as_u64().unwrap());
|
||||
let mut d = (*s.doc().unwrap().doc).clone();
|
||||
assert!(flare_settings(&d, id).is_some());
|
||||
let mut extras = d.node_mut(id).unwrap().extras_mut();
|
||||
let spec = extras.flare.as_deref_mut().expect("flare settings");
|
||||
spec.params.as_object_mut().unwrap().remove("y2");
|
||||
drop(extras);
|
||||
assert!(flare_settings(&d, id).is_none());
|
||||
}
|
||||
|
||||
/// `shape.editFlare` on a flare scaled far down: a `pathLength`, an end point or a center that,
|
||||
/// taken back to where the flare was drawn, is not a finite number is an error, and the flare keeps
|
||||
/// its settings.
|
||||
|
||||
@@ -1129,6 +1129,30 @@ fn shared_effects_and_new_fills_reach_every_selected_object() {
|
||||
assert!(s.execute("appearance.moveItem", &json!({"from": 1, "to": 0, "aligned": true})).is_err());
|
||||
}
|
||||
|
||||
/// Aligned rows copied to `to`: refused when the selected stacks differ, and placed at `to` in each object when the
|
||||
/// stacks are the same, as an aligned move is.
|
||||
#[test]
|
||||
fn aligned_copies_go_to_to_when_the_stacks_are_the_same() {
|
||||
let mut s = session();
|
||||
let (a, b) = mixed_circles(&mut s, true);
|
||||
let was = (node(&s, a).appearance.clone(), node(&s, b).appearance.clone());
|
||||
assert!(s.execute("appearance.duplicateItem", &json!({"index": 1, "to": 0, "aligned": true})).is_err());
|
||||
assert_eq!((node(&s, a).appearance.clone(), node(&s, b).appearance.clone()), was, "nothing changed");
|
||||
|
||||
let mut s = session();
|
||||
let (a, b) = mixed_circles(&mut s, false);
|
||||
run(&mut s, "paint.setFill", json!({"ids": [b.0], "color": "#ffff00"}));
|
||||
assert_eq!(node(&s, a).appearance, node(&s, b).appearance);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
// The stroke (row 1) copied to the bottom of each stack: [Stroke, Fill, Stroke].
|
||||
run(&mut s, "appearance.duplicateItem", json!({"index": 1, "to": 0, "aligned": true}));
|
||||
for id in [a, b] {
|
||||
assert_eq!(node(&s, id).appearance.items.iter().map(AppearanceItem::kind_name).collect::<Vec<_>>(), ["stroke", "fill", "stroke"]);
|
||||
assert_eq!(stroke(&node(&s, id), 0).width, 11.0);
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step");
|
||||
}
|
||||
|
||||
/// An effect applied to the first object's stroke row goes on the equal stroke of the other
|
||||
/// object, which sits lower in a longer stack there.
|
||||
#[test]
|
||||
|
||||
@@ -2228,6 +2228,73 @@ fn place_and_break_link_round_trip_geometry() {
|
||||
assert_eq!(n.appearance.stroke_width(), 1.0, "strokes are not scaled by normalisation");
|
||||
}
|
||||
|
||||
/// In Draw Behind, Place Symbol Instance puts the instance directly below the bottommost selected
|
||||
/// object (beside the compound path that holds a selected path, above a clipping path), or at the
|
||||
/// bottom of the current layer with nothing selected, selected and in one undo step. Draw Normal
|
||||
/// and Draw Inside keep it on top, and a locked layer refuses it with no edit.
|
||||
#[test]
|
||||
fn placed_instances_go_below_the_selection_in_draw_behind() {
|
||||
let mut s = session();
|
||||
let (inst, name, _) = make_symbol(&mut s);
|
||||
let (a, b) = (rect(&mut s, 0.0, 0.0, 10.0, 10.0), rect(&mut s, 20.0, 0.0, 10.0, 10.0));
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
let kids = |s: &Session, id: NodeId| node(s, id).children().unwrap().iter().map(|c| c.id).collect::<Vec<_>>();
|
||||
let place = |s: &mut Session| NodeId(s.execute("symbol.place", &json!({"name": name, "x": 300, "y": 200})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap();
|
||||
select(&mut s, &[b]);
|
||||
let before = undo_len(&s);
|
||||
let p = place(&mut s);
|
||||
assert_eq!(kids(&s, layer), vec![inst, a, p, b], "directly below the selected object");
|
||||
assert_eq!(undo_len(&s), before + 1);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [p]);
|
||||
assert!(close(bounds(&s, p), Rect::new(260.0, 180.0, 340.0, 220.0), 1e-9), "{:?}", bounds(&s, p));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(kids(&s, layer), vec![inst, a, b]);
|
||||
// Below the bottommost of several selected objects.
|
||||
select(&mut s, &[b, a]);
|
||||
let p = place(&mut s);
|
||||
assert_eq!(kids(&s, layer), vec![inst, p, a, b]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// With nothing selected, at the bottom of the current layer.
|
||||
select(&mut s, &[]);
|
||||
let p = place(&mut s);
|
||||
assert_eq!(kids(&s, layer), vec![p, inst, a, b]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// A path selected in a compound path: beside the compound path, not inside it.
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
let compound = kids(&s, layer)[1];
|
||||
let member = kids(&s, compound)[1];
|
||||
select(&mut s, &[member]);
|
||||
let p = place(&mut s);
|
||||
assert_eq!(kids(&s, layer), vec![inst, p, compound]);
|
||||
assert_eq!(kids(&s, compound).len(), 2);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// Draw Normal and Draw Inside put it on top of the layer.
|
||||
for mode in ["normal", "inside"] {
|
||||
select(&mut s, &[compound]);
|
||||
s.execute("view.drawMode", &json!({"mode": mode})).unwrap();
|
||||
let p = place(&mut s);
|
||||
assert_eq!(kids(&s, layer), vec![inst, compound, p], "{mode}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
// In a clipping layer the clipping path stays at the bottom, the selected clipping path too.
|
||||
s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap();
|
||||
s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap();
|
||||
assert_eq!(kids(&s, layer), vec![compound, inst]);
|
||||
for picked in [&[][..], &[compound]] {
|
||||
select(&mut s, picked);
|
||||
let p = place(&mut s);
|
||||
assert_eq!(kids(&s, layer), vec![compound, p, inst], "{picked:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
// A locked layer takes nothing.
|
||||
s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap();
|
||||
let before = (undo_len(&s), s.doc().unwrap().doc.clone());
|
||||
assert!(s.execute("symbol.place", &json!({"name": name})).is_err());
|
||||
assert_eq!((undo_len(&s), &s.doc().unwrap().doc), (before.0, &before.1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_instance_fill_does_not_tint_expanded_symbol_art() {
|
||||
for command in ["symbol.breakLink", "object.expand"] {
|
||||
|
||||
@@ -3493,6 +3493,34 @@ fn live_paint_bucket_keeps_its_colors_through_the_stop_eyedropper_and_a_cmd_clic
|
||||
assert_eq!((s.paint.fill.clone(), s.tool_returns_to()), (fill, None), "the pick ended without a sample");
|
||||
}
|
||||
|
||||
/// A Cmd-drag of a corner widget with the Live Paint Bucket that is cut short by choosing the
|
||||
/// bucket again (the Selection tool it lent cancels the drag as it goes back) leaves the bucket's
|
||||
/// colors as they were, with New Art Has Basic Appearance off: the selected object's appearance
|
||||
/// does not replace them.
|
||||
#[test]
|
||||
fn live_paint_bucket_keeps_its_colors_when_a_lent_drag_is_cut_short() {
|
||||
let v = ViewInfo::default();
|
||||
let mut s = session();
|
||||
let rect = rect(&mut s, 300.0, 300.0, 100.0, 100.0);
|
||||
s.execute("paint.setFill", &json!({"color": "#00ff00", "ids": [rect.0]})).unwrap();
|
||||
s.execute("appearance.setNewArtBasic", &json!({"on": false})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [rect.0]})).unwrap();
|
||||
s.select_tool("livePaintBucket", v).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
let fill = s.paint.fill.clone();
|
||||
let st = s.doc().unwrap();
|
||||
let w = vectorcraft_tools::corners::CornerWidgets::showing(&st.doc, &st.selection, v.zoom, false, true, 180.0).expect("corner widgets show");
|
||||
let at = w.visible().next().expect("a widget");
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, at.x, at.y).with_mods(cmd), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, at.x + 8.0, at.y + 8.0).with_mods(cmd), v).unwrap();
|
||||
assert_eq!(s.tool_id(), "selection", "the bucket lent the Selection tool for the drag");
|
||||
assert!(s.in_interaction(), "the corner widget drag is in progress");
|
||||
s.select_tool("livePaintBucket", v).unwrap();
|
||||
assert_eq!(s.tool_id(), "livePaintBucket");
|
||||
assert_eq!(s.paint.fill, fill, "the bucket's fill stays");
|
||||
}
|
||||
|
||||
/// A gradient stop selected on the selection's gradient is not selected once the Live Paint
|
||||
/// Bucket is active (its proxies show the default paint), and one selected on the bucket's
|
||||
/// gradient is not selected once another tool is chosen.
|
||||
@@ -4630,6 +4658,93 @@ fn live_paint_group_with_only_source_paths_ignores_add_fill_and_add_stroke_of_it
|
||||
assert!(s.execute("appearance.addFill", &json!({"target": "contents"})).is_err(), "no selection is still refused");
|
||||
}
|
||||
|
||||
/// Whether every face of Live Paint group `g` holds only fill rows and every edge only stroke rows.
|
||||
fn parts_hold_their_kind(s: &Session, g: NodeId) -> bool {
|
||||
let (faces, edges) = part_looks(s, g);
|
||||
faces.iter().all(|a| a.items.iter().all(|it| it.is_fill())) && edges.iter().all(|a| a.items.iter().all(|it| !it.is_fill()))
|
||||
}
|
||||
|
||||
/// A graphic style applied to the contents of a Live Paint group, replacing their appearance or added to it, gives
|
||||
/// the faces its fills and the edges its strokes, and the faces and edges are not linked to it.
|
||||
#[test]
|
||||
fn live_paint_group_contents_take_a_graphic_style_by_kind() {
|
||||
let red = Paint::solid(Color::from_hex("#ff0000").unwrap());
|
||||
let blue = Paint::solid(Color::from_hex("#0000ff").unwrap());
|
||||
for add in [false, true] {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
let r = rect(&mut s, 400.0, 0.0, 50.0, 50.0);
|
||||
s.execute("select.set", &json!({"ids": [r.0]})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap();
|
||||
s.execute("graphicStyle.new", &json!({"name": "Both", "id": r.0})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
s.execute("graphicStyle.apply", &json!({"name": "Both", "target": "contents", "add": add})).unwrap();
|
||||
assert!(parts_hold_their_kind(&s, g), "add {add}: faces hold fills and edges strokes");
|
||||
let (faces, edges) = part_looks(&s, g);
|
||||
assert!(faces.iter().all(|a| a.items.iter().any(|it| *it.paint() == red)), "add {add}: each face takes the style's fill");
|
||||
assert!(edges.iter().all(|a| a.items.iter().any(|it| *it.paint() == blue)), "add {add}: each edge takes the style's stroke");
|
||||
let n = node(&s, g);
|
||||
let mut parts = vectorcraft_tools::builder::faces(&n).into_iter().chain(vectorcraft_tools::builder::edges(&n));
|
||||
assert!(parts.all(|p| p.extras().graphic_style.is_none()), "add {add}: no face or edge is linked");
|
||||
}
|
||||
}
|
||||
|
||||
/// A fill-only graphic style added to the contents of a Live Paint group without faces changes nothing and records no
|
||||
/// undo step.
|
||||
#[test]
|
||||
fn live_paint_group_contents_without_faces_take_no_fill_only_style() {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
let faces: Vec<NodeId> = vectorcraft_tools::builder::faces(&node(&s, g)).iter().map(|p| p.id).collect();
|
||||
s.edit("t", |d, _| {
|
||||
d.children_mut(Some(g)).unwrap().retain(|c| !faces.contains(&c.id));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = rect(&mut s, 400.0, 0.0, 50.0, 50.0);
|
||||
s.edit("t", |d, _| {
|
||||
let fill = AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::from_hex("#ff0000").unwrap())));
|
||||
d.node_mut(r).unwrap().appearance = vectorcraft_doc::Appearance { items: vec![fill], ..Default::default() }.into();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("graphicStyle.new", &json!({"name": "Fill", "id": r.0})).unwrap();
|
||||
// The edges are linked to a style of their own, which they keep.
|
||||
let edge = vectorcraft_tools::builder::edges(&node(&s, g))[0].id;
|
||||
s.execute("graphicStyle.new", &json!({"name": "Edge", "id": edge.0})).unwrap();
|
||||
assert!(node(&s, g).children().unwrap().iter().any(|c| c.extras().graphic_style.is_some()), "an edge is linked");
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
let (before, undo) = (node(&s, g), s.doc().unwrap().history.undo.len());
|
||||
s.execute("graphicStyle.apply", &json!({"name": "Fill", "target": "contents", "add": true})).unwrap();
|
||||
assert_eq!(node(&s, g), before, "the edges keep their rows and their link");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
|
||||
}
|
||||
|
||||
/// Clear Appearance and Reduce to Basic Appearance on the contents of a Live Paint group leave each face with fill
|
||||
/// rows only and each edge with stroke rows only.
|
||||
#[test]
|
||||
fn live_paint_group_contents_clear_and_reduce_keep_each_part_to_its_kind() {
|
||||
for cmd in ["appearance.clear", "appearance.reduceToBasic"] {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap();
|
||||
// A face and an edge given rows of the other kind through their own ids.
|
||||
let n = node(&s, g);
|
||||
let (face, edge) = (vectorcraft_tools::builder::faces(&n)[0].id, vectorcraft_tools::builder::edges(&n)[0].id);
|
||||
s.execute("appearance.addStroke", &json!({"ids": [face.0]})).unwrap();
|
||||
s.execute("appearance.addFill", &json!({"ids": [edge.0]})).unwrap();
|
||||
assert!(!parts_hold_their_kind(&s, g), "{cmd}: the face and the edge hold rows of the other kind");
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
s.execute(cmd, &json!({"target": "contents"})).unwrap();
|
||||
assert!(parts_hold_their_kind(&s, g), "{cmd}: faces hold fills and edges strokes");
|
||||
let (faces, edges) = part_looks(&s, g);
|
||||
assert!(faces.iter().chain(&edges).all(|a| !a.items.is_empty()), "{cmd}: each face and edge keeps a row");
|
||||
}
|
||||
}
|
||||
|
||||
/// A selected Live Paint group with no part of the edited kind is still a selection: a stroke edit
|
||||
/// of a group without edges, or a fill gradient edit of a group without faces, changes nothing and
|
||||
/// leaves the settings for new art as they are.
|
||||
|
||||
@@ -176,6 +176,13 @@ fn click(s: &mut Session, mods: Mods, x: f64, y: f64) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The path the last `shape.curvatureCircle` drew on.
|
||||
fn drawn_on(s: &Session) -> NodeId {
|
||||
let (cmd, p) = s.journal.last().unwrap().clone();
|
||||
assert_eq!(cmd, C);
|
||||
id_of(&p)
|
||||
}
|
||||
|
||||
/// With the Curvature Circle tool, a click on a path draws the circle that matches it there, in
|
||||
/// one undo step; with Shift, on the other side. A click on a straight line or away from every
|
||||
/// path draws nothing.
|
||||
@@ -223,4 +230,27 @@ fn the_next_click_passes_over_the_circle_the_tool_drew() {
|
||||
assert_eq!(object_count(&s), count + 1, "the circle drawn first is within reach again");
|
||||
let third = *s.doc().unwrap().selection.objects.first().unwrap();
|
||||
assert!(bounds_are(&s, third, Rect::new(100.0, 200.0, 300.0, 400.0)), "the click drew the first circle's own circle");
|
||||
assert_eq!(drawn_on(&s), first, "the click hit the first circle");
|
||||
}
|
||||
|
||||
/// After Deselect, the pointer reaches the circle the tool drew again, with no edit in between,
|
||||
/// and still does when the circle is selected again before the pointer moves.
|
||||
#[test]
|
||||
fn after_deselect_the_pointer_reaches_the_circle_the_tool_drew() {
|
||||
for reselect in [false, true] {
|
||||
let mut s = session();
|
||||
let path = parabola(&mut s);
|
||||
s.select_tool("curvatureCircle", view()).unwrap();
|
||||
click(&mut s, Mods::default(), 200.0, 200.0);
|
||||
let first = *s.doc().unwrap().selection.objects.first().unwrap();
|
||||
assert_eq!(drawn_on(&s), path);
|
||||
let undo = undo_len(&s);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
if reselect {
|
||||
s.execute("select.set", &json!({"ids": [first.0]})).unwrap();
|
||||
}
|
||||
assert_eq!(undo_len(&s), undo, "Deselect is not an edit");
|
||||
click(&mut s, Mods::default(), 280.0, 236.0);
|
||||
assert_eq!(drawn_on(&s), first, "the click hit the circle drawn first ({reselect})");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -220,6 +220,53 @@ fn update_link_takes_the_files_new_clipping_path() {
|
||||
assert!((after - before / 2.0).abs() < 1e-6, "the clipping path follows the file: {before} → {after}");
|
||||
}
|
||||
|
||||
/// For an image changed by Perspective Distort or Free Distort, Update Links and Relink draw the
|
||||
/// DCS file's new clipping path through the image's corners, and a file without one leaves a plain
|
||||
/// group.
|
||||
#[test]
|
||||
fn update_and_relink_draw_the_files_clipping_path_through_a_distorted_images_corners() {
|
||||
let dir = temp_dir("distorted-clip");
|
||||
let path = write(&dir, "pic.eps", &two_plates());
|
||||
let mut s = session();
|
||||
let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap();
|
||||
let group = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
let id = image_of(&s, &r["ids"][0]).id;
|
||||
s.execute("select.set", &json!({ "ids": [group.0] })).unwrap();
|
||||
s.execute("object.distort", &json!({ "corners": [[100, 100], [160, 104], [150, 140], [96, 136]] })).unwrap();
|
||||
let node = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
assert!(node(&s).is_distorted_image());
|
||||
let corners = node(&s).image_corners().unwrap();
|
||||
// The clip group's path anchors, and points of the 2 × 2 pixels where the corners put them.
|
||||
let anchors = |s: &Session| {
|
||||
let NodeKind::Group { children, clip: true } = &s.doc().unwrap().doc.node(group).unwrap().kind else { panic!("a clipping group") };
|
||||
let NodeKind::Path { path, clipping: true, .. } = &children[0].kind else { panic!("a clipping path") };
|
||||
path.anchors().map(|(_, _, a)| a.p).collect::<Vec<_>>()
|
||||
};
|
||||
let on_page = |s: &Session, x: f64| {
|
||||
let map = node(s).image_map().unwrap();
|
||||
[(0.0, 0.0), (x, 0.0), (x, 2.0), (0.0, 2.0)].map(|(px, py)| map.apply(vectorcraft_geom::Point::new(px, py)).unwrap())
|
||||
};
|
||||
let matches = |found: &[vectorcraft_geom::Point], want: &[vectorcraft_geom::Point]| {
|
||||
found.len() == want.len() && want.iter().all(|w| found.iter().any(|f| f.distance(*w) < 1e-6))
|
||||
};
|
||||
assert!(matches(&anchors(&s), &on_page(&s, 1.0)), "the left half: {:?} vs {:?}", anchors(&s), on_page(&s, 1.0));
|
||||
// The same file, its composite drawn through the left quarter of the page (same length).
|
||||
let quarter = String::from_utf8(two_plates()).unwrap().replacen("10 0 lineto 10 10 lineto", " 5 0 lineto 5 10 lineto", 1);
|
||||
std::fs::write(&path, quarter.as_bytes()).unwrap();
|
||||
s.execute("links.update", &json!({ "ids": [id.0] })).unwrap();
|
||||
assert!(matches(&anchors(&s), &on_page(&s, 0.5)), "the left quarter: {:?} vs {:?}", anchors(&s), on_page(&s, 0.5));
|
||||
assert_eq!(node(&s).image_corners().unwrap(), corners);
|
||||
// Relink to a file whose composite has no clipping path.
|
||||
let unclipped = String::from_utf8(two_plates()).unwrap().replacen("closepath clip newpath", "closepath newpath ", 1);
|
||||
let other = write(&dir, "other.eps", unclipped.as_bytes());
|
||||
s.execute("links.relink", &json!({ "ids": [id.0], "path": other })).unwrap();
|
||||
match &s.doc().unwrap().doc.node(group).unwrap().kind {
|
||||
NodeKind::Group { children, clip: false } => assert_eq!(children.iter().map(|c| c.id).collect::<Vec<_>>(), [id]),
|
||||
other => panic!("a plain group of the image: {other:?}"),
|
||||
}
|
||||
assert_eq!(node(&s).image_corners().unwrap(), corners);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_link_clips_an_image_whose_file_gained_a_clipping_path() {
|
||||
let dir = temp_dir("update-gained-clip");
|
||||
|
||||
@@ -2692,6 +2692,28 @@ fn a_smooth_drag_that_only_meets_corners_adds_no_undo_step() {
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
}
|
||||
|
||||
/// Drags of the Smooth tool again and again along the lower half of an ellipse add no anchors after
|
||||
/// the first, which splits the two segments the drag's reach ends on, and leave no corner. The
|
||||
/// anchors at those splits lie on the edge of the next drag's reach, where the segment beyond each
|
||||
/// one is in reach at that anchor only, so the next drag leaves that segment as it is.
|
||||
#[test]
|
||||
fn smooth_drags_again_and_again_along_part_of_an_ellipse_add_no_anchors_or_corners() {
|
||||
let mut s = session();
|
||||
let r = s.execute("shape.ellipse", &json!({"x": 100, "y": 100, "width": 200, "height": 120})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let drag: Vec<Point> =
|
||||
(0..=32).map(|i| f64::from(i) / 32.0 * std::f64::consts::PI).map(|a| Point::new(200.0 + 100.0 * a.cos(), 160.0 + 60.0 * a.sin())).collect();
|
||||
let mut first = None;
|
||||
for pass in 1..=6 {
|
||||
smooth_pass(&mut s, &drag);
|
||||
let p = path(&s, id);
|
||||
let turns = smooth_anchor_turns(&p.subpaths[0]);
|
||||
assert!(turns.iter().all(|t| *t < 1.0), "pass {pass} leaves a corner: {turns:?}");
|
||||
assert_eq!(p.anchor_count(), *first.get_or_insert(p.anchor_count()), "pass {pass}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn join_tool_joins_two_lines() {
|
||||
let mut s = session();
|
||||
@@ -3313,6 +3335,66 @@ fn path_eraser_width_outside_its_range_is_refused() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `path.smoothRegion` refuses a `radius` outside 0.001 to 1000 pt and a `fidelity` outside the
|
||||
/// Smooth tool's tolerance range, and `path.joinScrub` a `tolerance` outside 0.001 to 1000 pt: the
|
||||
/// document, the selection and the undo history do not change. The ends of each range are taken,
|
||||
/// and null is read as the key left out, which smooths or joins in one undo step.
|
||||
#[test]
|
||||
fn smooth_and_join_refuse_a_reach_or_fidelity_outside_its_range() {
|
||||
let mut s = session();
|
||||
let anchors: Vec<_> = (0..=40).map(|i| json!({"x": 100.0 + i as f64 * 5.0, "y": if i % 2 == 0 { 200.0 } else { 203.0 }})).collect();
|
||||
let r = s.execute("path.create", &json!({"anchors": anchors})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let drag = json!({"points": [[90, 200], [200, 200], [310, 200]]});
|
||||
let (lo, hi) = (vectorcraft_tools::draw2::SMOOTH_MIN_TOLERANCE, vectorcraft_tools::draw2::SMOOTH_MAX_TOLERANCE);
|
||||
let reaches = [json!(0), json!(-1), json!(0.0009), json!(1e-300), json!(1000.01), json!(1e300)];
|
||||
let fidelities = [json!(0), json!(-1), json!(lo / 2.0), json!(hi * 1.01), json!(1e300)];
|
||||
let refused = reaches
|
||||
.iter()
|
||||
.map(|x| ("radius", x, "`radius` must be from 0.001 to 1000".to_string()))
|
||||
.chain(fidelities.iter().map(|x| ("fidelity", x, format!("`fidelity` must be from {lo} to {hi} pt"))));
|
||||
for (key, x, want) in refused {
|
||||
let sel = s.doc().unwrap().selection.clone();
|
||||
refuses_with(&mut s, "path.smoothRegion", &with(&drag, json!({ key: x })), &want);
|
||||
assert_eq!(s.doc().unwrap().selection, sel, "{key} {x} changed the selection");
|
||||
}
|
||||
for extra in [json!({"radius": 0.001}), json!({"radius": 1000}), json!({"fidelity": lo}), json!({"fidelity": hi})] {
|
||||
let undo = undo_steps(&s);
|
||||
s.execute("path.smoothRegion", &with(&drag, extra.clone())).unwrap_or_else(|e| panic!("{extra}: {e}"));
|
||||
while undo_steps(&s) > undo {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
}
|
||||
let before = path(&s, id);
|
||||
let undo = undo_steps(&s);
|
||||
s.execute("path.smoothRegion", &with(&drag, json!({"radius": null, "fidelity": null}))).unwrap();
|
||||
assert!(path(&s, id) != before, "the default radius and fidelity smoothed nothing");
|
||||
assert_eq!(undo_steps(&s), undo + 1);
|
||||
|
||||
let mut s = session();
|
||||
line(&mut s, 100.0, 100.0, 200.0, 100.0);
|
||||
line(&mut s, 205.0, 100.0, 300.0, 150.0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let scrub = json!({"points": [[202, 90], [202, 110]]});
|
||||
for x in &reaches {
|
||||
refuses_with(&mut s, "path.joinScrub", &with(&scrub, json!({"tolerance": x})), "`tolerance` must be from 0.001 to 1000");
|
||||
assert_eq!(paths(&s).len(), 2, "tolerance {x}");
|
||||
}
|
||||
s.execute("path.joinScrub", &with(&scrub, json!({"tolerance": 0.001}))).unwrap();
|
||||
assert_eq!(paths(&s).len(), 2, "0.001 pt reaches neither end");
|
||||
let undo = undo_steps(&s);
|
||||
s.execute("path.joinScrub", &with(&scrub, json!({"tolerance": 1000}))).unwrap();
|
||||
while undo_steps(&s) > undo {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("path.joinScrub", &with(&scrub, json!({"tolerance": null}))).unwrap();
|
||||
assert_eq!(paths(&s).len(), 1, "the default tolerance joined nothing");
|
||||
assert_eq!(undo_steps(&s), undo + 1);
|
||||
}
|
||||
|
||||
/// The Eraser, Path Eraser, Smooth, Join and Blob Brush commands refuse a size, angle, roundness,
|
||||
/// width, radius, fidelity or tolerance given as text or as another value that is not a number, and change
|
||||
/// nothing; null is read as the key left out.
|
||||
|
||||
@@ -587,6 +587,186 @@ fn direct_selection_paints_one_object_of_one_dynamic_instance() {
|
||||
assert_eq!(pixel(&s, 80, 30), BLUE);
|
||||
}
|
||||
|
||||
/// Instance `inst` with a new fill (`fill`) or stroke row without paint whose effect is `effect`
|
||||
/// with `params`.
|
||||
fn row_effect(s: &mut Session, inst: NodeId, fill: bool, effect: &str, params: Value) {
|
||||
s.execute(if fill { "appearance.addFill" } else { "appearance.addStroke" }, &json!({"ids": [inst.0]})).unwrap();
|
||||
let row = node(s, inst).appearance.items.len() - 1;
|
||||
s.execute("appearance.setItem", &json!({"ids": [inst.0], "index": row, "none": true})).unwrap();
|
||||
s.execute("effect.apply", &json!({"ids": [inst.0], "item": row, "effect": effect, "params": params})).unwrap();
|
||||
}
|
||||
|
||||
/// The object of `inst`'s art that Direct Selection picks at (`x`, `y`) with `opt`.
|
||||
fn part_at(s: &Session, inst: NodeId, (x, y): (f64, f64), opt: vectorcraft_doc::hit::HitOptions) -> Option<Vec<u32>> {
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
vectorcraft_doc::hit::symbol_part_at(doc, doc.node(inst).unwrap(), vectorcraft_geom::Point::new(x, y), opt)
|
||||
}
|
||||
|
||||
/// The box of the outline of the object at `path` in `inst`'s art, as Direct Selection draws it.
|
||||
fn part_outline_box(s: &Session, inst: NodeId, path: &[u32]) -> Rect {
|
||||
use vectorcraft_geom::kurbo::Shape;
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let outline = vectorcraft_doc::hit::symbol_part_outline_in_view(doc, doc.node(inst).unwrap(), path, Default::default()).unwrap();
|
||||
outline.bounding_box()
|
||||
}
|
||||
|
||||
/// A geometry effect on a dynamic instance's fill or stroke moves where the objects of its art
|
||||
/// are drawn: Direct Selection picks an object where it is drawn, not where its own shape no longer
|
||||
/// paints, and outlines it there; Outline view still takes the plain shapes.
|
||||
#[test]
|
||||
fn direct_selection_picks_a_part_where_the_instance_fill_and_stroke_effects_draw_it() {
|
||||
use vectorcraft_doc::hit::HitOptions;
|
||||
let opt = HitOptions { tol: 1.0, ..Default::default() };
|
||||
let mut s = session();
|
||||
let inst = pair(&mut s, "dynamic");
|
||||
row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100}));
|
||||
// The squares are drawn at x 110..150 and 160..200.
|
||||
assert_eq!(part_at(&s, inst, (130.0, 30.0), opt), Some(vec![0]), "the first square where it is drawn");
|
||||
assert_eq!(part_at(&s, inst, (180.0, 30.0), opt), Some(vec![1]), "the second square where it is drawn");
|
||||
assert_eq!(part_at(&s, inst, (80.0, 30.0), opt), None, "where the second square's own shape no longer paints");
|
||||
assert_eq!(part_at(&s, inst, (60.5, 30.0), opt), None, "the plain edge of the second square");
|
||||
assert_eq!(part_at(&s, inst, (60.5, 30.0), HitOptions { outline: true, ..opt }), Some(vec![1]), "Outline view draws the plain shapes");
|
||||
let b = part_outline_box(&s, inst, &[0]);
|
||||
assert!((b.x0 - 110.0).abs() < 0.5 && (b.x1 - 150.0).abs() < 0.5, "the outline follows the moved square: {b:?}");
|
||||
direct(&mut s, (130.0, 30.0), (130.0, 30.0), Mods::default());
|
||||
let sel = s.doc().unwrap().selection.clone();
|
||||
assert_eq!(sel.objects, [inst]);
|
||||
assert_eq!(sel.symbol_part, Some(vectorcraft_doc::SymbolPart { instance: inst, path: vec![0] }), "a press on the drawn square picks it");
|
||||
|
||||
// A stroke effect: Offset Path moves the first square's stroke out to x = 0.
|
||||
let mut s = session();
|
||||
let (a, b) = (square(&mut s, 10.0), square(&mut s, 60.0));
|
||||
s.execute("paint.setStroke", &json!({"ids": [a.0, b.0], "color": "#00ff00"})).unwrap();
|
||||
let inst = id(&s.execute("symbol.new", &json!({"name": "Pair", "ids": [a.0, b.0], "type": "dynamic"})).unwrap());
|
||||
row_effect(&mut s, inst, false, "path.offsetPath", json!({"offset": 10}));
|
||||
assert_eq!(part_at(&s, inst, (0.5, 30.0), opt), Some(vec![0]), "the moved stroke");
|
||||
assert_eq!(part_at(&s, inst, (30.0, 30.0), opt), Some(vec![0]), "the fill keeps its shape");
|
||||
let b = part_outline_box(&s, inst, &[0]);
|
||||
assert!(b.x0 < 1.0 && b.x1 > 59.0, "the outline takes in the moved stroke: {b:?}");
|
||||
|
||||
// A symbol instance in the art takes the effect too: it is picked and outlined where its art is
|
||||
// drawn, not in its box. The fill effect moves its square; its image has no fill and stays.
|
||||
let mut s = session();
|
||||
let a = square(&mut s, 10.0);
|
||||
place_image(&mut s);
|
||||
let img = top(&s);
|
||||
let inner = id(&s.execute("symbol.new", &json!({"name": "Inner", "ids": [a.0, img.0]})).unwrap());
|
||||
let b = square(&mut s, 60.0);
|
||||
let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [inner.0, b.0], "type": "dynamic"})).unwrap());
|
||||
row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100}));
|
||||
assert_eq!(part_at(&s, inst, (130.0, 30.0), opt), Some(vec![0]), "the nested instance's square where it is drawn");
|
||||
assert_eq!(part_at(&s, inst, (65.0, 35.0), opt), Some(vec![0]), "the nested instance's image");
|
||||
assert_eq!(part_at(&s, inst, (30.0, 30.0), opt), None, "the nested instance's own box");
|
||||
let b = part_outline_box(&s, inst, &[0]);
|
||||
assert!((b.x0 - 50.0).abs() < 0.5 && (b.x1 - 150.0).abs() < 0.5, "the outline takes in the moved square and the image: {b:?}");
|
||||
|
||||
// A nested instance with a geometry effect of its own is picked where both effects draw it.
|
||||
let mut s = session();
|
||||
let a = square(&mut s, 10.0);
|
||||
let inner = id(&s.execute("symbol.new", &json!({"name": "Inner", "ids": [a.0]})).unwrap());
|
||||
s.execute("effect.apply", &json!({"ids": [inner.0], "effect": "distort.transform", "params": {"moveV": 30}})).unwrap();
|
||||
let b = square(&mut s, 60.0);
|
||||
let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [inner.0, b.0], "type": "dynamic"})).unwrap());
|
||||
row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100}));
|
||||
assert_eq!(part_at(&s, inst, (130.0, 60.0), opt), Some(vec![0]), "the nested square moved by both effects");
|
||||
assert_eq!(part_at(&s, inst, (30.0, 30.0), opt), None, "the nested instance's own box");
|
||||
let b = part_outline_box(&s, inst, &[0]);
|
||||
assert!((b.x0 - 110.0).abs() < 0.5 && (b.y0 - 40.0).abs() < 0.5 && (b.y1 - 80.0).abs() < 0.5, "the outline follows both effects: {b:?}");
|
||||
|
||||
// Type with a fill of its own in the art is picked and outlined where the fill effect draws its
|
||||
// glyphs, not in its own bounds.
|
||||
let mut s = session();
|
||||
let t = id(&s.execute("text.create", &json!({"x": 10, "y": 45, "size": 40, "text": "I"})).unwrap());
|
||||
s.execute("appearance.addFill", &json!({"ids": [t.0]})).unwrap();
|
||||
let plain = {
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
doc.node(t).unwrap().geometric_bounds().unwrap()
|
||||
};
|
||||
let b = square(&mut s, 60.0);
|
||||
let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [t.0, b.0], "type": "dynamic"})).unwrap());
|
||||
row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100}));
|
||||
// The type's own color still paints the glyph in place; the new fill paints it 100 pt right.
|
||||
let drawn = part_outline_box(&s, inst, &[0]);
|
||||
assert!(drawn.x1 > plain.x1 + 90.0 && drawn.x1 < plain.x1 + 101.0, "the outline takes in the moved glyph: {drawn:?}, plain {plain:?}");
|
||||
let glyph = drawn.x1 - 100.0 - drawn.x0;
|
||||
let (x, y) = (drawn.x1 - glyph / 2.0, (drawn.y0 + drawn.y1) / 2.0);
|
||||
assert_eq!(part_at(&s, inst, (x, y), opt), Some(vec![0]), "the type where the fill effect draws its glyph");
|
||||
assert_eq!(part_at(&s, inst, (plain.x0 + 1.0, plain.y0 + 1.0), opt), None, "the type's own bounds, off its glyph");
|
||||
let by_path = HitOptions { type_path_only: true, ..opt };
|
||||
assert_eq!(part_at(&s, inst, (plain.x1 - 1.5, 45.0), by_path), Some(vec![0]), "Type Object Selection by Path Only takes the baseline");
|
||||
|
||||
// A nested instance whose own effect adds only pixels (a drop shadow) is still picked where the
|
||||
// outer fill effect draws its art.
|
||||
let mut s = session();
|
||||
let a = square(&mut s, 10.0);
|
||||
let inner = id(&s.execute("symbol.new", &json!({"name": "Inner", "ids": [a.0]})).unwrap());
|
||||
s.execute("effect.apply", &json!({"ids": [inner.0], "effect": "stylize.dropShadow"})).unwrap();
|
||||
let b = square(&mut s, 60.0);
|
||||
let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [inner.0, b.0], "type": "dynamic"})).unwrap());
|
||||
row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100}));
|
||||
assert_eq!(part_at(&s, inst, (130.0, 30.0), opt), Some(vec![0]), "the shadowed nested square where it is drawn");
|
||||
assert_eq!(part_at(&s, inst, (30.0, 30.0), opt), None, "the shadowed nested instance's own box");
|
||||
|
||||
// An image whose fill has Convert to Shape is picked and outlined where the instance's fill
|
||||
// effect moves that shape.
|
||||
let mut s = session();
|
||||
place_image(&mut s);
|
||||
let img = top(&s);
|
||||
let frame = node(&s, img).geometric_bounds().unwrap();
|
||||
s.execute("appearance.addFill", &json!({"ids": [img.0]})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [img.0], "color": "#00ff00", "item": 0})).unwrap();
|
||||
s.execute("effect.apply", &json!({"ids": [img.0], "effect": "convertToShape.rectangle", "item": 0})).unwrap();
|
||||
let b = square(&mut s, 200.0);
|
||||
let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [img.0, b.0], "type": "dynamic"})).unwrap());
|
||||
row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100}));
|
||||
let c = frame.center();
|
||||
assert_eq!(part_at(&s, inst, (c.x + 100.0, c.y), opt), Some(vec![0]), "the image where its fill is drawn");
|
||||
let o = part_outline_box(&s, inst, &[0]);
|
||||
assert!(o.x1 > frame.x1 + 99.0, "the outline takes in the moved fill: {o:?}, frame {frame:?}");
|
||||
}
|
||||
|
||||
/// A clipping path in a dynamic symbol's art with a geometry effect of its own is picked by its
|
||||
/// own geometry, and Direct Selection outlines that geometry, not the shape the effect draws.
|
||||
#[test]
|
||||
fn a_picked_clipping_path_is_outlined_by_its_own_geometry() {
|
||||
let mut s = session();
|
||||
let content = square(&mut s, 20.0);
|
||||
let clip = square(&mut s, 10.0);
|
||||
s.execute("object.clippingMask.make", &json!({"ids": [content.0, clip.0]})).unwrap();
|
||||
s.execute("effect.apply", &json!({"ids": [clip.0], "effect": "path.offsetPath", "params": {"offset": 10}})).unwrap();
|
||||
let group = top(&s);
|
||||
assert!(node(&s, group).clips());
|
||||
let inst = id(&s.execute("symbol.new", &json!({"name": "Clip", "ids": [group.0], "type": "dynamic"})).unwrap());
|
||||
let b = part_outline_box(&s, inst, &[0]);
|
||||
assert!((b.x0 - 10.0).abs() < 0.5 && (b.x1 - 50.0).abs() < 0.5, "the clipping path's own edge: {b:?}");
|
||||
}
|
||||
|
||||
/// A symbol instance in a dynamic symbol's art whose own art is a clip group takes the instance's
|
||||
/// fill effect on the clip group's members, which the canvas draws moved: Direct Selection picks it
|
||||
/// where its member is drawn, not where the member's own shape is, and outlines it there.
|
||||
#[test]
|
||||
fn a_nested_instance_of_a_clip_group_is_picked_where_the_fill_effect_draws_its_art() {
|
||||
use vectorcraft_doc::hit::HitOptions;
|
||||
let opt = HitOptions { tol: 1.0, ..Default::default() };
|
||||
let mut s = session();
|
||||
let content = square(&mut s, 10.0);
|
||||
let clip = id(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 200, "height": 60})).unwrap());
|
||||
s.execute("object.clippingMask.make", &json!({"ids": [content.0, clip.0]})).unwrap();
|
||||
let group = top(&s);
|
||||
assert!(node(&s, group).clips());
|
||||
let inner = id(&s.execute("symbol.new", &json!({"name": "Inner", "ids": [group.0]})).unwrap());
|
||||
let b = square(&mut s, 160.0);
|
||||
let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [inner.0, b.0], "type": "dynamic"})).unwrap());
|
||||
row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100}));
|
||||
// The member is drawn at x 110..150, inside the clipping path.
|
||||
assert_eq!(pixel(&s, 130, 30), BLUE, "the canvas draws the member moved");
|
||||
assert_ne!(pixel(&s, 30, 30), BLUE, "and not in its own place");
|
||||
assert_eq!(part_at(&s, inst, (130.0, 30.0), opt), Some(vec![0]), "the nested instance where its member is drawn");
|
||||
assert_eq!(part_at(&s, inst, (30.0, 30.0), opt), None, "the member's own place");
|
||||
let o = part_outline_box(&s, inst, &[0]);
|
||||
assert!((o.x0 - 110.0).abs() < 0.5 && (o.x1 - 150.0).abs() < 0.5, "the outline follows the moved member: {o:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drag_of_a_picked_object_moves_nothing_and_says_why() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -283,6 +283,41 @@ fn point_commands_need_a_freeform_gradient() {
|
||||
assert!(s.execute("paint.freeform.addPoint", &json!({"at": [1, 1]})).is_err());
|
||||
}
|
||||
|
||||
/// While the Live Paint Bucket is the active tool, the point and line commands that name no `ids`,
|
||||
/// `id` or `item` leave a selected freeform fill as it is and report an error, as
|
||||
/// `paint.freeform.get` finds no freeform gradient then. With `ids` they edit that object. `get` and
|
||||
/// `selectPoint` with an index name the bucket's colors in their error.
|
||||
#[test]
|
||||
fn point_commands_without_a_target_leave_the_selection_alone_under_the_bucket() {
|
||||
let (mut s, id) = freeform_rect();
|
||||
run(&mut s, "paint.freeform.addLine", json!({"points": [0, 1]}));
|
||||
run(&mut s, "paint.freeform.selectPoint", json!({"index": 1}));
|
||||
s.select_tool("livePaintBucket", ViewInfo::default()).unwrap();
|
||||
// get and selectPoint with an index name the bucket's colors; clearing the point still works.
|
||||
for (cmd, p) in [("paint.freeform.get", json!({})), ("paint.freeform.selectPoint", json!({"index": 0}))] {
|
||||
let err = s.execute(cmd, &p).unwrap_err().to_string();
|
||||
assert!(err.contains("Live Paint Bucket"), "{cmd}: {err}");
|
||||
}
|
||||
run(&mut s, "paint.freeform.selectPoint", json!({"index": null}));
|
||||
let before = points(&s, id);
|
||||
// A bad `aligned` is reported as such, before the missing target.
|
||||
let err = s.execute("paint.freeform.addPoint", &json!({"at": [150, 150], "aligned": 3})).unwrap_err().to_string();
|
||||
assert!(err.contains("aligned"), "{err}");
|
||||
for (cmd, p) in [
|
||||
("paint.freeform.addPoint", json!({"at": [150, 150]})),
|
||||
("paint.freeform.setPoint", json!({"index": 0, "color": "#ff0000"})),
|
||||
("paint.freeform.deletePoint", json!({"index": 0})),
|
||||
("paint.freeform.addLine", json!({"points": [1, 2]})),
|
||||
("paint.freeform.splitLine", json!({"line": 0, "segment": 0})),
|
||||
("paint.freeform.setPoint", json!({"index": 0, "color": "#ff0000", "ids": null})),
|
||||
] {
|
||||
assert!(s.execute(cmd, &p).is_err(), "{cmd} {p}");
|
||||
assert_eq!(points(&s, id), before, "{cmd} {p}: the object's points");
|
||||
}
|
||||
run(&mut s, "paint.freeform.setPoint", json!({"index": 0, "color": "#ff0000", "ids": [id.0]}));
|
||||
assert_ne!(points(&s, id), before, "with ids the object's point changes");
|
||||
}
|
||||
|
||||
/// The point and line commands refuse a point, line or segment of 2^32 + k, where k names one that
|
||||
/// exists, and the points and the selected point stay as they were. A 32-bit build read the number
|
||||
/// as k.
|
||||
|
||||
@@ -51,6 +51,53 @@ fn sample_color_with_a_stop_recolours_that_stop_in_one_undo_step() {
|
||||
);
|
||||
}
|
||||
|
||||
/// With `stop` and objects in `ids`, the stop is recolored in the first object's gradient, not in
|
||||
/// the gradient behind the proxy: the selection's, or the Live Paint Bucket's while it is active.
|
||||
#[test]
|
||||
fn sample_color_with_a_stop_and_ids_recolours_the_first_given_objects_gradient() {
|
||||
let mut s = session();
|
||||
let target = rect(&mut s, 10.0, 10.0, 100.0, 100.0);
|
||||
let three = json!([{"offset": 0, "color": "#ffffff"}, {"offset": 0.5, "color": "#888888"}, {"offset": 1, "color": "#000000"}]);
|
||||
s.execute("paint.setFill", &json!({"gradient": {"stops": three}})).unwrap();
|
||||
let selected = rect(&mut s, 200.0, 10.0, 100.0, 100.0);
|
||||
s.execute("paint.setFill", &json!({"gradient": {}})).unwrap();
|
||||
s.execute("paint.sampleColor", &json!({"color": "#ff0000", "stop": 2, "ids": [target.0]})).unwrap();
|
||||
assert_eq!(stop_hexes(&s, target, false), ["#ffffff", "#888888", "#ff0000"], "the given object's three stops");
|
||||
assert_eq!(stop_hexes(&s, selected, false), ["#ffffff", "#000000"], "the selection");
|
||||
// The bucket's solid fill, and then a two-stop gradient of its own.
|
||||
s.select_tool("livePaintBucket", ViewInfo::default()).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
|
||||
s.execute("paint.sampleColor", &json!({"color": "#0000ff", "stop": 0, "ids": [target.0]})).unwrap();
|
||||
assert_eq!(stop_hexes(&s, target, false), ["#0000ff", "#888888", "#ff0000"], "under the bucket's solid fill");
|
||||
s.execute("paint.setFill", &json!({"gradient": {}})).unwrap();
|
||||
s.execute("paint.sampleColor", &json!({"color": "#00ffff", "stop": 1, "ids": [target.0]})).unwrap();
|
||||
assert_eq!(stop_hexes(&s, target, false), ["#0000ff", "#00ffff", "#ff0000"], "under the bucket's gradient");
|
||||
// A given object without a gradient has no stop to recolor.
|
||||
s.execute("paint.setFill", &json!({"color": "#00ff00", "ids": [selected.0]})).unwrap();
|
||||
let err = s.execute("paint.sampleColor", &json!({"color": "#0000ff", "stop": 0, "ids": [selected.0]})).unwrap_err();
|
||||
assert!(err.to_string().contains("not a gradient"), "{err}");
|
||||
// A member of a compound path: the compound path's gradient, which the edit changes.
|
||||
s.select_tool("selection", ViewInfo::default()).unwrap();
|
||||
let (a, b) = (rect(&mut s, 10.0, 300.0, 50.0, 50.0), rect(&mut s, 100.0, 300.0, 50.0, 50.0));
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
let compound = s.doc().unwrap().selection.objects[0];
|
||||
s.execute("paint.setFill", &json!({"gradient": {"stops": three}, "ids": [compound.0]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [selected.0]})).unwrap();
|
||||
s.execute("paint.sampleColor", &json!({"color": "#ff0000", "stop": 2, "ids": [a.0]})).unwrap();
|
||||
assert_eq!(stop_hexes(&s, compound, false), ["#ffffff", "#888888", "#ff0000"], "the compound path's three stops");
|
||||
// A group: the stops of its first painted object, which every painted object of the group takes.
|
||||
let (c, d) = (rect(&mut s, 10.0, 400.0, 50.0, 50.0), rect(&mut s, 100.0, 400.0, 50.0, 50.0));
|
||||
s.execute("paint.setFill", &json!({"gradient": {"stops": three}, "ids": [c.0]})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#00ff00", "ids": [d.0]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [c.0, d.0]})).unwrap();
|
||||
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [selected.0]})).unwrap();
|
||||
s.execute("paint.sampleColor", &json!({"color": "#0000ff", "stop": 0, "ids": [group.0]})).unwrap();
|
||||
assert_eq!(stop_hexes(&s, c, false), ["#0000ff", "#888888", "#000000"], "the group's first object");
|
||||
assert_eq!(stop_hexes(&s, d, false), ["#0000ff", "#888888", "#000000"], "the group's other object");
|
||||
}
|
||||
|
||||
fn fill_geom(s: &Session, id: NodeId) -> Option<GradientGeom> {
|
||||
match s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint() {
|
||||
Paint::Gradient(g) => g.geom,
|
||||
|
||||
@@ -13,7 +13,8 @@ use crate::*;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
// A fixed created date: two sessions made in different seconds would otherwise differ in it.
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600, "created": 0})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
|
||||
@@ -456,6 +456,92 @@ fn a_pattern_item_adds_the_swatch_of_a_pattern_the_document_holds_without_one()
|
||||
assert!(!s.doc().unwrap().doc.swatches_iter().any(is_dots), "undone with the paint");
|
||||
}
|
||||
|
||||
/// A pattern item whose art links to a global color that the document has under the same name in
|
||||
/// another color keeps the item's color: the color comes in under a numbered name and the pattern
|
||||
/// links to it. Used again, the pattern and that color are reused. A document whose pattern of
|
||||
/// that name links to the document's own color (as pasting with Merge leaves it) reuses that one.
|
||||
#[test]
|
||||
fn a_pattern_item_keeps_its_global_color_when_the_document_has_that_name_in_another_color() {
|
||||
let mut s = session();
|
||||
let lib = run(&mut s, "library.create", json!({}))["id"].as_str().unwrap().to_string();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
let dot = run(&mut s, "shape.ellipse", json!({"x": 0, "y": 0, "width": 10, "height": 10}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
|
||||
make_pattern(&mut s, &dot, "Dots");
|
||||
let a = run(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 40, "height": 40}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Dots", "ids": [a]}));
|
||||
run(&mut s, "select.set", json!({"ids": [a]}));
|
||||
run(&mut s, "library.add", json!({"library": lib, "kind": "fillPattern"}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
let names = |s: &Session, base: &str| -> Vec<String> {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
d.swatches_iter().filter(|w| w.name.starts_with(base)).map(|w| w.name.clone()).collect()
|
||||
};
|
||||
let art_link = |s: &Session, pattern: &str| match s.doc().unwrap().doc.pattern(pattern).unwrap().art[0].appearance.fill_paint() {
|
||||
vectorcraft_color::Paint::Solid { swatch, color, .. } => (swatch, color.to_hex()),
|
||||
p => panic!("the pattern's art is not filled with a color: {p:?}"),
|
||||
};
|
||||
// A document whose Ink is red.
|
||||
let red_ink = |s: &mut Session| {
|
||||
run(s, "file.new", json!({"width": 300, "height": 300}));
|
||||
run(s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
let b = run(s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 80, "height": 80}))["id"].clone();
|
||||
run(s, "select.set", json!({"ids": [b]}));
|
||||
};
|
||||
red_ink(&mut s);
|
||||
let r = run(&mut s, "library.use", json!({"library": lib, "kind": "fillPattern", "item": "Dots"}));
|
||||
assert_eq!(r["pattern"], "Dots", "{r}");
|
||||
assert_eq!(art_link(&s, "Dots"), (Some("Ink 2".to_string()), "#0000ff".to_string()));
|
||||
assert_eq!(names(&s, "Ink"), ["Ink", "Ink 2"]);
|
||||
run(&mut s, "library.use", json!({"library": lib, "kind": "fillPattern", "item": "Dots", "to": "stroke"}));
|
||||
assert_eq!(s.doc().unwrap().doc.patterns.len(), 1, "the pattern is reused");
|
||||
assert_eq!(names(&s, "Ink"), ["Ink", "Ink 2"], "the color is reused");
|
||||
// Pasted with Merge, the pattern links to the document's red Ink.
|
||||
red_ink(&mut s);
|
||||
run(&mut s, "edit.paste", json!({"swatchConflict": "merge"}));
|
||||
assert_eq!(art_link(&s, "Dots"), (Some("Ink".to_string()), "#ff0000".to_string()));
|
||||
let r = run(&mut s, "library.use", json!({"library": lib, "kind": "fillPattern", "item": "Dots"}));
|
||||
assert_eq!(r["pattern"], "Dots", "{r}");
|
||||
assert_eq!(s.doc().unwrap().doc.patterns.len(), 1, "the pattern is reused");
|
||||
assert_eq!(names(&s, "Ink"), ["Ink"]);
|
||||
}
|
||||
|
||||
/// A pattern pasted with Merge whose art uses a tint of a global color is reused by its pattern
|
||||
/// item after the tint swatch is deleted: the tint swatch comes back and no copy of the pattern is
|
||||
/// added.
|
||||
#[test]
|
||||
fn a_merged_pattern_whose_tint_swatch_was_deleted_is_reused() {
|
||||
let mut s = session();
|
||||
let lib = run(&mut s, "library.create", json!({}))["id"].as_str().unwrap().to_string();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"swatch": "Ink", "tint": 50}));
|
||||
let dot = run(&mut s, "shape.ellipse", json!({"x": 0, "y": 0, "width": 10, "height": 10}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "tint": 50, "ids": [dot]}));
|
||||
make_pattern(&mut s, &dot, "Dots");
|
||||
let a = run(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 40, "height": 40}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Dots", "ids": [a]}));
|
||||
run(&mut s, "select.set", json!({"ids": [a]}));
|
||||
run(&mut s, "library.add", json!({"library": lib, "kind": "fillPattern"}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
run(&mut s, "file.new", json!({"width": 300, "height": 300}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
run(&mut s, "edit.paste", json!({"swatchConflict": "merge"}));
|
||||
let tints: Vec<String> =
|
||||
s.doc().unwrap().doc.swatches_iter().filter(|w| w.name != "Ink" && w.name.starts_with("Ink")).map(|w| w.name.clone()).collect();
|
||||
assert_eq!(tints.len(), 1, "the tint swatch comes with the paste: {tints:?}");
|
||||
run(&mut s, "swatch.delete", json!({"names": tints, "unlink": false}));
|
||||
let b = run(&mut s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 80, "height": 80}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [b]}));
|
||||
let r = run(&mut s, "library.use", json!({"library": lib, "kind": "fillPattern", "item": "Dots"}));
|
||||
assert_eq!(r["pattern"], "Dots", "{r}");
|
||||
assert_eq!(s.doc().unwrap().doc.patterns.len(), 1, "the pattern is reused");
|
||||
let restored = s.doc().unwrap().doc.swatch(&tints[0]).map(|w| w.paint.clone());
|
||||
assert!(
|
||||
matches!(&restored, Some(vectorcraft_color::Paint::Solid { swatch: Some(base), tint, .. }) if base == "Ink" && (*tint - 0.5).abs() < 1e-6),
|
||||
"the tint swatch comes back as a tint of the document's Ink: {restored:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Gradients and patterns go out to a library file and come back; read from a file, a gradient
|
||||
/// with too few stops is dropped, one out of range is put in range, and a pattern whose data is
|
||||
/// damaged or doesn't hold its pattern fails cleanly when used.
|
||||
|
||||
@@ -663,6 +663,213 @@ fn update_links_keeps_a_distorted_images_corners() {
|
||||
scale_matches_ppi(&mut s);
|
||||
}
|
||||
|
||||
/// Relink with scope `all` puts the new file's pixels between the corners of the distorted images
|
||||
/// in symbols too, and scales each one's transform to the new pixel size, so a placement by the
|
||||
/// transform keeps the old size.
|
||||
#[test]
|
||||
fn relink_of_all_instances_keeps_the_corners_of_distorted_images_in_symbols() {
|
||||
let dir = Folder::new("distorted-relink-all");
|
||||
let (photo, other) = (dir.file("photo.png"), dir.file("other.png"));
|
||||
write(&photo, &png(20, 10, RED));
|
||||
write(&other, &png(60, 20, BLUE));
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &photo);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[150, 100], [250, 110], [260, 200], [140, 190]]})).unwrap();
|
||||
let before = s.doc().unwrap().doc.node(id).unwrap().image_corners().unwrap();
|
||||
// The far corner of the pixels as the transform alone places them.
|
||||
let far = |s: &Session| {
|
||||
let NodeKind::Image(im) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("an image") };
|
||||
im.xf * vectorcraft_geom::Point::new(f64::from(im.width), f64::from(im.height))
|
||||
};
|
||||
let far_before = far(&s);
|
||||
// A distorted copy in a symbol shows the same file.
|
||||
let copy = place(&mut s, &photo);
|
||||
s.execute("select.set", &json!({"ids": [copy.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[10, 10], [60, 15], [58, 50], [5, 45]]})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "Mark", "ids": [copy.0]})).unwrap();
|
||||
let in_symbol = |s: &Session| {
|
||||
let mut out = vec![];
|
||||
s.doc().unwrap().doc.symbols[0].art.walk(&mut |n| {
|
||||
if let NodeKind::Image(im) = &n.kind {
|
||||
out.push((n.image_quad(), (im.width, im.height)));
|
||||
}
|
||||
});
|
||||
out
|
||||
};
|
||||
let [(Some(symbol_quad), (20, 10))] = in_symbol(&s)[..] else { panic!("one distorted image in the symbol: {:?}", in_symbol(&s)) };
|
||||
let r = s.execute("links.relink", &json!({"ids": [id.0], "path": other, "scope": "all"})).unwrap();
|
||||
let relinked = r["relinked"].as_array().unwrap();
|
||||
assert!(relinked.len() == 2 && relinked.contains(&json!(id.0)), "the image and the symbol's: {r}");
|
||||
assert!(r.get("warnings").is_none(), "no preserve was given: {r}");
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
assert_eq!((n.is_distorted_image(), n.image_corners().unwrap()), (true, before));
|
||||
assert_eq!((image(&s, id).width, image(&s, id).height), (60, 20));
|
||||
assert!(far(&s).distance(far_before) < 1e-9, "{:?} vs {far_before:?}", far(&s));
|
||||
assert_eq!(in_symbol(&s), [(Some(symbol_quad), (60, 20))], "the symbol's image keeps its corners");
|
||||
}
|
||||
|
||||
/// Relink with scope `all` puts the new file's pixels between the corners of a distorted image in
|
||||
/// an opacity mask's art.
|
||||
#[test]
|
||||
fn relink_of_all_instances_keeps_the_corners_of_a_distorted_image_in_an_opacity_mask() {
|
||||
let dir = Folder::new("distorted-relink-mask");
|
||||
let (photo, other) = (dir.file("photo.png"), dir.file("other.png"));
|
||||
write(&photo, &png(20, 10, RED));
|
||||
write(&other, &png(60, 20, BLUE));
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &photo);
|
||||
let masked = super::rect(&mut s, 10.0, 10.0, 60.0, 60.0);
|
||||
let mask = place(&mut s, &photo);
|
||||
s.execute("select.set", &json!({"ids": [mask.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[10, 10], [60, 15], [58, 50], [5, 45]]})).unwrap();
|
||||
s.execute("transparency.makeOpacityMask", &json!({"ids": [masked.0, mask.0]})).unwrap();
|
||||
// The image in the art of `masked`'s opacity mask: (id, corners, pixel size).
|
||||
let in_mask = |s: &Session| {
|
||||
let mut out = vec![];
|
||||
s.doc().unwrap().doc.visit_stored(|n, place| {
|
||||
if let NodeKind::Image(im) = &n.kind
|
||||
&& place.mask_of == Some(masked)
|
||||
{
|
||||
out.push((n.id, n.image_quad(), (im.width, im.height)));
|
||||
}
|
||||
});
|
||||
out
|
||||
};
|
||||
let [(mask_id, Some(quad), (20, 10))] = in_mask(&s)[..] else { panic!("one distorted image in the mask: {:?}", in_mask(&s)) };
|
||||
let r = s.execute("links.relink", &json!({"ids": [id.0], "path": other, "scope": "all"})).unwrap();
|
||||
let relinked = r["relinked"].as_array().unwrap();
|
||||
assert!(relinked.len() == 2 && relinked.contains(&json!(mask_id.0)), "the image and the mask's: {r}");
|
||||
assert_eq!(in_mask(&s), [(mask_id, Some(quad), (60, 20))], "the mask's image keeps its corners");
|
||||
}
|
||||
|
||||
/// Relink, Embed and Unembed keep a distorted image's corners, each in one undo step: Relink puts
|
||||
/// the new file's pixels between them whatever `preserve` and the Placement Options say, Embed
|
||||
/// keeps the pixels in the document, and Unembed links the image to the file it writes.
|
||||
#[test]
|
||||
fn relink_embed_and_unembed_keep_a_distorted_images_corners() {
|
||||
let dir = Folder::new("distorted-relink");
|
||||
let (photo, other, written) = (dir.file("photo.png"), dir.file("other.png"), dir.file("written.png"));
|
||||
write(&photo, &png(20, 10, RED));
|
||||
write(&other, &png(60, 20, BLUE));
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &photo);
|
||||
s.execute("links.placementOptions", &json!({"ids": [id.0], "preserve": "fill", "clip": true})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
// Around the artboard's center, where `centre_colour` looks.
|
||||
s.execute("object.distort", &json!({"corners": [[150, 100], [250, 110], [260, 200], [140, 190]]})).unwrap();
|
||||
let corners = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().image_corners().unwrap();
|
||||
let before = corners(&s);
|
||||
let distorted = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().is_distorted_image();
|
||||
let clipped = |s: &Session| {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
matches!(d.parent_of(id).and_then(|p| d.node(p)).map(|p| &p.kind), Some(NodeKind::Group { clip: true, .. }))
|
||||
};
|
||||
let undo_len = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
|
||||
|
||||
let undo = undo_len(&s);
|
||||
let r = s.execute("links.relink", &json!({"ids": [id.0], "path": other, "preserve": "fileDimensions"})).unwrap();
|
||||
// The given preserve is reported as not applied.
|
||||
let warning = format!("preserve was not applied to image {}: an image changed by Perspective Distort or Free Distort keeps its corners", id.0);
|
||||
assert_eq!(r, json!({"relinked": [id.0], "notFound": [], "warnings": [warning]}));
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
assert!(distorted(&s));
|
||||
assert_eq!(corners(&s), before);
|
||||
assert!(!clipped(&s), "not clipped by its Placement Options");
|
||||
let im = image(&s, id);
|
||||
assert_eq!((im.width, im.height), (60, 20));
|
||||
assert_eq!(im.link.as_ref().map(|l| l.path.as_str()), Some(other.as_str()));
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE));
|
||||
|
||||
let r = s.execute("links.embed", &json!({"ids": [id.0]})).unwrap();
|
||||
assert_eq!(r["embedded"], json!([id.0]), "{r}");
|
||||
assert_eq!(undo_len(&s), undo + 2);
|
||||
assert!(distorted(&s));
|
||||
assert_eq!(corners(&s), before);
|
||||
assert!(image(&s, id).link.is_none());
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE));
|
||||
|
||||
let r = s.execute("links.unembed", &json!({"id": id.0, "path": written})).unwrap();
|
||||
assert_eq!(r["id"], json!(id.0), "{r}");
|
||||
assert_eq!(undo_len(&s), undo + 3);
|
||||
assert!(distorted(&s));
|
||||
assert_eq!(corners(&s), before);
|
||||
assert!(!clipped(&s));
|
||||
let im = image(&s, id);
|
||||
assert_eq!((im.width, im.height), (60, 20));
|
||||
assert!(im.link.is_some());
|
||||
assert!(Path::new(&written).exists());
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE));
|
||||
|
||||
// Undo takes each back to the same corners, and the first file's pixels in the end.
|
||||
for _ in 0..3 {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(distorted(&s));
|
||||
assert_eq!(corners(&s), before);
|
||||
}
|
||||
assert_eq!((image(&s, id).width, image(&s, id).height), (20, 10));
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
|
||||
}
|
||||
|
||||
/// Unembed into a folder keeps a distorted image's corners, in one undo step.
|
||||
#[test]
|
||||
fn unembed_to_a_folder_keeps_a_distorted_images_corners() {
|
||||
let dir = Folder::new("distorted-unembed-folder");
|
||||
let (photo, out) = (dir.file("photo.png"), dir.file("out"));
|
||||
std::fs::create_dir_all(&out).unwrap();
|
||||
write(&photo, &png(20, 10, RED));
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &photo);
|
||||
s.execute("links.embed", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[150, 100], [250, 110], [260, 200], [140, 190]]})).unwrap();
|
||||
let corners = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().image_corners().unwrap();
|
||||
let before = corners(&s);
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute("links.unembed", &json!({"ids": [id.0], "folder": out})).unwrap();
|
||||
assert_eq!(r["unembedded"][0]["id"], json!(id.0), "{r}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
assert!(s.doc().unwrap().doc.node(id).unwrap().is_distorted_image());
|
||||
assert_eq!(corners(&s), before);
|
||||
assert!(image(&s, id).link.is_some());
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
|
||||
}
|
||||
|
||||
/// Embed reads the file of a distorted image that shows its saved preview and keeps the file's
|
||||
/// pixels in the document between the image's corners, in one undo step.
|
||||
#[test]
|
||||
fn embed_reads_a_distorted_images_file_between_its_corners() {
|
||||
let dir = Folder::new("distorted-embed-preview");
|
||||
let photo = dir.file("photo.png");
|
||||
// Large enough that the document saves a smaller preview of it.
|
||||
write(&photo, &png(600, 300, RED));
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &photo);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[150, 100], [250, 110], [260, 200], [140, 190]]})).unwrap();
|
||||
let corners = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().image_corners().unwrap();
|
||||
let before = corners(&s);
|
||||
let doc_path = dir.file("poster.vectorcraft");
|
||||
save(&mut s, &doc_path);
|
||||
std::fs::remove_file(&photo).unwrap();
|
||||
open(&mut s, &doc_path);
|
||||
assert!(s.doc().unwrap().doc.images[&image(&s, id).key].is_proxy(), "the preview stands in");
|
||||
assert!(s.doc().unwrap().doc.node(id).unwrap().is_distorted_image());
|
||||
write(&photo, &png(400, 200, BLUE));
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute("links.embed", &json!({"ids": [id.0]})).unwrap();
|
||||
assert_eq!(r, json!({"embedded": [id.0], "missing": []}));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
assert!(n.is_distorted_image());
|
||||
assert_eq!(n.image_corners().unwrap(), before);
|
||||
let im = image(&s, id);
|
||||
assert_eq!((im.width, im.height, im.link.is_none()), (400, 200, true));
|
||||
assert!(!s.doc().unwrap().doc.images[&im.key].is_proxy(), "the file's pixels are in the document");
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE));
|
||||
}
|
||||
|
||||
/// Update Links reads a changed file again for the images inside symbols, patterns and opacity
|
||||
/// masks too: those showing the same content as an image in the layers, and those no object in the
|
||||
/// layers shows. Each takes the file's place as its own Placement Options say, in one undo step,
|
||||
@@ -2617,6 +2824,37 @@ fn confined_screens_rows_check_the_artboard_each_file_holds() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A confined caller's single-file PDF with Preserve Editing of several artboards carries the art
|
||||
/// of every artboard on its pages: an image linked outside the read roots on the second artboard
|
||||
/// alone refuses it. A single-file PDF of assets is refused before any link is checked.
|
||||
#[test]
|
||||
fn confined_single_file_pdf_checks_every_artboard_it_carries() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let away = Folder::new("single-pdf-away");
|
||||
let home = Folder::new("single-pdf-home");
|
||||
let photo = away.file("photo.png");
|
||||
write(&photo, &png(60, 30, RED));
|
||||
let mut s = session();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
|
||||
let rect: vectorcraft_doc::NodeId = serde_json::from_value(r["id"].clone()).unwrap();
|
||||
s.execute("artboard.new", &json!({"x": 2000, "y": 0, "width": 200, "height": 200})).unwrap();
|
||||
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
|
||||
let p = |folder: &str| json!({"range": "1-2", "folder": home.file(folder), "pdfs": "single", "formats": [{"format": "pdf", "preserveEditing": true}]});
|
||||
let r = confine(roots.as_ref(), || s.execute("document.exportForScreens", &p("plain"))).unwrap_or_else(|e| panic!("{e}"));
|
||||
assert_eq!(r["files"].as_array().map(Vec::len), Some(1), "{r}");
|
||||
let r = s.execute("file.place", &json!({"path": photo, "at": [2100, 100]})).unwrap();
|
||||
assert_eq!(r["linked"], true, "{r}");
|
||||
let e = confine(roots.as_ref(), || s.execute("document.exportForScreens", &p("linked"))).expect_err("second artboard links outside").to_string();
|
||||
assert!(e.contains("a linked image file is outside the read roots"), "{e}");
|
||||
assert!(!Path::new(&home.file("linked")).exists(), "the refused export writes no folder");
|
||||
let asset = s.execute("assets.add", &json!({"ids": [rect.0]})).unwrap()["assets"][0].as_u64().unwrap();
|
||||
let assets = json!({"assets": [asset], "folder": home.file("assets"), "pdfs": "single", "formats": [{"format": "pdf", "preserveEditing": true}]});
|
||||
let e = confine(roots.as_ref(), || s.execute("assets.export", &assets)).expect_err("single-file PDF of assets").to_string();
|
||||
assert!(e.contains("pdfs `single` writes artboards as the pages of one PDF"), "{e}");
|
||||
assert!(!Path::new(&home.file("assets")).exists(), "the refused export writes no folder");
|
||||
}
|
||||
|
||||
/// A confined caller's native outputs (a native file or template, an EPS or `.ai` file, a PDF with
|
||||
/// Preserve Editing, a package's document) carry the document without the Export for Screens
|
||||
/// folder when it is outside the read roots, with the other export settings and the art; the open
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
//! Gradient mesh points picked with one of the tools that pick them (the Mesh tool, Direct
|
||||
//! Selection, the Lasso, the Polygonal Lasso) stay picked when another of them is chosen, or lent
|
||||
//! for a Cmd-click, so a fill color then recolors just them.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_doc::NodeKind;
|
||||
use vectorcraft_tools::{Mods, PointerEvent, PointerKind};
|
||||
|
||||
use crate::*;
|
||||
|
||||
/// A session with a selected 1 x 1 gradient mesh (four white points) at (10, 10), 50 pt square.
|
||||
fn mesh_session() -> (Session, NodeId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
let m = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.mesh.create", &json!({"ids": [m.0], "rows": 1, "cols": 1})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [m.0]})).unwrap();
|
||||
(s, m)
|
||||
}
|
||||
|
||||
fn colors(s: &Session, m: NodeId) -> Vec<Color> {
|
||||
match &s.doc().unwrap().doc.node(m).unwrap().kind {
|
||||
NodeKind::Mesh(g) => g.points.iter().map(|p| p.color).collect(),
|
||||
k => panic!("not a mesh: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Click mesh point `i` of `m` with the active tool.
|
||||
fn press(s: &mut Session, m: NodeId, i: usize, mods: Mods) {
|
||||
let q = match &s.doc().unwrap().doc.node(m).unwrap().kind {
|
||||
NodeKind::Mesh(g) => g.points[i].p,
|
||||
k => panic!("not a mesh: {k:?}"),
|
||||
};
|
||||
for kind in [PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(kind, q.x, q.y).with_mods(mods), ViewInfo::default()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// A point picked with the Mesh tool stays picked through Direct Selection, the Lasso and the
|
||||
/// Polygonal Lasso and back to the Mesh tool: each fill color recolors just that point.
|
||||
#[test]
|
||||
fn mesh_point_picks_carry_between_the_mesh_point_tools() {
|
||||
let (mut s, m) = mesh_session();
|
||||
let v = ViewInfo::default();
|
||||
let white = colors(&s, m)[0];
|
||||
s.select_tool("mesh", v).unwrap();
|
||||
press(&mut s, m, 0, Mods::default());
|
||||
for (tool, hex, c) in [
|
||||
("directSelection", "#0000ff", Color::rgb8(0, 0, 255)),
|
||||
("lasso", "#00ff00", Color::rgb8(0, 255, 0)),
|
||||
("polygonalLasso", "#ff0000", Color::rgb8(255, 0, 0)),
|
||||
("directSelection", "#ffff00", Color::rgb8(255, 255, 0)),
|
||||
("mesh", "#00ffff", Color::rgb8(0, 255, 255)),
|
||||
] {
|
||||
s.select_tool(tool, v).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": hex})).unwrap();
|
||||
assert_eq!(colors(&s, m), [c, white, white, white], "{tool} recolors only the picked point");
|
||||
}
|
||||
}
|
||||
|
||||
/// A point picked with Direct Selection stays picked for the Mesh tool.
|
||||
#[test]
|
||||
fn direct_selection_picks_carry_to_the_mesh_tool() {
|
||||
let (mut s, m) = mesh_session();
|
||||
let v = ViewInfo::default();
|
||||
let white = colors(&s, m)[0];
|
||||
s.select_tool("directSelection", v).unwrap();
|
||||
press(&mut s, m, 2, Mods::default());
|
||||
s.select_tool("mesh", v).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
|
||||
assert_eq!(colors(&s, m), [white, white, Color::rgb8(0, 0, 255), white]);
|
||||
}
|
||||
|
||||
/// The Selection tool picks no mesh points: after it, the Mesh tool starts with none picked, and a
|
||||
/// fill color leaves every point as it was.
|
||||
#[test]
|
||||
fn a_tool_that_picks_no_mesh_points_drops_the_picks() {
|
||||
let (mut s, m) = mesh_session();
|
||||
let v = ViewInfo::default();
|
||||
let before = colors(&s, m);
|
||||
s.select_tool("mesh", v).unwrap();
|
||||
press(&mut s, m, 0, Mods::default());
|
||||
s.select_tool("selection", v).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [m.0]})).unwrap();
|
||||
s.select_tool("mesh", v).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
|
||||
assert_eq!(colors(&s, m), before, "no point is picked");
|
||||
}
|
||||
|
||||
/// A plain Lasso click away from the art deselects it and unpicks the points the Mesh tool picked,
|
||||
/// so the Mesh tool chosen next has none picked.
|
||||
#[test]
|
||||
fn a_lasso_click_that_deselects_unpicks_the_mesh_points() {
|
||||
let (mut s, m) = mesh_session();
|
||||
let v = ViewInfo::default();
|
||||
let before = colors(&s, m);
|
||||
s.select_tool("mesh", v).unwrap();
|
||||
press(&mut s, m, 0, Mods::default());
|
||||
s.select_tool("lasso", v).unwrap();
|
||||
for kind in [PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(kind, 500.0, 500.0), v).unwrap();
|
||||
}
|
||||
assert!(s.doc().unwrap().selection.objects.is_empty(), "the click deselects the mesh");
|
||||
s.execute("select.set", &json!({"ids": [m.0]})).unwrap();
|
||||
s.select_tool("mesh", v).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
|
||||
assert_eq!(colors(&s, m), before, "no point is picked");
|
||||
}
|
||||
|
||||
/// Direct Selection lent to the Mesh tool for a Cmd-click starts from the Mesh tool's picks, so a
|
||||
/// Shift-click adds to them, and gives back what it left picked.
|
||||
#[test]
|
||||
fn the_lent_direct_selection_carries_the_mesh_tools_picks() {
|
||||
let (mut s, m) = mesh_session();
|
||||
let v = ViewInfo::default();
|
||||
let white = colors(&s, m)[0];
|
||||
// Cmd lends the selection tool chosen last.
|
||||
s.select_tool("directSelection", v).unwrap();
|
||||
s.select_tool("mesh", v).unwrap();
|
||||
press(&mut s, m, 0, Mods::default());
|
||||
press(&mut s, m, 3, Mods { cmd: true, shift: true, ..Default::default() });
|
||||
assert_eq!(s.tool_id(), "mesh");
|
||||
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
|
||||
let b = Color::rgb8(0, 0, 255);
|
||||
assert_eq!(colors(&s, m), [b, white, white, b], "both points stay picked");
|
||||
}
|
||||
@@ -1736,11 +1736,17 @@ fn pathfinder_options_round_trip_and_refuse_bad_values() {
|
||||
assert_eq!(s.execute("prefs.get", &json!({"key": "pathfinder"})).unwrap(), set);
|
||||
let mm = s.execute("object.pathfinder.options", &json!({"precision": "1 mm"})).unwrap()["precision"].as_f64().unwrap();
|
||||
assert!((mm - 72.0 / 25.4).abs() < 1e-9, "a length with a unit: {mm}");
|
||||
for (given, want) in [("10 pt", 10.0), ("0.25", 0.25)] {
|
||||
let r = s.execute("object.pathfinder.options", &json!({"precision": given})).unwrap();
|
||||
assert_eq!(r["precision"], json!(want), "{given}");
|
||||
}
|
||||
s.execute("object.pathfinder.options", &json!({"precision": 0.5})).unwrap();
|
||||
for bad in [
|
||||
json!({"precision": 0}),
|
||||
json!({"precision": 11}),
|
||||
json!({"precision": "x"}),
|
||||
json!({"precision": "1abc"}),
|
||||
json!({"precision": "0.5 extra"}),
|
||||
json!({"precision": -1}),
|
||||
json!({"removeRedundantPoints": "yes"}),
|
||||
json!({"removeUnpainted": 1}),
|
||||
@@ -2067,6 +2073,23 @@ fn a_precision_set_after_a_scale_past_its_range_is_kept() {
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
|
||||
}
|
||||
|
||||
/// Soft Mix's Mixing Rate is compared by value: 50 over a stored 50.0 records no undo step, and 51
|
||||
/// is an edit.
|
||||
#[test]
|
||||
fn a_soft_mix_rate_set_to_its_value_records_no_step() {
|
||||
let mut s = session();
|
||||
let (a, b) = (rect(&mut s, 0.0, 0.0, 100.0, 100.0), rect(&mut s, 50.0, 50.0, 100.0, 100.0));
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "pathfinder.softMix", "params": {"mixingRate": 50.0}})).unwrap();
|
||||
assert_eq!(first_effect_params(&s)["mixingRate"], json!(50.0));
|
||||
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let before = steps(&s);
|
||||
assert_eq!(s.execute("effect.setParams", &json!({"index": 0, "params": {"mixingRate": 50}})).unwrap(), json!({"ids": []}));
|
||||
assert_eq!((first_effect_params(&s)["mixingRate"].clone(), steps(&s)), (json!(50.0), before), "50 over 50.0: no step");
|
||||
assert_ne!(s.execute("effect.setParams", &json!({"index": 0, "params": {"mixingRate": 51}})).unwrap(), json!({"ids": []}));
|
||||
assert_eq!((first_effect_params(&s)["mixingRate"].clone(), steps(&s)), (json!(51), before + 1), "51 is an edit");
|
||||
}
|
||||
|
||||
/// A single group containing multiple overlapping paths is accepted by Crop.
|
||||
#[test]
|
||||
fn crop_operates_on_a_single_selected_group_of_paths() {
|
||||
|
||||
@@ -334,7 +334,7 @@ fn replace_art_is_refused_without_changing_anything() {
|
||||
for (case, p, why) in [
|
||||
("no name", json!({}), "missing name".to_string()),
|
||||
("no pattern", json!({"name": "Stripes"}), "no pattern `Stripes`".into()),
|
||||
("no art", json!({"name": "Dots", "ids": [9999]}), "select the art for the pattern tile".into()),
|
||||
("no art", json!({"name": "Dots", "ids": []}), "select the art for the pattern tile".into()),
|
||||
("painted with it", json!({"name": "Dots", "ids": [other.0]}), "art painted with `Dots` can't be its tile".into()),
|
||||
("through a pattern", json!({"name": "Dots", "ids": [via.0]}), "art painted with `Dots` can't be its tile".into()),
|
||||
("through a symbol", json!({"name": "Dots", "ids": [instance.0]}), "art painted with `Dots` can't be its tile".into()),
|
||||
@@ -359,6 +359,28 @@ fn replace_art_is_refused_without_changing_anything() {
|
||||
unchanged(&s, &before, steps, "while editing");
|
||||
}
|
||||
|
||||
/// Make, Replace Pattern Art and the Repeat commands return an error, changing nothing, when an
|
||||
/// `ids` entry names no object, also beside one that does: they never act on the rest alone.
|
||||
#[test]
|
||||
fn pattern_and_repeat_commands_refuse_an_unknown_id_without_changing_anything() {
|
||||
let mut s = session();
|
||||
make_dots(&mut s);
|
||||
let blue = blue_rect(&mut s);
|
||||
let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len());
|
||||
for (cmd, p) in [
|
||||
("object.pattern.replaceArt", json!({"name": "Dots", "ids": [blue.0, 9999]})),
|
||||
("object.pattern.make", json!({"name": "P", "ids": [blue.0, 9999]})),
|
||||
("object.repeat.radial", json!({"ids": [blue.0, 9999]})),
|
||||
("object.repeat.grid", json!({"ids": [9999, blue.0]})),
|
||||
("object.repeat.mirror", json!({"ids": [9999]})),
|
||||
] {
|
||||
let err = s.execute(cmd, &p).unwrap_err();
|
||||
assert!(err.to_string().contains("no such object id 9999"), "{cmd}: {err}");
|
||||
assert_eq!(doc(&s), &before, "{cmd}: the document stays");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{cmd}: no undo step");
|
||||
}
|
||||
}
|
||||
|
||||
fn doc_mut(s: &mut Session) -> &mut vectorcraft_doc::Document {
|
||||
Arc::make_mut(&mut s.doc_mut().unwrap().doc)
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_geom::{PathData, Point, SubPath};
|
||||
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
|
||||
use vectorcraft_tools::{Mods, Overlay, PointerEvent, PointerKind, ToolKey};
|
||||
|
||||
use crate::tooling::ViewInfo;
|
||||
use crate::*;
|
||||
@@ -43,13 +43,20 @@ fn pt(x: f64, y: f64) -> Point {
|
||||
}
|
||||
|
||||
fn press(s: &mut Session, pts: &[(f64, f64)]) {
|
||||
let v = view();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, pts[0].0, pts[0].1), v).unwrap();
|
||||
press_in(s, pts, view());
|
||||
}
|
||||
|
||||
fn press_in(s: &mut Session, pts: &[(f64, f64)], v: ViewInfo) {
|
||||
press_with(s, pts, v, Mods::default());
|
||||
}
|
||||
|
||||
fn press_with(s: &mut Session, pts: &[(f64, f64)], v: ViewInfo, m: Mods) {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, pts[0].0, pts[0].1).with_mods(m), v).unwrap();
|
||||
for &(x, y) in &pts[1..] {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, x, y), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, x, y).with_mods(m), v).unwrap();
|
||||
}
|
||||
let l = pts[pts.len() - 1];
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, l.0, l.1), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, l.0, l.1).with_mods(m), v).unwrap();
|
||||
}
|
||||
|
||||
fn click(s: &mut Session, x: f64, y: f64) {
|
||||
@@ -505,6 +512,311 @@ fn a_click_on_an_open_end_continues_the_path() {
|
||||
assert_eq!(ends, [pt(200.0, 100.0), pt(100.0, 100.0), pt(100.0, 200.0)]);
|
||||
}
|
||||
|
||||
/// With Smart Guides on, a click near another path's anchor puts the point on that anchor; with
|
||||
/// them off, the point stays where the click was.
|
||||
#[test]
|
||||
fn a_point_snaps_to_a_smart_guide() {
|
||||
for (guides, want) in [(true, pt(300.0, 300.0)), (false, pt(302.0, 301.0))] {
|
||||
let mut s = session();
|
||||
s.execute("shape.line", &json!({"x1": 300, "y1": 300, "x2": 500, "y2": 450})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
quick_pen(&mut s);
|
||||
let v = ViewInfo { smart_guides: guides, ..Default::default() };
|
||||
press_in(&mut s, &[(100.0, 100.0)], v);
|
||||
press_in(&mut s, &[(302.0, 301.0)], v);
|
||||
let drawn = paths(&s).into_iter().find(|(_, p)| p.subpaths[0].anchors.first().is_some_and(|a| a.p == pt(100.0, 100.0))).unwrap();
|
||||
assert!(drawn.1.subpaths[0].anchors.last().unwrap().p.distance(want) < 1e-9, "{guides}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A point 100 pt from (200, 100) and 30.5° below the +x direction a path from (100, 100) ends in:
|
||||
/// a continuous arc to it sweeps 61°.
|
||||
fn arc_end_61() -> Point {
|
||||
let half = 30.5f64.to_radians();
|
||||
pt(200.0 + 100.0 * half.cos(), 100.0 + 100.0 * half.sin())
|
||||
}
|
||||
|
||||
/// The protractor's 60° tick for the arc to [`arc_end_61`]: on the same circle, a 60° sweep.
|
||||
fn tick_60() -> Point {
|
||||
let r = 50.0 / 30.5f64.to_radians().sin();
|
||||
pt(200.0 + r * 30f64.to_radians().cos(), 100.0 + r * 30f64.to_radians().sin())
|
||||
}
|
||||
|
||||
/// A path from (100, 100) to (200, 100) drawn with Quick Pen, the action then a continuous arc.
|
||||
fn continuous_arc_after_a_line(s: &mut Session, v: ViewInfo) {
|
||||
quick_pen(s);
|
||||
press_in(s, &[(100.0, 100.0)], v);
|
||||
press_in(s, &[(200.0, 100.0)], v);
|
||||
key(s, ToolKey::AltTap);
|
||||
}
|
||||
|
||||
/// The last point of the path the tool drew (any other path is a two-point line).
|
||||
fn drawn_end(s: &Session) -> Point {
|
||||
let drawn = paths(s).into_iter().find(|(_, p)| p.subpaths[0].anchors.len() >= 3).unwrap();
|
||||
drawn.1.subpaths[0].anchors.last().unwrap().p
|
||||
}
|
||||
|
||||
/// A continuous arc dragged to end 61° round goes onto the protractor's 60° tick with Smart Guides
|
||||
/// on, also with Shift held, which does not constrain Quick Pen points; with them off it ends at
|
||||
/// the pointer. A Smart Guide in reach (another path's anchor) wins over the tick, also with its
|
||||
/// label hidden, and so do Snap to Grid and Snap to Pixel.
|
||||
#[test]
|
||||
fn a_continuous_arc_end_snaps_to_the_protractor() {
|
||||
let at = arc_end_61();
|
||||
let anchor = pt(at.x + 0.2, at.y + 0.15);
|
||||
let fresh = session();
|
||||
let g = &fresh.doc().unwrap().doc.grid;
|
||||
let step = g.spacing / g.subdivisions.max(1) as f64;
|
||||
let on_grid = pt((at.x / step).round() * step, (at.y / step).round() * step);
|
||||
let on_pixel = pt(at.x.round(), at.y.round());
|
||||
let shift = Mods { shift: true, ..Default::default() };
|
||||
// (Smart Guides, the other path, Snap to Grid, Snap to Pixel, Anchor/Path Labels, mods, where
|
||||
// the end goes, the pointer)
|
||||
let cases = [
|
||||
(true, false, false, false, true, Mods::default(), tick_60(), at),
|
||||
(true, false, false, false, true, shift, tick_60(), at),
|
||||
(false, false, false, false, true, Mods::default(), at, at),
|
||||
(true, true, false, false, true, Mods::default(), anchor, at),
|
||||
(true, false, true, false, true, Mods::default(), on_grid, on_grid),
|
||||
(true, false, false, true, true, Mods::default(), on_pixel, on_pixel),
|
||||
// Exactly on the anchor, which shows no guide with the labels off.
|
||||
(true, true, false, false, false, Mods::default(), anchor, anchor),
|
||||
];
|
||||
for (guides, other, grid, pixel, labels, m, want, pointer) in cases {
|
||||
let mut s = session();
|
||||
s.prefs.anchor_path_labels = labels;
|
||||
if other {
|
||||
s.execute("shape.line", &json!({"x1": anchor.x, "y1": anchor.y, "x2": 600, "y2": anchor.y})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
}
|
||||
let v = ViewInfo { smart_guides: guides, snap_to_grid: grid, snap_to_pixel: pixel, ..Default::default() };
|
||||
continuous_arc_after_a_line(&mut s, v);
|
||||
press_with(&mut s, &[(280.0, 140.0), (pointer.x, pointer.y)], v, m);
|
||||
let end = drawn_end(&s);
|
||||
assert!(end.distance(want) < 1e-6, "{guides} {other} {grid} {pixel} {labels} {m:?}: {end:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// With Smart Guides on, a click without a drag puts a continuous arc's end on the protractor's
|
||||
/// tick; after Alt switches to a sharp-corner arc, a click at the same place puts the end at the
|
||||
/// pointer.
|
||||
#[test]
|
||||
fn a_click_puts_a_continuous_arc_end_on_a_tick() {
|
||||
let at = arc_end_61();
|
||||
let v = ViewInfo::default();
|
||||
for (taps, want) in [(0, tick_60()), (1, at)] {
|
||||
let mut s = session();
|
||||
continuous_arc_after_a_line(&mut s, v);
|
||||
for _ in 0..taps {
|
||||
key(&mut s, ToolKey::AltTap);
|
||||
}
|
||||
press_in(&mut s, &[(at.x, at.y)], v);
|
||||
let end = drawn_end(&s);
|
||||
assert!(end.distance(want) < 1e-6, "{taps}: {end:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Alt tapped during a press moves the end of the piece for the new action at once, with no
|
||||
/// further drag: a continuous arc's end on the 60° tick goes to the pointer once the piece is a
|
||||
/// sharp-corner arc, after a drag and after a press that has not dragged, and a line's end at the
|
||||
/// pointer goes onto the tick once the piece is a continuous arc.
|
||||
#[test]
|
||||
fn an_alt_tap_during_a_press_moves_the_end_for_the_new_action() {
|
||||
let at = arc_end_61();
|
||||
let v = ViewInfo::default();
|
||||
// (drag first, Alt taps before the press, the end before Alt, the end after it)
|
||||
for (drag, taps, before, after) in [(true, 0, tick_60(), at), (false, 0, tick_60(), at), (true, 2, at, tick_60())] {
|
||||
let mut s = session();
|
||||
continuous_arc_after_a_line(&mut s, v);
|
||||
for _ in 0..taps {
|
||||
key(&mut s, ToolKey::AltTap);
|
||||
}
|
||||
let first = if drag { (280.0, 140.0) } else { (at.x, at.y) };
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, first.0, first.1), v).unwrap();
|
||||
if drag {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, at.x, at.y), v).unwrap();
|
||||
}
|
||||
assert!(drawn_end(&s).distance(before) < 1e-6, "{drag} {taps}: {:?}", drawn_end(&s));
|
||||
s.tool_key(ToolKey::AltTap, Mods::default(), v).unwrap();
|
||||
assert!(drawn_end(&s).distance(after) < 1e-6, "{drag} {taps} after Alt: {:?}", drawn_end(&s));
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, at.x, at.y), v).unwrap();
|
||||
assert!(drawn_end(&s).distance(after) < 1e-6, "{drag} {taps} placed: {:?}", drawn_end(&s));
|
||||
}
|
||||
}
|
||||
|
||||
/// After a click puts a continuous arc's end on a tick away from the pointer, no preview runs from
|
||||
/// the placed end back to where the pointer was; the next move shows the preview again.
|
||||
#[test]
|
||||
fn a_click_on_a_tick_leaves_no_preview_back_to_the_pointer() {
|
||||
let at = arc_end_61();
|
||||
let v = ViewInfo::default();
|
||||
let mut s = session();
|
||||
continuous_arc_after_a_line(&mut s, v);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, at.x, at.y), v).unwrap();
|
||||
press_in(&mut s, &[(at.x, at.y)], v);
|
||||
assert!(drawn_end(&s).distance(tick_60()) < 1e-6);
|
||||
let label = |s: &mut Session| s.overlays(v).iter().any(|o| matches!(o, Overlay::Measure { .. }));
|
||||
assert!(!label(&mut s), "no distance label back to the pointer");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 400.0, 300.0), v).unwrap();
|
||||
assert!(label(&mut s));
|
||||
}
|
||||
|
||||
/// Hovering near a tick as a continuous arc puts the distance label beside the tick; after Alt
|
||||
/// switches the action, the same hover puts it beside the pointer.
|
||||
#[test]
|
||||
fn a_hover_snaps_to_a_tick_only_for_a_continuous_arc() {
|
||||
let at = arc_end_61();
|
||||
let tick = tick_60();
|
||||
let v = ViewInfo::default();
|
||||
let mut s = session();
|
||||
continuous_arc_after_a_line(&mut s, v);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, at.x, at.y), v).unwrap();
|
||||
let label = |s: &mut Session| {
|
||||
s.overlays(v).iter().find_map(|o| match o {
|
||||
Overlay::Measure { p, .. } => Some(*p),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
let off = label(&mut s).unwrap() - tick;
|
||||
assert!(off.x > 0.0 && (off.x - off.y).abs() < 1e-9, "the label sits diagonally off the tick: {off:?}");
|
||||
for _ in 0..2 {
|
||||
key(&mut s, ToolKey::AltTap);
|
||||
assert!((label(&mut s).unwrap() - off).distance(at) < 1e-9, "{:?}", s.tool_options()["action"]);
|
||||
}
|
||||
}
|
||||
|
||||
/// A hover made with Smart Guides off shows nothing once they are turned on under the still
|
||||
/// pointer, so it shows no tick that a click would not use (another path's anchor under the
|
||||
/// pointer takes the click). The next move shows the hover again, its label beside the anchor;
|
||||
/// once Smart Guides are turned off again, its guides are hidden with it, also after a click.
|
||||
#[test]
|
||||
fn a_hover_shows_nothing_after_smart_guides_change() {
|
||||
let at = arc_end_61();
|
||||
let off = ViewInfo { smart_guides: false, ..Default::default() };
|
||||
let on = ViewInfo::default();
|
||||
let mut s = session();
|
||||
s.execute("shape.line", &json!({"x1": at.x, "y1": at.y, "x2": 600, "y2": at.y})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
continuous_arc_after_a_line(&mut s, off);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, at.x, at.y), off).unwrap();
|
||||
let label = |s: &mut Session, v: ViewInfo| {
|
||||
s.overlays(v).iter().find_map(|o| match o {
|
||||
Overlay::Measure { p, .. } => Some(*p),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
assert!(label(&mut s, off).is_some());
|
||||
assert_eq!(label(&mut s, on), None, "the hover from before the change shows nothing");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, at.x, at.y), on).unwrap();
|
||||
let off_anchor = label(&mut s, on).unwrap() - at;
|
||||
assert!(off_anchor.x > 0.0 && (off_anchor.x - off_anchor.y).abs() < 1e-9, "the label sits diagonally off the anchor: {off_anchor:?}");
|
||||
let only_points = |s: &mut Session, v: ViewInfo| s.overlays(v).iter().all(|o| matches!(o, Overlay::CurvePoint { .. }));
|
||||
assert!(!only_points(&mut s, on));
|
||||
assert!(only_points(&mut s, off), "only the path's points show");
|
||||
// A click before the pointer moves does not bring the stale hover back.
|
||||
press_in(&mut s, &[(400.0, 300.0)], off);
|
||||
assert_eq!(label(&mut s, off), None, "no label for the stale hover after the click");
|
||||
}
|
||||
|
||||
/// While the pointer hovers, the tool asks the canvas to hover it again when the view, the document
|
||||
/// or the selection changes under a still pointer, so the snapped point follows the art; a press
|
||||
/// stops it until the next move.
|
||||
#[test]
|
||||
fn a_hover_is_hovered_again_when_the_art_changes() {
|
||||
let mut s = session();
|
||||
continuous_arc_after_a_line(&mut s, view());
|
||||
assert!(!s.tool_wants_rehover());
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 280.0, 180.0), view()).unwrap();
|
||||
assert!(s.tool_wants_rehover());
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 280.0, 180.0), view()).unwrap();
|
||||
assert!(!s.tool_wants_rehover());
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 180.0), view()).unwrap();
|
||||
assert!(!s.tool_wants_rehover());
|
||||
}
|
||||
|
||||
/// A hover on the path's last point, which another path's anchor shares, shows that anchor's Smart
|
||||
/// Guide; after Smart Guides are turned off, a click there adds nothing and the guide stays hidden
|
||||
/// while the button is held and after it is let go.
|
||||
#[test]
|
||||
fn a_click_that_adds_nothing_keeps_a_stale_hover_hidden() {
|
||||
let off = ViewInfo { smart_guides: false, ..Default::default() };
|
||||
let on = ViewInfo::default();
|
||||
let mut s = session();
|
||||
s.execute("shape.line", &json!({"x1": 200, "y1": 100, "x2": 200, "y2": 400})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
continuous_arc_after_a_line(&mut s, on);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 200.0, 100.0), on).unwrap();
|
||||
let only_points = |s: &mut Session, v: ViewInfo| s.overlays(v).iter().all(|o| matches!(o, Overlay::CurvePoint { .. }));
|
||||
assert!(!only_points(&mut s, on), "the anchor's guide shows");
|
||||
assert!(only_points(&mut s, off));
|
||||
let steps = undo_steps(&s);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), off).unwrap();
|
||||
assert!(only_points(&mut s, off), "the guide stays hidden while the button is held");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 100.0), off).unwrap();
|
||||
assert_eq!(undo_steps(&s), steps, "the click adds nothing");
|
||||
assert!(only_points(&mut s, off), "the guide stays hidden");
|
||||
}
|
||||
|
||||
/// While a press drags an arc, the tool shows its protractor; while it drags a line, it shows none.
|
||||
#[test]
|
||||
fn an_arc_drag_shows_the_protractor() {
|
||||
let mut s = session();
|
||||
quick_pen(&mut s);
|
||||
let protractors = |s: &mut Session| s.overlays(view()).iter().filter(|o| matches!(o, Overlay::Path { .. })).count();
|
||||
for (action, shown) in [("line", 0), ("continuousArc", 1), ("sharpArc", 1)] {
|
||||
key(&mut s, ToolKey::Escape);
|
||||
s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "line"})).unwrap();
|
||||
click(&mut s, 100.0, 100.0);
|
||||
click(&mut s, 200.0, 100.0);
|
||||
s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": action})).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 150.0), view()).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 180.0), view()).unwrap();
|
||||
assert_eq!(protractors(&mut s), shown, "{action}");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 180.0), view()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// While hovering, the piece the next click adds shows its protractor beside the rubber band, and
|
||||
/// neither shows with the Pen tool's rubber band preference off; a line has no protractor. (Smart
|
||||
/// Guides are off, so no guide paths show.)
|
||||
#[test]
|
||||
fn a_hovered_arc_shows_the_protractor_with_the_rubber_band() {
|
||||
for (rubber_band, action, paths) in [(true, "continuousArc", 2), (true, "line", 1), (false, "continuousArc", 0)] {
|
||||
let mut s = session();
|
||||
s.prefs.pen_rubber_band = rubber_band;
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
click(&mut s, 200.0, 100.0);
|
||||
s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": action})).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 280.0, 180.0), view()).unwrap();
|
||||
let shown = s.overlays(view()).iter().filter(|o| matches!(o, Overlay::Path { .. })).count();
|
||||
assert_eq!(shown, paths, "{rubber_band} {action}");
|
||||
}
|
||||
}
|
||||
|
||||
/// With Measurement Labels on, hovering after the path's last point shows the distance label
|
||||
/// beside the pointer; with them off, no label shows.
|
||||
#[test]
|
||||
fn hovering_shows_the_distance_label() {
|
||||
for labels in [true, false] {
|
||||
let mut s = session();
|
||||
s.prefs.measurement_labels = labels;
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
click(&mut s, 200.0, 100.0);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 300.0, 200.0), view()).unwrap();
|
||||
let o = s.overlays(view());
|
||||
let label = o.iter().find_map(|o| match o {
|
||||
Overlay::Measure { p, .. } => Some(*p),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(label.is_some(), labels);
|
||||
if let Some(p) = label {
|
||||
assert!(p.x > 300.0 && p.y > 200.0, "beside the pointer: {p:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `path.quickPen` makes a new path with the current paint, or a black stroke without any.
|
||||
#[test]
|
||||
fn path_quick_pen_makes_a_stroked_path() {
|
||||
|
||||
@@ -418,7 +418,8 @@ fn script_file_encoding_binary_ascii() {
|
||||
}
|
||||
|
||||
/// A script's own folder is only read: writing there, and anywhere it was not given, is refused,
|
||||
/// and with nobody to ask its file dialogs give `null`. Aliases and `execute` are not available.
|
||||
/// and with nobody to ask its file dialogs give `null`. Setting `hidden` and `createAlias` are
|
||||
/// refused there too, and `execute` is not available.
|
||||
#[test]
|
||||
fn script_file_writes_outside_its_places_and_headless_dialogs_are_refused() {
|
||||
let base = folder("writes");
|
||||
@@ -454,10 +455,10 @@ fn script_file_writes_outside_its_places_and_headless_dialogs_are_refused() {
|
||||
null,
|
||||
false,
|
||||
"Script files cannot be opened in another application",
|
||||
"Script file hidden setting cannot be changed",
|
||||
DENIED,
|
||||
false,
|
||||
false,
|
||||
"Script files cannot make aliases",
|
||||
DENIED,
|
||||
""
|
||||
]])
|
||||
);
|
||||
@@ -465,6 +466,7 @@ fn script_file_writes_outside_its_places_and_headless_dialogs_are_refused() {
|
||||
assert_eq!(r["written"], json!([]));
|
||||
assert_eq!(std::fs::read(base.join("main/keep.txt")).unwrap(), b"keep");
|
||||
assert!(!base.join("main/new.txt").exists() && !base.join("main/made").exists() && !base.join("main/c.txt").exists());
|
||||
assert!(!base.join("main/.keep.txt").exists() && std::fs::symlink_metadata(base.join("main/l")).is_err());
|
||||
assert!(!Path::new(&outside).exists());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
@@ -693,6 +695,250 @@ fn a_renamed_file_names_its_old_and_new_paths_in_written() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
const NOT_FOUND: &str = "Script file does not exist";
|
||||
#[cfg(unix)]
|
||||
const NOT_REGULAR: &str = "Script file is not a regular file";
|
||||
#[cfg(unix)]
|
||||
const TAKEN: &str = "Script file name is already in use";
|
||||
|
||||
/// On Unix setting `hidden` renames a file with one dot added or its leading dots taken off, and the
|
||||
/// object takes the new path: a file it has open stays open and is written at the new path, a file
|
||||
/// already as asked keeps its name, and a name in use, a name of dots alone and a folder are refused.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn script_file_hidden_renames_the_file_with_a_leading_dot() {
|
||||
let base = folder("hidden");
|
||||
let mut s = with_data(&base);
|
||||
let r = run_in(
|
||||
&mut s,
|
||||
&base,
|
||||
"var d = Folder.userData.fsName, u = new File(d + '/u.txt'); u.open('w'); u.write('kept');\n\
|
||||
var before = u.fsName; u.hidden = true;\n\
|
||||
var out = [u.name, u.hidden, u.error, new File(d + '/.u.txt').hidden, new File(before).exists];\n\
|
||||
u.hidden = true; out.push(u.name, u.error, u.write('+'), u.close()); u.open('r'); out.push(u.read()); u.close();\n\
|
||||
u.hidden = false; out.push(u.name, u.hidden, new File(d + '/.u.txt').exists);\n\
|
||||
var dots = new File(d + '/...'); dots.open('w'); dots.close(); dots.hidden = false; out.push(dots.error, dots.exists);\n\
|
||||
var v = new File(d + '/v.txt'), w = new File(d + '/.v.txt'); v.open('w'); v.close(); w.open('w'); w.write('w'); w.close();\n\
|
||||
v.hidden = true; out.push(v.error, v.name, w.length);\n\
|
||||
var g = new Folder(d + '/g'); g.create(); var gf = new File(g.fsName); gf.hidden = true; out.push(gf.error, g.exists);\n\
|
||||
vc.log(out); vc.log(d);",
|
||||
)
|
||||
.unwrap();
|
||||
let no_hidden = "Script file hidden setting cannot be changed";
|
||||
assert_eq!(
|
||||
r["log"][0],
|
||||
json!([
|
||||
".u.txt",
|
||||
true,
|
||||
"",
|
||||
true,
|
||||
false,
|
||||
".u.txt",
|
||||
"",
|
||||
true,
|
||||
true,
|
||||
"kept+",
|
||||
"u.txt",
|
||||
false,
|
||||
false,
|
||||
no_hidden,
|
||||
true,
|
||||
TAKEN,
|
||||
"v.txt",
|
||||
1,
|
||||
NOT_REGULAR,
|
||||
true
|
||||
])
|
||||
);
|
||||
let d = PathBuf::from(r["log"][1].as_str().unwrap());
|
||||
let mut names: Vec<String> = std::fs::read_dir(&d).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
|
||||
names.sort();
|
||||
assert_eq!(names, ["...", ".v.txt", "g", "u.txt", "v.txt"]);
|
||||
let written: Vec<&str> = r["written"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
for name in ["u.txt", ".u.txt"] {
|
||||
assert!(written.contains(&d.join(name).to_string_lossy().as_ref()), "{name} in {written:?}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Setting `hidden` gives the file a new name, which must be a place the script may write too: a
|
||||
/// file allowed on its own in a save dialog keeps its name.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn script_file_hidden_needs_the_new_name_to_be_writable() {
|
||||
let base = folder("hiddengrant");
|
||||
let picked = base.join("picked/s.txt");
|
||||
write(&picked, b"s");
|
||||
let mut s = with_data(&base);
|
||||
start_framed(
|
||||
&mut s,
|
||||
&base,
|
||||
"var f = File.saveDialog('s'); f.hidden = true; var out = [f.error, f.name, f.hidden]; out.push(f.rename('t.txt'), f.error, f.name); vc.log(out);",
|
||||
);
|
||||
assert!(pump_to_picker(&mut s).is_none());
|
||||
assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![picked.to_string_lossy().into_owned()], always: false }));
|
||||
let r = pump_to_picker(&mut s).unwrap().unwrap();
|
||||
assert_eq!(r["log"], json!([[DENIED, "s.txt", false, false, DENIED, "s.txt"]]));
|
||||
assert!(picked.exists() && !base.join("picked/.s.txt").exists() && !base.join("picked/t.txt").exists());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// On Unix `createAlias` makes a link, in a place the script may write, to a file it may read: the
|
||||
/// link is an alias that resolves to the file and reads it, `hidden` tells of the link's own name,
|
||||
/// setting `hidden` and `remove` change the link alone, and writing through it to a file the script
|
||||
/// may only read is refused. A link that leads out of the script's places afterward reads nothing.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn script_file_create_alias_links_to_a_file_the_script_may_read() {
|
||||
let base = folder("alias");
|
||||
write(&base.join("main/keep.txt"), b"keep");
|
||||
write(&base.join("main/.hid.txt"), b"hid");
|
||||
write(&base.join("secret.txt"), b"secret");
|
||||
let mut s = with_data(&base);
|
||||
let r = run_in(
|
||||
&mut s,
|
||||
&base,
|
||||
"var d = Folder.userData.fsName, k = new File('keep.txt'), l = new File(d + '/l');\n\
|
||||
var out = [l.createAlias(k), l.error, l.alias, l.resolve().fsName === k.fsName, l.hidden, k.alias];\n\
|
||||
l.open('r'); out.push(l.read()); l.close();\n\
|
||||
out.push(l.open('w'), l.error, l.open('a'), l.error);\n\
|
||||
var h = new File(d + '/h'); out.push(h.createAlias('.hid.txt'), h.hidden, h.resolve().name);\n\
|
||||
l.hidden = true; out.push(l.name, l.alias, l.hidden, k.exists, k.hidden);\n\
|
||||
out.push(l.remove(), l.exists, k.exists); vc.log(out); vc.log(d);",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
r["log"][0],
|
||||
json!([
|
||||
true, "", true, true, false, false, "keep", false, DENIED, false, DENIED, true, false, ".hid.txt", ".l", true, true, true, false, true,
|
||||
false, true
|
||||
])
|
||||
);
|
||||
let d = PathBuf::from(r["log"][1].as_str().unwrap());
|
||||
assert_eq!(std::fs::read(base.join("main/keep.txt")).unwrap(), b"keep");
|
||||
assert!(std::fs::symlink_metadata(d.join("l")).is_err() && std::fs::symlink_metadata(d.join(".l")).is_err());
|
||||
let written: Vec<&str> = r["written"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
assert!(written.contains(&d.join("l").to_string_lossy().as_ref()), "{written:?}");
|
||||
std::fs::remove_file(d.join("h")).unwrap();
|
||||
std::os::unix::fs::symlink(base.join("secret.txt"), d.join("h")).unwrap();
|
||||
let r = run_in(&mut s, &base, "var h = new File(Folder.userData.fsName + '/h'); vc.log([h.open('r'), h.error, h.alias, h.resolve()]);").unwrap();
|
||||
assert_eq!(r["log"], json!([[false, DENIED, false, null]]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `createAlias` makes nothing where the script may only read or may not go at all, at a name in use
|
||||
/// (a link that leads nowhere included), to a folder, to a file outside its places, in the settings
|
||||
/// folder or behind a link that leads out, to a file that is not there, or without a target.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn script_file_create_alias_is_refused_outside_the_scripts_places() {
|
||||
let base = folder("aliasdenied");
|
||||
write(&base.join("main/keep.txt"), b"keep");
|
||||
write(&base.join("secret.txt"), b"secret");
|
||||
write(&base.join("main/settings/Script Grants.json"), b"{\"version\": 1, \"grants\": []}");
|
||||
std::fs::create_dir_all(base.join("main/sub")).unwrap();
|
||||
std::fs::create_dir_all(base.join("elsewhere")).unwrap();
|
||||
std::os::unix::fs::symlink(base.join("secret.txt"), base.join("main/out.txt")).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.attach_script_data(base.join("main/settings/Script Data"));
|
||||
let d = PathBuf::from(run_in(&mut s, &base, "vc.log(Folder.userData.fsName);").unwrap()["log"][0].as_str().unwrap());
|
||||
write(&d.join("taken"), b"t");
|
||||
std::os::unix::fs::symlink(base.join("nowhere"), d.join("dangling")).unwrap();
|
||||
let text = format!(
|
||||
"var d = Folder.userData.fsName, out = [];\n\
|
||||
function a(at, to) {{ var f = new File(at); out.push(f.createAlias(to), f.error); }}\n\
|
||||
a('own', 'keep.txt'); a(d + '/taken', 'keep.txt'); a(d + '/dangling', 'keep.txt'); a(d + '/dir', 'sub');\n\
|
||||
a(d + '/s', {:?}); a(d + '/g', 'settings/Script Grants.json'); a(d + '/o', 'out.txt'); a(d + '/n'); a(d + '/m', 'missing.txt');\n\
|
||||
a({:?}, 'keep.txt'); vc.log(out);",
|
||||
base.join("secret.txt").to_string_lossy(),
|
||||
base.join("elsewhere/x").to_string_lossy()
|
||||
);
|
||||
let r = run_in(&mut s, &base, &text).unwrap();
|
||||
assert_eq!(
|
||||
r["log"],
|
||||
json!([[
|
||||
false,
|
||||
DENIED,
|
||||
false,
|
||||
TAKEN,
|
||||
false,
|
||||
TAKEN,
|
||||
false,
|
||||
NOT_REGULAR,
|
||||
false,
|
||||
DENIED,
|
||||
false,
|
||||
DENIED,
|
||||
false,
|
||||
DENIED,
|
||||
false,
|
||||
NOT_FOUND,
|
||||
false,
|
||||
NOT_FOUND,
|
||||
false,
|
||||
DENIED
|
||||
]])
|
||||
);
|
||||
assert!(std::fs::symlink_metadata(base.join("main/own")).is_err());
|
||||
assert_eq!(std::fs::read_dir(base.join("elsewhere")).unwrap().count(), 0);
|
||||
for name in ["dir", "s", "g", "o", "n", "m"] {
|
||||
assert!(std::fs::symlink_metadata(d.join(name)).is_err(), "{name}");
|
||||
}
|
||||
assert_eq!(std::fs::read(d.join("taken")).unwrap(), b"t");
|
||||
assert_eq!(std::fs::read_link(d.join("dangling")).unwrap(), base.join("nowhere"));
|
||||
assert_eq!(r["written"], json!([]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A link put in place of the folder an alias goes in, after the alias's place was looked up, does
|
||||
/// not leave a new link where it leads.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn script_file_alias_is_not_left_behind_a_folder_replaced_by_a_link() {
|
||||
let base = folder("aliasrace");
|
||||
write(&base.join("main/keep.txt"), b"keep");
|
||||
let outside = base.join("outside");
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
let mut s = with_data(&base);
|
||||
let to = outside.clone();
|
||||
crate::script::files::BEFORE_ALIAS_LINK.with(|h| {
|
||||
*h.borrow_mut() = Some(Box::new(move |at: &Path| {
|
||||
let sub = at.parent().unwrap();
|
||||
std::fs::rename(sub, sub.with_file_name("moved")).unwrap();
|
||||
std::os::unix::fs::symlink(&to, sub).unwrap();
|
||||
}));
|
||||
});
|
||||
let r = run_in(
|
||||
&mut s,
|
||||
&base,
|
||||
"var d = Folder.userData.fsName; new Folder(d + '/sub').create(); var l = new File(d + '/sub/l'); vc.log([l.createAlias('keep.txt'), l.error]);",
|
||||
);
|
||||
crate::script::files::BEFORE_ALIAS_LINK.with(|h| h.borrow_mut().take());
|
||||
assert_eq!(r.unwrap()["log"], json!([[false, DENIED]]));
|
||||
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0, "no link is left outside the script's places");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Where a hidden file is not one whose name starts with a dot, setting `hidden` and `createAlias`
|
||||
/// set `error` and change nothing.
|
||||
#[cfg(not(unix))]
|
||||
#[test]
|
||||
fn script_file_hidden_and_aliases_are_refused_off_unix() {
|
||||
let base = folder("hiddenoff");
|
||||
write(&base.join("main/keep.txt"), b"keep");
|
||||
let mut s = with_data(&base);
|
||||
let r = run_in(
|
||||
&mut s,
|
||||
&base,
|
||||
"var d = Folder.userData.fsName, u = new File(d + '/u.txt'); u.open('w'); u.close(); u.hidden = true; var out = [u.error, u.name];\n\
|
||||
var l = new File(d + '/l'); out.push(l.createAlias('keep.txt'), l.error, l.exists); vc.log(out);",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r["log"], json!([["Script file hidden setting cannot be changed", "u.txt", false, "Script files cannot make aliases", false]]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The open modes, the encodings that cannot hold a character, `copy` over a file, `remove` of a
|
||||
/// folder only when it is empty, `rename` refusing a name in use, `create`, and setting `length` and
|
||||
/// `readonly`.
|
||||
@@ -1213,6 +1459,35 @@ fn script_file_rename_does_not_move_the_settings_folder() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// In a folder granted in a file dialog, a file is not renamed to the name of the settings folder,
|
||||
/// and on Unix setting `hidden` does not give it that name either.
|
||||
#[test]
|
||||
fn script_file_rename_does_not_take_the_settings_folders_name() {
|
||||
let base = folder("renamein");
|
||||
write(&base.join("cfg"), b"c");
|
||||
write(&base.join("x.txt"), b"x");
|
||||
let mut s = Session::new();
|
||||
s.attach_script_data(base.join(".cfg/Script Data"));
|
||||
let hide =
|
||||
if cfg!(unix) { "var h = new File(p.fsName + '/cfg'); h.hidden = true; out.push(h.error, h.name);" } else { "out.push(DENIED, 'cfg');" };
|
||||
let denied = format!("var DENIED = {DENIED:?};");
|
||||
start_framed(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"{denied} var p = Folder.selectDialog('p'), x = new File(p.fsName + '/x.txt'), out = [x.rename('.cfg'), x.error, x.name]; {hide} vc.log(out);"
|
||||
),
|
||||
);
|
||||
assert!(pump_to_picker(&mut s).is_none());
|
||||
assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![base.to_string_lossy().into_owned()], always: false }));
|
||||
let r = pump_to_picker(&mut s).unwrap().unwrap();
|
||||
assert_eq!(r["log"], json!([[false, DENIED, "x.txt", DENIED, "cfg"]]));
|
||||
assert!(!base.join(".cfg").is_file());
|
||||
assert_eq!(std::fs::read(base.join("x.txt")).unwrap(), b"x");
|
||||
assert_eq!(std::fs::read(base.join("cfg")).unwrap(), b"c");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Where case does not matter, a folder named in another case is still the folder that holds the
|
||||
/// settings folder, or the settings folder itself: it is not renamed or removed.
|
||||
#[cfg(any(windows, target_os = "macos"))]
|
||||
|
||||
@@ -122,34 +122,87 @@ fn separate_runs_on_one_path_simplify_independently_in_one_step() {
|
||||
assert_eq!(s.doc().unwrap().selection.anchors.get(&id), Some(&sel));
|
||||
}
|
||||
|
||||
/// The points of a closed 80-gon of radius 100 round (300, 300), starting at (400, 300).
|
||||
fn eighty_gon() -> Vec<(f64, f64)> {
|
||||
(0..80).map(|i| (f64::from(i) * std::f64::consts::TAU / 80.0).sin_cos()).map(|(y, x)| (300.0 + 100.0 * x, 300.0 + 100.0 * y)).collect()
|
||||
}
|
||||
|
||||
/// On a closed 80-gon, a run from anchor 70 through the start point to anchor 10 simplifies as one
|
||||
/// run: anchor 0 goes, anchors 11–69 stay exactly as they were (the path now starts at anchor 10),
|
||||
/// anchors 10 and 70 stay where they were with their outer handles, and the path stays closed.
|
||||
/// run: anchor 0 goes, and the path starts at a new anchor where the refitted run passes nearest
|
||||
/// it; anchors 11–69 stay exactly as they were, anchors 10 and 70 stay where they were with their
|
||||
/// outer handles, the path stays closed, and the refitted run stays direct-selected.
|
||||
#[test]
|
||||
fn a_run_across_the_start_of_a_closed_path_simplifies_as_one() {
|
||||
let mut s = session();
|
||||
let pts: Vec<(f64, f64)> =
|
||||
(0..80).map(|i| (f64::from(i) * std::f64::consts::TAU / 80.0).sin_cos()).map(|(y, x)| (300.0 + 100.0 * x, 300.0 + 100.0 * y)).collect();
|
||||
let id = polyline(&mut s, &pts, true);
|
||||
let id = polyline(&mut s, &eighty_gon(), true);
|
||||
let original = path_of(&s, id).subpaths[0].clone();
|
||||
select_anchors(&mut s, id, &[(70, 79), (0, 10)]);
|
||||
s.execute("object.path.simplify", &json!({"tolerance": 1})).unwrap();
|
||||
let sp = path_of(&s, id).subpaths[0].clone();
|
||||
assert!(sp.closed);
|
||||
assert!(sp.anchors.len() < 80 - 10, "{}", sp.anchors.len());
|
||||
assert!(!sp.anchors.iter().any(|a| a.p == original.anchors[0].p), "anchor 0 was inside the run");
|
||||
assert_eq!(sp.anchors.to_vec()[1..60], original.anchors.to_vec()[11..70]);
|
||||
assert_eq!((sp.anchors[0].p, sp.anchors[0].h_out), (original.anchors[10].p, original.anchors[10].h_out));
|
||||
assert_eq!((sp.anchors[60].p, sp.anchors[60].h_in), (original.anchors[70].p, original.anchors[70].h_in));
|
||||
for i in 0..60 {
|
||||
assert_eq!(sp.segment(i), original.segment(10 + i));
|
||||
}
|
||||
let moved = sp.anchors[0].p.distance(original.anchors[0].p);
|
||||
assert!(moved <= 1.0 + 1e-9, "the start moved {moved} pt");
|
||||
let n = sp.anchors.len();
|
||||
assert!(worst_offset(&original, (70..80).chain(0..10), &sp, 60..n) <= 1.0 + 1e-6);
|
||||
let sel: BTreeSet<_> = std::iter::once((0, 0)).chain((60..n).map(|i| (0, i))).collect();
|
||||
let k = sp.anchors.iter().position(|a| a.p == original.anchors[10].p).unwrap();
|
||||
let mut turned = sp.clone();
|
||||
turned.anchors.rotate_left(k);
|
||||
assert_eq!(turned.anchors.to_vec()[1..60], original.anchors.to_vec()[11..70]);
|
||||
assert_eq!((turned.anchors[0].p, turned.anchors[0].h_out), (original.anchors[10].p, original.anchors[10].h_out));
|
||||
assert_eq!((turned.anchors[60].p, turned.anchors[60].h_in), (original.anchors[70].p, original.anchors[70].h_in));
|
||||
for i in 0..60 {
|
||||
assert_eq!(turned.segment(i), original.segment(10 + i));
|
||||
}
|
||||
assert!(worst_offset(&original, (70..80).chain(0..10), &turned, 60..n) <= 1.0 + 1e-6);
|
||||
let sel: BTreeSet<_> = (0..=k).chain(k + 60..n).map(|i| (0, i)).collect();
|
||||
assert_eq!(s.doc().unwrap().selection.anchors.get(&id), Some(&sel));
|
||||
}
|
||||
|
||||
/// Smooth of a direct-selected run across the start of a closed 80-gon starts the path near where it
|
||||
/// started too, with fewer anchors.
|
||||
#[test]
|
||||
fn smoothing_a_run_across_the_start_keeps_the_start() {
|
||||
let mut s = session();
|
||||
let id = polyline(&mut s, &eighty_gon(), true);
|
||||
let original = path_of(&s, id).subpaths[0].clone();
|
||||
select_anchors(&mut s, id, &[(70, 79), (0, 10)]);
|
||||
s.execute("object.path.smooth", &json!({"level": 50})).unwrap();
|
||||
let sp = path_of(&s, id).subpaths[0].clone();
|
||||
assert!(sp.closed && sp.anchors.len() < 80, "{}", sp.anchors.len());
|
||||
let moved = sp.anchors[0].p.distance(original.anchors[0].p);
|
||||
assert!(moved <= 5.0, "the start moved {moved} pt, to {:?}", sp.anchors[0].p);
|
||||
}
|
||||
|
||||
/// A dashed closed path keeps its start, where its dashes begin, through Simplify and through
|
||||
/// Smooth: a loop of radius 50 round (300, 300) with a needle out to (550, 300), starting on the far
|
||||
/// side of the loop at (250, 300). Its stroke stays as it was, and each command is one undo step.
|
||||
#[test]
|
||||
fn a_dashed_closed_path_keeps_its_start_through_simplify_and_smooth() {
|
||||
let mut s = session();
|
||||
let at = |deg: f64| (300.0 + 50.0 * deg.to_radians().cos(), 300.0 + 50.0 * deg.to_radians().sin());
|
||||
let pts: Vec<(f64, f64)> =
|
||||
(0..=20).map(|i| at(180.0 + 8.95 * f64::from(i))).chain([(550.0, 300.0)]).chain((0..20).map(|i| at(1.0 + 8.95 * f64::from(i)))).collect();
|
||||
let id = polyline(&mut s, &pts, true);
|
||||
s.execute("stroke.set", &json!({"ids": [id.0], "weight": 2, "dash": [10, 5]})).unwrap();
|
||||
let stroke = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().appearance.clone();
|
||||
let style = stroke(&s);
|
||||
let original = path_of(&s, id).subpaths[0].clone();
|
||||
// (command, params, how far the start may move: Simplify's tolerance, or Smooth's smoothing and tolerance)
|
||||
let commands = [("object.path.simplify", json!({"tolerance": 1}), 1.0 + 1e-9), ("object.path.smooth", json!({"level": 50}), 5.0)];
|
||||
for (command, params, limit) in commands {
|
||||
let steps = undo_len(&s);
|
||||
s.execute(command, ¶ms).unwrap();
|
||||
assert_eq!(undo_len(&s), steps + 1, "{command}");
|
||||
let sp = path_of(&s, id).subpaths[0].clone();
|
||||
assert!(sp.closed && sp.anchors.len() < original.anchors.len(), "{command}: {}", sp.anchors.len());
|
||||
let moved = sp.anchors[0].p.distance(original.anchors[0].p);
|
||||
assert!(moved <= limit, "{command}: the start moved {moved} pt, to {:?}", sp.anchors[0].p);
|
||||
assert_eq!(stroke(&s), style, "{command}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(path_of(&s, id).subpaths[0], original, "{command}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Segments picked with the Direct Selection tool simplify the same way, and stay picked as
|
||||
/// segments.
|
||||
#[test]
|
||||
|
||||
@@ -516,6 +516,978 @@ fn a_library_pattern_keeps_its_global_color_when_the_document_has_that_name_in_a
|
||||
assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Tiles"])), "{again}");
|
||||
}
|
||||
|
||||
/// A library with pattern swatch `Tiles`, whose pattern `Squares` is filled with global color
|
||||
/// `Ink` (#0000ff), loaded into `s`, which is then left in a new document whose own global `Ink`
|
||||
/// is #ff0000 → the library's id. The library document's square painted with `Tiles` is on the
|
||||
/// clipboard.
|
||||
fn squares_library_and_a_red_ink(s: &mut Session) -> Value {
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_doc::pattern::pattern_paint;
|
||||
run(s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
s.edit("Pattern", |d, _| {
|
||||
let ink = Paint::Solid { color: Color::rgb8(0, 0, 0xff), swatch: Some("Ink".into()), tint: 1.0 };
|
||||
let square = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 6.0, 6.0));
|
||||
let square = vectorcraft_doc::Node::path(d.alloc_id(), square, vectorcraft_doc::Appearance::basic(ink, Paint::None, 0.0));
|
||||
let tile = vectorcraft_geom::Rect::new(0.0, 0.0, 8.0, 8.0);
|
||||
d.patterns.push(vectorcraft_doc::PatternDef { tile, ..vectorcraft_doc::PatternDef::new("Squares", vec![Arc::new(square)]) });
|
||||
d.swatches.push(vectorcraft_color::Swatch { name: "Tiles".into(), paint: pattern_paint("Squares"), global: false, spot: false });
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let b64 = run(s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone();
|
||||
let r = run(s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone();
|
||||
run(s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]}));
|
||||
run(s, "select.set", json!({"ids": [r]}));
|
||||
run(s, "edit.copy", json!({}));
|
||||
run(s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
id
|
||||
}
|
||||
|
||||
/// The names of the swatches of `s`'s document that are `base` or a numbered copy of it.
|
||||
fn named_after(s: &Session, base: &str) -> Vec<String> {
|
||||
let copy = |n: &str| n == base || n.strip_prefix(base).and_then(|r| r.strip_prefix(' ')).is_some_and(|r| r.bytes().all(|b| b.is_ascii_digit()));
|
||||
doc(s).swatches_iter().filter(|w| copy(&w.name)).map(|w| w.name.clone()).collect()
|
||||
}
|
||||
|
||||
/// A library color that the document has as a numbered copy of the same color ("Ink 2", brought by
|
||||
/// the pattern added with it before) is that copy: adding the pattern and the color again adds
|
||||
/// nothing.
|
||||
#[test]
|
||||
fn adding_a_library_pattern_and_its_color_again_reuses_the_numbered_color() {
|
||||
let mut s = session();
|
||||
let id = squares_library_and_a_red_ink(&mut s);
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink"]}));
|
||||
assert_eq!(r["added"], json!(["Tiles", "Ink 2"]), "{r}");
|
||||
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink"]}));
|
||||
assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Tiles", "Ink 2"])), "{again}");
|
||||
assert_eq!(named_after(&s, "Ink"), ["Ink", "Ink 2"]);
|
||||
}
|
||||
|
||||
/// The colors a library pattern brings with its art are listed with the swatches added, the
|
||||
/// numbered ones included, when the call adds the pattern swatch alone.
|
||||
#[test]
|
||||
fn the_colors_a_library_pattern_brings_are_listed_as_added() {
|
||||
let mut s = session();
|
||||
let id = squares_library_and_a_red_ink(&mut s);
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
|
||||
assert_eq!(named_after(&s, "Ink"), ["Ink", "Ink 2"]);
|
||||
assert_eq!(r["added"], json!(["Tiles", "Ink 2"]), "{r}");
|
||||
}
|
||||
|
||||
/// A library pattern that is already in the document with its art linked to the document's own
|
||||
/// color of that name (as pasting with Merge leaves it) is that pattern: adding its swatch adds no
|
||||
/// numbered copy of the pattern or of the color.
|
||||
#[test]
|
||||
fn a_library_pattern_linked_to_the_documents_own_color_is_not_added_again() {
|
||||
let mut s = session();
|
||||
let id = squares_library_and_a_red_ink(&mut s);
|
||||
run(&mut s, "edit.paste", json!({"swatchConflict": "merge"}));
|
||||
assert_eq!(doc(&s).patterns.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), ["Squares"]);
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
|
||||
assert_eq!(doc(&s).patterns.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), ["Squares"], "{r}");
|
||||
assert_eq!(named_after(&s, "Ink"), ["Ink"], "{r}");
|
||||
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
|
||||
assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Tiles"])), "{again}");
|
||||
}
|
||||
|
||||
/// With `apply`, the color picked first is the one applied, even when a pattern added in the same
|
||||
/// call brings a numbered copy of its name.
|
||||
#[test]
|
||||
fn apply_paints_with_the_picked_color_not_one_a_pattern_brought() {
|
||||
let mut s = session();
|
||||
let id = squares_library_and_a_red_ink(&mut s);
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
// The document's Ink is the library's color as a process color.
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff"}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Tiles"], "apply": "fill"}));
|
||||
assert_eq!(named_after(&s, "Ink"), ["Ink", "Ink 2"], "{r}");
|
||||
// The picked global color is not the process one: it comes in numbered, and the pattern's art
|
||||
// takes it.
|
||||
assert_eq!(r["applied"], "Ink 2", "{r}");
|
||||
assert!(is_global(&s, "Ink 2", "#0000ff"), "{r}");
|
||||
// A picked color the document already has is applied, not the pattern added after it.
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Tiles"], "apply": "fill"}));
|
||||
assert_eq!((&r["existing"], &r["applied"]), (&json!(["Ink"]), &json!("Ink")), "{r}");
|
||||
}
|
||||
|
||||
/// A numbered copy that another swatch of the same name hides (the document finds the first of a
|
||||
/// name) is not taken for a library color, even when it has that color.
|
||||
#[test]
|
||||
fn a_hidden_numbered_copy_is_not_taken_for_a_library_color() {
|
||||
let mut s = session();
|
||||
let id = squares_library_and_a_red_ink(&mut s);
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.newGroup", json!({"name": "Blues", "swatches": ["Ink 2"]}));
|
||||
s.edit("Green", |d, _| {
|
||||
let green = Paint::Solid { color: Color::rgb8(0, 0xff, 0), swatch: None, tint: 1.0 };
|
||||
d.swatches.push(vectorcraft_color::Swatch { name: "Ink 2".into(), paint: green, global: true, spot: false });
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink"]}));
|
||||
assert_eq!(r["existing"], json!([]), "{r}");
|
||||
let name = r["added"][0].as_str().unwrap_or_default().to_string();
|
||||
let blue = doc(&s).swatch(&name).and_then(|w| w.paint.color()).map(|c| c.to_hex());
|
||||
assert_eq!(blue.as_deref(), Some("#0000ff"), "{r}");
|
||||
}
|
||||
|
||||
/// The global color the swatch `name` of `s`'s document is a tint of.
|
||||
fn tint_base(s: &Session, name: &str) -> Option<String> {
|
||||
match doc(s).swatch(name).map(|w| &w.paint) {
|
||||
Some(Paint::Solid { swatch, .. }) => swatch.clone(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A library with global color `Ink` (#0000ff) and its tint `Ink half` loaded into `s`, which is
|
||||
/// then left in a new document whose own global `Ink` is #ff0000 → the library's id.
|
||||
fn tinted_ink_library_and_a_red_ink(s: &mut Session) -> Value {
|
||||
run(s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
|
||||
let b64 = run(s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone();
|
||||
run(s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
id
|
||||
}
|
||||
|
||||
/// A library tint added with its global color, which comes in under a numbered name, is a tint of
|
||||
/// that numbered color, not of the document's own color of the library color's name.
|
||||
#[test]
|
||||
fn a_library_tint_follows_its_color_to_its_numbered_name() {
|
||||
let mut s = session();
|
||||
let id = tinted_ink_library_and_a_red_ink(&mut s);
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink half"]}));
|
||||
assert_eq!(r["added"], json!(["Ink 2", "Ink half"]), "{r}");
|
||||
assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{r}");
|
||||
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink half"]}));
|
||||
assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Ink 2", "Ink half"])), "{again}");
|
||||
}
|
||||
|
||||
/// A library tint picked before its global color still follows the color to its numbered name.
|
||||
#[test]
|
||||
fn a_library_tint_picked_before_its_color_follows_it_to_its_numbered_name() {
|
||||
let mut s = session();
|
||||
let id = tinted_ink_library_and_a_red_ink(&mut s);
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half", "Ink"]}));
|
||||
assert_eq!(r["added"], json!(["Ink half", "Ink 2"]), "{r}");
|
||||
assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{r}");
|
||||
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half", "Ink"]}));
|
||||
assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Ink half", "Ink 2"])), "{again}");
|
||||
}
|
||||
|
||||
/// A library tint added without its global color finds the numbered copy an earlier add brought.
|
||||
#[test]
|
||||
fn a_library_tint_added_alone_finds_its_colors_numbered_copy() {
|
||||
let mut s = session();
|
||||
let id = tinted_ink_library_and_a_red_ink(&mut s);
|
||||
run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink"]}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]}));
|
||||
assert_eq!(r["added"], json!(["Ink half"]), "{r}");
|
||||
assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{r}");
|
||||
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]}));
|
||||
assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Ink half"])), "{again}");
|
||||
}
|
||||
|
||||
/// A library tint added alone links to the numbered copy of its own color, not to another library
|
||||
/// color's copy of the same paint.
|
||||
#[test]
|
||||
fn a_library_tint_added_alone_skips_another_library_colors_copy() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink 2"]}));
|
||||
assert_eq!(r["added"], json!(["Ink 3"]), "{r}");
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]}));
|
||||
assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 3"), "{r}");
|
||||
}
|
||||
|
||||
/// A library tint added alone finds its color's numbered copy when a color group of the document
|
||||
/// has the color's name.
|
||||
#[test]
|
||||
fn a_library_tint_finds_its_colors_copy_beside_a_group_of_its_name() {
|
||||
let mut s = session();
|
||||
let id = tinted_ink_library_and_a_red_ink(&mut s);
|
||||
run(&mut s, "swatch.delete", json!({"names": ["Ink"]}));
|
||||
run(&mut s, "swatch.newGroup", json!({"name": "Ink", "colors": ["#123456"]}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink"]}));
|
||||
assert_eq!(r["added"], json!(["Ink 2"]), "{r}");
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]}));
|
||||
assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{r}");
|
||||
}
|
||||
|
||||
/// A library pattern whose art uses a tint of a library color added earlier in the same call
|
||||
/// does not bring a second copy of that tint, also when the call does not pick the color.
|
||||
#[test]
|
||||
fn a_pattern_after_its_tint_in_one_call_does_not_copy_the_tint() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "tint": 50, "ids": [dot]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Squares", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone();
|
||||
for names in [json!(["Ink", "Ink half", "Squares"]), json!(["Ink half", "Ink", "Squares"]), json!(["Ink half", "Squares"])] {
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names}));
|
||||
assert_eq!(named_after(&s, "Ink half"), ["Ink half"], "{names}: {r}");
|
||||
assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{names}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A library color added under a numbered name skips the names of the library's other swatches,
|
||||
/// so adding it again finds that copy.
|
||||
#[test]
|
||||
fn a_library_colors_copy_skips_the_librarys_other_names() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink"]}));
|
||||
assert_eq!(r["added"], json!(["Ink 3"]), "{r}");
|
||||
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink"]}));
|
||||
assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Ink 3"])), "{again}");
|
||||
}
|
||||
|
||||
/// A library tint links to a global color even when the document has a process color of the same
|
||||
/// name and paint, which the picked library color matches: the pattern's art brings the global one.
|
||||
#[test]
|
||||
fn a_library_tint_links_to_the_global_color_a_pattern_brought() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
for names in [json!(["Ink", "Tiles", "Ink half"]), json!(["Ink", "Ink half", "Tiles"])] {
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff"}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names}));
|
||||
let base = tint_base(&s, "Ink half").unwrap_or_default();
|
||||
assert!(doc(&s).swatch(&base).is_some_and(|w| w.global), "{names}: {r}");
|
||||
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": names}));
|
||||
assert_eq!(named_after(&s, "Ink half"), ["Ink half"], "{names}: {again}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A library tint added with a pattern whose art brought the tint's global color under a numbered
|
||||
/// name is a tint of that numbered color.
|
||||
#[test]
|
||||
fn a_library_tint_follows_the_color_a_pattern_brought() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink half"]}));
|
||||
assert!(r["added"].as_array().is_some_and(|a| a.contains(&json!("Ink 2"))), "{r}");
|
||||
assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{r}");
|
||||
}
|
||||
|
||||
/// A numbered copy of a color's name that the library also has as a swatch of its own stands for
|
||||
/// that swatch alone, even when both library swatches have its color.
|
||||
#[test]
|
||||
fn a_numbered_copy_the_library_also_names_is_not_shared() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink 2"]}));
|
||||
assert_eq!((&r["added"], &r["existing"]), (&json!(["Ink 3"]), &json!(["Ink 2"])), "{r}");
|
||||
}
|
||||
|
||||
/// A tint of the document whose global color was deleted without unlinking it is the library's
|
||||
/// tint only with that color: adding the tint brings the color back under its name, listed as
|
||||
/// added, and the tint links to it again.
|
||||
#[test]
|
||||
fn a_library_tint_whose_color_the_document_deleted_brings_the_color_back() {
|
||||
let mut s = session();
|
||||
let id = tinted_ink_library_and_a_red_ink(&mut s);
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
|
||||
run(&mut s, "swatch.delete", json!({"names": ["Ink"], "unlink": false}));
|
||||
assert!(doc(&s).swatch("Ink").is_none());
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]}));
|
||||
assert_eq!((&r["added"], &r["existing"]), (&json!(["Ink"]), &json!(["Ink half"])), "{r}");
|
||||
assert!(is_global(&s, "Ink", "#0000ff"), "{r}");
|
||||
assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink"), "{r}");
|
||||
assert_eq!(named_after(&s, "Ink half"), ["Ink half"], "{r}");
|
||||
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]}));
|
||||
assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Ink half"])), "{again}");
|
||||
}
|
||||
|
||||
/// A numbered tint of the document whose global color was deleted without unlinking it is the
|
||||
/// library's tint only with that color: adding the tint brings the color back under its name.
|
||||
#[test]
|
||||
fn a_numbered_tint_whose_color_the_document_deleted_brings_the_color_back() {
|
||||
let mut s = session();
|
||||
let id = tinted_ink_library_and_a_red_ink(&mut s);
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink half", "color": "#00ff00"}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink half 2", "swatch": "Ink", "tint": 50}));
|
||||
run(&mut s, "swatch.delete", json!({"names": ["Ink"], "unlink": false}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]}));
|
||||
assert_eq!((&r["added"], &r["existing"]), (&json!(["Ink"]), &json!(["Ink half 2"])), "{r}");
|
||||
assert!(is_global(&s, "Ink", "#0000ff"), "{r}");
|
||||
assert_eq!(tint_base(&s, "Ink half 2").as_deref(), Some("Ink"), "{r}");
|
||||
}
|
||||
|
||||
/// A deleted color that a document tint found here links to keeps its name when the call also
|
||||
/// picks it, so a pattern added earlier in the call whose art brings another color of a taken
|
||||
/// name does not take that name first.
|
||||
#[test]
|
||||
fn a_deleted_color_a_found_tint_links_to_keeps_its_name_beside_a_pattern() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#00ff00", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2 half", "swatch": "Ink 2", "tint": 50}));
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2 half", "swatch": "Ink 2", "tint": 50}));
|
||||
run(&mut s, "swatch.delete", json!({"names": ["Ink 2"], "unlink": false}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink 2 half", "Ink 2"]}));
|
||||
assert!(r["existing"].as_array().is_some_and(|a| a.contains(&json!("Ink 2 half"))), "{r}");
|
||||
assert_eq!(tint_base(&s, "Ink 2 half").as_deref(), Some("Ink 2"), "{r}");
|
||||
assert!(is_global(&s, "Ink 2", "#0000ff"), "{r}");
|
||||
let fill = doc(&s).pattern("Tiles").unwrap().art[0].appearance.fill_paint();
|
||||
let Paint::Solid { swatch, .. } = &fill else { panic!("the tile is filled with a color: {fill:?}") };
|
||||
let green = swatch.clone().unwrap_or_default();
|
||||
assert!(is_global(&s, &green, "#00ff00"), "{r}");
|
||||
}
|
||||
|
||||
/// A library tint added with a pattern whose art took a numbered copy that the library also names
|
||||
/// is found again on the next add: the tint links to the copy the art took, and adding the pattern
|
||||
/// and the tint again adds nothing.
|
||||
#[test]
|
||||
fn a_library_tint_linked_to_the_copy_a_pattern_took_is_found_again() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink half"]}));
|
||||
let base = tint_base(&s, "Ink half").unwrap_or_default();
|
||||
assert!(is_global(&s, &base, "#0000ff"), "{r}");
|
||||
// The pattern's art and the tint link to the same color.
|
||||
let fill = doc(&s).pattern("Tiles").unwrap().art[0].appearance.fill_paint();
|
||||
let Paint::Solid { swatch, .. } = &fill else { panic!("the tile is filled with a color: {fill:?}") };
|
||||
assert_eq!(swatch.as_deref(), Some(base.as_str()), "{r}");
|
||||
let swatches = doc(&s).swatches_iter().count();
|
||||
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink half"]}));
|
||||
assert_eq!(again["added"], json!([]), "{again}");
|
||||
assert_eq!(doc(&s).swatches_iter().count(), swatches, "{again}");
|
||||
assert_eq!(named_after(&s, "Ink half"), ["Ink half"], "{again}");
|
||||
assert_eq!(tint_base(&s, "Ink half"), Some(base), "{again}");
|
||||
}
|
||||
|
||||
/// Without a pattern whose art takes it, a numbered copy that the library also names stands for
|
||||
/// that library swatch alone: the document's tint linked to it is not the library's tint of the
|
||||
/// color the copy is numbered after.
|
||||
#[test]
|
||||
fn a_tint_linked_to_a_copy_the_library_names_is_not_another_colors_tint() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink 2", "tint": 50}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]}));
|
||||
assert_eq!(r["existing"], json!([]), "{r}");
|
||||
let added = r["added"][0].as_str().unwrap_or_default().to_string();
|
||||
let base = tint_base(&s, &added).unwrap_or_default();
|
||||
assert!(base != "Ink 2" && is_global(&s, &base, "#0000ff"), "{r}");
|
||||
}
|
||||
|
||||
/// A numbered copy of a color's name that the library also has as a swatch of another color is
|
||||
/// still the copy of the color: adding the color to a document that has such a copy (as a pattern
|
||||
/// added by an earlier version left it) adds no other copy.
|
||||
#[test]
|
||||
fn a_numbered_copy_named_like_another_library_color_is_found() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink"]}));
|
||||
assert_eq!((&r["added"], &r["existing"]), (&json!([]), &json!(["Ink 2"])), "{r}");
|
||||
}
|
||||
|
||||
/// A library tint picked before its global color links to the color under the name it comes in
|
||||
/// with, not to a numbered copy of the same color when the document has none of the color's name.
|
||||
#[test]
|
||||
fn a_library_tint_links_to_its_color_under_the_name_it_comes_in_with() {
|
||||
let mut s = session();
|
||||
let id = tinted_ink_library_and_a_red_ink(&mut s);
|
||||
run(&mut s, "swatch.delete", json!({"names": ["Ink"]}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
|
||||
for names in [json!(["Ink half", "Ink"]), json!(["Ink", "Ink half"])] {
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names}));
|
||||
assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink"), "{names}: {r}");
|
||||
run(&mut s, "swatch.delete", json!({"names": ["Ink half", "Ink"]}));
|
||||
}
|
||||
}
|
||||
|
||||
/// A library tint of a spot color links to the spot color a pattern's art brought, not to the
|
||||
/// document's global process color of the same name and paint.
|
||||
#[test]
|
||||
fn a_library_spot_tint_links_to_the_spot_color_not_a_process_one() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "spot": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
for names in [json!(["Ink", "Tiles", "Ink half"]), json!(["Ink half", "Tiles"])] {
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names}));
|
||||
let base = tint_base(&s, "Ink half").unwrap_or_default();
|
||||
assert!(doc(&s).swatch(&base).is_some_and(|w| w.spot), "{names}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The library's process color of a numbered name is not the document's global color of that name
|
||||
/// and paint, so that global color is the numbered copy of the library's global color it is named
|
||||
/// after.
|
||||
#[test]
|
||||
fn a_numbered_process_color_of_the_library_is_not_the_documents_global_copy() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff"}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink 2"]}));
|
||||
assert_eq!((&r["added"], &r["existing"]), (&json!(["Ink 2 2"]), &json!(["Ink 2"])), "{r}");
|
||||
}
|
||||
|
||||
/// A library tint added with a pattern whose art took the document's numbered copy of the tint's
|
||||
/// color is a tint of that copy.
|
||||
#[test]
|
||||
fn a_library_tint_follows_the_numbered_color_a_pattern_took() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
for names in [json!(["Tiles", "Ink half"]), json!(["Ink half", "Tiles"])] {
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names}));
|
||||
assert_eq!(named_after(&s, "Ink"), ["Ink 2"], "{names}: {r}");
|
||||
assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{names}: {r}");
|
||||
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": names}));
|
||||
assert_eq!(named_after(&s, "Ink half"), ["Ink half"], "{names}: {again}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A numbered copy that the library's own tint of that name is, once its color is linked as the
|
||||
/// document has it, is not also taken for the library tint it is numbered after.
|
||||
#[test]
|
||||
fn a_numbered_tint_the_library_has_is_not_shared() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Half", "swatch": "Ink", "tint": 50}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Half 2", "swatch": "Ink", "tint": 50}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Half", "color": "#00ff00"}));
|
||||
run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Half 2"]}));
|
||||
assert_eq!(tint_base(&s, "Half 2").as_deref(), Some("Ink 2"));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Half", "Half 2"]}));
|
||||
assert_eq!(r["existing"], json!(["Half 2"]), "{r}");
|
||||
assert_eq!(r["added"].as_array().map(Vec::len), Some(1), "{r}");
|
||||
}
|
||||
|
||||
/// The document's swatch `name` is a global color showing `hex`.
|
||||
fn is_global(s: &Session, name: &str, hex: &str) -> bool {
|
||||
doc(s).swatch(name).is_some_and(|w| w.global && w.paint.color().is_some_and(|c| c.to_hex() == hex))
|
||||
}
|
||||
|
||||
/// A library inks library (global `Ink` #0000ff and its tint `Ink half`) loaded into `s`, which is
|
||||
/// then left in a new document whose own `Ink` is the same blue as a process color → the id.
|
||||
fn tinted_ink_library_and_a_process_ink(s: &mut Session) -> Value {
|
||||
let id = tinted_ink_library_and_a_red_ink(s);
|
||||
run(s, "swatch.delete", json!({"names": ["Ink"]}));
|
||||
run(s, "swatch.new", json!({"name": "Ink", "color": "#0000ff"}));
|
||||
id
|
||||
}
|
||||
|
||||
/// A library global color is not the document's process color of the same name and paint: it
|
||||
/// comes in numbered, its tint links to it, and adding the two again adds nothing.
|
||||
#[test]
|
||||
fn a_library_tint_of_a_color_the_document_has_as_process_is_added_once() {
|
||||
let mut s = session();
|
||||
let id = tinted_ink_library_and_a_process_ink(&mut s);
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink half"]}));
|
||||
let base = tint_base(&s, "Ink half").unwrap_or_default();
|
||||
assert!(base != "Ink" && is_global(&s, &base, "#0000ff"), "{r}");
|
||||
let before = (named_after(&s, "Ink"), named_after(&s, "Ink half"));
|
||||
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink half"]}));
|
||||
assert_eq!(again["added"], json!([]), "{again}");
|
||||
assert_eq!((named_after(&s, "Ink"), named_after(&s, "Ink half")), before, "{r} then {again}");
|
||||
}
|
||||
|
||||
/// A library tint added without its global color, in a document whose swatch of the color's name
|
||||
/// is another color or a process color, brings its color along and links to it, not to the
|
||||
/// document's swatch; adding the tint again adds nothing.
|
||||
#[test]
|
||||
fn a_library_tint_added_alone_brings_its_color_beside_a_namesake() {
|
||||
for process in [false, true] {
|
||||
let mut s = session();
|
||||
let id = if process { tinted_ink_library_and_a_process_ink(&mut s) } else { tinted_ink_library_and_a_red_ink(&mut s) };
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]}));
|
||||
let base = tint_base(&s, "Ink half").unwrap_or_default();
|
||||
assert!(base != "Ink" && is_global(&s, &base, "#0000ff"), "process {process}: {r}");
|
||||
assert_eq!(r["added"], json!(["Ink half", base]), "process {process}: {r}");
|
||||
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]}));
|
||||
assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Ink half"])), "process {process}: {again}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A library tint of a spot color is not the document's tint of the same name and paint whose
|
||||
/// color is a global process color: adding it alone brings the spot color and a tint of it.
|
||||
#[test]
|
||||
fn a_library_spot_tint_is_not_the_documents_tint_of_a_process_namesake() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "spot": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]}));
|
||||
let tint = r["added"][0].as_str().unwrap_or_default().to_string();
|
||||
let base = tint_base(&s, &tint).unwrap_or_default();
|
||||
assert!(doc(&s).swatch(&base).is_some_and(|w| w.spot), "{r}");
|
||||
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]}));
|
||||
assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!([tint])), "{again}");
|
||||
}
|
||||
|
||||
/// A tint of a process namesake that a pattern's art brings is not taken for a picked library
|
||||
/// tint of a spot color.
|
||||
#[test]
|
||||
fn a_library_spot_tint_is_not_a_process_tint_a_pattern_brought() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "spot": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Ink half", "ids": [dot]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]}));
|
||||
run(&mut s, "select.set", json!({"ids": [r]}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "edit.paste", json!({"swatchConflict": "merge"}));
|
||||
let tints: Vec<String> = doc(&s).swatches_iter().filter(|w| w.name.starts_with("Ink half")).map(|w| w.name.clone()).collect();
|
||||
if !tints.is_empty() {
|
||||
run(&mut s, "swatch.delete", json!({"names": tints}));
|
||||
}
|
||||
run(&mut s, "swatch.delete", json!({"names": ["Tiles"]}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink half"]}));
|
||||
let picked = r["added"].as_array().and_then(|a| a.iter().filter_map(|n| n.as_str()).find(|n| n.starts_with("Ink half"))).unwrap_or_default();
|
||||
let base = tint_base(&s, picked).unwrap_or_default();
|
||||
assert!(doc(&s).swatch(&base).is_some_and(|w| w.spot), "{r}");
|
||||
}
|
||||
|
||||
/// A library tint of a spot color added with a pattern whose art the document holds linked to its
|
||||
/// process color of the spot color's name and paint (as pasting with Merge leaves it) links to a
|
||||
/// spot color, not to that process color, in either pick order.
|
||||
#[test]
|
||||
fn a_library_spot_tint_is_not_linked_to_the_process_color_a_merged_pattern_takes() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "spot": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]}));
|
||||
run(&mut s, "select.set", json!({"ids": [r]}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
for names in [json!(["Ink half", "Tiles"]), json!(["Tiles", "Ink half"])] {
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "edit.paste", json!({"swatchConflict": "merge"}));
|
||||
// The paste merged the spot color into the document's process color of its name.
|
||||
assert_eq!(named_after(&s, "Ink"), ["Ink"], "{names}");
|
||||
assert!(doc(&s).swatch("Ink").is_some_and(|w| w.global && !w.spot), "{names}");
|
||||
run(&mut s, "swatch.delete", json!({"names": ["Tiles"]}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names}));
|
||||
let base = tint_base(&s, "Ink half").unwrap_or_default();
|
||||
assert!(doc(&s).swatch(&base).is_some_and(|w| w.spot), "{names}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A color a library pattern's art brings under a numbered name does not take a name the library
|
||||
/// gives another swatch: adding that swatch next adds it under its own name, and adding the two
|
||||
/// again adds nothing.
|
||||
#[test]
|
||||
fn a_color_a_pattern_brings_skips_the_librarys_numbered_names() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true}));
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
|
||||
let brought =
|
||||
first["added"].as_array().and_then(|a| a.iter().filter_map(|n| n.as_str()).find(|n| n.starts_with("Ink"))).unwrap_or_default().to_string();
|
||||
assert!(brought != "Ink 2" && is_global(&s, &brought, "#0000ff"), "{first}");
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]}));
|
||||
assert_eq!(r["added"], json!(["Ink 2"]), "{r}");
|
||||
assert!(is_global(&s, "Ink 2", "#00ff00"), "{r}");
|
||||
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink", "Ink 2"]}));
|
||||
assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Tiles", brought, "Ink 2"])), "{again}");
|
||||
}
|
||||
|
||||
/// A pattern whose art brings both a color and the library's numbered color of the same name keeps
|
||||
/// the numbered color under its own name, and the other color takes the next free one.
|
||||
#[test]
|
||||
fn a_pattern_bringing_a_color_and_its_numbered_namesake_keeps_the_librarys_name() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true}));
|
||||
let blue = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 3, "height": 6}))["id"].clone();
|
||||
let green = run(&mut s, "shape.rectangle", json!({"x": 3, "y": 0, "width": 3, "height": 6}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [blue]}));
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Ink 2", "ids": [green]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [blue, green]}));
|
||||
run(&mut s, "select.set", json!({"ids": [blue, green]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
|
||||
assert!(is_global(&s, "Ink 2", "#00ff00"), "{r}");
|
||||
assert!(named_after(&s, "Ink").iter().any(|n| n != "Ink" && n != "Ink 2" && is_global(&s, n, "#0000ff")), "{r}");
|
||||
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink", "Ink 2"]}));
|
||||
assert_eq!(again["added"], json!([]), "{again}");
|
||||
}
|
||||
|
||||
/// A library pattern with a numbered name comes in under that name when the document does not use
|
||||
/// it.
|
||||
#[test]
|
||||
fn a_numbered_library_pattern_keeps_its_name() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles 2", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]}));
|
||||
assert!(r["added"].as_array().is_some_and(|a| a.contains(&json!("Tiles 2"))), "{r}");
|
||||
assert!(doc(&s).pattern("Tiles 2").is_some(), "{r}");
|
||||
}
|
||||
|
||||
/// A color a library pattern's art brings does not change art of the document that is still
|
||||
/// linked to a deleted color of a numbered name the library uses.
|
||||
#[test]
|
||||
fn a_color_a_pattern_brings_leaves_links_to_a_deleted_color_alone() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true}));
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#ffff00", "global": true}));
|
||||
let box_id = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Ink 2", "ids": [box_id]}));
|
||||
run(&mut s, "swatch.delete", json!({"names": ["Ink 2"], "unlink": false}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
|
||||
let fill = doc(&s).node(vectorcraft_doc::NodeId(box_id.as_u64().unwrap())).unwrap().appearance.fill_paint();
|
||||
let Paint::Solid { swatch, .. } = &fill else { panic!("the box is filled with a color: {fill:?}") };
|
||||
assert_eq!(swatch.as_deref(), Some("Ink 2"), "{r}");
|
||||
assert!(doc(&s).swatch("Ink 2").is_none(), "{r}");
|
||||
}
|
||||
|
||||
/// A library tint added without its global color to a document that has no swatch of the color's
|
||||
/// name brings the color along under its own name.
|
||||
#[test]
|
||||
fn a_library_tint_added_alone_brings_its_missing_color() {
|
||||
let mut s = session();
|
||||
let id = tinted_ink_library_and_a_red_ink(&mut s);
|
||||
run(&mut s, "swatch.delete", json!({"names": ["Ink"]}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]}));
|
||||
assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink"), "{r}");
|
||||
assert!(is_global(&s, "Ink", "#0000ff"), "{r}");
|
||||
}
|
||||
|
||||
/// A library tint added with a pattern the document already has (pasted with Merge, so it brings
|
||||
/// no colors), through the pattern's own swatch or another library swatch of it, is added once,
|
||||
/// however often the two are added.
|
||||
#[test]
|
||||
fn a_library_tint_with_a_pattern_the_document_has_is_added_once() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Squares", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
s.edit("Dots", |d, _| {
|
||||
let paint = vectorcraft_doc::pattern::pattern_paint("Squares");
|
||||
d.swatches.push(vectorcraft_color::Swatch { name: "Dots".into(), paint, global: false, spot: false });
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone();
|
||||
let r = run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Squares", "ids": [r]}));
|
||||
run(&mut s, "select.set", json!({"ids": [r]}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
run(&mut s, "edit.paste", json!({"swatchConflict": "merge"}));
|
||||
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Squares", "Ink half"]}));
|
||||
let before = named_after(&s, "Ink half");
|
||||
for pattern in ["Squares", "Dots"] {
|
||||
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": [pattern, "Ink half"]}));
|
||||
assert_eq!(named_after(&s, "Ink half"), before, "{pattern}: {first} then {again}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A library gradient whose stops link to a color and to the Registration swatch, picked before or
|
||||
/// after a pattern whose art brings the color under a numbered name, is not added a second time.
|
||||
#[test]
|
||||
fn a_gradient_with_a_registration_stop_before_its_pattern_is_not_copied() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
let fade = json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "swatch": "[Registration]"}]});
|
||||
run(&mut s, "swatch.new", json!({"name": "Fade", "gradient": fade}));
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Fade", "ids": [dot]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Squares", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone();
|
||||
for names in [json!(["Fade", "Squares"]), json!(["Squares", "Fade"])] {
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names}));
|
||||
assert_eq!(named_after(&s, "Fade"), ["Fade"], "{names}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A library tint follows its color when the call picks the color, even when a pattern added
|
||||
/// before it took the document's numbered copy of that color, with the color itself or with the
|
||||
/// tint in its art.
|
||||
#[test]
|
||||
fn a_library_tint_follows_its_picked_color_not_the_copy_a_pattern_took() {
|
||||
for tint in [100, 50] {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "tint": tint, "ids": [dot]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
|
||||
let names = json!(["Tiles", "Ink half", "Ink"]);
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names}));
|
||||
let picked = r["added"].as_array().and_then(|a| a.iter().find(|n| n.as_str().is_some_and(|n| n.starts_with("Ink half"))).cloned());
|
||||
let picked = picked.and_then(|n| n.as_str().map(str::to_string)).unwrap_or_default();
|
||||
assert_eq!(tint_base(&s, &picked).as_deref(), Some("Ink"), "tint {tint}: {r}");
|
||||
let before = named_after(&s, "Ink half");
|
||||
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": names}));
|
||||
assert_eq!(named_after(&s, "Ink half"), before, "tint {tint}: {again}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A library tint is not taken for the tint a pattern brought back in the library color's place
|
||||
/// when that tint shows the document's own color (the pattern's art links to it, as pasting with
|
||||
/// Merge leaves it): it comes in as a tint of the library color's numbered copy.
|
||||
#[test]
|
||||
fn a_library_tint_is_not_the_one_a_merged_pattern_brought() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "tint": 50, "ids": [dot]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Squares", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone();
|
||||
let r = run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Squares", "ids": [r]}));
|
||||
run(&mut s, "select.set", json!({"ids": [r]}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
run(&mut s, "edit.paste", json!({"swatchConflict": "merge"}));
|
||||
assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink"), "the pasted tint follows the document's Ink");
|
||||
run(&mut s, "swatch.delete", json!({"names": ["Ink half"], "unlink": false}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Squares", "Ink", "Ink half"]}));
|
||||
assert_eq!(doc(&s).patterns.len(), 1, "{r}");
|
||||
let tint = r["added"][1].as_str().unwrap_or_default().to_string();
|
||||
assert!(tint.starts_with("Ink half"), "{r}");
|
||||
assert_eq!(tint_base(&s, &tint).as_deref(), Some("Ink 2"), "{r}");
|
||||
}
|
||||
|
||||
/// A library gradient is not taken for the gradient a pattern brought back in its place when that
|
||||
/// gradient's stops show the document's own color.
|
||||
#[test]
|
||||
fn a_library_gradient_is_not_the_one_a_merged_pattern_brought() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
let fade = json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": "#ffffff"}]});
|
||||
run(&mut s, "swatch.new", json!({"name": "Fade", "gradient": fade}));
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Fade", "ids": [dot]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Squares", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone();
|
||||
let r = run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Squares", "ids": [r]}));
|
||||
run(&mut s, "select.set", json!({"ids": [r]}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
run(&mut s, "edit.paste", json!({"swatchConflict": "merge"}));
|
||||
run(&mut s, "swatch.delete", json!({"names": ["Fade"], "unlink": false}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Squares", "Ink", "Fade"]}));
|
||||
assert_eq!(doc(&s).patterns.len(), 1, "{r}");
|
||||
let fade = r["added"][1].as_str().unwrap_or_default().to_string();
|
||||
assert!(fade.starts_with("Fade"), "{r}");
|
||||
let (first, link) = match doc(&s).swatch(&fade).map(|w| &w.paint) {
|
||||
Some(Paint::Gradient(g)) => (g.gradient.stops.first().map(|stop| stop.color), g.gradient.stops.first().and_then(|stop| stop.swatch.clone())),
|
||||
_ => (None, None),
|
||||
};
|
||||
assert_eq!(link.as_deref(), Some("Ink 2"), "the stop links to the library's color: {r}");
|
||||
let blue = match doc(&s).swatch("Ink 2").map(|w| &w.paint) {
|
||||
Some(Paint::Solid { color, .. }) => Some(*color),
|
||||
_ => None,
|
||||
};
|
||||
assert!(blue.is_some() && first == blue, "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swatch_exchange_files_load_add_and_list_as_user_libraries() {
|
||||
let bytes = vectorcraft_testkit::ase::sample();
|
||||
|
||||
@@ -514,3 +514,45 @@ fn another_documents_symbol_is_added_and_placed_in_one_step() {
|
||||
let e = s.execute("symbol.placeFromDocument", &json!({"sourceDocument": source, "name": "Star"})).unwrap_err();
|
||||
assert!(e.to_string().contains("no longer open"), "{e}");
|
||||
}
|
||||
|
||||
/// A symbol dragged onto the canvas, from another document's Symbols panel or from a symbol
|
||||
/// library, is stacked as Place Symbol Instance stacks it: in Draw Behind directly below the
|
||||
/// selected object, or at the bottom of the current layer with nothing selected, in one undo step
|
||||
/// with the symbol it adds. A locked layer refuses it with no edit.
|
||||
#[test]
|
||||
fn dropped_symbols_go_below_the_selection_in_draw_behind() {
|
||||
let mut s = kit();
|
||||
let source = s.doc().unwrap().uid;
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
let rect =
|
||||
|s: &mut Session, x: f64| NodeId(run(s, "shape.rectangle", json!({"x": x, "y": 0, "width": 10, "height": 10}))["id"].as_u64().unwrap());
|
||||
let (a, b) = (rect(&mut s, 0.0), rect(&mut s, 20.0));
|
||||
let layer = doc(&s).layers[0].id;
|
||||
let kids = |s: &Session| doc(s).node(layer).unwrap().children().unwrap().iter().map(|c| c.id).collect::<Vec<_>>();
|
||||
run(&mut s, "view.drawMode", json!({"mode": "behind"}));
|
||||
let drops = [
|
||||
("symbol.placeFromDocument", json!({"sourceDocument": source, "name": "Badge", "x": 30, "y": 40}), "id"),
|
||||
("symbol.addFromLibrary", json!({"library": "basic shapes", "name": "Square", "place": true, "x": 30, "y": 40}), "placed"),
|
||||
];
|
||||
for (cmd, p, key) in &drops {
|
||||
for (picked, at) in [(vec![b], 1), (vec![], 0)] {
|
||||
run(&mut s, "select.set", json!({"ids": picked.iter().map(|i| i.0).collect::<Vec<_>>()}));
|
||||
let before = undo_len(&s);
|
||||
let placed = NodeId(run(&mut s, cmd, p.clone())[*key].as_u64().unwrap());
|
||||
let mut want = vec![a, b];
|
||||
want.insert(at, placed);
|
||||
assert_eq!(kids(&s), want, "{cmd} {picked:?}");
|
||||
assert_eq!(undo_len(&s), before + 1, "{cmd}");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [placed]);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert!(symbols(&s).is_empty(), "{cmd}: the undo takes the added symbol too");
|
||||
}
|
||||
}
|
||||
// A locked layer takes nothing.
|
||||
run(&mut s, "layer.setProps", json!({"id": layer.0, "locked": true}));
|
||||
let before = (undo_len(&s), doc(&s).clone());
|
||||
for (cmd, p, _) in &drops {
|
||||
assert!(s.execute(cmd, p).is_err(), "{cmd}");
|
||||
assert_eq!((undo_len(&s), doc(&s)), (before.0, &before.1), "{cmd}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -671,6 +671,48 @@ fn character_ruby_and_path_handle_refuse_a_param_of_the_wrong_type() {
|
||||
s.execute("text.setPathHandle", &handle(Value::Null)).unwrap();
|
||||
}
|
||||
|
||||
/// Range edits, Set Text, area and on-path type and the glyph commands refuse a param of the wrong
|
||||
/// type with an error naming the param, and leave the document and the undo history as they were:
|
||||
/// text that is not a string, a byte offset that is fractional or negative, and a point that is not
|
||||
/// two numbers. Null counts as a param left out, which keeps its default.
|
||||
#[test]
|
||||
fn text_edits_refuse_a_param_of_the_wrong_type() {
|
||||
use crate::tests::not_refused;
|
||||
let mut s = session();
|
||||
let id = text(&mut s, "abc");
|
||||
let frame = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 100, "height": 50})).unwrap()["id"].clone();
|
||||
let line = s.execute("path.create", &json!({"anchors": [{"x": 100, "y": 400}, {"x": 400, "y": 400}]})).unwrap()["id"].clone();
|
||||
let string = |k: &str| format!("`{k}` must be a string");
|
||||
let whole = "`start` must be a whole number".to_string();
|
||||
let point = "`at` must be a point: [x, y]".to_string();
|
||||
let calls: Vec<(String, Value, String)> = [
|
||||
("text.editRange", json!({"id": id.0, "start": 0, "end": 1, "insert": 5}), string("insert")),
|
||||
("text.editRange", json!({"id": id.0, "start": 0, "end": 3, "insert": ["x"]}), string("insert")),
|
||||
("text.setText", json!({"ids": [id.0], "text": true}), string("text")),
|
||||
("text.createInPath", json!({"path": frame, "mode": 1}), string("mode")),
|
||||
("text.createInPath", json!({"path": frame, "text": true}), string("text")),
|
||||
("text.createInPath", json!({"path": line, "mode": "onPath", "text": "a", "at": [1, "y"]}), point.clone()),
|
||||
("text.createInPath", json!({"path": line, "mode": "onPath", "at": [100]}), point.clone()),
|
||||
("text.createInPath", json!({"path": frame, "text": "a", "at": "start"}), point),
|
||||
("text.touchType", json!({"id": id.0, "start": 1.5, "dy": 2}), whole.clone()),
|
||||
("text.touchType", json!({"id": id.0, "start": -1, "dy": 2}), whole.clone()),
|
||||
("text.glyphAlternates", json!({"id": id.0, "start": 1.5}), whole.clone()),
|
||||
("text.setGlyphAlternate", json!({"id": id.0, "start": -1, "gid": null}), whole),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(cmd, p, msg)| (cmd.to_string(), p, msg))
|
||||
.collect();
|
||||
let wrong = not_refused(&mut s, &calls);
|
||||
assert!(wrong.is_empty(), "not refused: {wrong:#?}");
|
||||
// Null keeps each default: nothing inserted, area type with no text, no start point.
|
||||
s.execute("text.editRange", &json!({"id": id.0, "start": 0, "end": 1, "insert": null})).unwrap();
|
||||
assert_eq!(obj(&s, id).plain_text(), "bc");
|
||||
let r = s.execute("text.createInPath", &json!({"path": frame, "mode": null, "text": null, "at": null})).unwrap();
|
||||
let t = obj(&s, NodeId(r["id"].as_u64().unwrap()));
|
||||
assert!(matches!(t.kind, TextKind::Area { .. }) && t.plain_text().is_empty(), "{:?}", t.kind);
|
||||
s.execute("text.createInPath", &json!({"path": line, "mode": "onPath", "text": "a", "at": [100, 400]})).unwrap();
|
||||
}
|
||||
|
||||
/// Where each glyph of type object `id` is drawn from (its origin in font units), document space.
|
||||
fn glyph_pens(s: &Session, id: NodeId) -> Vec<(usize, Point)> {
|
||||
let t = obj(s, id);
|
||||
|
||||
@@ -582,6 +582,8 @@ fn colour_table_fixed_palette_keeps_an_opaque_color() {
|
||||
let clear: Vec<String> = (1..255).map(|i| format!("#00{i:02x}00")).chain(["#0000ee".to_string()]).collect();
|
||||
let palette: Vec<String> = std::iter::once("#0000ff".to_string()).chain(clear.iter().cloned()).collect();
|
||||
let p = json!({"format": "png8", "dither": "none", "colors": 256, "colorTable": {"customPalette": palette, "transparent": clear}});
|
||||
let v = run(&mut d, "document.exportForWeb.preview", p.clone());
|
||||
assert_eq!(v["mappedToTransparent"], json!(["#0000ee"]), "the color that did not fit is listed: {v}");
|
||||
let img = pixels(&one(&mut d, p));
|
||||
assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(15, 5).0[3], img.get_pixel(25, 5).0[3]), ([0, 0, 255, 255], 0, 0));
|
||||
// Without transparent pixels the colors mapped to transparent still take one slot together.
|
||||
@@ -598,6 +600,49 @@ fn colour_table_fixed_palette_keeps_an_opaque_color() {
|
||||
assert_eq!((img.get_pixel(5, 5).0[3], img.get_pixel(15, 5).0[3], img.get_pixel(25, 5).0), (0, 0, [0, 0, 255, 255]));
|
||||
}
|
||||
|
||||
/// With transparent pixels, the colors of a fixed palette mapped to transparent share the
|
||||
/// transparent pixels' slot, so at 256 colors all 255 opaque colors keep their entries.
|
||||
#[test]
|
||||
fn colour_table_fixed_palette_with_transparent_pixels_keeps_255_opaque_colors() {
|
||||
// A 16×16 grid of 2×2 squares in 255 colors, the last cell left empty (transparent).
|
||||
let mut s = session(32.0, 32.0);
|
||||
let color = |i: usize| format!("#{:02x}{:02x}80", i, 255 - i);
|
||||
for i in 0..255 {
|
||||
rect(&mut s, [(i % 16) as f64 * 2.0, (i / 16) as f64 * 2.0, 2.0, 2.0], &color(i));
|
||||
}
|
||||
let palette: Vec<String> = (0..255).map(color).chain(["#000000".to_string()]).collect();
|
||||
for table in [json!({"customPalette": palette, "transparent": ["#000000"]}), json!({"customPalette": palette[..255], "transparent": []})] {
|
||||
let p = json!({"format": "png8", "dither": "none", "colors": 256, "colorTable": table});
|
||||
let img = pixels(&one(&mut s, p.clone()));
|
||||
let opaque: std::collections::HashSet<[u8; 4]> = img.pixels().map(|p| p.0).filter(|p| p[3] == 255).collect();
|
||||
assert_eq!(opaque.len(), 255, "{p}");
|
||||
assert_eq!((img.get_pixel(29, 31).0, img.get_pixel(31, 31).0[3]), ([254, 1, 128, 255], 0), "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// When Colors leaves a fixed palette fewer slots than it has colors, its locked and shifted colors
|
||||
/// keep their slots first (shifted ones before locked ones), so a shifted color still shows its new
|
||||
/// color.
|
||||
#[test]
|
||||
fn colour_table_fixed_palette_keeps_locked_and_shifted_colors_first() {
|
||||
let mut s = session(30.0, 10.0);
|
||||
rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#ff0000");
|
||||
rect(&mut s, [10.0, 0.0, 10.0, 10.0], "#00ff00");
|
||||
rect(&mut s, [20.0, 0.0, 10.0, 10.0], "#0000ff");
|
||||
let palette = json!(["#ff0000", "#00ff00", "#0000ff"]);
|
||||
let p = json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": {"customPalette": palette, "shifted": {"#0000ff": "#ff8800"}}});
|
||||
let img = pixels(&one(&mut s, p));
|
||||
assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(25, 5).0), ([255, 0, 0, 255], [255, 136, 0, 255]));
|
||||
// A shifted color keeps its slot before the locked ones.
|
||||
let table = json!({"customPalette": palette, "locked": ["#ff0000", "#00ff00"], "shifted": {"#0000ff": "#ff8800"}});
|
||||
let img = pixels(&one(&mut s, json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": table})));
|
||||
assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(25, 5).0), ([255, 0, 0, 255], [255, 136, 0, 255]));
|
||||
let p = json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": {"customPalette": palette, "locked": ["#0000ff"]}});
|
||||
let v = run(&mut s, "document.exportForWeb.preview", p);
|
||||
let sources: Vec<&Value> = v["colors"].as_array().unwrap().iter().map(|c| &c["source"]).collect();
|
||||
assert_eq!(sources, vec![&json!("#ff0000"), &json!("#0000ff")], "the palette keeps its order: {v}");
|
||||
}
|
||||
|
||||
/// A color shifted by hand (`colorTable.shifted`) is written as the color picked wherever it is in
|
||||
/// the image, the other colors stay, the table shows it as shifted and locked, and the preview is
|
||||
/// the file.
|
||||
|
||||
@@ -254,6 +254,170 @@ fn canceling_an_alt_drag_leaves_the_document_as_it_was() {
|
||||
assert!(s.doc().unwrap().interaction.is_none());
|
||||
}
|
||||
|
||||
/// Returns the ids of the children of the document's layer `layer` (0 is the bottom one).
|
||||
fn layer_kids(s: &Session, layer: usize) -> Vec<NodeId> {
|
||||
s.doc().unwrap().doc.layers[layer].children().unwrap().iter().map(|n| n.id).collect()
|
||||
}
|
||||
|
||||
/// Returns a session with three squares side by side, `a`, `b` and `c` from the bottom of the
|
||||
/// stack up, and `b` selected; and their ids.
|
||||
fn three_squares() -> (Session, [NodeId; 3]) {
|
||||
let mut s = session();
|
||||
let ids = [100.0, 200.0, 300.0].map(|x| rect(&mut s, x, 100.0, 40.0, 40.0));
|
||||
s.execute("select.set", &json!({"ids": [ids[1].0]})).unwrap();
|
||||
(s, ids)
|
||||
}
|
||||
|
||||
/// Alt-drags the selection 80 pt down with `tool`, pressing at `press`.
|
||||
fn alt_drag(s: &mut Session, tool: &str, press: (f64, f64)) {
|
||||
s.select_tool(tool, ViewInfo::default()).unwrap();
|
||||
drag_at(s, PointerKind::Down, press, true);
|
||||
for dy in [20.0, 50.0, 80.0] {
|
||||
drag_at(s, PointerKind::Drag, (press.0, press.1 + dy), true);
|
||||
}
|
||||
drag_at(s, PointerKind::Up, (press.0, press.1 + 80.0), true);
|
||||
}
|
||||
|
||||
/// In Draw Behind, an Alt-drag with the Selection tool, or with Direct Selection on an object
|
||||
/// selected whole, puts the copy directly below its original, selected, in one undo step. In Draw
|
||||
/// Normal and Draw Inside the copy goes directly above it, as before.
|
||||
#[test]
|
||||
fn an_alt_drag_in_draw_behind_puts_the_copy_directly_below_its_original() {
|
||||
for (tool, press) in [("selection", (220.0, 120.0)), ("directSelection", (200.0, 100.0))] {
|
||||
for mode in ["behind", "normal", "inside"] {
|
||||
let (mut s, [a, b, c]) = three_squares();
|
||||
s.execute("view.drawMode", &json!({"mode": mode})).unwrap();
|
||||
let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s));
|
||||
alt_drag(&mut s, tool, press);
|
||||
let what = format!("{tool}, {mode}");
|
||||
let kids = layer_kids(&s, 0);
|
||||
let copy = s.doc().unwrap().selection.objects.clone();
|
||||
assert_eq!(copy.len(), 1, "{what}: the copy is selected");
|
||||
let want = if mode == "behind" { vec![a, copy[0], b, c] } else { vec![a, b, copy[0], c] };
|
||||
assert_eq!(kids, want, "{what}");
|
||||
assert!(close(bounds(&s, copy[0]), Rect::new(200.0, 180.0, 240.0, 220.0)), "{what}: {:?}", bounds(&s, copy[0]));
|
||||
assert!(close(bounds(&s, b), Rect::new(200.0, 100.0, 240.0, 140.0)), "{what}: the original stays");
|
||||
assert_eq!(undo_len(&s), undo + 1, "{what}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(*s.doc().unwrap().doc == *before, "{what}: Undo gives back the document");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// In Draw Behind, an Alt-drag of several objects puts each copy directly below its own original,
|
||||
/// in the original's group or layer: objects side by side in one layer, a group (copied whole) and
|
||||
/// an object in another layer.
|
||||
#[test]
|
||||
fn an_alt_drag_in_draw_behind_puts_each_copy_below_its_own_original() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 40.0, 40.0);
|
||||
let x = rect(&mut s, 200.0, 100.0, 40.0, 40.0);
|
||||
let y = rect(&mut s, 260.0, 100.0, 40.0, 40.0);
|
||||
s.execute("select.set", &json!({"ids": [x.0, y.0]})).unwrap();
|
||||
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let c = rect(&mut s, 400.0, 100.0, 40.0, 40.0);
|
||||
s.execute("layer.new", &json!({})).unwrap();
|
||||
let d = rect(&mut s, 500.0, 100.0, 40.0, 40.0);
|
||||
assert_eq!(layer_kids(&s, 0), vec![a, g, c]);
|
||||
assert_eq!(layer_kids(&s, 1), vec![d]);
|
||||
s.execute("select.set", &json!({"ids": [a.0, g.0, c.0, d.0]})).unwrap();
|
||||
s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap();
|
||||
let undo = undo_len(&s);
|
||||
alt_drag(&mut s, "selection", (120.0, 120.0));
|
||||
let (bottom, top) = (layer_kids(&s, 0), layer_kids(&s, 1));
|
||||
assert_eq!(bottom.len(), 6, "{bottom:?}");
|
||||
assert_eq!([bottom[1], bottom[3], bottom[5], top[1]], [a, g, c, d], "the originals keep their order");
|
||||
let copies = [bottom[0], bottom[2], bottom[4], top[0]];
|
||||
let mut selected = s.doc().unwrap().selection.objects.clone();
|
||||
selected.sort_unstable();
|
||||
let mut want = copies.to_vec();
|
||||
want.sort_unstable();
|
||||
assert_eq!(selected, want, "the copies are selected");
|
||||
let group_copy = s.doc().unwrap().doc.node(copies[1]).unwrap().children().map(Vec::len);
|
||||
assert_eq!(group_copy, Some(2), "the group is copied whole, once");
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
}
|
||||
|
||||
/// `drawBehind` puts the copies of an interaction's previews below their originals only in Draw
|
||||
/// Behind and only with `copy`: a later preview without it does not reuse the copies made below,
|
||||
/// and a transform with `copy` but without `drawBehind`, `object.move` with `copy`, and Transform
|
||||
/// Again after an Alt-drag in Draw Behind put their copies above. A `drawBehind` that is not true or
|
||||
/// false is refused, and the document and its undo history stay as they were.
|
||||
#[test]
|
||||
fn only_an_alt_drag_copy_follows_draw_behind() {
|
||||
let (mut s, [a, b, c]) = three_squares();
|
||||
s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap();
|
||||
s.begin_interaction("Copy").unwrap();
|
||||
let below = json!({"matrix": [1, 0, 0, 1, 0, 80], "copy": true, "drawBehind": true});
|
||||
s.preview("object.transform", &below).unwrap();
|
||||
let first = s.doc().unwrap().selection.objects.clone();
|
||||
assert_eq!(layer_kids(&s, 0), vec![a, first[0], b, c]);
|
||||
s.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, 0, 90], "copy": true})).unwrap();
|
||||
let second = s.doc().unwrap().selection.objects.clone();
|
||||
assert_eq!(layer_kids(&s, 0), vec![a, b, second[0], c], "a copy without `drawBehind` goes above");
|
||||
s.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, 0, 90], "copy": false, "drawBehind": true})).unwrap();
|
||||
assert_eq!(layer_kids(&s, 0), vec![a, b, c], "without `copy`, nothing is copied");
|
||||
s.cancel_interaction().unwrap();
|
||||
|
||||
let (mut s, [a, b, c]) = three_squares();
|
||||
s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap();
|
||||
for (cmd, params) in
|
||||
[("object.transform", json!({"matrix": [1, 0, 0, 1, 0, 80], "copy": true})), ("object.move", json!({"dx": 0, "dy": 80, "copy": true}))]
|
||||
{
|
||||
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
|
||||
let copy = ids_of(&s.execute(cmd, ¶ms).unwrap());
|
||||
assert_eq!(layer_kids(&s, 0), vec![a, b, copy[0], c], "{cmd}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
// An object listed twice is copied twice, each copy directly below it in turn.
|
||||
let twice =
|
||||
ids_of(&s.execute("object.transform", &json!({"matrix": [1, 0, 0, 1, 0, 80], "copy": true, "drawBehind": true, "ids": [b.0, b.0]})).unwrap());
|
||||
assert_eq!(layer_kids(&s, 0), vec![a, twice[0], twice[1], b, c]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
|
||||
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
|
||||
alt_drag(&mut s, "selection", (220.0, 120.0));
|
||||
let copy = s.doc().unwrap().selection.objects.clone();
|
||||
assert_eq!(layer_kids(&s, 0), vec![a, copy[0], b, c]);
|
||||
let Some(LastTransform::Matrix(_, options)) = s.doc().unwrap().last_transform.clone() else { panic!("the drag is kept for Transform Again") };
|
||||
assert!(options.get("drawBehind").is_none(), "{options}");
|
||||
let again = ids_of(&s.execute("object.transformAgain", &json!({})).unwrap());
|
||||
assert_eq!(layer_kids(&s, 0), vec![a, copy[0], again[0], b, c], "Transform Again copies above");
|
||||
|
||||
let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s));
|
||||
let e = s.execute("object.transform", &json!({"matrix": [1, 0, 0, 1, 0, 80], "copy": true, "drawBehind": "yes"})).unwrap_err();
|
||||
assert!(e.to_string().contains("`drawBehind` must be true or false"), "{e}");
|
||||
assert!(Arc::ptr_eq(&s.doc().unwrap().doc, &before));
|
||||
assert_eq!(undo_len(&s), undo);
|
||||
}
|
||||
|
||||
/// In Draw Behind, the copy of a clip group's clipping path goes directly above it, so the clipping
|
||||
/// path stays the group's bottom child; the copy of the clipped art goes below that art.
|
||||
#[test]
|
||||
fn a_copy_in_draw_behind_leaves_the_clipping_path_at_the_bottom() {
|
||||
let mut s = session();
|
||||
let art = rect(&mut s, 100.0, 100.0, 80.0, 80.0);
|
||||
rect(&mut s, 110.0, 110.0, 40.0, 40.0);
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let kids = |s: &Session| -> Vec<NodeId> { s.doc().unwrap().doc.node(g).unwrap().children().unwrap().iter().map(|n| n.id).collect() };
|
||||
let [mask, clipped] = kids(&s)[..] else { panic!("{:?}", kids(&s)) };
|
||||
assert_eq!(clipped, art);
|
||||
s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap();
|
||||
let params = |ids: [NodeId; 2]| json!({"matrix": [1, 0, 0, 1, 0, 80], "copy": true, "drawBehind": true, "ids": [ids[0].0, ids[1].0]});
|
||||
let copies = ids_of(&s.execute("object.transform", ¶ms([mask, art])).unwrap());
|
||||
assert_eq!(kids(&s), vec![mask, copies[0], copies[1], art]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// An object listed twice is copied one at a time, over the clipping path too.
|
||||
let copies = ids_of(&s.execute("object.transform", ¶ms([mask, mask])).unwrap());
|
||||
assert_eq!(kids(&s), vec![mask, copies[1], copies[0], art]);
|
||||
}
|
||||
|
||||
/// Returns the `ids` of a command's reply.
|
||||
fn ids_of(r: &Value) -> Vec<NodeId> {
|
||||
r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect()
|
||||
}
|
||||
|
||||
/// Returns a session with the grid and the square of [`persp_session`], the grid shown with its
|
||||
/// right plane active, and a group of two squares attached to the right plane beside the square,
|
||||
/// with the square and the group selected; and the square's id.
|
||||
@@ -879,13 +1043,6 @@ fn distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one() {
|
||||
for (cmd, params) in [
|
||||
("object.cropImage", json!({})),
|
||||
("imageTrace.make", json!({})),
|
||||
("links.relink", json!({"path": "/nowhere/pic.png"})),
|
||||
// Refused before the folder is searched, so a file missing there does not hide it.
|
||||
("links.relink", json!({"folder": "/nowhere"})),
|
||||
("links.embed", json!({"ids": [img.0]})),
|
||||
("links.unembed", json!({})),
|
||||
// Refused before any file is written.
|
||||
("links.unembed", json!({"folder": "/nowhere"})),
|
||||
("object.createObjectMosaic", json!({})),
|
||||
("object.mesh.create", json!({})),
|
||||
(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Hosting the active tool: pointer/key events → actions → commands.
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
use vectorcraft_doc::Selection;
|
||||
use vectorcraft_doc::{NodeId, Selection};
|
||||
use vectorcraft_geom::Point;
|
||||
use vectorcraft_tools::distort::perspective::widget::WidgetPlace;
|
||||
use vectorcraft_tools::draw2::FEEDBACK;
|
||||
@@ -186,12 +186,13 @@ impl Session {
|
||||
let text_selection = ((id == "eyedropper" && is_type(self.tool.id())) || (self.tool.id() == "eyedropper" && is_type(id)))
|
||||
.then(|| self.tool.options())
|
||||
.filter(|o| o.get("editing").is_some_and(|v| !v.is_null()) && o.get("start") != o.get("end"));
|
||||
// The gradient mesh points the Mesh tool, Direct Selection or the Lasso picked stay picked
|
||||
// for the Eyedropper, which samples into them (#8090), and for the tool after it.
|
||||
let mesh_points = (id == "eyedropper" || self.tool.id() == "eyedropper")
|
||||
// The gradient mesh points the Mesh tool, Direct Selection, the Lasso or the Polygonal Lasso
|
||||
// picked stay picked when another of these tools or the Eyedropper, which samples into
|
||||
// them (#8090), is chosen: a fill color then recolors just them. None stay picked when
|
||||
// none were.
|
||||
let mesh_points = (Self::picks_mesh_points(id) && Self::picks_mesh_points(self.tool.id()))
|
||||
.then(|| self.tool.options().get("meshPoints").cloned())
|
||||
.flatten()
|
||||
.filter(|v| v.as_array().is_some_and(|a| !a.is_empty()));
|
||||
.flatten();
|
||||
self.deactivate_tool(view)?;
|
||||
self.keep_tool_settings();
|
||||
self.tool = self.make_tool(id);
|
||||
@@ -208,6 +209,13 @@ impl Session {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Does tool `id` pick gradient mesh points (its `meshPoints` option): the Mesh tool, Direct
|
||||
/// Selection, the Lasso, the Polygonal Lasso and the Eyedropper? Group Selection, which
|
||||
/// selects whole objects, does not.
|
||||
fn picks_mesh_points(id: &str) -> bool {
|
||||
matches!(id, "mesh" | "directSelection" | "lasso" | "polygonalLasso" | "eyedropper")
|
||||
}
|
||||
|
||||
/// Deactivate the tool and apply the actions it returns. In a batch, a Cancel is left out: the
|
||||
/// batch settled the tool's drag when it began, and the open interaction holds the batch's
|
||||
/// steps, which the batch keeps or rolls back as a whole.
|
||||
@@ -292,9 +300,9 @@ impl Session {
|
||||
// double-click or triple-click compares.
|
||||
self.tool.press_elsewhere();
|
||||
let mut lent = self.make_tool(id);
|
||||
// The gradient mesh points the Eyedropper holds are the lent tool's picks, which a Shift
|
||||
// click adds to (#8090).
|
||||
if self.tool.id() == "eyedropper" {
|
||||
// The gradient mesh points the lending tool picked (the Mesh tool's, the Lasso's, the
|
||||
// Eyedropper's) are the lent tool's picks, which a Shift click adds to (#8090).
|
||||
if Self::picks_mesh_points(self.tool.id()) && Self::picks_mesh_points(id) {
|
||||
let points = self.tool.options().get("meshPoints").cloned().unwrap_or_else(|| Value::Array(vec![]));
|
||||
lent.set_option("meshPoints", &points);
|
||||
}
|
||||
@@ -311,12 +319,22 @@ impl Session {
|
||||
/// Pen goes on drawing its path), less the work the gesture ended as a command would: a
|
||||
/// Cmd+click that takes the type being edited out of the selection ends its edit (#3779).
|
||||
pub(crate) fn give_back_tool(&mut self, view: ViewInfo) -> Result<()> {
|
||||
let lent_by_bucket = self.lent_by_bucket();
|
||||
let Some(lender) = self.lender.take() else { return Ok(()) };
|
||||
// The points the lent tool left picked go back to the Eyedropper, none when it unpicked
|
||||
// them all (#8090). Group Selection picks no mesh points, so the Eyedropper keeps its own.
|
||||
let mesh_points =
|
||||
(lender.id() == "eyedropper" && self.tool.id() != "groupSelection").then(|| self.tool.options().get("meshPoints").cloned()).flatten();
|
||||
// The points the lent tool left picked go back to the tool it was lent to when that tool
|
||||
// picks mesh points, none when it unpicked them all (#8090). Group Selection and the
|
||||
// Selection tool pick no mesh points, so the tool keeps its own. Unchanged picks are not
|
||||
// set again, so the Mesh tool keeps the point whose handles it shows.
|
||||
let mesh_points = (Self::picks_mesh_points(lender.id()) && Self::picks_mesh_points(self.tool.id()))
|
||||
.then(|| self.tool.options().get("meshPoints").cloned())
|
||||
.flatten()
|
||||
.filter(|p| lender.options().get("meshPoints") != Some(p));
|
||||
// The lent tool's last actions (a drag it cancels or keeps) still count as the Live Paint
|
||||
// Bucket's when the bucket lent it ([`Session::bucket_paints`]).
|
||||
let outer_bucket = self.back_to_bucket;
|
||||
self.back_to_bucket |= lent_by_bucket;
|
||||
let r = self.deactivate_tool(view);
|
||||
self.back_to_bucket = outer_bucket;
|
||||
self.keep_tool_settings();
|
||||
self.tool = lender;
|
||||
if let Some(points) = mesh_points {
|
||||
@@ -1536,11 +1554,12 @@ impl Session {
|
||||
}
|
||||
|
||||
/// Let the active tool finish work a command from outside it ended ([`vectorcraft_tools::Tool::after_command`]):
|
||||
/// the Type tool and the Eyedropper clear a character range whose text is no longer selected.
|
||||
/// the Type tool and the Eyedropper clear a character range whose text is no longer selected,
|
||||
/// and the Curvature Circle tool lets the pointer reach its circles once none is selected.
|
||||
/// After `edit.undo` or `edit.redo` (`cmd`), the tool is told first, so the Type tool puts the
|
||||
/// caret where the step changed the text.
|
||||
pub(crate) fn after_command(&mut self, cmd: Option<&str>) {
|
||||
if self.in_tool_actions || (!self.tool.wants_text() && self.tool.id() != "eyedropper") {
|
||||
if self.in_tool_actions || (!self.tool.wants_text() && !matches!(self.tool.id(), "eyedropper" | vectorcraft_tools::curvature_circle::ID)) {
|
||||
return;
|
||||
}
|
||||
if let Some(cmd @ ("edit.undo" | "edit.redo")) = cmd {
|
||||
@@ -1742,7 +1761,7 @@ impl Session {
|
||||
(st.doc.clone(), st.selection.clone(), st.revision, self.pending_paint.clone(), interaction_fields)
|
||||
};
|
||||
let (overlays, transform_box) = if self.preview(cmd, p).is_ok() {
|
||||
let overlays = self.active().map(|st| outlines_for_selection(&st.doc, &st.selection)).unwrap_or_default();
|
||||
let overlays = self.active().map(|st| outlines_for_selection(&st.doc, &st.selection, cmd, p)).unwrap_or_default();
|
||||
let (objects, color) = self
|
||||
.active()
|
||||
.map(|st| (st.selection.objects.clone(), st.selection.objects.first().map(|id| st.doc.layer_color(*id))))
|
||||
@@ -1783,11 +1802,17 @@ const FEEDBACK_MAX_POINTS: usize = 100_000;
|
||||
|
||||
/// The outlines of every selected object, a group's members each with their own, or the selection's
|
||||
/// bounds when the outlines' points and the objects evaluated to make them come to more than
|
||||
/// [`FEEDBACK_MAX_POINTS`].
|
||||
fn outlines_for_selection(doc: &vectorcraft_doc::Document, selection: &Selection) -> Vec<Overlay> {
|
||||
let nodes = selection.objects.iter().filter_map(|&id| doc.node(id));
|
||||
let outlines = vectorcraft_render::drawn_outlines(doc, nodes, FEEDBACK_MAX_POINTS).unwrap_or_else(|| {
|
||||
doc.bounds_of(&selection.objects, true).map(|b| vectorcraft_geom::shapes::rectangle(b).to_bezpath()).into_iter().collect()
|
||||
});
|
||||
/// [`FEEDBACK_MAX_POINTS`]. A `dimension.update` preview (`cmd`, `p`) that names its dimensions,
|
||||
/// as the Dimension tool sends for a dimension it drags, outlines those dimensions instead.
|
||||
fn outlines_for_selection(doc: &vectorcraft_doc::Document, selection: &Selection, cmd: &str, p: &Value) -> Vec<Overlay> {
|
||||
let named: Vec<NodeId> = if cmd == "dimension.update" {
|
||||
p.get("ids").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_u64).map(NodeId).collect()
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
let objects = if named.is_empty() { &selection.objects } else { &named };
|
||||
let nodes = objects.iter().filter_map(|&id| doc.node(id));
|
||||
let outlines = vectorcraft_render::drawn_outlines(doc, nodes, FEEDBACK_MAX_POINTS)
|
||||
.unwrap_or_else(|| doc.bounds_of(objects, true).map(|b| vectorcraft_geom::shapes::rectangle(b).to_bezpath()).into_iter().collect());
|
||||
outlines.into_iter().map(|path| Overlay::Path { path, color: FEEDBACK, width: 1.0, dashed: false }).collect()
|
||||
}
|
||||
|
||||
@@ -2095,7 +2095,8 @@ proptest! {
|
||||
|
||||
/// Mutated copies of the PSD and PSB samples never crash opening them with their layers, hidden
|
||||
/// ones too: the PSD's layer records, channel lengths and data, and the PSB's layer count.
|
||||
/// (Masks, clipping and groups are covered by `tests_psdlayers::damaged_layers_never_panic`.)
|
||||
/// (Masks, clipping and groups are covered by `tests_psdlayers::damaged_layers_never_panic`, and
|
||||
/// Invert, Threshold and Posterize layers by `tests_psdlayers::damaged_adjustment_layers_never_panic`.)
|
||||
/// Neither does `document.psdInfo`, nor placing them with their layers as objects.
|
||||
#[test]
|
||||
fn mutated_layered_psds_open_without_panics(which in 6usize..8, cut in 0usize..1_000_000, edits in prop::collection::vec((0usize..1_000_000, any::<u8>()), 0..12)) {
|
||||
|
||||
@@ -2077,18 +2077,19 @@ fn a_dimension_line_placed_beside_another_lands_on_its_level() {
|
||||
run(&mut s, "object.lock", json!({}));
|
||||
assert_eq!(level_next(&mut s, plain, 172.5), (pt(200.0, 172.5), pt(300.0, 172.5)));
|
||||
// A dimension of the right edge has a vertical line, which is not parallel to the first: the
|
||||
// pointer 2.5 points below the first line's level places it where the pointer is.
|
||||
// pointer 2.5 points right of the first line's left end, within reach across the vertical
|
||||
// line, places it where the pointer is.
|
||||
let (mut s, _) = level_start(plain);
|
||||
linear_click(&mut s, plain, 300.0, 200.0);
|
||||
linear_click(&mut s, plain, 300.0, 300.0);
|
||||
linear_click(&mut s, plain, 330.0, 172.5);
|
||||
linear_click(&mut s, plain, 102.5, 172.5);
|
||||
let id = s.doc().unwrap().selection.objects[0].0;
|
||||
assert_eq!(recipe(&s, id).line_ends(), (pt(330.0, 200.0), pt(330.0, 300.0)));
|
||||
assert_eq!(recipe(&s, id).line_ends(), (pt(102.5, 200.0), pt(102.5, 300.0)));
|
||||
}
|
||||
|
||||
/// While a dimension is placed with its line on the level of another, one alignment guide runs
|
||||
/// along the level across both lines. Off the level, after a dropped press and with Alignment
|
||||
/// Guides off, no guide shows.
|
||||
/// along the level across both lines. Off the level, after a dropped press and with Smart Guides
|
||||
/// or Alignment Guides off, no guide shows.
|
||||
#[test]
|
||||
fn a_dimension_line_on_another_level_shows_one_guide_across_both() {
|
||||
let plain = ViewInfo::default();
|
||||
@@ -2097,7 +2098,10 @@ fn a_dimension_line_on_another_level_shows_one_guide_across_both() {
|
||||
linear_click(&mut s, plain, 200.0, 200.0);
|
||||
linear_click(&mut s, plain, 300.0, 200.0);
|
||||
let guides = guide_lines(&mut s, plain, 250.0, 172.5);
|
||||
assert!(guides.iter().any(|(a, b)| near(*a, pt(100.0, 170.0)) && near(*b, pt(300.0, 170.0))), "{guides:?}");
|
||||
assert!(matches!(guides.as_slice(), [(a, b)] if near(*a, pt(100.0, 170.0)) && near(*b, pt(300.0, 170.0))), "{guides:?}");
|
||||
// Smart Guides turned off before the next pointer move: the guide goes.
|
||||
let off = ViewInfo { smart_guides: false, ..plain };
|
||||
assert!(s.overlays(off).iter().all(|o| !matches!(o, vectorcraft_engine::tools::Overlay::Line { .. })), "{:?}", s.overlays(off));
|
||||
assert!(guide_lines(&mut s, plain, 250.0, 180.0).is_empty(), "no guide off the level");
|
||||
// A press on the level that the app drops cancels the preview, and its guide goes with it.
|
||||
assert!(!guide_lines(&mut s, plain, 250.0, 172.5).is_empty());
|
||||
@@ -2115,6 +2119,328 @@ fn a_dimension_line_on_another_level_shows_one_guide_across_both() {
|
||||
assert_eq!(recipe(&s, id).line_ends(), (pt(200.0, 170.0), pt(300.0, 170.0)));
|
||||
}
|
||||
|
||||
/// A drag with the Dimension tool from a dimension already drawn moves its line as far across as
|
||||
/// the pointer moved, keeps what it measures and its link to the art, and is one undo step. A
|
||||
/// click on its line does not move it, and neither does Escape during the drag.
|
||||
#[test]
|
||||
fn dragging_a_placed_dimension_with_the_dimension_tool_moves_its_line() {
|
||||
let plain = ViewInfo::default();
|
||||
let pt = vectorcraft_geom::Point::new;
|
||||
let (mut s, first) = level_start(plain);
|
||||
let (count, label) = (s.doc().unwrap().doc.node_count(), text(&s, first));
|
||||
let drag = |s: &mut Session, from: (f64, f64), to: (f64, f64)| {
|
||||
for (kind, (x, y)) in [(PointerKind::Move, from), (PointerKind::Down, from), (PointerKind::Drag, to), (PointerKind::Up, to)] {
|
||||
s.pointer(&PointerEvent::new(kind, x, y), plain).unwrap();
|
||||
}
|
||||
};
|
||||
// Dragged up and to the side: the line goes up as far as the pointer, and stays over the
|
||||
// points it measures.
|
||||
drag(&mut s, (150.0, 170.0), (180.0, 130.0));
|
||||
assert!(!s.in_interaction());
|
||||
assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0)));
|
||||
assert_eq!((recipe(&s, first).a, recipe(&s, first).b), (pt(100.0, 200.0), pt(200.0, 200.0)));
|
||||
assert_eq!((s.doc().unwrap().doc.node_count(), text(&s, first)), (count, label));
|
||||
// One undo step puts it back.
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0)));
|
||||
run(&mut s, "edit.redo", json!({}));
|
||||
assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0)));
|
||||
// Still linked: moving the art moves its points, and the line keeps its distance from them.
|
||||
let art = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id.0;
|
||||
run(&mut s, "select.set", json!({"ids":[art]}));
|
||||
run(&mut s, "object.move", json!({"dx":0,"dy":10}));
|
||||
assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 140.0), pt(200.0, 140.0)));
|
||||
run(&mut s, "object.move", json!({"dx":0,"dy":-10}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
run(&mut s, "dimension.update", json!({"ids":[first],"at":[150,170]}));
|
||||
assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0)));
|
||||
// A click on the line picks a point there and leaves the dimension where it is.
|
||||
linear_click(&mut s, plain, 150.0, 170.0);
|
||||
s.tool_key(ToolKey::Escape, Mods::default(), plain).unwrap();
|
||||
assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0)));
|
||||
// Escape during the drag leaves it where it was.
|
||||
ev(&mut s, PointerKind::Down, 150.0, 170.0);
|
||||
ev(&mut s, PointerKind::Drag, 150.0, 120.0);
|
||||
assert!(s.in_interaction());
|
||||
s.tool_key(ToolKey::Escape, Mods::default(), plain).unwrap();
|
||||
ev(&mut s, PointerKind::Up, 150.0, 120.0);
|
||||
assert!(!s.in_interaction());
|
||||
assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0)));
|
||||
// A locked dimension is not moved: the drag from its line drags out nothing either.
|
||||
run(&mut s, "select.set", json!({"ids":[first]}));
|
||||
run(&mut s, "object.lock", json!({}));
|
||||
drag(&mut s, (150.0, 170.0), (150.0, 130.0));
|
||||
assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0)));
|
||||
assert_eq!(s.doc().unwrap().doc.node_count(), count);
|
||||
}
|
||||
|
||||
/// A dimension moved with the Dimension tool lands on the level of a parallel dimension line
|
||||
/// within the Smart Guides snapping tolerance, and its own line before the drag is not a level.
|
||||
#[test]
|
||||
fn a_dimension_moved_beside_another_lands_on_its_level() {
|
||||
let plain = ViewInfo::default();
|
||||
let pt = vectorcraft_geom::Point::new;
|
||||
let (mut s, first) = level_start(plain);
|
||||
linear_click(&mut s, plain, 200.0, 200.0);
|
||||
linear_click(&mut s, plain, 300.0, 200.0);
|
||||
linear_click(&mut s, plain, 250.0, 150.0);
|
||||
let second = s.doc().unwrap().selection.objects[0].0;
|
||||
run(&mut s, "select.none", json!({}));
|
||||
assert_eq!(recipe(&s, second).line_ends(), (pt(200.0, 150.0), pt(300.0, 150.0)));
|
||||
let drag = |s: &mut Session, from: (f64, f64), to: (f64, f64)| {
|
||||
for (kind, (x, y)) in [(PointerKind::Down, from), (PointerKind::Drag, to), (PointerKind::Up, to)] {
|
||||
s.pointer(&PointerEvent::new(kind, x, y), plain).unwrap();
|
||||
}
|
||||
};
|
||||
// 3.5 points off its own level, with no other level there: where the pointer puts it.
|
||||
drag(&mut s, (150.0, 170.0), (150.0, 166.5));
|
||||
assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 166.5), pt(200.0, 166.5)));
|
||||
// 2.5 points below the first line's new level: on it.
|
||||
drag(&mut s, (250.0, 150.0), (250.0, 169.0));
|
||||
assert_eq!(recipe(&s, second).line_ends(), (pt(200.0, 166.5), pt(300.0, 166.5)));
|
||||
}
|
||||
|
||||
/// `dimension.update` with `at` puts a linear dimension's line, an angular dimension's arc or a
|
||||
/// radius line through the point, and keeps what each measures; a bad `at` changes nothing.
|
||||
#[test]
|
||||
fn dimension_update_at_moves_the_line_through_the_point() {
|
||||
let mut s = session();
|
||||
let line = edge(&mut s);
|
||||
let linear = dim(&mut s, line);
|
||||
let label = text(&s, linear);
|
||||
run(&mut s, "dimension.update", json!({"ids":[linear],"at":[130,50]}));
|
||||
let d = recipe(&s, linear);
|
||||
assert!((d.line_ends().0.y - 50.0).abs() < 1e-9 && (d.line_ends().1.y - 50.0).abs() < 1e-9, "{:?}", d.line_ends());
|
||||
assert_eq!(text(&s, linear), label);
|
||||
let angular = run(&mut s, "dimension.create", json!({"mode":"angular","a":[100,0],"vertex":[0,0],"b":[0,100]}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "dimension.update", json!({"ids":[angular],"at":[60,0]}));
|
||||
assert!((recipe(&s, angular).offset - 60.0).abs() < 1e-9);
|
||||
let circle = run(&mut s, "shape.ellipse", json!({"x":100,"y":100,"width":144,"height":144}))["id"].as_u64().unwrap();
|
||||
let radius = run(&mut s, "dimension.create", json!({"mode":"radius","source":{"kind":"circle","node":circle}}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "dimension.update", json!({"ids":[radius],"at":[172,400]}));
|
||||
let d = recipe(&s, radius);
|
||||
assert!(d.b.distance(vectorcraft_geom::Point::new(172.0, 244.0)) < 1e-6, "turned toward the point: {:?}", d.b);
|
||||
assert!((d.a.distance(d.b) - 72.0).abs() < 1e-6, "the radius stays");
|
||||
let before = recipe(&s, linear);
|
||||
for bad in [json!([1]), json!("x"), json!([0, 1e12])] {
|
||||
assert!(s.execute("dimension.update", &json!({"ids":[linear],"at":bad})).is_err(), "{bad}");
|
||||
assert_eq!(recipe(&s, linear), before);
|
||||
}
|
||||
}
|
||||
|
||||
/// A dimension dragged with the Dimension tool follows the part grabbed: a diameter grabbed on its
|
||||
/// far half turns that half toward the pointer, and an angular arc grabbed away from its middle
|
||||
/// grows by as much as the pointer moved away from the vertex.
|
||||
#[test]
|
||||
fn a_dragged_dimension_follows_the_part_grabbed() {
|
||||
let plain = ViewInfo::default();
|
||||
let mut s = session();
|
||||
let circle = run(&mut s, "shape.ellipse", json!({"x":100,"y":100,"width":144,"height":144}))["id"].as_u64().unwrap();
|
||||
let diameter = run(&mut s, "dimension.create", json!({"mode":"diameter","source":{"kind":"circle","node":circle}}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "dimension.update", json!({"ids":[diameter],"at":[244,172]}));
|
||||
let angular =
|
||||
run(&mut s, "dimension.create", json!({"mode":"angular","a":[500,400],"vertex":[400,400],"b":[400,500],"offset":60}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "select.none", json!({}));
|
||||
s.select_tool("dimension", plain).unwrap();
|
||||
let drag = |s: &mut Session, from: (f64, f64), to: (f64, f64)| {
|
||||
for (kind, (x, y)) in [(PointerKind::Move, from), (PointerKind::Down, from), (PointerKind::Drag, to), (PointerKind::Up, to)] {
|
||||
s.pointer(&PointerEvent::new(kind, x, y), plain).unwrap();
|
||||
}
|
||||
};
|
||||
// Grabbed left of the center and dragged up: the left half goes up, the right half down.
|
||||
drag(&mut s, (120.0, 172.0), (120.0, 152.0));
|
||||
let d = recipe(&s, diameter);
|
||||
assert!(d.b.y > 172.0 + 1.0, "the half not grabbed turns away from the pointer: {:?}", d.b);
|
||||
assert!((d.a.distance(d.b) - 72.0).abs() < 1e-6, "the radius stays");
|
||||
// Grabbed at the center: it turns toward the pointer.
|
||||
drag(&mut s, (172.0, 172.0), (172.0, 100.0));
|
||||
assert!(recipe(&s, diameter).b.distance(vectorcraft_geom::Point::new(172.0, 100.0)) < 1e-6, "{:?}", recipe(&s, diameter).b);
|
||||
// Grabbed 10° from the arc's start and dragged 20 points straight away from the vertex.
|
||||
let (sin, cos) = 10f64.to_radians().sin_cos();
|
||||
drag(&mut s, (400.0 + 60.0 * cos, 400.0 + 60.0 * sin), (400.0 + 80.0 * cos, 400.0 + 80.0 * sin));
|
||||
assert!((recipe(&s, angular).offset - 80.0).abs() < 1e-6, "the arc's radius: {}", recipe(&s, angular).offset);
|
||||
}
|
||||
|
||||
/// The Dimension tool takes a drag only from a dimension the canvas hits: one painted wider than
|
||||
/// the reach is taken by its stroke, while one outside isolation mode, around an isolated part of
|
||||
/// it, clipped away where the press is or drawn elsewhere by a geometry effect stays put. With
|
||||
/// Real-time Drawing off the dimension being dragged is outlined.
|
||||
#[test]
|
||||
fn a_dimension_is_dragged_only_where_the_canvas_hits_it() {
|
||||
use vectorcraft_engine::tools::Overlay;
|
||||
let plain = ViewInfo::default();
|
||||
let pt = vectorcraft_geom::Point::new;
|
||||
let at_170 = (pt(100.0, 170.0), pt(200.0, 170.0));
|
||||
let drag = |s: &mut Session, from: (f64, f64), to: (f64, f64)| {
|
||||
for (kind, (x, y)) in [(PointerKind::Move, from), (PointerKind::Down, from), (PointerKind::Drag, to), (PointerKind::Up, to)] {
|
||||
s.pointer(&PointerEvent::new(kind, x, y), plain).unwrap();
|
||||
}
|
||||
};
|
||||
// A 30-point line: a press 13 points from its middle is on its stroke.
|
||||
let (mut s, first) = level_start(plain);
|
||||
run(&mut s, "dimension.update", json!({"ids":[first],"options":{"lineWeight":30}}));
|
||||
drag(&mut s, (115.0, 183.0), (115.0, 143.0));
|
||||
assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0)));
|
||||
// Outside the isolated group: not moved.
|
||||
let (mut s, first) = level_start(plain);
|
||||
let rect = run(&mut s, "shape.rectangle", json!({"x":400,"y":50,"width":50,"height":50}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "select.set", json!({"ids":[rect]}));
|
||||
let group = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "object.isolate", json!({"id": group}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
drag(&mut s, (150.0, 170.0), (150.0, 130.0));
|
||||
assert_eq!(recipe(&s, first).line_ends(), at_170);
|
||||
// In a clipping mask that leaves its right half out: not taken there, taken on its left half.
|
||||
let (mut s, first) = level_start(plain);
|
||||
let mask = run(&mut s, "shape.rectangle", json!({"x":90,"y":140,"width":50,"height":90}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "select.set", json!({"ids":[first, mask]}));
|
||||
run(&mut s, "object.clippingMask.make", json!({}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let count = s.doc().unwrap().doc.node_count();
|
||||
drag(&mut s, (180.0, 170.0), (180.0, 130.0));
|
||||
assert_eq!((recipe(&s, first).line_ends(), s.doc().unwrap().doc.node_count()), (at_170, count));
|
||||
// That press picked a point, as a click there does: Escape drops it.
|
||||
s.tool_key(ToolKey::Escape, Mods::default(), plain).unwrap();
|
||||
drag(&mut s, (120.0, 170.0), (120.0, 130.0));
|
||||
assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0)));
|
||||
// In a group whose Transform effect draws it 50 points lower: not taken where it is drawn.
|
||||
let (mut s, first) = level_start(plain);
|
||||
run(&mut s, "select.set", json!({"ids":[first]}));
|
||||
let group = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "effect.apply", json!({"effect":"distort.transform","ids":[group],"params":{"moveV":50}}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
drag(&mut s, (150.0, 220.0), (150.0, 260.0));
|
||||
assert_eq!(recipe(&s, first).line_ends(), at_170);
|
||||
// In Outline view the canvas draws no effects: taken where its recipe puts it.
|
||||
s.tool_key(ToolKey::Escape, Mods::default(), plain).unwrap();
|
||||
let outline = ViewInfo { outline: true, ..plain };
|
||||
for (kind, y) in [(PointerKind::Move, 170.0), (PointerKind::Down, 170.0), (PointerKind::Drag, 130.0), (PointerKind::Up, 130.0)] {
|
||||
s.pointer(&PointerEvent::new(kind, 150.0, y), outline).unwrap();
|
||||
}
|
||||
assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0)));
|
||||
// A Transform effect on its parts draws them 50 points lower: not taken where they are drawn.
|
||||
let (mut s, first) = level_start(plain);
|
||||
let parts: Vec<u64> = s.doc().unwrap().doc.node(NodeId(first)).unwrap().children().unwrap().iter().map(|c| c.id.0).collect();
|
||||
run(&mut s, "effect.apply", json!({"effect":"distort.transform","ids":parts,"params":{"moveV":50}}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
drag(&mut s, (150.0, 220.0), (150.0, 260.0));
|
||||
assert_eq!(recipe(&s, first).line_ends(), at_170);
|
||||
// With one of its parts isolated, the dimension around it is outside the editing scope.
|
||||
let (mut s, first) = level_start(plain);
|
||||
let part = {
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let parts = doc.node(NodeId(first)).unwrap().children().unwrap();
|
||||
// The dimension line, which the press below lands on.
|
||||
let line = parts.iter().find(|c| c.geometric_bounds().is_some_and(|r| r.x0 < 150.0 && r.x1 > 150.0 && r.y0 < 171.0 && r.y1 > 169.0));
|
||||
line.unwrap().id.0
|
||||
};
|
||||
run(&mut s, "object.isolate", json!({"id": part}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
drag(&mut s, (150.0, 170.0), (150.0, 130.0));
|
||||
assert_eq!(recipe(&s, first).line_ends(), at_170);
|
||||
// Real-time Drawing off: the dimension is outlined where the drag puts it, and other selected
|
||||
// art, which the drag does not move, is not.
|
||||
let (mut s, first) = level_start(plain);
|
||||
let rect = run(&mut s, "shape.rectangle", json!({"x":400,"y":400,"width":50,"height":50}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "select.set", json!({"ids":[first, rect]}));
|
||||
run(&mut s, "prefs.set", json!({"key": "realTimeDrawing", "value": false}));
|
||||
for (kind, y) in [(PointerKind::Move, 170.0), (PointerKind::Down, 170.0), (PointerKind::Drag, 110.0)] {
|
||||
s.pointer(&PointerEvent::new(kind, 150.0, y), plain).unwrap();
|
||||
}
|
||||
let boxes: Vec<vectorcraft_geom::Rect> = s
|
||||
.overlays(plain)
|
||||
.into_iter()
|
||||
.filter_map(|o| if let Overlay::Path { path, .. } = o { Some(vectorcraft_geom::kurbo::Shape::bounding_box(&path)) } else { None })
|
||||
.collect();
|
||||
assert!(boxes.iter().any(|r| r.y0 < 111.0 && r.y1 > 109.0 && r.width() >= 99.0), "the dragged dimension is outlined at its new place");
|
||||
assert!(!boxes.iter().any(|r| r.x1 > 399.0), "the rectangle is not outlined: {boxes:?}");
|
||||
}
|
||||
|
||||
/// A geometry effect on a part of a dimension other than the one pressed keeps the Dimension tool
|
||||
/// from dragging it, and the effect stays on that part.
|
||||
#[test]
|
||||
fn a_geometry_effect_on_another_part_keeps_the_dimension_in_place() {
|
||||
let plain = ViewInfo::default();
|
||||
let pt = vectorcraft_geom::Point::new;
|
||||
let (mut s, first) = level_start(plain);
|
||||
let extension = {
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let parts = doc.node(NodeId(first)).unwrap().children().unwrap();
|
||||
// The extension line at x = 100, which the press below on the dimension line misses.
|
||||
let line = parts.iter().find(|c| c.geometric_bounds().is_some_and(|r| r.x1 < 101.0 && r.height() > 10.0));
|
||||
line.unwrap().id.0
|
||||
};
|
||||
run(&mut s, "effect.apply", json!({"effect":"distort.transform","ids":[extension],"params":{"moveH":-60}}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
for (kind, y) in [(PointerKind::Move, 170.0), (PointerKind::Down, 170.0), (PointerKind::Drag, 130.0), (PointerKind::Up, 130.0)] {
|
||||
s.pointer(&PointerEvent::new(kind, 150.0, y), plain).unwrap();
|
||||
}
|
||||
assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0)));
|
||||
let kept = s.doc().unwrap().doc.node(NodeId(extension)).is_some_and(|n| !n.appearance.effects.is_empty());
|
||||
assert!(kept, "the extension line keeps its effect");
|
||||
}
|
||||
|
||||
/// In isolation mode, art outside the isolated group does not take a press on a dimension inside
|
||||
/// it: the drag moves the dimension.
|
||||
#[test]
|
||||
fn art_outside_isolation_does_not_take_the_press_on_a_dimension() {
|
||||
let plain = ViewInfo::default();
|
||||
let pt = vectorcraft_geom::Point::new;
|
||||
let (mut s, first) = level_start(plain);
|
||||
// A line across the dimension line, outside the group isolated below. The press, a point below
|
||||
// the dimension line, is nearer to it than to the dimension line.
|
||||
run(&mut s, "path.create", json!({"d": "M150 100 L150 250"}));
|
||||
run(&mut s, "select.set", json!({"ids":[first]}));
|
||||
let group = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "object.isolate", json!({"id": group}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
for (kind, y) in [(PointerKind::Move, 171.0), (PointerKind::Down, 171.0), (PointerKind::Drag, 131.0), (PointerKind::Up, 131.0)] {
|
||||
s.pointer(&PointerEvent::new(kind, 150.0, y), plain).unwrap();
|
||||
}
|
||||
assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0)));
|
||||
}
|
||||
|
||||
/// A dimension pasted into a document that had none is dragged with the Dimension tool like one
|
||||
/// drawn there.
|
||||
#[test]
|
||||
fn a_dimension_pasted_into_another_document_is_dragged() {
|
||||
let plain = ViewInfo::default();
|
||||
let (mut s, first) = level_start(plain);
|
||||
run(&mut s, "select.set", json!({"ids":[first]}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
run(&mut s, "file.new", json!({"width": 612, "height": 792}));
|
||||
run(&mut s, "edit.paste", json!({}));
|
||||
let pasted = s.doc().unwrap().selection.objects[0].0;
|
||||
run(&mut s, "select.none", json!({}));
|
||||
s.select_tool("dimension", plain).unwrap();
|
||||
let (a, b) = recipe(&s, pasted).line_ends();
|
||||
let mid = a.midpoint(b);
|
||||
for (kind, y) in [(PointerKind::Move, mid.y), (PointerKind::Down, mid.y), (PointerKind::Drag, mid.y - 40.0), (PointerKind::Up, mid.y - 40.0)] {
|
||||
s.pointer(&PointerEvent::new(kind, mid.x, y), plain).unwrap();
|
||||
}
|
||||
let (a2, b2) = recipe(&s, pasted).line_ends();
|
||||
assert!((a2.y - (a.y - 40.0)).abs() < 1e-6 && (b2.y - (b.y - 40.0)).abs() < 1e-6, "{:?} → {:?}", (a, b), (a2, b2));
|
||||
}
|
||||
|
||||
/// A file that holds a dimension but was saved without the document's dimension flag (as one saved
|
||||
/// after a dimension was pasted into a document that had none) opens with its dimension dragged
|
||||
/// by the Dimension tool.
|
||||
#[test]
|
||||
fn a_dimension_in_a_file_saved_without_the_flag_is_dragged() {
|
||||
let plain = ViewInfo::default();
|
||||
let pt = vectorcraft_geom::Point::new;
|
||||
let (s, first) = level_start(plain);
|
||||
let mut doc = s.doc().unwrap().doc.as_ref().clone();
|
||||
doc.dimensions = false;
|
||||
let mut reopened = Session::new();
|
||||
reopened.add_document(vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(), None);
|
||||
reopened.select_tool("dimension", plain).unwrap();
|
||||
for (kind, y) in [(PointerKind::Move, 170.0), (PointerKind::Down, 170.0), (PointerKind::Drag, 130.0), (PointerKind::Up, 130.0)] {
|
||||
reopened.pointer(&PointerEvent::new(kind, 150.0, y), plain).unwrap();
|
||||
}
|
||||
assert_eq!(recipe(&reopened, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0)));
|
||||
}
|
||||
|
||||
/// A second dimension of the same two points as a dimension already drawn lands on its level too.
|
||||
/// Off every level, a pointer moved in small steps while it is placed puts the line at each step,
|
||||
/// with no pull from the preview of the dimension itself.
|
||||
|
||||
@@ -32,6 +32,7 @@ mod pen_rubber_band;
|
||||
mod ruler_guide_nodes;
|
||||
mod ruler_guide_perf;
|
||||
mod ruler_origin;
|
||||
mod script_host_vs_scriptcheck;
|
||||
mod selection_commands;
|
||||
mod stroke_visibility;
|
||||
mod text_stroke_scale;
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
//! Every global and member the script host (`script.run`) adds to the JavaScript engine is in one of
|
||||
//! the tables below, and each name that reaches outside the document has the `outside` id
|
||||
//! `script.check` (`vectorcraft-scriptcheck`) gives it. The names are read from a run: the own
|
||||
//! properties of the global object, of each object or function it holds and of each function's
|
||||
//! `prototype`, with a setter listed again as `name=`. The names a plain `vectorcraft_js::Realm` also
|
||||
//! has are the language's, which reach files and other apps only through the host; `eval` and
|
||||
//! `Function` still have rows, since they run code the checker can't read. A name the host adds
|
||||
//! without a row fails the test.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_js::{DirectiveName, JsValue, Realm};
|
||||
use vectorcraft_scriptcheck::{Limits, check};
|
||||
|
||||
/// The names that reach outside the document: each with a script that uses it and the `outside` id
|
||||
/// the checker gives that script.
|
||||
const OUTSIDE: &[(&str, &str, &str)] = &[
|
||||
("eval", "eval(s);", "unseenCode"),
|
||||
("Function", "var g = new Function(s);", "unseenCode"),
|
||||
("$.evalFile", "$.evalFile(p);", "unseenCode"),
|
||||
("$.getenv", "var h = $.getenv(n);", "environment"),
|
||||
("$.setenv", "$.setenv(n, v);", "environment"),
|
||||
("File.prototype.open", "var f = new File(p); f.open('w');", "filesWritten"),
|
||||
("File.prototype.write", "var f = new File(p); f.write(s);", "filesWritten"),
|
||||
("File.prototype.writeln", "var f = new File(p); f.writeln(s);", "filesWritten"),
|
||||
("File.prototype.copy", "var f = new File(p); f.copy(q);", "filesWritten"),
|
||||
("File.prototype.createAlias", "var f = new File(p); f.createAlias(q);", "filesWritten"),
|
||||
("File.prototype.remove", "var f = new File(p); f.remove();", "filesWritten"),
|
||||
("File.prototype.rename", "var f = new File(p); f.rename(q);", "filesWritten"),
|
||||
("File.prototype.length=", "var f = new File(p); f.length = 0;", "filesWritten"),
|
||||
("File.prototype.hidden=", "var f = new File(p); f.hidden = true;", "filesWritten"),
|
||||
("File.prototype.readonly=", "var f = new File(p); f.readonly = true;", "filesWritten"),
|
||||
("File.prototype.execute", "var f = new File(p); f.execute();", "filesOpened"),
|
||||
("Folder.prototype.create", "var d = new Folder(p); d.create();", "filesWritten"),
|
||||
("Folder.prototype.remove", "var d = new Folder(p); d.remove();", "filesWritten"),
|
||||
("Folder.prototype.rename", "var d = new Folder(p); d.rename(q);", "filesWritten"),
|
||||
("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"),
|
||||
];
|
||||
|
||||
/// The names the host adds that stay inside the document and the run, by the object that has them.
|
||||
/// Reading a file or a folder, a file dialog and a message to the person do not change anything
|
||||
/// outside it.
|
||||
const INSIDE: &[(&str, &str)] = &[
|
||||
("", "$ File Folder alert confirm localize prompt toSource"),
|
||||
("Object.prototype.", "toSource"),
|
||||
("localize.", "length"),
|
||||
("toSource.", "length"),
|
||||
(
|
||||
"$.",
|
||||
"about appEncoding appEncoding= bp build buildDate colorPicker decimalPoint engineName error fileName flags \
|
||||
flags= gc global hiresTimer includePath level line locale locale= localize localize= memCache memCache= os screens \
|
||||
sleep stack strict version write writeln",
|
||||
),
|
||||
("File.", "decode encode fs isEncodingAvailable openDialog saveDialog length prototype"),
|
||||
(
|
||||
"File.prototype.",
|
||||
"absoluteURI alias changePath close constructor created creator displayName encoding encoding= eof error error= \
|
||||
exists fsName fullName getRelativeURI hidden length lineFeed lineFeed= modified name openDlg parent path read \
|
||||
readch readln readonly relativeURI resolve saveDlg seek tell toString type",
|
||||
),
|
||||
(
|
||||
"Folder.",
|
||||
"appData appPackage commonFiles current current= decode desktop encode fs isEncodingAvailable length myDocuments \
|
||||
prototype selectDialog startup system temp trash userData",
|
||||
),
|
||||
(
|
||||
"Folder.prototype.",
|
||||
"absoluteURI alias changePath constructor created displayName error error= exists fsName fullName getFiles \
|
||||
getRelativeURI modified name parent path relativeURI resolve selectDlg toString",
|
||||
),
|
||||
];
|
||||
|
||||
/// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's
|
||||
/// own API, and what `vc.run` does depends on the command it runs.
|
||||
const NOT_CHECKED: &str = "vc";
|
||||
|
||||
/// An expression whose value is the list of names, one to a line.
|
||||
const LIST: &str = r#"(function () {
|
||||
var out = [];
|
||||
function add(o, prefix) {
|
||||
var own = Object.getOwnPropertyNames(o);
|
||||
for (var i = 0; i < own.length; i++) {
|
||||
out.push(prefix + own[i]);
|
||||
var d = Object.getOwnPropertyDescriptor(o, own[i]);
|
||||
if (d && d.set) out.push(prefix + own[i] + "=");
|
||||
}
|
||||
}
|
||||
var g = (function () { return this; })();
|
||||
var globals = Object.getOwnPropertyNames(g);
|
||||
add(g, "");
|
||||
for (var i = 0; i < globals.length; i++) {
|
||||
var v = g[globals[i]];
|
||||
if (v !== null && (typeof v == "object" || typeof v == "function")) {
|
||||
add(v, globals[i] + ".");
|
||||
if (typeof v == "function" && v.prototype !== null && typeof v.prototype == "object") add(v.prototype, globals[i] + ".prototype.");
|
||||
}
|
||||
}
|
||||
return out.join("\n");
|
||||
})()"#;
|
||||
|
||||
/// The names a script run by the host has.
|
||||
fn host_names() -> BTreeSet<String> {
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("script.run", &json!({"source": format!("vc.log({LIST});"), "name": "list.js"})).unwrap();
|
||||
let text = r["log"][0].as_str().unwrap_or_else(|| panic!("no list in {r}"));
|
||||
text.lines().map(str::to_string).collect()
|
||||
}
|
||||
|
||||
/// The names a plain JavaScript engine has.
|
||||
fn language_names() -> BTreeSet<String> {
|
||||
match Realm::new().run(LIST) {
|
||||
Ok(JsValue::String(text)) => text.lines().map(str::to_string).collect(),
|
||||
other => panic!("no list: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn table_names() -> BTreeSet<String> {
|
||||
let inside = INSIDE.iter().flat_map(|(prefix, names)| names.split_whitespace().map(move |n| format!("{prefix}{n}")));
|
||||
OUTSIDE.iter().map(|(n, ..)| n.to_string()).chain(inside).chain([NOT_CHECKED.to_string()]).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_name_the_host_adds_has_a_row() {
|
||||
let host = host_names();
|
||||
let language = language_names();
|
||||
let table = table_names();
|
||||
let not_checked = |n: &&String| n.starts_with(&format!("{NOT_CHECKED}."));
|
||||
let missing: Vec<_> = host.difference(&language).filter(|n| !table.contains(*n) && !not_checked(n)).collect();
|
||||
assert!(missing.is_empty(), "the host adds these names, which no table here lists: {missing:?}");
|
||||
let gone: Vec<_> = table.difference(&host).collect();
|
||||
assert!(gone.is_empty(), "the tables list these names, which a script run by the host does not have: {gone:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_name_that_reaches_outside_has_its_checker_id() {
|
||||
for (name, script, id) in OUTSIDE {
|
||||
let r = check("probe.jsx", script.as_bytes(), None, &Limits::default());
|
||||
let ids: Vec<_> = r.outside.iter().map(|o| o.id).collect();
|
||||
assert!(ids.contains(id), "{name}: the checker gives {ids:?} for {script:?}, not {id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A line with the directive `d`. The match has no catch-all, so a new directive needs a row, and
|
||||
/// [`DirectiveName::from_name`] reads only the directives in [`DirectiveName::ALL`].
|
||||
fn directive_line(d: DirectiveName) -> &'static str {
|
||||
match d {
|
||||
DirectiveName::Include => "#include \"lib.jsxinc\"",
|
||||
DirectiveName::IncludePath => "#includepath \"lib\"",
|
||||
DirectiveName::Script => "#script Tidy",
|
||||
DirectiveName::Strict => "#strict on",
|
||||
DirectiveName::Target => "#target vectorcraft",
|
||||
DirectiveName::TargetEngine => "#targetengine session",
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_checker_lists_every_directive_the_host_reads() {
|
||||
for d in DirectiveName::ALL {
|
||||
let line = directive_line(d);
|
||||
let r = check("probe.jsx", format!("{line}\nvar a = 1;\n").as_bytes(), None, &Limits::default());
|
||||
let listed: Vec<_> = r.directives.iter().map(|d| d.name.to_string()).collect();
|
||||
assert_eq!(listed, [d.as_str()], "{line}");
|
||||
}
|
||||
}
|
||||
@@ -719,7 +719,9 @@ fn alpha_against_supersampled(d: &Document) -> (usize, usize, u8, usize, Vec<Str
|
||||
/// underlay of its faces clipped to the surface's outline: at 1:1, no pixel inside the art lets the
|
||||
/// background through where a 3x render averaged down is opaque, none paints past the outline, and
|
||||
/// a surface's opacity, its gradient's transparent stops and its blending mode apply once. The same
|
||||
/// holds for the art read back from SVG and PDF and for Expand Appearance.
|
||||
/// holds for the art read back from SVG and PDF and for Expand Appearance. Inside the body, the alpha
|
||||
/// is 153 within 3 levels with a fill opacity of 60%, 214 within 3 levels with 60% gradient stops
|
||||
/// (front and back faces at 60% each), and 255 when opaque.
|
||||
#[test]
|
||||
fn colored_revolve_faces_leave_no_alpha_holes_at_one_to_one() {
|
||||
let gradient = |opacity: f64| {
|
||||
@@ -764,6 +766,21 @@ fn colored_revolve_faces_leave_no_alpha_holes_at_one_to_one() {
|
||||
] {
|
||||
let (measured, off, worst, past, first) = alpha_against_supersampled(&d);
|
||||
assert!(measured > 10_000, "{name} {of}: {measured} pixels inside");
|
||||
// The 3x comparison passes when an opacity is lost or doubled at both scales, so the
|
||||
// surface's alpha is also checked against the value it should have.
|
||||
// With 60% gradient stops, each face takes the stops' opacity, so where the front and
|
||||
// back of the body overlap the alpha is 1 - 0.4 * 0.4 of 255.
|
||||
let alpha = render(&d).pixel(150, 200)[3];
|
||||
let expected = if name.ends_with("fill at 60%") {
|
||||
150..=156
|
||||
} else if name.ends_with("gradient at 60%") {
|
||||
211..=217
|
||||
} else {
|
||||
255..=255
|
||||
};
|
||||
if !expected.contains(&alpha) {
|
||||
failures.push(format!("{name} {of}: surface alpha {alpha}, expected {expected:?}"));
|
||||
}
|
||||
if off > 0 || past > 0 {
|
||||
failures.push(format!("{name} {of}: of {measured} pixels, {off} off (at most {worst}), {past} past the outline: {first:?}"));
|
||||
}
|
||||
|
||||
@@ -883,9 +883,10 @@ proptest! {
|
||||
}
|
||||
|
||||
/// A plug-in that calls the storage imports with hostile keys (`..`, separators, device names,
|
||||
/// control characters, too long), values, lengths and pointers in and out of its memory runs to
|
||||
/// an output, never a panic; every call returns a length or a storage code, and the settings and
|
||||
/// cache of another plug-in in the same store stay as they were.
|
||||
/// control characters, too long), values, lengths up to about 1 MiB and pointers in and out of
|
||||
/// its memory runs to an output, or on a small budget to its instruction budget, never a panic;
|
||||
/// every call returns a length or a storage code, and the settings and cache of another plug-in
|
||||
/// in the same store stay as they were.
|
||||
#[test]
|
||||
fn hostile_storage_arguments_never_crash(
|
||||
calls in prop::collection::vec(
|
||||
@@ -894,11 +895,12 @@ proptest! {
|
||||
prop_oneof![any::<i32>(), 0x1ff00..0x20100i32, Just(0x2000)],
|
||||
prop_oneof![any::<i32>(), 0..80i32],
|
||||
prop_oneof![any::<i32>(), 0x1ff00..0x20100i32, Just(0x3000)],
|
||||
prop_oneof![any::<i32>(), 0..5000i32],
|
||||
prop_oneof![any::<i32>(), 0..5000i32, 0..1_100_000i32],
|
||||
),
|
||||
0..16,
|
||||
),
|
||||
key in prop::collection::vec(prop_oneof![Just(b'a'), Just(b'.'), Just(b'/'), Just(b'\\'), Just(b'_'), any::<u8>()], 0..80),
|
||||
fuel in prop::option::of(1_000..200_000u64),
|
||||
) {
|
||||
use vectorcraft_plugins::host::STORAGE_BUDGET;
|
||||
use vectorcraft_plugins::storage::Meter;
|
||||
@@ -936,17 +938,31 @@ proptest! {
|
||||
.collect();
|
||||
let text: String = key.iter().map(|b| format!("\\{b:02x}")).collect();
|
||||
let imports = format!(r#"{} (data (i32.const 0x2000) "{text}")"#, tpl::STORAGE_IMPORTS);
|
||||
let wasm = wat::parse_str(tpl::with_imports(&storing("fuzz.storage"), &imports, &format!("(local $r i32) {body}"), r#"{"objects":[]}"#)).unwrap();
|
||||
// 64 more pages hold the values of the large writes.
|
||||
let wasm = wat::parse_str(tpl::with_imports(
|
||||
&storing("fuzz.storage"),
|
||||
&imports,
|
||||
&format!("(local $r i32) (drop (memory.grow (i32.const 64))) {body}"),
|
||||
r#"{"objects":[]}"#,
|
||||
))
|
||||
.unwrap();
|
||||
// A failed case leaves its module installed, and the cases that shrink it install others
|
||||
// under the same id.
|
||||
let r = catch_quiet(|| {
|
||||
s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true}))
|
||||
.map_err(|e| e.to_string())?;
|
||||
let p = vectorcraft_plugins::registry::get("fuzz.storage").ok_or("not installed")?;
|
||||
p.run(b"{\"objects\":[]}", b"{}").map_err(|e| e.to_string())
|
||||
// A small budget runs out on the bytes the storage calls move.
|
||||
let limits = Limits { fuel_base: fuel.unwrap_or(p.limits().fuel_base), fuel_per_byte: 0, ..p.limits().clone() };
|
||||
p.run_limited(b"{\"objects\":[]}", b"{}", &limits).map_err(|e| e.to_string())
|
||||
});
|
||||
let out = r.map_err(|msg| TestCaseError::fail(format!("panicked on {calls:?}: {msg}")))?;
|
||||
prop_assert!(out.is_ok(), "{:?}", out);
|
||||
prop_assert!(
|
||||
out.is_ok() || (fuel.is_some() && out == Err(Error::Limit("instruction budget".into()).to_string())),
|
||||
"{:?} on {:?} instructions",
|
||||
out,
|
||||
fuel
|
||||
);
|
||||
prop_assert_eq!(theirs.setting("mine", m).unwrap(), Some(b"kept".to_vec()));
|
||||
prop_assert_eq!(theirs.cache_entry("mine", m).unwrap(), Some(b"kept".to_vec()));
|
||||
prop_assert_eq!(theirs.cache_bytes(), 4);
|
||||
|
||||
@@ -463,6 +463,177 @@ fn expand_appearance_keeps_a_plug_in_effect_safe_mode_skips() {
|
||||
s.execute("effect.expandAppearance", &json!({})).unwrap();
|
||||
}
|
||||
|
||||
/// In Safe Mode, Expand Appearance refuses a group whose raster effect makes an image of a plain
|
||||
/// instance in it when the instance's symbol art holds a plug-in effect.
|
||||
#[test]
|
||||
fn expand_appearance_in_safe_mode_checks_symbol_art_a_group_image_draws() {
|
||||
let _f = fresh();
|
||||
let mut s = Session::new();
|
||||
let fx = wat::parse_str(tpl::returning(&tpl::manifest("test.sm.sym", "effect", "{}"), r#"{"objects":[]}"#)).unwrap();
|
||||
s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&fx)})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "plugin.test.sm.sym"})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "fx"})).unwrap();
|
||||
let plain = s.execute("symbol.place", &json!({"name": "fx", "x": 100, "y": 100})).unwrap()["id"].clone();
|
||||
let refused = |s: &mut Session, group: &Value| {
|
||||
let before = s.execute("document.inspect", &json!({})).unwrap();
|
||||
safe_mode::set_active(Some(safe_mode::Source::Flag));
|
||||
let err = s.execute("effect.expandAppearance", &json!({"ids": [group]})).unwrap_err().to_string();
|
||||
safe_mode::set_active(None);
|
||||
assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}");
|
||||
assert_eq!(s.execute("document.inspect", &json!({})).unwrap(), before, "nothing changes");
|
||||
};
|
||||
// A Gaussian Blur of the group's own.
|
||||
let group = s.execute("object.group", &json!({"ids": [plain]})).unwrap()["id"].clone();
|
||||
s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [group], "params": {"radius": 2}})).unwrap();
|
||||
refused(&mut s, &group);
|
||||
// A Gaussian Blur on a fill of a group around a group that holds another plain instance.
|
||||
let blurred_fill = {
|
||||
let t = s.execute("shape.rectangle", &json!({"x": 150, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [t], "item": 0, "params": {"radius": 2}})).unwrap();
|
||||
s.doc().unwrap().doc.node(vectorcraft_engine::doc::NodeId(t)).unwrap().appearance.items[0].clone()
|
||||
};
|
||||
let plain = s.execute("symbol.place", &json!({"name": "fx", "x": 100, "y": 20})).unwrap()["id"].clone();
|
||||
let inner = s.execute("object.group", &json!({"ids": [plain]})).unwrap()["id"].clone();
|
||||
let outer = s.execute("object.group", &json!({"ids": [inner]})).unwrap()["id"].as_u64().unwrap();
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc)
|
||||
.node_mut(vectorcraft_engine::doc::NodeId(outer))
|
||||
.unwrap()
|
||||
.appearance
|
||||
.items
|
||||
.push(blurred_fill);
|
||||
refused(&mut s, &json!(outer));
|
||||
}
|
||||
|
||||
/// In Safe Mode, a hidden plain instance draws nothing in the image a group's raster effect makes,
|
||||
/// so its symbol art's plug-in effect doesn't stop Expand Appearance of the group; shown, it does.
|
||||
#[test]
|
||||
fn expand_appearance_in_safe_mode_skips_symbol_art_of_a_hidden_instance_a_group_image_leaves_out() {
|
||||
let _f = fresh();
|
||||
let mut s = Session::new();
|
||||
let fx = wat::parse_str(tpl::returning(&tpl::manifest("test.sm.hid", "effect", "{}"), r#"{"objects":[]}"#)).unwrap();
|
||||
s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&fx)})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "plugin.test.sm.hid"})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "fx"})).unwrap();
|
||||
let hide = |s: &mut Session, id: u64| {
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(vectorcraft_engine::doc::NodeId(id)).unwrap().visible = false;
|
||||
};
|
||||
let expand = |s: &mut Session, group: u64| {
|
||||
safe_mode::set_active(Some(safe_mode::Source::Flag));
|
||||
let r = s.execute("effect.expandAppearance", &json!({"ids": [group]}));
|
||||
safe_mode::set_active(None);
|
||||
r
|
||||
};
|
||||
// A blurred group of a visible rectangle and an instance, then one of a visible rectangle and a
|
||||
// group around an instance; the instance, or the group around it, is shown and then hidden.
|
||||
for wrap in [false, true] {
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap()["id"].clone();
|
||||
let mut hidden = s.execute("symbol.place", &json!({"name": "fx", "x": 150, "y": 150})).unwrap()["id"].clone();
|
||||
if wrap {
|
||||
hidden = s.execute("object.group", &json!({"ids": [hidden]})).unwrap()["id"].clone();
|
||||
}
|
||||
let group = s.execute("object.group", &json!({"ids": [rect, hidden]})).unwrap()["id"].clone();
|
||||
s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [group], "params": {"radius": 2}})).unwrap();
|
||||
let (hidden, group) = (hidden.as_u64().unwrap(), group.as_u64().unwrap());
|
||||
let err = expand(&mut s, group).unwrap_err().to_string();
|
||||
assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}");
|
||||
hide(&mut s, hidden);
|
||||
expand(&mut s, group).unwrap();
|
||||
}
|
||||
// Expansion still makes the image of a hidden blurred group, or of one in a hidden group, so
|
||||
// a shown instance in it still stops it.
|
||||
let plain = s.execute("symbol.place", &json!({"name": "fx", "x": 150, "y": 20})).unwrap()["id"].clone();
|
||||
let blurred = s.execute("object.group", &json!({"ids": [plain]})).unwrap()["id"].clone();
|
||||
s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [blurred], "params": {"radius": 2}})).unwrap();
|
||||
let parent = s.execute("object.group", &json!({"ids": [blurred]})).unwrap()["id"].as_u64().unwrap();
|
||||
hide(&mut s, parent);
|
||||
let err = expand(&mut s, parent).unwrap_err().to_string();
|
||||
assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}");
|
||||
let blurred = blurred.as_u64().unwrap();
|
||||
hide(&mut s, blurred);
|
||||
let err = expand(&mut s, blurred).unwrap_err().to_string();
|
||||
assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}");
|
||||
}
|
||||
|
||||
/// In Safe Mode, the image a layer's raster effect makes leaves out a template sublayer, so the symbol
|
||||
/// art of a plain instance in it doesn't stop Expand Appearance of the layer; in a plain sublayer, it does.
|
||||
#[test]
|
||||
fn expand_appearance_in_safe_mode_skips_symbol_art_in_a_template_sublayer_a_layer_image_leaves_out() {
|
||||
let _f = fresh();
|
||||
let mut s = Session::new();
|
||||
let fx = wat::parse_str(tpl::returning(&tpl::manifest("test.sm.tpl", "effect", "{}"), r#"{"objects":[]}"#)).unwrap();
|
||||
s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&fx)})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "plugin.test.sm.tpl"})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "fx"})).unwrap();
|
||||
let layer = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("layer.setCurrent", &json!({"id": layer})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap();
|
||||
let instance = s.execute("symbol.place", &json!({"name": "fx", "x": 150, "y": 150})).unwrap()["id"].as_u64().unwrap();
|
||||
let sub = s.execute("layer.newSublayer", &json!({"parent": layer})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("layer.move", &json!({"ids": [instance], "target": sub})).unwrap();
|
||||
s.execute("layer.target", &json!({"id": layer})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [layer], "item": null, "params": {"radius": 2}})).unwrap();
|
||||
let blurred = |s: &Session| s.doc().unwrap().doc.node(vectorcraft_engine::doc::NodeId(layer)).unwrap().appearance.effects.len();
|
||||
assert_eq!(blurred(&s), 1, "the layer has its own Gaussian Blur");
|
||||
let expand = |s: &mut Session| {
|
||||
s.execute("layer.target", &json!({"id": layer})).unwrap();
|
||||
safe_mode::set_active(Some(safe_mode::Source::Flag));
|
||||
let r = s.execute("effect.expandAppearance", &json!({}));
|
||||
safe_mode::set_active(None);
|
||||
r
|
||||
};
|
||||
let err = expand(&mut s).unwrap_err().to_string();
|
||||
assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}");
|
||||
s.execute("layer.setProps", &json!({"id": sub, "template": true})).unwrap();
|
||||
expand(&mut s).unwrap();
|
||||
}
|
||||
|
||||
/// In Safe Mode, a group whose Gaussian Blur makes it one image leaves out a hidden blurred group in
|
||||
/// it, which makes no image of its own, so the symbol art of a plain instance there doesn't stop
|
||||
/// Expand Appearance. Under a Drop Shadow, whose members expand on their own, the hidden group still
|
||||
/// makes its image, so it does.
|
||||
#[test]
|
||||
fn expand_appearance_in_safe_mode_skips_a_hidden_blurred_group_that_a_blurred_group_image_leaves_out() {
|
||||
let _f = fresh();
|
||||
let mut s = Session::new();
|
||||
let fx = wat::parse_str(tpl::returning(&tpl::manifest("test.sm.nest", "effect", "{}"), r#"{"objects":[]}"#)).unwrap();
|
||||
s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&fx)})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "plugin.test.sm.nest"})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "fx"})).unwrap();
|
||||
let expand = |s: &mut Session, group: u64| {
|
||||
safe_mode::set_active(Some(safe_mode::Source::Flag));
|
||||
let r = s.execute("effect.expandAppearance", &json!({"ids": [group]}));
|
||||
safe_mode::set_active(None);
|
||||
r
|
||||
};
|
||||
for (outer, allowed) in [("blur.gaussian", true), ("stylize.dropShadow", false)] {
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap()["id"].clone();
|
||||
let plain = s.execute("symbol.place", &json!({"name": "fx", "x": 150, "y": 150})).unwrap()["id"].clone();
|
||||
let inner = s.execute("object.group", &json!({"ids": [plain]})).unwrap()["id"].clone();
|
||||
s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [inner], "params": {"radius": 2}})).unwrap();
|
||||
let group = s.execute("object.group", &json!({"ids": [rect, inner]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": outer, "ids": [group]})).unwrap();
|
||||
let inner = vectorcraft_engine::doc::NodeId(inner.as_u64().unwrap());
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(inner).unwrap().visible = false;
|
||||
let r = expand(&mut s, group);
|
||||
if allowed {
|
||||
r.unwrap();
|
||||
// The blurred group became its image: the hidden group in it was not expanded on its own.
|
||||
assert!(s.doc().unwrap().doc.node(inner).is_none(), "the hidden group went into the image");
|
||||
} else {
|
||||
let err = r.unwrap_err().to_string();
|
||||
assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{outer}: {err}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// In Safe Mode, a plug-in effect in the art of a graph design in a series stops Expand Appearance of the graph only
|
||||
/// when an effect of the series group draws that art with the group.
|
||||
#[test]
|
||||
|
||||
@@ -112,6 +112,26 @@ fn preflight_resolution_follows_placed_size_and_both_axes() {
|
||||
assert!(codes(&screen).is_empty(), "{screen}");
|
||||
}
|
||||
|
||||
/// A distorted image's resolution is measured at its middle, as Image Info measures it.
|
||||
#[test]
|
||||
fn preflight_resolution_of_a_distorted_image_is_image_infos() {
|
||||
let dir = Folder::new("preflight-resolution-distorted");
|
||||
let path = dir.file("picture.png");
|
||||
std::fs::write(&path, png(100, 100, [200, 50, 10])).unwrap();
|
||||
let mut s = new();
|
||||
let id = s.execute("file.place", &json!({ "path": path, "link": false, "at": [200, 200] })).unwrap()["ids"][0].clone();
|
||||
s.execute("select.set", &json!({ "ids": [id] })).unwrap();
|
||||
s.execute("object.setBounds", &json!({ "width": 24, "height": 24 })).unwrap();
|
||||
assert!(codes(&s.execute("document.preflight", &json!({ "minPpi": 200 })).unwrap()).is_empty());
|
||||
// The top stays 24 pt wide; the bottom is 120 pt wide.
|
||||
s.execute("object.distort", &json!({ "corners": [[188, 188], [212, 188], [260, 212], [140, 212]] })).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().is_distorted_image());
|
||||
let info = s.execute("image.info", &json!({ "id": id })).unwrap();
|
||||
let r = s.execute("document.preflight", &json!({ "minPpi": 200 })).unwrap();
|
||||
let f = r["findings"].as_array().unwrap().iter().find(|f| f["code"] == "lowResolution").expect("a low resolution finding");
|
||||
assert_eq!(f["effectivePpi"], info["ppi"], "{info}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_resolution_accepts_the_exact_threshold_but_rejects_a_real_shortfall() {
|
||||
let dir = Folder::new("preflight-resolution-boundary");
|
||||
|
||||
@@ -9309,6 +9309,57 @@ fn a_masked_copy_nested_too_deep_for_its_mask_keeps_all_of_its_pixels() {
|
||||
assert!(whole >= 2, "the first copy and a copy whose mask is left out: {sizes:?}");
|
||||
}
|
||||
|
||||
/// A distorted image in the art of an opacity mask written at the deepest level a mask takes is
|
||||
/// written as its pieces, as an undistorted image there is written whole: the mask keeps its art.
|
||||
#[test]
|
||||
fn a_distorted_image_in_a_mask_at_the_nesting_limit_keeps_its_pixels() {
|
||||
// GUARDS: the distorted image was written there as an empty group, so the mask hid the object.
|
||||
let masks = |distorted: bool| {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let mut masked = speckled_photo(&mut doc);
|
||||
let mut art = speckled_photo(&mut doc);
|
||||
if distorted {
|
||||
let q = [(40.0, 10.0), (100.0, 10.0), (148.0, 138.0), (20.0, 138.0)].map(|(x, y)| vectorcraft_geom::Point::new(x, y));
|
||||
art.set_image_corners(q).unwrap();
|
||||
}
|
||||
masked.extras_mut().mask = Some(Box::new(OpacityMask { art: Arc::new(art), clip: false, invert: false, disabled: false, linked: true }));
|
||||
doc.symbols.push(Symbol { dynamic: false, name: "S0".into(), art: Arc::new(masked) });
|
||||
// Each isolated instance is written as its art, a level deeper: the masked object's mask
|
||||
// art is at the limit.
|
||||
for i in 1..writer::MAX_NEST - 1 {
|
||||
let mut inner = instance(&mut doc, &format!("S{}", i - 1), Affine::IDENTITY);
|
||||
inner.isolate = true;
|
||||
doc.symbols.push(Symbol { dynamic: false, name: format!("S{i}"), art: Arc::new(inner) });
|
||||
}
|
||||
let mut outer = instance(&mut doc, &format!("S{}", writer::MAX_NEST - 2), Affine::IDENTITY);
|
||||
outer.isolate = true;
|
||||
doc.insert(Some(layer), usize::MAX, outer).unwrap();
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
assert!(!out.warnings.iter().any(|w| w == writer::DEEP_MASKS), "{:?}", out.warnings);
|
||||
// Each mask read back, by whether its art holds an image.
|
||||
let back = read_back(&doc);
|
||||
let mut found = vec![];
|
||||
let mut look = |n: &Node| {
|
||||
if let Some(m) = n.extras().mask.as_ref() {
|
||||
let mut image = false;
|
||||
m.art.walk(&mut |c| image |= matches!(c.kind, NodeKind::Image(_)));
|
||||
found.push(image);
|
||||
}
|
||||
};
|
||||
for l in &back.layers {
|
||||
l.walk(&mut look);
|
||||
}
|
||||
for s in &back.symbols {
|
||||
s.art.walk(&mut look);
|
||||
}
|
||||
found
|
||||
};
|
||||
let (plain, distorted) = (masks(false), masks(true));
|
||||
assert!(!plain.is_empty() && plain.iter().all(|i| *i), "{plain:?}");
|
||||
assert_eq!(distorted, plain);
|
||||
}
|
||||
|
||||
/// [`warped_photo`] linked to `/Users/someone/Job/art/photo.png`, in folder `art` next to the
|
||||
/// document's.
|
||||
fn linked_warped_photo(doc: &mut Document, effects: Vec<vectorcraft_doc::Effect>) -> Node {
|
||||
|
||||
@@ -974,8 +974,9 @@ impl<'a> Writer<'a> {
|
||||
self.warn(w);
|
||||
}
|
||||
let moved = bounds && self.wrap_on_bounds(n, state);
|
||||
// A gradient mesh's drawn look is paths, which hold nothing: it is written at any depth.
|
||||
if self.nest < MAX_NEST || matches!(n.kind, NodeKind::Mesh(_)) {
|
||||
// A gradient mesh's drawn look is paths, and a distorted image's is clipped copies of its
|
||||
// image, which hold nothing: they are written at any depth.
|
||||
if self.nest < MAX_NEST || matches!(n.kind, NodeKind::Mesh(_)) || n.is_distorted_image() {
|
||||
let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n);
|
||||
self.nest += 1;
|
||||
self.drawn += 1;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user