Merge remote-tracking branch 'origin/main' into fix/7112

# Conflicts:
#	crates/engine/src/cmd/buildcmds.rs
This commit is contained in:
bflatastic
2026-11-19 21:21:47 +07:00
99 changed files with 6477 additions and 454 deletions
Generated
+44 -40
View File
@@ -1001,7 +1001,7 @@ dependencies = [
[[package]]
name = "craft-affinity"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"crc32fast",
"flate2",
@@ -1012,12 +1012,12 @@ dependencies = [
[[package]]
name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
[[package]]
name = "craft-dds"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"rayon",
]
@@ -1025,12 +1025,12 @@ dependencies = [
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
[[package]]
name = "craft-dxf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"craft-codepage",
"encoding_rs",
@@ -1042,12 +1042,12 @@ dependencies = [
[[package]]
name = "craft-eps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
[[package]]
name = "craft-font-catalog"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"harfrust 0.13.3",
"kurbo 0.13.1",
@@ -1061,12 +1061,12 @@ dependencies = [
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
[[package]]
name = "craft-gif"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"gif",
]
@@ -1074,7 +1074,7 @@ dependencies = [
[[package]]
name = "craft-gzip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"flate2",
]
@@ -1082,7 +1082,7 @@ dependencies = [
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"fixed_decimal",
"icu_decimal",
@@ -1105,7 +1105,7 @@ dependencies = [
[[package]]
name = "craft-image-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"craft-dds",
"craft-jpeg",
@@ -1132,7 +1132,7 @@ dependencies = [
[[package]]
name = "craft-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"thiserror 2.0.21",
]
@@ -1140,8 +1140,9 @@ dependencies = [
[[package]]
name = "craft-jxl"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"brotli-decompressor 5.0.3",
"jixel",
"jxl-oxide",
"thiserror 2.0.21",
@@ -1150,7 +1151,7 @@ dependencies = [
[[package]]
name = "craft-keymap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"egui",
"serde",
@@ -1160,7 +1161,7 @@ dependencies = [
[[package]]
name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"brotli-decompressor 6.3.2",
"chrono",
@@ -1172,7 +1173,7 @@ dependencies = [
[[package]]
name = "craft-metafile"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"encoding_rs",
"image",
@@ -1183,7 +1184,7 @@ dependencies = [
[[package]]
name = "craft-mime"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"chrono",
"craft-codepage",
@@ -1193,7 +1194,7 @@ dependencies = [
[[package]]
name = "craft-pdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"hayro-interpret",
"hayro-syntax",
@@ -1204,15 +1205,16 @@ dependencies = [
[[package]]
name = "craft-plotter"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57#a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"kurbo 0.13.1",
"thiserror 2.0.21",
]
[[package]]
name = "craft-print"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"craft-winprint-gdi",
"log",
@@ -1226,7 +1228,7 @@ dependencies = [
[[package]]
name = "craft-proof"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"log",
"miniz_oxide 0.9.1",
@@ -1237,7 +1239,7 @@ dependencies = [
[[package]]
name = "craft-ps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"flate2",
"kurbo 0.13.1",
@@ -1246,7 +1248,7 @@ dependencies = [
[[package]]
name = "craft-psd"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"encoding_rs",
"flate2",
@@ -1257,7 +1259,7 @@ dependencies = [
[[package]]
name = "craft-stream-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"fax",
"hayro-ccitt",
@@ -1268,12 +1270,14 @@ dependencies = [
[[package]]
name = "craft-svg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"craft-image-codecs",
"craft-xml",
"data-url",
"flate2",
"gif",
"image-webp",
"kurbo 0.13.1",
"quick-xml 0.41.0",
"resvg 0.48.1",
@@ -1287,7 +1291,7 @@ dependencies = [
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -1296,7 +1300,7 @@ dependencies = [
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"craft-fonts-build",
"craft-i18n",
@@ -1317,7 +1321,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"chrono",
"dunce",
@@ -1344,7 +1348,7 @@ dependencies = [
[[package]]
name = "craft-vectorcraft-format"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"flate2",
"serde",
@@ -1355,7 +1359,7 @@ dependencies = [
[[package]]
name = "craft-web-api"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"js-sys",
"serde_json",
@@ -1366,7 +1370,7 @@ dependencies = [
[[package]]
name = "craft-window"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"egui",
"objc2 0.6.5",
@@ -1385,7 +1389,7 @@ dependencies = [
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"quick-xml 0.41.0",
"serde",
@@ -2492,7 +2496,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
[[package]]
name = "hayro-cmap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"brotli",
"hayro-postscript",
@@ -2501,7 +2505,7 @@ dependencies = [
[[package]]
name = "hayro-interpret"
version = "0.7.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"bitflags 2.13.2",
"hayro-cmap",
@@ -2519,7 +2523,7 @@ dependencies = [
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"fearless_simd",
"hayro-ccitt",
@@ -2537,12 +2541,12 @@ dependencies = [
[[package]]
name = "hayro-postscript"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"flate2",
"hayro-ccitt",
@@ -3342,7 +3346,7 @@ dependencies = [
[[package]]
name = "krilla"
version = "0.8.2"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"base64 0.22.1",
"bumpalo",
@@ -3451,7 +3455,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
[[package]]
name = "linesweeper"
version = "0.5.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
dependencies = [
"arrayvec",
"kurbo 0.13.1",
+32 -32
View File
@@ -11,40 +11,40 @@ rust-version = "1.95"
repository = "https://github.com/storytold/vectorcraft"
[workspace.dependencies]
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", default-features = false, features = ["interpret", "write"] }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", features = ["serde"] }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", default-features = false, features = ["interpret", "write"] }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", features = ["serde"] }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
# Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per
# desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.)
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", features = ["egui"] }
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", features = ["egui"] }
# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON.
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
# Native Affinity documents (craft-libs#914).
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
# DXF tags, reader and writer (craft-libs#778, #926, #927).
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
# WMF, EMF and EMF+ reader (craft-libs#778).
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", default-features = false, features = ["write"] }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", features = ["egui"] }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", default-features = false, features = ["write"] }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", features = ["egui"] }
# internal
vectorcraft-geom = { path = "crates/geom" }
vectorcraft-color = { path = "crates/color" }
@@ -185,13 +185,13 @@ lto = "thin"
codegen-units = 1
[patch.crates-io]
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
+1 -1
View File
@@ -17,7 +17,7 @@ path = "src/main.rs"
vectorcraft-engine = { workspace = true, features = ["bundled-fonts", "heif"] }
vectorcraft-ui-egui = { workspace = true }
# The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", version = "0.1.0" }
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", version = "0.1.0" }
vectorcraft-format = { workspace = true }
vectorcraft-text = { workspace = true }
egui = { workspace = true }
+65 -1
View File
@@ -124,6 +124,54 @@ impl ArrowStyle {
}
}
/// `arrowHead`: null, or a built-in stroke arrowhead by its name (`Barbed`, as `stroke.set` takes
/// it). A custom arrowhead and an unknown name are refused.
mod arrow_head {
use crate::Arrowhead;
use serde::de::{Error, IntoDeserializer, Visitor};
use serde::{Deserialize, Deserializer};
pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<Arrowhead>, D::Error> {
deserializer.deserialize_option(Name)
}
/// Reads the name where it is, without a copy of its own.
struct Name;
impl<'de> Visitor<'de> for Name {
type Value = Option<Arrowhead>;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("a built-in stroke arrowhead name or null")
}
fn visit_none<E: Error>(self) -> Result<Self::Value, E> {
Ok(None)
}
fn visit_unit<E: Error>(self) -> Result<Self::Value, E> {
Ok(None)
}
fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error> {
deserializer.deserialize_str(self)
}
fn visit_str<E: Error>(self, name: &str) -> Result<Self::Value, E> {
// No built-in name is this long, so a longer one is refused without parsing it.
let parsed: Result<Arrowhead, serde::de::value::Error> =
if name.len() > 64 { Err(serde::de::value::Error::custom("too long")) } else { Arrowhead::deserialize(name.into_deserializer()) };
match parsed {
Ok(head) if !matches!(head, Arrowhead::Custom(_)) => Ok(Some(head)),
_ => {
let shown: String = name.chars().take(64).collect();
Err(E::custom(format!("Unknown arrowhead {shown}: a built-in stroke arrowhead name or null")))
}
}
}
}
}
/// Where the label sits across the dimension line.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
@@ -157,6 +205,12 @@ pub struct DimensionOptions {
pub line_type: LineType,
pub line_color: [u8; 3],
pub arrow_style: ArrowStyle,
/// A built-in stroke arrowhead drawn at both ends in place of `arrow_style`'s head. Versions
/// that have the stroke arrowhead but do not read this keep the saved arrows until they draw
/// the dimension again, and then draw `arrow_style`. Versions without the stroke arrowhead do
/// not open the file.
#[serde(deserialize_with = "arrow_head::deserialize", skip_serializing_if = "Option::is_none")]
pub arrow_head: Option<crate::Arrowhead>,
pub arrow_scale: f64,
pub extension_weight: f64,
pub extension_type: LineType,
@@ -186,6 +240,7 @@ impl Default for DimensionOptions {
line_type: LineType::Solid,
line_color: [0, 0, 0],
arrow_style: ArrowStyle::Filled,
arrow_head: None,
arrow_scale: 100.0,
extension_weight: 0.5,
extension_type: LineType::Solid,
@@ -209,7 +264,8 @@ impl DimensionOptions {
/// tolerantly so a newer version's options don't stop a document opening.
pub fn from_params(v: serde_json::Value) -> Result<Self, String> {
if let (Some(given), Ok(serde_json::Value::Object(known))) = (v.as_object(), serde_json::to_value(Self::default()))
&& let Some(k) = given.keys().find(|k| !known.contains_key(*k))
// `arrowHead` is left out of the saved options when it is null.
&& let Some(k) = given.keys().find(|k| !known.contains_key(*k) && k.as_str() != "arrowHead")
{
return Err(format!("Unknown dimension option {k}"));
}
@@ -228,8 +284,16 @@ impl DimensionOptions {
}
Ok(f)
}
/// The stroke arrowhead drawn at each end of the dimension line: `arrow_head`, or else the
/// arrow style's head.
pub fn arrowhead(&self) -> Option<crate::Arrowhead> {
self.arrow_head.clone().or_else(|| self.arrow_style.arrowhead())
}
pub fn validate(&self) -> Result<(), String> {
self.factor()?;
if matches!(self.arrow_head, Some(crate::Arrowhead::Custom(_))) {
return Err("A dimension's arrowhead is a built-in stroke arrowhead".into());
}
if self.precision > 6 {
return Err("Choose a precision from 0 to 6".into());
}
+29 -7
View File
@@ -144,10 +144,36 @@ impl LiveShape {
/// from straight up (the Rotate field's sense). None for other shapes.
pub fn polygon_angle(&self) -> Option<f64> {
let LiveShape::Polygon { .. } = self else { return None };
// No −0° or 360° from rounding: a polygon drawn upright reads 0°.
self.shape_angle()
}
/// A rectangle's, ellipse's or polygon's angle (Rectangle, Ellipse and Polygon Angle): the
/// counterclockwise degrees in [0, 360) it is turned by (the Rotate field's sense). A rectangle or
/// ellipse drawn level reads 0°, as does a polygon drawn with its first vertex straight up. None for
/// other shapes.
pub fn shape_angle(&self) -> Option<f64> {
let (LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. }) = self else { return None };
// No −0° or 360° from rounding: a shape drawn level reads 0°.
let a = (-self.angle_deg()).rem_euclid(360.0);
Some(if a > 360.0 - 1e-9 { 0.0 } else { a + 0.0 })
}
/// Turn a rectangle, ellipse or polygon about its center to `angle` (degrees, as
/// [`LiveShape::shape_angle`]), keeping its size, corners and pie. Nothing changes for other
/// shapes or an angle that isn't finite.
pub fn set_shape_angle(&mut self, angle: f64) {
let Some(now) = self.shape_angle() else { return };
if !angle.is_finite() {
return;
}
// Brought into [0, 360) first: `now - angle` loses `now` for a very large angle.
let angle = angle.rem_euclid(360.0);
let (xf, local) = match self {
LiveShape::Rectangle { w, h, xf, .. } | LiveShape::Ellipse { w, h, xf, .. } => (xf, Point::new(*w / 2.0, *h / 2.0)),
LiveShape::Polygon { xf, .. } => (xf, Point::ZERO),
LiveShape::Line { .. } | LiveShape::Path { .. } => return,
};
let center = *xf * local;
*xf = Affine::rotate_about((now - angle).to_radians(), center) * *xf;
}
/// Whether a polygon's sides are all as long: `xf` scales it evenly and doesn't shear it. True
/// for other shapes.
pub fn polygon_sides_equal(&self) -> bool {
@@ -171,12 +197,8 @@ impl LiveShape {
}
/// Turn a polygon about its centre to `angle` (degrees, as [`LiveShape::polygon_angle`]).
pub fn set_polygon_angle(&mut self, angle: f64) {
let Some(now) = self.polygon_angle() else { return };
if let LiveShape::Polygon { xf, .. } = self
&& angle.is_finite()
{
let centre = *xf * Point::ZERO;
*xf = Affine::rotate_about((now - angle).to_radians(), centre) * *xf;
if let LiveShape::Polygon { .. } = self {
self.set_shape_angle(angle);
}
}
/// A line's length in the document, from its first end to its second. None for other shapes.
+14
View File
@@ -184,6 +184,20 @@ fn a_polygon_reports_and_takes_its_radius_angle_and_equal_sides() {
assert_eq!((e.polygon_radius(), e.polygon_angle()), (None, None));
}
/// A very large angle turns a rectangle to that angle modulo 360, whatever angle it had before.
#[test]
fn a_shape_takes_a_very_large_angle() {
let close = |a: f64, b: f64| (a - b).abs() < 1e-6;
let want = 1e20f64.rem_euclid(360.0);
for turned in [0.0, 90.0] {
let xf = Affine::translate((50.0, 50.0)) * Affine::rotate(-f64::to_radians(turned));
let mut r = LiveShape::Rectangle { w: 100.0, h: 50.0, radii: [0.0; 4], kinds: Default::default(), radii_relative: false, xf };
assert!(close(r.shape_angle().unwrap(), turned), "{:?}", r.shape_angle());
r.set_shape_angle(1e20);
assert!(close(r.shape_angle().unwrap(), want), "from {turned}°: {:?}, not {want}", r.shape_angle());
}
}
/// A node holding a live rectangle (`w` × `h`, all radii `r`, placed by `xf`) and its path.
fn live_rect(w: f64, h: f64, r: f64, xf: Affine) -> Node {
let live = LiveShape::Rectangle { w, h, radii: [r; 4], kinds: Default::default(), radii_relative: false, xf };
+1 -1
View File
@@ -911,7 +911,7 @@ pub use buildcmds::{TracePreset, TracePresetChange};
pub use buildcmds::{TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES};
/// An Image Trace made off the UI thread, and what it traced (#3098).
pub use buildcmds::{TraceRun, Traced};
pub use buildcmds::{TraceRun, Traced, image_trace_target};
/// The saved Image Trace presets' revision and latest changes ([`crate::Session`] keeps them).
pub(crate) use buildcmds::TracePresetChanges;
+44
View File
@@ -182,6 +182,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
BuiltinBrushLibrary { id: "energy-beams", name: "Energy Beams", make: energy_beams },
BuiltinBrushLibrary { id: "dry-media", name: "Dry Media", make: dry_media },
BuiltinBrushLibrary { id: "tech-circuit", name: "Tech Circuit", make: tech_circuit },
BuiltinBrushLibrary { id: "engraving", name: "Engraving", make: engraving },
BuiltinBrushLibrary { id: "arrows", name: "Arrows", make: arrows },
BuiltinBrushLibrary { id: "image-brush", name: "Image Brush", make: image_brush },
];
@@ -237,6 +238,49 @@ fn art(name: &str, art: Node, colorization: Colorization) -> Brush {
Brush { name: name.into(), kind: BrushKind::Art(ArtBrush { art, colorization, ..Default::default() }) }
}
/// Original fine-line art for an engraving-style brush library.
fn engraving() -> BrushLibrary {
let lines = |count: usize, width: f64, spacing: f64| {
group(
(0..count)
.map(|i| {
let y = (i as f64 - (count - 1) as f64 / 2.0) * spacing;
black(shapes::rectangle(Rect::new(0.0, y - width / 2.0, 100.0, y + width / 2.0)))
})
.collect(),
)
};
let taper = group(
(0..5)
.map(|i| {
let y = (i as f64 - 2.0) * 2.2;
black(polygon(&[(0.0, y - 0.35), (80.0, y - 0.35), (100.0, y), (80.0, y + 0.35), (0.0, y + 0.35)]))
})
.collect(),
);
let broken = group(
(0..5)
.flat_map(|row| {
(0..4).map(move |segment| {
let x = segment as f64 * 25.0 + if row % 2 == 0 { 0.0 } else { 8.0 };
let y = (row as f64 - 2.0) * 2.2;
black(shapes::rectangle(Rect::new(x, y - 0.3, (x + 16.0).min(100.0), y + 0.3)))
})
})
.collect(),
);
built(
"Engraving",
Document::new(100.0, 100.0),
vec![
art("Fine Hatching", lines(5, 0.65, 2.2), Colorization::Tints),
art("Dense Hatching", lines(9, 0.42, 1.2), Colorization::Tints),
art("Tapered Hatching", taper, Colorization::Tints),
art("Broken Hatching", broken, Colorization::Tints),
],
)
}
/// An Arrows brush whose art stretches only between `start` and `end` (fractions of its length).
fn arrow_art(name: &str, art: Node, start: f64, end: f64) -> Brush {
Brush {
+3 -1
View File
@@ -42,7 +42,9 @@ pub(crate) use live_paint::{LivePaintMove, check_part_name, clear_part_name, iso
use live_paint::{lp_expand, lp_fill, lp_gap_options, lp_info, lp_make, lp_merge, lp_release, lp_stroke_edge};
use shape_builder::{sb_merge, sb_regions};
pub(crate) use trace::TracePresetChanges;
pub use trace::{TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES, TracePreset, TracePresetChange, TraceRun, Traced};
pub use trace::{
TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES, TracePreset, TracePresetChange, TraceRun, Traced, image_trace_target,
};
use trace::{
trace_expand, trace_make, trace_presets_delete, trace_presets_export, trace_presets_import, trace_presets_save, trace_release, trace_set_view,
};
+25 -19
View File
@@ -765,6 +765,30 @@ struct Prepared {
library: Vec<([u8; 3], Paint)>,
}
/// The object `imageTrace.make` would trace, without preparing settings or reading image bytes.
pub fn image_trace_target(s: &Session, p: &Value) -> Result<NodeId> {
target_image(s, "imageTrace.make", p).map(|(target, _)| target)
}
fn target_image(s: &Session, c: &str, p: &Value) -> Result<(NodeId, Box<ImageObject>)> {
let roots = root_ids(s, p)?;
let d = &s.doc()?.doc;
roots
.iter()
.find_map(|r| {
let n = d.node(*r)?;
match &n.kind {
NodeKind::Image(i) => Some((*r, i.clone())),
_ if is_trace_group(n) => match &n.children()?.first()?.kind {
NodeKind::Image(i) => Some((*r, i.clone())),
_ => None,
},
_ => None,
}
})
.ok_or_else(|| bad(c, "select an image (or an Image Trace group)"))
}
/// What command `c` with params `p` traces, and how, from the session: everything but the trace.
fn prepare(s: &Session, c: &str, p: &Value) -> Result<Prepared> {
let mut params = trace_params(s, c, p)?;
@@ -784,25 +808,7 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result<Prepared> {
None if is(tr::preset(named)) || is(tr::enhanced_preset(named)) => named.to_string(),
None => "Custom".to_string(),
};
let roots = root_ids(s, p)?;
// The image (inside a trace group, or selected directly).
let (target, image) = {
let d = &s.doc()?.doc;
roots
.iter()
.find_map(|r| {
let n = d.node(*r)?;
match &n.kind {
NodeKind::Image(i) => Some((*r, i.clone())),
_ if is_trace_group(n) => match &n.children()?.first()?.kind {
NodeKind::Image(i) => Some((*r, i.clone())),
_ => None,
},
_ => None,
}
})
.ok_or_else(|| bad(c, "select an image (or an Image Trace group)"))?
};
let (target, image) = target_image(s, c, p)?;
if by_color && s.doc()?.doc.node(target).is_some_and(vectorcraft_render::effects::has_pathfinder) {
return Err(bad(c, LIVE_PATHFINDER_BY_COLOR));
}
+1 -1
View File
@@ -1003,7 +1003,7 @@ impl PasteProfile {
if o.keys().any(|k| k != "rgb" && k != "cmyk") {
return Err(refuse());
}
let model = |m: &str| o.get(m).map(&one).transpose();
let model = |m: &str| o.get(m).map(one).transpose();
Ok(Some(PasteChoice { rgb: model("rgb")?, cmyk: model("cmyk")? }))
}
Some(v) => {
+2 -2
View File
@@ -14,7 +14,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Create Dimension",
[],
None,
"{mode?: linear|angular|radius|diameter, a?: [x,y], b?: [x,y], vertex?: [x,y], source?: {kind: segment, edge: {node,subpath,segment}}|{kind: angle, first: edge, second: edge}|{kind: circle, node}|{kind: arc, edge}|{kind: points, a?, b?, vertex?: {node,subpath,anchor}, freeA?, freeB?: a point that is not an anchor, {kind: onSegment, edge: {node,subpath,segment}, t: 0..1 (curve parameter)}|{kind: anchors, node, anchors: [{subpath,anchor,part?: point|in|out (the anchor, default, or its in or out handle),weight}] (2 or 3 points of one path whose weights add up to 1), across?: (2 anchors only: times the first-to-second anchor vector (x,y) turned to (-y,x), which points down when the vector points right)} (an end is an anchor or a free point, not both)}, orientation?: aligned|horizontal|vertical (linear only: the distance between the points, or only its horizontal or vertical part; default aligned), offset?: pt (the line's distance from the first point: along the left normal of a → b when aligned, downward when horizontal, leftward when vertical; negative goes the other way), options?: {units: in|mm|pt|pc|px|cm|m|ft|yd, precision: 0-6, scale: drawing:real, hideUnits, lineWeight, lineType: solid|dashed|dotted, lineColor: [r,g,b], arrowStyle: filled|open|tick|none, arrowScale: %, extensionWeight, extensionType, extensionColor, extensionOffset, extensionLength, hideExtensions, fontFamily, fontStyle, fontSize, textColor, textPosition: away|between, textAlignment: left|center|right, textOffset}} → {id,label}; linked measurements follow source edits",
"{mode?: linear|angular|radius|diameter, a?: [x,y], b?: [x,y], vertex?: [x,y], source?: {kind: segment, edge: {node,subpath,segment}}|{kind: angle, first: edge, second: edge}|{kind: circle, node}|{kind: arc, edge}|{kind: points, a?, b?, vertex?: {node,subpath,anchor}, freeA?, freeB?: a point that is not an anchor, {kind: onSegment, edge: {node,subpath,segment}, t: 0..1 (curve parameter)}|{kind: anchors, node, anchors: [{subpath,anchor,part?: point|in|out (the anchor, default, or its in or out handle),weight}] (2 or 3 points of one path whose weights add up to 1), across?: (2 anchors only: times the first-to-second anchor vector (x,y) turned to (-y,x), which points down when the vector points right)} (an end is an anchor or a free point, not both)}, orientation?: aligned|horizontal|vertical (linear only: the distance between the points, or only its horizontal or vertical part; default aligned), offset?: pt (the line's distance from the first point: along the left normal of a → b when aligned, downward when horizontal, leftward when vertical; negative goes the other way), options?: {units: in|mm|pt|pc|px|cm|m|ft|yd, precision: 0-6, scale: drawing:real, hideUnits, lineWeight, lineType: solid|dashed|dotted, lineColor: [r,g,b], arrowStyle: filled|open|tick|none, arrowHead: null|a built-in stroke.set arrowhead name (Barbed, LineArrow…; drawn at both ends in place of arrowStyle's head; versions that have the stroke arrowhead but do not read arrowHead draw arrowStyle when they draw the dimension again; custom arrowheads are refused), arrowScale: %, extensionWeight, extensionType, extensionColor, extensionOffset, extensionLength, hideExtensions, fontFamily, fontStyle, fontSize, textColor, textPosition: away|between, textAlignment: left|center|right, textOffset}} → {id,label}; linked measurements follow source edits",
has_doc,
create
),
@@ -565,7 +565,7 @@ fn appearance(o: &DimensionOptions, mode: ColorMode, ext: bool, arrows: bool) ->
LineType::Solid => None,
};
if arrows {
let head = o.arrow_style.arrowhead();
let head = o.arrowhead();
st.start_arrow = head.clone();
st.end_arrow = head;
st.arrow_scale = (o.arrow_scale, o.arrow_scale);
+610 -96
View File
@@ -24,20 +24,28 @@
//! Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color, Lighter Color) is merged with the
//! layers below it in its group. A Dissolve layer's partly transparent pixels are merged as opaque
//! or transparent, opaque at the share of its pixels their transparency gives, in a fixed pattern
//! that differs from layer to layer. When a merge's canvases would need more memory than allowed,
//! the layer comes in alone: in the Normal mode, or unclipped.
//! Hidden layers are left out unless `hidden` asks for them. A hidden layer that would need a merge
//! (one in a mode VectorCraft lacks, one that layers are clipped to, one clipped to another, or
//! one below a merged layer) is always left out, with the layers clipped to it. Adjustment layers,
//! fill layers that store no pixels and whose fill isn't read or whose shape is a vector mask,
//! layer effects that are switched on, knockouts and vector masks aren't applied; the warnings
//! count them and the hidden layers left out.
//! that differs from layer to layer. A layer or group in a group whose Knockout setting is 1 (read
//! as a shallow knockout) is merged with the layers below it in its group too, as the import option
//! describes: where it has pixels, they are cleared to transparency and it is drawn there at its fill
//! opacity, and its opacity fades that back toward them. In a pass-through group this is done only
//! when it and the visible layers below it are in the Normal mode. When a merge's canvases would need more
//! memory than allowed, the layer comes in alone: in the Normal mode, unclipped, or without its
//! knockout. Hidden layers are left out unless `hidden` asks for them. A hidden layer that would need
//! a merge (one in a mode VectorCraft lacks, one with a knockout in a group that changes the layers
//! below it, one that layers are clipped to, one clipped to another, or one below a merged layer) is
//! always left out, with the layers clipped to it. Adjustment layers, fill layers that store no
//! pixels and whose fill isn't read or whose shape is a vector mask, layer effects that are switched
//! on, vector masks, and the knockouts of top-level layers, of clipped layers, of layers that others
//! are clipped to and of layers in a pass-through group with a layer in another mode, and other
//! Knockout values, aren't applied; the warnings count them and the hidden layers left out.
//!
//! The file is untrusted: every count, length and size is checked before anything is allocated,
//! groups nest at most [`MAX_DEPTH`] deep (layers deeper than a document may nest merge into the
//! group around them, with a warning), each layer's pixels, like the canvases one step of a
//! merge holds together, must fit the memory allowed, and all the pixels decoded and the canvases
//! the merges make must fit [`TOTAL_DECODED`] times that.
//! the merges make must fit [`TOTAL_DECODED`] times that. A merge being tried may take that much
//! past what was read before it. What the merges that aren't made, or that a hidden layer would
//! need, decoded and made is counted apart, against the same limit.
use std::cell::Cell;
use std::sync::Arc;
@@ -66,6 +74,13 @@ const MAX_CHANNELS: usize = 56;
const MIN_RECORD: usize = 34;
const DAMAGED: &str = "the PSD file's layer records are damaged";
#[cfg(test)]
thread_local! {
/// The layer lists imports on this thread have walked, and the most a test lets them walk
/// before the import stops with an error.
pub(super) static WALKS: Cell<(usize, usize)> = const { Cell::new((0, usize::MAX)) };
}
/// The keys of the tagged blocks that make a layer an adjustment layer.
const ADJUSTMENTS: [&[u8; 4]; 18] = [
b"levl", b"curv", b"brit", b"blnc", b"hue ", b"hue2", b"selc", b"mixr", b"grdm", b"phfl", b"expA", b"vibA", b"thrs", b"nvrt", b"post", b"clrL",
@@ -227,7 +242,9 @@ struct Record<'a> {
content: Content,
effects: bool,
vector_mask: bool,
knockout: bool,
/// The Knockout setting's byte (`knko`): 0 none, 1 a shallow knockout. Any other value isn't
/// applied.
knockout: u8,
}
/// The layer records of `info` (the layer count, the records, then their channels' data).
@@ -285,7 +302,7 @@ fn record<'a>(r: &mut Reader<'a>, psb: bool) -> Result<(Record<'a>, Vec<(i16, us
content: Content::Pixels,
effects: false,
vector_mask: false,
knockout: false,
knockout: 0,
};
rec.read_extra(extra, psb)?;
Ok((rec, lengths))
@@ -345,8 +362,7 @@ impl Record<'_> {
b"lfx2" | b"lmfx" => effects = Some(effects == Some(true) || effects_on(data)),
b"lrFX" => old_effects = true,
b"vmsk" | b"vsms" => self.vector_mask = true,
// Shallow or deep knockout.
b"knko" => self.knockout = data.first().is_some_and(|&k| k != 0),
b"knko" => self.knockout = data.first().copied().unwrap_or(0),
k if ADJUSTMENTS.contains(&k) => self.content = Content::Adjustment,
_ => {}
}
@@ -612,6 +628,8 @@ struct Unit<'i> {
body: Body<'i>,
/// While layers are clipped to it: how its merged canvas is shaped.
clip: Option<Clip>,
/// Layers are clipped to it, merged into it or not.
base: bool,
}
impl Unit<'_> {
@@ -640,13 +658,36 @@ enum Clip {
enum Body<'i> {
/// A layer record's pixels.
Layer(usize),
/// A group's layers.
Group(&'i [Item]),
/// A group's record and its layers.
Group(usize, &'i [Item]),
/// Layers merged into one image.
Merged(Canvas),
}
/// Where a layer list is.
#[derive(Clone, Copy, PartialEq)]
enum Level {
/// The file's top level.
Top,
/// An isolated group, or a group drawn on its own.
Group,
/// A pass-through group whose layers blend with what is below it.
Pass,
}
/// What a knockout's merge with the layers below it gives.
enum Knocked {
/// The merged canvas.
Merged(Canvas),
/// Nothing below it draws, it draws nothing, it is at 0 fill and cuts no painted pixel below
/// it, or what is below it and the merge are both transparent: it comes in as a layer of its own.
Nothing,
/// The canvases would need more memory than allowed.
TooLarge,
}
/// A unit's body drawn alone.
#[derive(Clone)]
enum Drawn {
/// It draws nothing.
Nothing,
@@ -663,6 +704,7 @@ struct Notes {
fills: usize,
effects: usize,
vector_masks: usize,
/// Layers whose knockout wasn't applied.
knockouts: usize,
/// Hidden layers left out, and layers clipped to them.
hidden: usize,
@@ -677,11 +719,17 @@ struct Notes {
/// The counts a merge that can't be made gives back.
#[derive(Clone, Copy)]
struct Counts {
/// The bytes spent so far (see [`Builder::spent`]).
spent: u64,
skipped: usize,
/// The knockouts counted as not applied.
unknocked: usize,
merged: usize,
unmerged: usize,
unclipped: usize,
clipped_out: usize,
/// The groups found to read no pixels.
blank: usize,
}
/// Adds the warning for `n` things to `out`: `one` when `n` is 1, `many` with the count in place
@@ -745,8 +793,17 @@ impl Notes {
out
}
fn counts(&self, skipped: usize) -> Counts {
Counts { skipped, merged: self.merged.len(), unmerged: self.unmerged, unclipped: self.unclipped, clipped_out: self.clipped_out }
fn counts(&self, spent: u64, skipped: usize, unknocked: usize, blank: usize) -> Counts {
Counts {
spent,
skipped,
unknocked,
merged: self.merged.len(),
unmerged: self.unmerged,
unclipped: self.unclipped,
clipped_out: self.clipped_out,
blank,
}
}
}
@@ -767,12 +824,47 @@ struct Builder<'a, F> {
notes: Notes,
/// The records [`Notes`] counted.
noted: Vec<bool>,
/// Those records, in the order they were counted.
noted_log: Vec<usize>,
/// The records counted as hidden layers left out.
skipped: Vec<bool>,
/// Those records, in the order they were counted.
skip_log: Vec<usize>,
/// The records counted as knockouts not applied.
unknocked: Vec<bool>,
/// Those records, in the order they were counted.
unknock_log: Vec<usize>,
/// The records counted as layers clipped to a fill that isn't drawn.
clipped_out: Vec<bool>,
/// Those records, in the order they were counted.
clipped_out_log: Vec<usize>,
/// The records counted as clipped layers left unclipped.
unclipped: Vec<bool>,
/// Those records, in the order they were counted.
unclip_log: Vec<usize>,
/// The records that came in as layers of the document (hidden ones too, with `hidden`): not left
/// out, though a drawing for a merge that wasn't made counted them.
kept: Vec<bool>,
/// Bytes of layer and mask pixels decoded, and of canvases the merges made, so far.
spent: Cell<u64>,
/// Those bytes that merges not made, and merges a hidden layer would need, took: given back to
/// `spent` and counted here instead, against the same limit.
wasted: Cell<u64>,
/// `spent` when the innermost merge being tried began: until it is made or given up, it may
/// spend the whole allowance past that (see [`Self::spend`]).
trial: Cell<u64>,
/// The layers whose pixels were read so far (each time they were).
painted: Cell<usize>,
/// What each group gave when drawn alone without reading any layer's pixels (nothing, or a
/// canvas without pixels, whatever the memory left): drawing it again gives that without
/// walking its layers.
blank: Vec<Option<Drawn>>,
/// The pass-through groups that laid nothing onto nothing (see [`Self::laid_nothing`]).
laid_blank: Vec<bool>,
/// The groups of both, in the order they were found.
blank_log: Vec<usize>,
/// How many times a merge was counted as not made because it needed more memory than allowed.
squeezed: usize,
}
impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
@@ -786,10 +878,38 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
}
/// Count `bytes` of decoded pixels, or of a canvas a merge makes, against the whole import's
/// allowance, [`TOTAL_DECODED`] times the memory allowed for one image.
/// allowance, [`TOTAL_DECODED`] times the memory allowed for one image. While a merge is tried
/// (see [`Self::try_from_here`]), only what it spent counts against the allowance.
fn spend(&self, bytes: u64) -> Result<(), String> {
let total = self.spent.get().saturating_add(bytes);
self.spent.set(total);
if total.saturating_sub(self.trial.get()) > self.max_alloc.saturating_mul(TOTAL_DECODED) {
return Err("the PSD file's layers take more memory to read than allowed".into());
}
Ok(())
}
/// Start trying a merge that may not be made: what it spends counts against the whole
/// allowance, however much was spent before it. Gives what [`Self::tried`] takes back.
fn try_from_here(&self) -> u64 {
self.trial.replace(self.spent.get())
}
/// End the merge tried since [`Self::try_from_here`] gave `outer`. A merge that is `made` keeps
/// what it spent, which must then fit the allowance with what was spent before it.
fn tried(&self, outer: u64, made: bool) -> Result<(), String> {
self.trial.set(outer);
if made { self.spend(0) } else { Ok(()) }
}
/// Move the bytes spent since `spent` was the count to [`Self::wasted`], which has an allowance
/// of its own as large: what a merge that isn't made decoded doesn't take the room for reading
/// the layers apart.
fn refund(&self, spent: u64) -> Result<(), String> {
let since = self.spent.get().saturating_sub(spent);
self.spent.set(self.spent.get().min(spent));
let total = self.wasted.get().saturating_add(since);
self.wasted.set(total);
if total > self.max_alloc.saturating_mul(TOTAL_DECODED) {
return Err("the PSD file's layers take more memory to read than allowed".into());
}
@@ -814,6 +934,7 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
Paint::Cmyk(ink) => (self.cmyk)(ink),
};
let px = image::Rgba([byte(rgb[0]), byte(rgb[1]), byte(rgb[2]), 255]);
self.painted.set(self.painted.get() + 1);
return Ok(Some((0, 0, RgbaImage::from_pixel(h.width, h.height, px))));
}
Content::Pixels | Content::Type | Content::Solid(_) | Content::Fill => rec.bounds.size(),
@@ -845,6 +966,7 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
let rgb = to_rgb(h, |c| planes.get(c).map_or(0.0, |p| at(p, linear, 0.0)), &self.cmyk);
image::Rgba([byte(rgb[0]), byte(rgb[1]), byte(rgb[2]), byte(at(&alpha, false, 1.0))])
});
self.painted.set(self.painted.get() + 1);
Ok(Some((i64::from(rec.bounds.left), i64::from(rec.bounds.top), img)))
}
@@ -897,7 +1019,7 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
for item in items {
let (i, body) = match item {
Item::Layer(i) => (*i, Body::Layer(*i)),
Item::Group(i, children) => (*i, Body::Group(children)),
Item::Group(i, children) => (*i, Body::Group(*i, children)),
};
let rec = self.record(i)?;
let (name, hidden, clipped, blend) = (rec.name.clone(), rec.hidden, rec.clipped, rec.blend);
@@ -920,14 +1042,26 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
Some(b) => {
// Counted even when it draws nothing (an adjustment layer).
self.note(i)?;
if !unclipped && self.clip(&mut out, b, &body, i, &name, blend, opacity)? {
// A clipped layer's knockout isn't applied.
if self.record(i)?.knockout != 0 {
self.unknock(i);
}
if let Some(u) = out.get_mut(b) {
u.base = true;
}
let spent = self.spent.get();
let outer = self.try_from_here();
let made = !unclipped && self.clip(&mut out, b, &body, i, &name, blend, opacity)?;
self.tried(outer, made)?;
if made {
continue;
}
self.refund(spent)?;
// The merge doesn't fit: this layer and the next ones clipped to the same
// base come in as layers of their own.
unclipped = true;
self.notes.unclipped += 1;
out.push(Unit { name, visible: true, opacity, blend, mask_of: Some(i), record: i, body, clip: None });
self.unclip(i);
out.push(Unit { name, visible: true, opacity, blend, mask_of: Some(i), record: i, body, clip: None, base: false });
}
}
continue;
@@ -939,7 +1073,7 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
continue;
}
self.note(i)?;
out.push(Unit { name, visible: !hidden, opacity, blend, mask_of: Some(i), record: i, body, clip: None });
out.push(Unit { name, visible: !hidden, opacity, blend, mask_of: Some(i), record: i, body, clip: None, base: false });
base = Some(Some(out.len() - 1));
}
for u in &mut out {
@@ -962,7 +1096,7 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
};
// A fill whose shape is a vector mask isn't drawn, and nothing clipped to it is either.
if undrawn && u.clip.is_none() {
self.notes.clipped_out += 1;
self.clip_out(i);
return Ok(true);
}
let layer = match self.draw_body(body, Some(i))? {
@@ -1045,12 +1179,15 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
// Once, though a merge may draw it again.
match self.noted.get_mut(i) {
Some(true) => return Ok(()),
Some(n) => *n = true,
Some(n) => {
*n = true;
self.noted_log.push(i);
}
None => {}
}
let (content, empty, effects, vector_mask, knockout) = {
let (content, empty, effects, vector_mask) = {
let rec = self.record(i)?;
(rec.content, rec.stores_nothing(), rec.effects, rec.vector_mask, rec.knockout)
(rec.content, rec.stores_nothing(), rec.effects, rec.vector_mask)
};
match content {
Content::Type => self.notes.types += 1,
@@ -1062,10 +1199,59 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
}
self.notes.effects += usize::from(effects);
self.notes.vector_masks += usize::from(vector_mask);
self.notes.knockouts += usize::from(knockout);
Ok(())
}
/// What [`Self::note`] has counted so far: the length of its log, and the counts.
fn noted_so_far(&self) -> (usize, [usize; 5]) {
let n = &self.notes;
(self.noted_log.len(), [n.types, n.adjustments, n.fills, n.effects, n.vector_masks])
}
/// Forget what [`Self::note`] counted since `so_far`, for layers that are left out.
fn unnote(&mut self, (logged, counts): (usize, [usize; 5])) {
for i in self.noted_log.split_off(logged) {
if let Some(n) = self.noted.get_mut(i) {
*n = false;
}
}
let n = &mut self.notes;
[n.types, n.adjustments, n.fills, n.effects, n.vector_masks] = counts;
}
/// Count record `i` as a layer whose knockout isn't applied (once).
fn unknock(&mut self, i: usize) {
if let Some(s) = self.unknocked.get_mut(i)
&& !*s
{
*s = true;
self.notes.knockouts += 1;
self.unknock_log.push(i);
}
}
/// Does unit `u`, at `level` above the units `below` it, take a shallow knockout this import
/// applies? Only a layer or group in a group, neither clipped nor a base of clipped layers, does;
/// in a pass-through group, only when it and the visible units below it are in the Normal mode, so
/// that none of them blends with what is below the group. Any other knockout is counted as not
/// applied. One at 0 opacity, or with no visible unit below it, changes nothing below it: it needs
/// no merge, and a hidden one isn't left out for it.
fn knocks(&mut self, u: &Unit<'_>, below: &[Unit<'_>], level: Level) -> Result<bool, String> {
let rec = self.record(u.record)?;
if rec.knockout == 0 {
return Ok(false);
}
let normal = |u: &Unit<'_>| u.blend == Blend::Mode(BlendMode::Normal);
let blends_out = level == Level::Pass && !(normal(u) && below.iter().filter(|b| b.visible).all(normal));
let applies = rec.knockout == 1 && level != Level::Top && !blends_out && !rec.clipped && !u.base && !matches!(u.body, Body::Merged(_));
// Its fill opacity isn't checked: at 0 fill it still clears what is below it.
let changes = rec.opacity > 0.0 && below.iter().any(|b| b.visible);
if !applies {
self.unknock(u.record);
}
Ok(applies && changes)
}
/// Count record `i` as a hidden layer left out (once).
fn skip(&mut self, i: usize) {
if let Some(s) = self.skipped.get_mut(i)
@@ -1077,21 +1263,100 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
}
}
/// `items`' units with the layers in blend modes VectorCraft lacks merged with those below.
fn merged<'i>(&mut self, items: &'i [Item], keep_hidden: bool) -> Result<Vec<Unit<'i>>, String> {
/// Count record `i` as a layer clipped to a fill that isn't drawn (once).
fn clip_out(&mut self, i: usize) {
if let Some(s) = self.clipped_out.get_mut(i)
&& !*s
{
*s = true;
self.notes.clipped_out += 1;
self.clipped_out_log.push(i);
}
}
/// Count record `i` as a clipped layer left unclipped (once).
fn unclip(&mut self, i: usize) {
self.squeezed += 1;
if let Some(s) = self.unclipped.get_mut(i)
&& !*s
{
*s = true;
self.notes.unclipped += 1;
self.unclip_log.push(i);
}
}
/// `items`' units, at `level`, with the layers in blend modes VectorCraft lacks, and in a group
/// the layers with a shallow knockout, merged with those below.
fn merged<'i>(&mut self, items: &'i [Item], keep_hidden: bool, level: Level) -> Result<Vec<Unit<'i>>, String> {
#[cfg(test)]
{
let (walked, most) = WALKS.get();
if walked >= most {
return Err("the import walked more layer lists than the test allows".into());
}
WALKS.set((walked + 1, most));
}
let mut out: Vec<Unit<'i>> = vec![];
for mut u in self.units(items, keep_hidden)? {
// A hidden layer in a mode VectorCraft lacks would need the merge for its mode: it is left
// out without being drawn.
if !u.visible && matches!(u.blend, Blend::Other(_)) {
self.skip(u.record);
continue;
}
if self.knocks(&u, &out, level)? {
let saved = self.saved();
let noted = self.noted_so_far();
let squeezed = self.squeezed;
let outer = self.try_from_here();
let knocked = self.knock(&out, &u)?;
self.tried(outer, u.visible && matches!(knocked, Knocked::Merged(_)))?;
match knocked {
// A hidden layer that would need the merge is left out, and nothing its drawing
// counted is counted.
Knocked::Merged(_) | Knocked::TooLarge if !u.visible => {
self.restore(saved)?;
self.unnote(noted);
self.skip(u.record);
continue;
}
Knocked::Merged(canvas) => {
self.take_merge(&mut out, &u, canvas);
if let Blend::Other(other) = u.blend
&& !self.notes.merged.contains(&other.label())
{
self.notes.merged.push(other.label());
}
continue;
}
// Nothing below it, or nothing of its own, to knock out: it comes in as a layer,
// with the hidden layers its drawing left out (see `kept`). What its drawing
// read is read again when it comes in. A hidden one may still be left out by a
// later merge: what its drawing counted is counted when it comes in instead.
Knocked::Nothing if !u.visible => {
self.restore(saved)?;
self.unnote(noted);
}
// A merge below it that its held canvas left without the memory it needed may
// be made when they come in without it: what drawing them counted is given back
// and counted again then.
Knocked::Nothing if self.squeezed != squeezed => self.restore(saved)?,
Knocked::Nothing => self.refund(saved.spent)?,
Knocked::TooLarge => {
self.restore(saved)?;
self.squeezed += 1;
self.unknock(u.record);
}
}
}
let Blend::Other(other) = u.blend else {
out.push(u);
continue;
};
// A hidden layer that would need the merge is left out.
if !u.visible {
self.skip(u.record);
continue;
}
// A merge that can't be made counts nothing its groups would have counted.
let saved = self.notes.counts(self.skip_log.len());
let saved = self.saved();
let outer = self.try_from_here();
let made = match out.as_mut_slice() {
// Onto the previous merge alone: composited onto its canvas, in place.
[prev] if prev.is_merge() => {
@@ -1113,45 +1378,20 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
}
_ => match self.merge(&out, &u)? {
Some(canvas) => {
let mut name = String::new();
for (k, b) in out.iter_mut().filter(|b| b.visible).enumerate() {
if k == 0 {
name = std::mem::take(&mut b.name);
} else {
name.push_str(" + ");
name.push_str(&b.name);
}
}
if out.iter().any(|b| b.visible) {
name.push_str(" + ");
}
name.push_str(&u.name);
// Hidden layers below are left out with the rest.
for b in out.iter().filter(|b| !b.visible).map(|b| b.record).collect::<Vec<_>>() {
self.skip(b);
}
out.clear();
out.push(Unit {
name,
visible: true,
opacity: 1.0,
blend: Blend::Mode(BlendMode::Normal),
mask_of: None,
record: u.record,
body: Body::Merged(canvas),
clip: None,
});
self.take_merge(&mut out, &u, canvas);
true
}
None => false,
},
};
self.tried(outer, made)?;
if made {
if !self.notes.merged.contains(&other.label()) {
self.notes.merged.push(other.label());
}
} else {
self.restore(saved);
self.restore(saved)?;
self.squeezed += 1;
self.notes.unmerged += 1;
u.blend = Blend::Mode(BlendMode::Normal);
out.push(u);
@@ -1160,18 +1400,51 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
Ok(out)
}
/// The counts as they were before a merge that couldn't be made.
fn restore(&mut self, c: Counts) {
/// The counts as they are, for [`Self::restore`].
fn saved(&self) -> Counts {
self.notes.counts(self.spent.get(), self.skip_log.len(), self.unknock_log.len(), self.blank_log.len())
}
/// The counts as they were before a merge that couldn't be made, the bytes it spent counted as
/// wasted (see [`Self::refund`]).
fn restore(&mut self, c: Counts) -> Result<(), String> {
self.refund(c.spent)?;
for i in self.skip_log.split_off(c.skipped) {
if let Some(s) = self.skipped.get_mut(i) {
*s = false;
self.notes.hidden = self.notes.hidden.saturating_sub(1);
}
}
for i in self.unknock_log.split_off(c.unknocked) {
if let Some(s) = self.unknocked.get_mut(i) {
*s = false;
self.notes.knockouts = self.notes.knockouts.saturating_sub(1);
}
}
// The groups found since: what their drawing counted is given back, so they are drawn again.
for g in self.blank_log.split_off(c.blank) {
if let Some(b) = self.blank.get_mut(g) {
*b = None;
}
if let Some(b) = self.laid_blank.get_mut(g) {
*b = false;
}
}
for i in self.unclip_log.split_off(c.unclipped) {
if let Some(s) = self.unclipped.get_mut(i) {
*s = false;
self.notes.unclipped = self.notes.unclipped.saturating_sub(1);
}
}
for i in self.clipped_out_log.split_off(c.clipped_out) {
if let Some(s) = self.clipped_out.get_mut(i) {
*s = false;
self.notes.clipped_out = self.notes.clipped_out.saturating_sub(1);
}
}
self.notes.merged.truncate(c.merged);
self.notes.unmerged = c.unmerged;
self.notes.unclipped = c.unclipped;
self.notes.clipped_out = c.clipped_out;
Ok(())
}
/// The visible units `below` with `top` composited over them; `None` when the canvas would need
@@ -1186,24 +1459,169 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
Ok(Some(acc.unwrap_or_default()))
}
/// `out` replaced by one layer: `canvas`, the merge of its visible units with `top`, named after
/// them, bottom first. Its hidden units are left out.
fn take_merge<'i>(&mut self, out: &mut Vec<Unit<'i>>, top: &Unit<'_>, canvas: Canvas) {
let mut name = String::new();
for (k, b) in out.iter_mut().filter(|b| b.visible).enumerate() {
if k == 0 {
name = std::mem::take(&mut b.name);
} else {
name.push_str(" + ");
name.push_str(&b.name);
}
}
if out.iter().any(|b| b.visible) {
name.push_str(" + ");
}
name.push_str(&top.name);
// Hidden layers below are left out with the rest.
for b in out.iter().filter(|b| !b.visible).map(|b| b.record).collect::<Vec<_>>() {
self.skip(b);
}
out.clear();
out.push(Unit {
name,
visible: true,
opacity: 1.0,
blend: Blend::Mode(BlendMode::Normal),
mask_of: None,
record: top.record,
body: Body::Merged(canvas),
clip: None,
base: false,
});
}
/// The visible units `below` with `top`, a layer with a shallow knockout, knocking them out: where
/// `top` has pixels, what is below it in its group is cleared to transparency (the group's own
/// backdrop) and `top` is drawn there at its fill opacity; its opacity then fades all of that
/// back toward the units below as they were. Its layer mask shapes the cut.
fn knock(&mut self, below: &[Unit<'_>], top: &Unit<'_>) -> Result<Knocked, String> {
let (fill, opacity) = {
let rec = self.record(top.record)?;
(rec.fill, rec.opacity)
};
let k = match self.draw_body(&top.body, top.mask_of)? {
Drawn::Nothing => return Ok(Knocked::Nothing),
Drawn::TooLarge => return Ok(Knocked::TooLarge),
Drawn::Canvas(c) if c.px.iter().all(|p| p[3] <= 0.0) => return Ok(Knocked::Nothing),
Drawn::Canvas(c) => c,
};
// At 0 fill, beside every layer below it, it cuts nothing: no canvas for them is needed.
if fill <= 0.0 && self.beside(below, &k)? {
return Ok(Knocked::Nothing);
}
// The layer's canvas is held while the units below are drawn.
let bytes = 16 * k.px.len() as u64;
self.held = self.held.saturating_add(bytes);
let mut acc: Option<Canvas> = None;
let mut drawn = Ok(true);
for u in below.iter().filter(|u| u.visible) {
drawn = self.composite(&mut acc, u);
if !matches!(drawn, Ok(true)) {
break;
}
}
self.held = self.held.saturating_sub(bytes);
if !drawn? {
return Ok(Knocked::TooLarge);
}
// Nothing below draws.
let Some(below) = acc.as_ref() else { return Ok(Knocked::Nothing) };
// At 0 fill it draws nothing of its own: where it cuts no painted pixel below, no canvas for
// the merge is needed.
if fill <= 0.0 && !cuts_paint(below, &k, top.blend, opacity, top.record) {
return Ok(Knocked::Nothing);
}
let clear = |c: &Canvas| c.px.iter().all(|p| p[3] <= 0.0);
let below_clear = clear(below);
if !knock_onto(&mut acc, &k, top.blend, fill, opacity, top.record, self.room(), &|n| self.spend(n))? {
return Ok(Knocked::TooLarge);
}
// Nothing below to cut, and nothing of its own drawn at its fill opacity.
if below_clear && acc.as_ref().is_none_or(clear) {
return Ok(Knocked::Nothing);
}
Ok(acc.map_or(Knocked::Nothing, Knocked::Merged))
}
/// Do the pixels `knock` paints lie outside the bounds of every visible unit `below`? Only the
/// bounds of layers and of merged canvases are known without drawing them: with a group below,
/// `false`.
fn beside(&self, below: &[Unit<'_>], knock: &Canvas) -> Result<bool, String> {
let width = knock.width.max(1);
let mut painted: Option<[i64; 4]> = None;
for (k, _) in knock.px.iter().enumerate().filter(|(_, p)| p[3] > 0.0) {
let (x, y) = (knock.left + (k % width) as i64, knock.top + (k / width) as i64);
painted = Some(painted.map_or([x, y, x + 1, y + 1], |[l, t, r, b]| [l.min(x), t.min(y), r.max(x + 1), b.max(y + 1)]));
}
let Some([left, top, right, bottom]) = painted else { return Ok(true) };
for u in below.iter().filter(|u| u.visible) {
let [l, t, r, b] = match &u.body {
Body::Merged(c) => [c.left, c.top, c.left + c.width as i64, c.top + c.height as i64],
Body::Layer(i) => {
let rec = self.record(*i)?;
match rec.content {
Content::Adjustment => continue,
Content::Solid(Some(_)) if rec.color_over_canvas() => [0, 0, i64::from(self.h.width), i64::from(self.h.height)],
_ => {
let (w, h) = rec.bounds.size();
let (l, t) = (i64::from(rec.bounds.left), i64::from(rec.bounds.top));
[l, t, l + w as i64, t + h as i64]
}
}
}
Body::Group(..) => return Ok(false),
};
if l < right && left < r && t < bottom && top < b {
return Ok(false);
}
}
Ok(true)
}
/// The bytes a merge step may still take: the memory allowed, less the copies of what is below
/// the pass-through groups being merged.
fn room(&self) -> u64 {
self.max_alloc.saturating_sub(self.held)
}
/// Note pass-through group `g` as laying nothing onto nothing when `acc`, nothing before, still
/// is and no layer's pixels were read since `painted`: laying its layers onto nothing again
/// gives nothing, with the same notes.
fn laid_nothing(&mut self, g: usize, acc: &Option<Canvas>, painted: usize) {
if acc.is_none()
&& self.painted.get() == painted
&& let Some(b) = self.laid_blank.get_mut(g)
&& !*b
{
*b = true;
self.blank_log.push(g);
}
}
/// Unit `u` composited onto `acc`. A pass-through group lays its layers onto `acc` one by one,
/// so that they blend with what is below it; at less than full opacity or with a layer mask, the
/// result is then faded back toward `acc` as it was by the opacity and the mask. Anything else
/// is drawn alone first. `false` when the canvas would need more memory than allowed.
fn composite(&mut self, acc: &mut Option<Canvas>, u: &Unit<'_>) -> Result<bool, String> {
if let (Body::Group(items), Blend::Pass) = (&u.body, u.blend) {
if let (Body::Group(g, items), Blend::Pass) = (&u.body, u.blend) {
let mask = match u.mask_of {
Some(i) if self.has_mask(Some(i))? => self.mask(i, false)?,
_ => None,
};
// Onto nothing, a group that laid nothing onto nothing before lays nothing again.
let (fresh, painted) = (acc.is_none(), self.painted.get());
if fresh && self.laid_blank.get(*g) == Some(&true) {
return Ok(true);
}
if u.opacity >= 1.0 && mask.is_none() {
return self.lay(acc, items);
let laid = self.lay(acc, items, Level::Pass)?;
if laid && fresh {
self.laid_nothing(*g, acc, painted);
}
return Ok(laid);
}
let bytes = acc.as_ref().map_or(0, |c| 16 * c.px.len() as u64);
if bytes > self.room() {
@@ -1212,11 +1630,14 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
self.spend(bytes)?;
let below = acc.clone();
self.held = self.held.saturating_add(bytes);
let laid = self.lay(acc, items);
let laid = self.lay(acc, items, Level::Pass);
self.held = self.held.saturating_sub(bytes);
if !laid? {
return Ok(false);
}
if fresh {
self.laid_nothing(*g, acc, painted);
}
if let Some(after) = acc.as_mut() {
fade(after, below.as_ref(), u.opacity, mask.as_ref());
}
@@ -1230,10 +1651,10 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
blend_onto(acc, &c, u.blend, u.opacity, u.record, self.room(), &|n| self.spend(n))
}
/// `items`' layers composited onto `acc` one by one; `false` when a canvas would need more
/// memory than allowed.
fn lay(&mut self, acc: &mut Option<Canvas>, items: &[Item]) -> Result<bool, String> {
for c in self.merged(items, false)? {
/// `items`' layers, the layers of a group at `level`, composited onto `acc` one by one; `false`
/// when a canvas would need more memory than allowed.
fn lay(&mut self, acc: &mut Option<Canvas>, items: &[Item], level: Level) -> Result<bool, String> {
for c in self.merged(items, false, level)? {
if !self.composite(acc, &c)? {
return Ok(false);
}
@@ -1271,13 +1692,29 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
}
None => return Ok(Drawn::Nothing),
},
Body::Group(items) => {
let mut acc: Option<Canvas> = None;
if !self.lay(&mut acc, items)? {
return Ok(Drawn::TooLarge);
Body::Group(g, items) => {
let drawn = match self.blank.get(*g).cloned().flatten() {
Some(d) => d,
None => {
let painted = self.painted.get();
let mut acc: Option<Canvas> = None;
if !self.lay(&mut acc, items, Level::Group)? {
return Ok(Drawn::TooLarge);
}
let d = acc.map_or(Drawn::Nothing, Drawn::Canvas);
if self.painted.get() == painted
&& let Some(b) = self.blank.get_mut(*g)
{
*b = Some(d.clone());
self.blank_log.push(*g);
}
d
}
};
match drawn {
Drawn::Canvas(c) => c,
other => return Ok(other),
}
let Some(acc) = acc else { return Ok(Drawn::Nothing) };
acc
}
};
if let Some(i) = mask_of {
@@ -1306,10 +1743,10 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
Ok(n)
}
/// Layers of the document for `items`, bottom first.
fn list(&mut self, items: &[Item]) -> Result<Vec<Arc<Node>>, String> {
/// Layers of the document for `items`, the layers at `level`, bottom first.
fn list(&mut self, items: &[Item], level: Level) -> Result<Vec<Arc<Node>>, String> {
let mut out = vec![];
for u in self.merged(items, self.hidden)? {
for u in self.merged(items, self.hidden, level)? {
if let Some(n) = self.node(u)? {
out.push(Arc::new(n));
}
@@ -1320,6 +1757,9 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
/// The layer of the document unit `u` becomes; `None` for a layer that draws nothing (an
/// adjustment layer, or one without pixels).
fn node(&mut self, u: Unit<'_>) -> Result<Option<Node>, String> {
if let Some(k) = self.kept.get_mut(u.record) {
*k = true;
}
let children = match &u.body {
Body::Layer(i) => match self.image(*i)? {
Some((left, top, img)) => vec![Arc::new(self.image_node(&u.name, left, top, img)?)],
@@ -1329,13 +1769,13 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
Some((left, top, img)) => vec![Arc::new(self.image_node(&u.name, left, top, img)?)],
None => return Ok(None),
},
Body::Group(items) => self.list(items)?,
Body::Group(_, items) => self.list(items, if u.blend == Blend::Pass { Level::Pass } else { Level::Group })?,
};
let mut layer = self.layer(&u.name);
layer.visible = u.visible;
layer.opacity = u.opacity.clamp(0.0, 1.0);
(layer.blend, layer.isolate) = match u.blend {
Blend::Mode(m) => (m, matches!(u.body, Body::Group(_))),
Blend::Mode(m) => (m, matches!(u.body, Body::Group(..))),
Blend::Pass | Blend::Other(_) => (BlendMode::Normal, false),
};
if let Some(c) = layer.children_mut() {
@@ -1443,6 +1883,71 @@ fn blend_onto(
max_alloc: u64,
spend: &dyn Fn(u64) -> Result<(), String>,
) -> Result<bool, String> {
if !cover(acc, src, max_alloc, spend)? {
return Ok(false);
}
let Some(out) = acc.as_mut() else { return Ok(false) };
// Only the source's rows and columns change.
let (sw, x0, y0) = (src.width.max(1), (src.left - out.left) as usize, (src.top - out.top) as usize);
for (k, s) in src.px.iter().enumerate() {
let Some(p) = out.px.get_mut((y0 + k / sw) * out.width + x0 + k % sw) else { continue };
let a = coverage(blend, s[3] * opacity, src.left + (k % sw) as i64, src.top + (k / sw) as i64, record);
*p = over(blend, *p, [s[0], s[1], s[2], a]);
}
Ok(true)
}
/// `knock` (of record `record`, in `blend`, with its `fill` and `opacity`), a layer with a shallow
/// knockout, knocking out `acc`, on a canvas covering both, as [`blend_onto`] makes it. Where
/// `knock` has pixels, its transparency is the share of `acc` cleared and replaced by its color at
/// `fill`; `opacity` then fades that back toward `acc` (in Dissolve, each pixel is cleared fully
/// or not at all, at the share its transparency times `opacity` gives). `false`, with `acc` as it
/// was, when the canvases would take more than `max_alloc` bytes.
#[allow(clippy::too_many_arguments)]
fn knock_onto(
acc: &mut Option<Canvas>,
knock: &Canvas,
blend: Blend,
fill: f32,
opacity: f32,
record: usize,
max_alloc: u64,
spend: &dyn Fn(u64) -> Result<(), String>,
) -> Result<bool, String> {
if !cover(acc, knock, max_alloc, spend)? {
return Ok(false);
}
let Some(out) = acc.as_mut() else { return Ok(false) };
let (fill, opacity) = (fill.clamp(0.0, 1.0), opacity.clamp(0.0, 1.0));
let (kw, x0, y0) = (knock.width.max(1), (knock.left - out.left) as usize, (knock.top - out.top) as usize);
for (k, s) in knock.px.iter().enumerate() {
let Some(p) = out.px.get_mut((y0 + k / kw) * out.width + x0 + k % kw) else { continue };
let t = coverage(blend, s[3].clamp(0.0, 1.0) * opacity, knock.left + (k % kw) as i64, knock.top + (k / kw) as i64, record);
let below = p[3].clamp(0.0, 1.0);
let alpha = (1.0 - t) * below + t * fill;
if alpha <= 0.0 {
*p = [0.0; 4];
continue;
}
let mix = |i: usize| ((1.0 - t) * below * p[i] + t * fill * s[i]) / alpha;
*p = [mix(0), mix(1), mix(2), alpha];
}
Ok(true)
}
/// Does `knock`, as [`knock_onto`] takes it, clear any of a pixel of `below` that has paint?
fn cuts_paint(below: &Canvas, knock: &Canvas, blend: Blend, opacity: f32, record: usize) -> bool {
let (kw, opacity) = (knock.width.max(1), opacity.clamp(0.0, 1.0));
knock.px.iter().enumerate().any(|(k, s)| {
let (x, y) = (knock.left + (k % kw) as i64, knock.top + (k / kw) as i64);
below.get(x, y).is_some_and(|b| b[3] > 0.0) && coverage(blend, s[3].clamp(0.0, 1.0) * opacity, x, y, record) > 0.0
})
}
/// `acc` grown, when it doesn't already, to a canvas covering itself and `src` (a new one counted
/// with `spend`). `false`, with `acc` as it was, when the canvases held, `acc` and `src` and a
/// larger canvas when one is needed, would take more than `max_alloc` bytes.
fn cover(acc: &mut Option<Canvas>, src: &Canvas, max_alloc: u64, spend: &dyn Fn(u64) -> Result<(), String>) -> Result<bool, String> {
let (mut left, mut top, mut right, mut bottom) = (src.left, src.top, src.left + src.width as i64, src.top + src.height as i64);
if let Some(a) = acc.as_ref() {
left = left.min(a.left);
@@ -1475,14 +1980,6 @@ fn blend_onto(
}
*acc = Some(out);
}
let Some(out) = acc.as_mut() else { return Ok(false) };
// Only the source's rows and columns change.
let (sw, x0, y0) = (src.width.max(1), (src.left - left) as usize, (src.top - top) as usize);
for (k, s) in src.px.iter().enumerate() {
let Some(p) = out.px.get_mut((y0 + k / sw) * width + x0 + k % sw) else { continue };
let a = coverage(blend, s[3] * opacity, src.left + (k % sw) as i64, src.top + (k / sw) as i64, record);
*p = over(blend, *p, [s[0], s[1], s[2], a]);
}
Ok(true)
}
@@ -1521,11 +2018,28 @@ pub(super) fn import(
layers: 0,
notes: Notes::default(),
noted: vec![false; records.len()],
noted_log: vec![],
skipped: vec![false; records.len()],
skip_log: vec![],
unknocked: vec![false; records.len()],
unknock_log: vec![],
clipped_out: vec![false; records.len()],
clipped_out_log: vec![],
unclipped: vec![false; records.len()],
unclip_log: vec![],
kept: vec![false; records.len()],
spent: Cell::new(0),
wasted: Cell::new(0),
trial: Cell::new(0),
painted: Cell::new(0),
blank: vec![None; records.len()],
laid_blank: vec![false; records.len()],
blank_log: vec![],
squeezed: 0,
};
let layers = b.list(&items)?;
let layers = b.list(&items, Level::Top)?;
// A drawing for a knockout or a clip leaves hidden layers out; those that came in anyway aren't.
b.notes.hidden = b.skipped.iter().zip(&b.kept).filter(|&(s, k)| *s && !*k).count();
let Builder { mut doc, notes, .. } = b;
if !layers.is_empty() {
doc.layers = layers;
@@ -646,6 +646,453 @@ fn dissolve_layers_merge_as_opaque_or_transparent_pixels() {
assert!((32..=96).contains(&red), "{red} of 256 pixels show the lower layer: {r}");
}
/// A layer with a Knockout value of `knko` and a fill opacity of `fill`.
fn knockout(l: L, knko: u8, fill: u8) -> L {
let mut l = l;
l.blocks.push((*b"knko", vec![knko, 0, 0, 0]));
l.blocks.push((*b"iOpa", vec![fill]));
l
}
/// A green layer under a group of `group_blend` holding a red layer and `cut` above it.
fn knockout_stack(group_blend: &'static [u8; 4], cut: L) -> Vec<L> {
vec![
layer("Outside", [0, 0, 4, 4], [0, 255, 0, 255]),
group_end(),
layer("Lower", [0, 0, 4, 4], [255, 0, 0, 255]),
cut,
group("Group", group_blend),
]
}
/// The names of the document's layers, and of the layers in its second one.
fn knockout_names(s: &Session) -> (Vec<String>, Vec<String>) {
let d = &s.doc().unwrap().doc;
let names = |ls: &[std::sync::Arc<Node>]| ls.iter().map(|l| name(l).to_string()).collect::<Vec<_>>();
(names(&d.layers), d.layers.get(1).and_then(|g| g.children()).map_or(vec![], |c| names(c)))
}
/// A layer with a shallow knockout in a group merges with the layers below it in the group: its
/// shape clears them to transparency, it draws there at its fill opacity, and its opacity fades
/// that. What is outside the group stays a layer of its own and shows through.
#[test]
fn knockout_layers_merge_with_the_layers_below_them_in_their_group() {
let cut = |fill: u8, opacity: u8| knockout(L { opacity, ..layer("Cut", [0, 0, 2, 2], [0, 0, 255, 255]) }, 1, fill);
for (fill, opacity, at_cut) in [(0, 255, [0, 0, 0, 0]), (128, 255, [0, 0, 255, 128]), (0, 128, [255, 0, 0, 127]), (255, 255, [0, 0, 255, 255])] {
for group_blend in [b"norm", b"pass"] {
let (s, r) = open(&file(4, 4, &knockout_stack(group_blend, cut(fill, opacity)), 8, false, false), json!({}));
assert_eq!(r["warnings"], json!([]), "{r}");
let (top, inner) = knockout_names(&s);
assert_eq!((top, inner), (vec!["Outside".to_string(), "Group".into()], vec!["Lower + Cut".to_string()]), "{fill} {opacity}");
let d = &s.doc().unwrap().doc;
assert_eq!(d.layers[1].isolate, group_blend == b"norm");
let ((x, y), px) = image_of(&s, &d.layers[1].children().unwrap()[0]);
assert_eq!(((x, y), px.dimensions()), ((0.0, 0.0), (4, 4)));
assert_eq!((px.get_pixel(1, 1).0, px.get_pixel(3, 3).0), (at_cut, [255, 0, 0, 255]), "{fill} {opacity}");
}
}
// A layer mask shapes the cut: where it hides the layer, nothing below is cleared.
let mut masked = cut(0, 255);
masked.mask = Some(([0, 0, 1, 1], 255, 0, vec![0]));
let (s, r) = open(&file(4, 4, &knockout_stack(b"norm", masked), 8, false, false), json!({}));
let px = image_of(&s, &s.doc().unwrap().doc.layers[1].children().unwrap()[0]).1;
assert_eq!((px.get_pixel(0, 0).0, px.get_pixel(1, 1).0), ([255, 0, 0, 255], [0, 0, 0, 0]), "{r}");
// Without a knockout (0), the layers stay apart.
let (s, r) =
open(&file(4, 4, &knockout_stack(b"norm", knockout(layer("Cut", [0, 0, 2, 2], [0, 0, 255, 255]), 0, 0)), 8, false, false), json!({}));
assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower".to_string(), "Cut".into()], &json!([])), "{r}");
}
/// The knockouts this import doesn't apply come in as layers, counted in a warning: at the top level,
/// on a clipped layer, and with a Knockout value other than 1. Hidden ones that would need the merge
/// are left out; one that draws nothing, or nothing below it, merges nothing.
#[test]
fn knockouts_that_arent_applied_are_said() {
const UNAPPLIED: &str = "the knockout of 1 layer wasn't applied";
let cut = |l: L, knko: u8| knockout(l, knko, 0);
let blue = || layer("Cut", [0, 0, 2, 2], [0, 0, 255, 255]);
// At the top level.
let layers = [layer("Lower", [0, 0, 4, 4], [255, 0, 0, 255]), cut(blue(), 1)];
let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({}));
assert_eq!((knockout_names(&s).0, &r["warnings"]), (vec!["Lower".to_string(), "Cut".into()], &json!([UNAPPLIED])), "{r}");
// Another Knockout value, and a clipped layer, in a group.
let (s, r) = open(&file(4, 4, &knockout_stack(b"norm", cut(blue(), 2)), 8, false, false), json!({}));
assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower".to_string(), "Cut".into()], &json!([UNAPPLIED])), "{r}");
let (s, r) = open(&file(4, 4, &knockout_stack(b"norm", cut(L { clipped: true, ..blue() }, 1)), 8, false, false), json!({}));
assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower + Cut".to_string()], &json!([UNAPPLIED])), "{r}");
// In a pass-through group, a layer below it, or the knockout itself, in another mode blends with
// what is outside the group: the layers stay apart, and the lower one still multiplies the green
// outside. In an isolated group they merge.
let mut multiply = knockout_stack(b"pass", cut(blue(), 1));
multiply[2].blend = b"mul ";
let (s, r) = open(&file(4, 4, &multiply, 8, false, false), json!({}));
assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower".to_string(), "Cut".into()], &json!([UNAPPLIED])), "{r}");
assert_eq!(s.doc().unwrap().doc.layers[1].children().unwrap()[0].blend, BlendMode::Multiply);
let (s, r) = open(&file(4, 4, &knockout_stack(b"pass", cut(L { blend: b"mul ", ..blue() }, 1)), 8, false, false), json!({}));
assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower".to_string(), "Cut".into()], &json!([UNAPPLIED])), "{r}");
multiply[4] = group("Group", b"norm");
let (s, r) = open(&file(4, 4, &multiply, 8, false, false), json!({}));
assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower + Cut".to_string()], &json!([])), "{r}");
// A hidden knockout would need the merge: left out, hidden layers asked for or not.
for hidden in [false, true] {
let (s, r) =
open(&file(4, 4, &knockout_stack(b"norm", cut(L { hidden: true, ..blue() }, 1)), 8, false, false), json!({"hiddenLayers": hidden}));
assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower".to_string()], &json!([HIDDEN_1])), "{hidden}: {r}");
}
// One that stores no pixels or only transparent ones cuts nothing, and merges nothing.
for (l, inner) in [(L { bare: true, ..blue() }, vec!["Lower"]), (layer("Cut", [0, 0, 2, 2], [0, 0, 255, 0]), vec!["Lower", "Cut"])] {
let (s, r) = open(&file(4, 4, &knockout_stack(b"norm", cut(l, 1)), 8, false, false), json!({}));
assert_eq!((knockout_names(&s).1, &r["warnings"]), (inner.iter().map(|n| n.to_string()).collect(), &json!([])), "{r}");
}
// Nothing below it in its group: it comes in as a layer.
let layers = [group_end(), cut(blue(), 1), group("Group", b"norm"), layer("Over", [0, 0, 1, 1], [9, 9, 9, 255])];
let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({}));
let d = &s.doc().unwrap().doc;
assert_eq!(d.layers[0].children().unwrap().iter().map(|c| name(c)).collect::<Vec<_>>(), ["Cut"], "{r}");
assert_eq!(r["warnings"], json!([]), "{r}");
}
/// A knockout that changes nothing below it leaves the layers apart, hidden ones included: one at 0
/// opacity, one at 0 fill over layers that are transparent or beside their painted pixels, and one
/// whose layer mask hides all of it. At 0 fill over painted layers, and
/// at a fill over transparent ones, it still merges. A knockout at 0 fill over a transparent layer
/// stays apart without a warning when their merge would need more memory than allowed.
#[test]
fn knockouts_that_change_nothing_keep_the_layers_apart() {
let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
let layers = [
group_end(),
layer("Lower", [0, 0, 2, 2], [255, 0, 0, 0]),
knockout(layer("Cut", [2, 2, 4, 4], [0, 0, 255, 255]), 1, 0),
group("Group", b"norm"),
];
// The two 2 × 2 layers drawn together fit 256 bytes, but not the 4 × 4 canvas covering both.
let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 256, cms).unwrap().unwrap();
assert_eq!(doc.layers[0].children().unwrap().iter().map(|c| name(c)).collect::<Vec<_>>(), ["Lower", "Cut"]);
assert!(warnings.is_empty(), "{warnings:?}");
let lower = |alpha: u8| layer("Lower", [0, 0, 4, 4], [255, 0, 0, alpha]);
let hidden = L { hidden: true, ..layer("Hidden", [0, 0, 4, 4], [0, 255, 0, 255]) };
let cut = |fill: u8, opacity: u8| knockout(L { opacity, ..layer("Cut", [0, 0, 2, 2], [0, 0, 255, 255]) }, 1, fill);
let inner = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(vec![], |c| c.iter().map(|l| name(l).to_string()).collect::<Vec<_>>());
for (alpha, fill, opacity, apart) in [(255, 0, 0, true), (0, 0, 255, true), (255, 0, 255, false), (0, 128, 255, false)] {
let layers = [group_end(), lower(alpha), hidden.clone(), cut(fill, opacity), group("Group", b"norm")];
let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({"hiddenLayers": true}));
let (names, warnings) = if apart { (vec!["Lower", "Hidden", "Cut"], json!([])) } else { (vec!["Lower + Cut"], json!([HIDDEN_1])) };
assert_eq!((inner(&s), &r["warnings"]), (names.iter().map(|n| n.to_string()).collect(), &warnings), "{alpha} {fill} {opacity}: {r}");
}
// A hidden knockout that needs no merge comes in with hidden layers: at 0 opacity, with nothing
// below it in its group, at 0 fill beside the painted pixels below it, and with a layer mask that
// hides all of it.
let hidden_cut = |opacity: u8| L { hidden: true, ..cut(0, opacity) };
let beside = L { hidden: true, ..knockout(layer("Cut", [0, 0, 2, 2], [0, 0, 255, 255]), 1, 0) };
let masked = L { hidden: true, mask: Some(([0, 0, 2, 2], 0, 0, vec![0; 4])), ..cut(255, 255) };
for (layers, names) in [
(vec![group_end(), lower(255), hidden_cut(0), group("Group", b"norm")], vec!["Lower", "Cut"]),
(vec![group_end(), hidden_cut(255), group("Group", b"norm")], vec!["Cut"]),
(vec![group_end(), layer("Lower", [2, 2, 4, 4], [255, 0, 0, 255]), beside, group("Group", b"norm")], vec!["Lower", "Cut"]),
(vec![group_end(), lower(255), masked.clone(), group("Group", b"norm")], vec!["Lower", "Cut"]),
] {
let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({"hiddenLayers": true}));
assert_eq!((inner(&s), &r["warnings"]), (names.iter().map(|n| n.to_string()).collect(), &json!([])), "{r}");
}
// With the mask switched off it would need the merge, and is left out.
let unmasked = L { mask: Some(([0, 0, 2, 2], 0, 2, vec![0; 4])), ..masked };
let (s, r) = open(&file(4, 4, &[group_end(), lower(255), unmasked, group("Group", b"norm")], 8, false, false), json!({"hiddenLayers": true}));
assert_eq!((inner(&s), &r["warnings"]), (vec!["Lower".to_string()], &json!([HIDDEN_1])), "{r}");
// A hidden knockout group that would need the merge is counted once, as a hidden layer left out:
// its type layer and its own hidden layer aren't counted.
let mut words = layer("Words", [0, 0, 2, 2], [0, 0, 0, 255]);
words.blocks.push((*b"TySh", vec![0; 4]));
let layers = [
group_end(),
lower(255),
group_end(),
words.clone(),
L { hidden: true, ..layer("Inner", [0, 0, 2, 2], [0, 0, 255, 255]) },
L { hidden: true, ..knockout(group("Cut", b"norm"), 1, 255) },
group("Group", b"norm"),
];
let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({"hiddenLayers": true}));
assert_eq!((inner(&s), &r["warnings"]), (vec!["Lower".to_string()], &json!([HIDDEN_1])), "{r}");
// One whose layer mask hides all of it needs no merge, but a knockout above it merges the layers
// and leaves it out: it is counted once, without its type layer.
let layers = [
group_end(),
lower(255),
group_end(),
words,
L { hidden: true, mask: Some(([0, 0, 2, 2], 0, 0, vec![0; 4])), ..knockout(group("Masked", b"norm"), 1, 255) },
cut(0, 255),
group("Group", b"norm"),
];
let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({"hiddenLayers": true}));
assert_eq!((inner(&s), &r["warnings"]), (vec!["Lower + Cut".to_string()], &json!([HIDDEN_1])), "{r}");
}
/// With hidden layers asked for, the hidden layers of a group drawn for a knockout or a clip that
/// isn't made come in, and aren't counted as left out: a knockout group over a layer that stores no
/// pixels, and a clipped group whose merge needs more memory than allowed.
#[test]
fn hidden_layers_of_a_group_drawn_for_a_merge_not_made_come_in() {
let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
let children = |l: &Node| l.children().map_or(vec![], |c| c.iter().map(|l| (name(l).to_string(), l.visible)).collect::<Vec<_>>());
let shown_and_hidden =
|| [group_end(), layer("Shown", [0, 0, 2, 2], [0, 0, 255, 255]), L { hidden: true, ..layer("Hidden", [2, 2, 4, 4], [0, 255, 0, 255]) }];
let both = vec![("Shown".to_string(), true), ("Hidden".to_string(), false)];
// A knockout group over a layer that stores no pixels.
let mut layers = vec![group_end(), L { bare: true, ..layer("Lower", [0, 0, 2, 2], [0; 4]) }];
layers.extend(shown_and_hidden());
layers.extend([knockout(group("Cut", b"norm"), 1, 255), group("Group", b"norm")]);
let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({"hiddenLayers": true}));
let d = &s.doc().unwrap().doc;
let cut = &d.layers[0].children().unwrap()[0];
assert_eq!((name(cut), children(cut), &r["warnings"]), ("Cut", both.clone(), &json!([])), "{r}");
// A clipped group whose merge with its base doesn't fit 320 bytes.
let mut layers = vec![layer("Base", [0, 0, 2, 2], [255, 0, 0, 255])];
layers.extend(shown_and_hidden());
layers[2].rect = [0, 0, 4, 4];
layers.push(L { clipped: true, ..group("Clipped", b"norm") });
let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), true, 320, cms).unwrap().unwrap();
let clipped = &doc.layers[1];
assert_eq!((name(clipped), children(clipped)), ("Clipped", both), "{warnings:?}");
assert_eq!(warnings, ["1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed"]);
}
/// A knockout's merge whose canvases would need more memory than allowed leaves the layers apart,
/// with a warning. One at 0 fill beside the painted pixels below it cuts nothing, and stays apart
/// whatever the memory.
#[test]
fn a_knockout_merge_past_the_memory_allowed_leaves_the_layers_apart() {
let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
let stack = |cut: [i32; 4]| {
let layers = [
group_end(),
layer("Lower", [0, 0, 2, 2], [255, 0, 0, 255]),
knockout(layer("Cut", cut, [0, 0, 255, 255]), 1, 0),
group("Group", b"norm"),
];
file(4, 4, &layers, 8, false, false)
};
let names = |doc: &vectorcraft_doc::Document| doc.layers[0].children().unwrap().iter().map(|c| name(c).to_string()).collect::<Vec<_>>();
let f = stack([1, 1, 3, 3]);
// Each 2 × 2 layer fits 128 bytes (16 a pixel), but not the canvas of the layer below with the
// knockout's canvas held beside it.
let (doc, warnings) = psdlayers::import(&f, false, 128, cms).unwrap().unwrap();
assert_eq!(names(&doc), ["Lower", "Cut"]);
assert_eq!(warnings, ["the knockout of 1 layer wasn't applied"]);
let (doc, warnings) = psdlayers::import(&f, false, 1 << 20, cms).unwrap().unwrap();
assert_eq!(names(&doc), ["Lower + Cut"]);
assert!(warnings.is_empty(), "{warnings:?}");
for max_alloc in [128, 1 << 20] {
let (doc, warnings) = psdlayers::import(&stack([2, 2, 4, 4]), false, max_alloc, cms).unwrap().unwrap();
assert_eq!(names(&doc), ["Lower", "Cut"], "{max_alloc}");
assert!(warnings.is_empty(), "{max_alloc}: {warnings:?}");
}
}
/// A knockout that cuts nothing gives back what drawing the layers below it counted: here a
/// knockout at 0 fill beside a group, whose own knockout doesn't fit 192 bytes while the outer
/// knockout's canvas is held, but merges when the group comes in.
#[test]
fn a_knockout_that_cuts_nothing_doesnt_keep_what_drawing_below_it_counted() {
let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
let layers = [
group_end(),
group_end(),
layer("Opaque", [0, 0, 2, 2], [255, 0, 0, 255]),
knockout(layer("Inner cut", [0, 0, 1, 2], [0, 0, 255, 255]), 1, 0),
group("Inner", b"norm"),
knockout(layer("Outer cut", [2, 2, 4, 4], [0, 0, 255, 255]), 1, 0),
group("Outer", b"norm"),
];
let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 192, cms).unwrap().unwrap();
let outer = doc.layers[0].children().unwrap();
assert_eq!(outer.iter().map(|c| name(c)).collect::<Vec<_>>(), ["Inner", "Outer cut"], "{warnings:?}");
assert_eq!(outer[0].children().unwrap().iter().map(|c| name(c)).collect::<Vec<_>>(), ["Opaque + Inner cut"], "{warnings:?}");
assert!(warnings.is_empty(), "{warnings:?}");
}
/// A knockout merge that can't be made leaves the import the whole allowance for reading the layers
/// apart: here the merge decodes 22 layers over one another before the layer beside them makes its
/// canvas too large, which used up nearly all of eight times 64 KiB. The merge has that allowance
/// also after five layers below the group were read, and a knockout at 0 fill over 22 transparent
/// layers, which cuts no paint after they are drawn, leaves the same room.
#[test]
fn a_knockout_merge_not_made_leaves_room_to_read_the_layers() {
let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
let mut layers = vec![group_end()];
layers.extend((0..22).map(|_| layer("Lower", [0, 0, 32, 32], [255, 0, 0, 255])));
layers.push(layer("Beside", [0, 64, 32, 96], [0, 255, 0, 255]));
layers.extend([knockout(layer("Cut", [0, 0, 32, 32], [0, 0, 255, 255]), 1, 0), group("Group", b"norm")]);
let (doc, warnings) = psdlayers::import(&file(96, 32, &layers, 8, false, false), false, 64 << 10, cms).unwrap().unwrap();
assert_eq!(doc.layers[0].children().unwrap().len(), 24, "{warnings:?}");
assert_eq!(warnings, ["the knockout of 1 layer wasn't applied"]);
let mut after_five = vec![layer("Outside", [0, 0, 32, 32], [0, 0, 0, 255]); 5];
after_five.extend(layers);
let (doc, warnings) = psdlayers::import(&file(96, 32, &after_five, 8, false, false), false, 64 << 10, cms).unwrap().unwrap();
assert_eq!((doc.layers.len(), doc.layers[5].children().unwrap().len()), (6, 24), "{warnings:?}");
assert_eq!(warnings, ["the knockout of 1 layer wasn't applied"]);
let mut layers = vec![group_end()];
layers.extend((0..22).map(|_| layer("Lower", [0, 0, 32, 32], [255, 0, 0, 0])));
layers.extend([knockout(layer("Cut", [0, 0, 32, 32], [0, 0, 255, 255]), 1, 0), group("Group", b"norm")]);
let (doc, warnings) = psdlayers::import(&file(32, 32, &layers, 8, false, false), false, 64 << 10, cms).unwrap().unwrap();
assert_eq!(doc.layers[0].children().unwrap().len(), 23, "{warnings:?}");
assert!(warnings.is_empty(), "{warnings:?}");
}
/// A hidden knockout in a mode VectorCraft lacks is left out without being drawn, hidden layers
/// asked for: here its pixels are larger than the memory allowed for one image.
#[test]
fn a_hidden_knockout_in_a_mode_vectorcraft_lacks_is_left_out_unread() {
let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
let layers = [
group_end(),
layer("Lower", [0, 0, 2, 2], [255, 0, 0, 255]),
L { hidden: true, blend: b"diss", ..knockout(layer("Cut", [0, 0, 8, 8], [0, 0, 255, 255]), 1, 255) },
group("Group", b"norm"),
];
let (doc, warnings) = psdlayers::import(&file(8, 8, &layers, 8, false, false), true, 128, cms).unwrap().unwrap();
assert_eq!(doc.layers[0].children().unwrap().iter().map(|c| name(c)).collect::<Vec<_>>(), ["Lower"]);
assert_eq!(warnings, [HIDDEN_1]);
}
/// A Dissolve knockout at part opacity clears each pixel below it fully or not at all, at the share
/// its opacity gives, as a Dissolve layer merges.
#[test]
fn a_dissolve_knockout_at_part_opacity_clears_whole_pixels() {
let cut = knockout(L { blend: b"diss", opacity: 128, ..layer("Cut", [0, 0, 16, 16], [0, 0, 255, 255]) }, 1, 0);
let layers = [group_end(), layer("Lower", [0, 0, 16, 16], [255, 0, 0, 255]), cut, group("Group", b"norm")];
let (s, r) = open(&file(16, 16, &layers, 8, false, false), json!({}));
let d = &s.doc().unwrap().doc;
let (_, px) = image_of(&s, &d.layers[0].children().unwrap()[0]);
assert!(px.pixels().all(|p| p.0 == [255, 0, 0, 255] || p.0[3] == 0), "{r}");
let red = px.pixels().filter(|p| p.0 == [255, 0, 0, 255]).count();
assert!((32..=224).contains(&red), "{red} of 256 pixels keep the lower layer: {r}");
}
/// The knockout of a layer that another is clipped to isn't applied, also when the clipped layer's
/// merge with it needs more memory than allowed and the two come in apart.
#[test]
fn a_clipping_base_knockout_isnt_applied_when_its_clip_doesnt_fit() {
let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
// The 4 × 4 clipped layer and its 2 × 2 base don't fit 320 bytes together for the clip; the
// base's knockout merge with the 2 × 2 layer below would.
let layers = [
group_end(),
layer("Lower", [0, 0, 2, 2], [255, 0, 0, 255]),
knockout(layer("Base", [0, 0, 2, 2], [0, 0, 255, 255]), 1, 0),
L { clipped: true, ..layer("Clipped", [0, 0, 4, 4], [0, 255, 0, 255]) },
group("Group", b"norm"),
];
let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 320, cms).unwrap().unwrap();
assert_eq!(doc.layers[0].children().unwrap().iter().map(|c| name(c)).collect::<Vec<_>>(), ["Lower", "Base", "Clipped"], "{warnings:?}");
assert_eq!(
warnings,
["the knockout of 1 layer wasn't applied", "1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed"]
);
}
/// A knockout group that comes in as a layer counts each layer clipped in it once in the warnings,
/// though its layers are also drawn for the knockout: one clipped to a fill that isn't drawn, and
/// one that a merge past the memory allowed leaves unclipped.
#[test]
fn a_knockout_group_that_comes_in_as_a_layer_counts_its_clipped_layers_once() {
let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
let empty = L { bare: true, ..layer("Empty", [0, 0, 2, 2], [0, 0, 0, 0]) };
// A fill whose shape is a vector mask, with a layer clipped to it: neither is drawn.
let mut soco = vec![0; 8];
for (key, v) in [(b"Rd doub", 255.0f64), (b"Grn doub", 0.0), (b"Bl doub", 51.0)] {
soco.extend(key);
soco.extend(v.to_be_bytes());
}
let mut outline = layer("Outline", [0, 0, 0, 0], [0; 4]);
outline.blocks.push((*b"SoCo", soco));
outline.blocks.push((*b"vsms", vec![0; 8]));
let on_outline = L { clipped: true, ..layer("On outline", [0, 0, 2, 2], [1, 1, 1, 255]) };
// Each 2 × 2 layer fits 128 bytes, and so do the two drawn together, but not the merge of the
// clipped one with the one below.
let base = layer("Base", [0, 0, 2, 2], [255, 0, 0, 255]);
let clipped = L { clipped: true, ..layer("Clipped", [0, 0, 2, 2], [0, 0, 255, 255]) };
for (inner, said) in [
(vec![outline, on_outline], "1 layer clipped to a fill layer that wasn't drawn was left out"),
(vec![base, clipped], "1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed"),
] {
let mut layers = vec![layer("Outside", [0, 0, 4, 4], [0, 255, 0, 255]), group_end(), empty.clone(), group_end()];
layers.extend(inner);
layers.extend([knockout(group("Cut", b"norm"), 1, 255), group("Group", b"norm")]);
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<_>>(), ["Outside", "Group"]);
assert!(warnings.iter().any(|w| w == said), "{said}: {warnings:?}");
}
}
/// A pass-through group that draws nothing still counts what its layers count in it, also when it
/// is drawn again inside a group that merges: a knockout above a Multiply layer isn't applied in a
/// pass-through group, though drawn alone it would be.
#[test]
fn a_pass_through_group_that_draws_nothing_still_counts_its_unapplied_knockouts() {
let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
let empty = |name: &'static str, blend: &'static [u8; 4]| L { bare: true, blend, ..layer(name, [0, 0, 2, 2], [0, 0, 0, 0]) };
let layers = [
layer("Lower", [0, 0, 4, 4], [255, 0, 0, 255]),
group_end(),
empty("Empty", b"norm"),
group_end(),
empty("Multiplied", b"mul "),
knockout(empty("Cut", b"norm"), 1, 255),
knockout(group("Through", b"pass"), 1, 255),
group("Dissolved", b"diss"),
];
let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 1 << 20, cms).unwrap().unwrap();
assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Lower + Dissolved"], "{warnings:?}");
assert_eq!(warnings, ["the knockout of 1 layer wasn't applied".to_string(), psdlayers::MERGED_WARNING.replace("{modes}", "Dissolve")]);
}
/// A group that draws nothing is drawn once, however deep the groups like it nest: here each holds
/// a layer that stores no pixels and, above it, the next group, with a knockout. The import walks
/// at most as many layer lists as the file has records, with isolated groups, with groups that
/// alternate with pass-through ones, with pass-through groups inside the outermost one (whose
/// knockouts aren't applied), and with a layer in a mode VectorCraft lacks in each (a merge of
/// nothing, a canvas without pixels).
#[test]
fn groups_that_draw_nothing_are_drawn_once_however_deep_they_nest() {
const LEVELS: usize = 48;
let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
let empty = |name: &'static str, blend: &'static [u8; 4]| L { bare: true, blend, ..layer(name, [0, 0, 2, 2], [0, 0, 0, 0]) };
// Which levels are pass-through groups.
let none: fn(usize) -> bool = |_| false;
let odd: fn(usize) -> bool = |k| k % 2 == 1;
let all: fn(usize) -> bool = |k| k > 0;
for (case, pass, dissolve, warned) in [
("isolated", none, false, vec![]),
("alternating", odd, false, vec![]),
("pass-through", all, false, vec![format!("the knockout of {} layers wasn't applied", LEVELS - 1)]),
("dissolved", none, true, vec![psdlayers::MERGED_WARNING.replace("{modes}", "Dissolve")]),
] {
let mut layers = vec![layer("Outside", [0, 0, 4, 4], [0, 255, 0, 255])];
for _ in 0..=LEVELS {
layers.push(group_end());
if dissolve {
layers.push(empty("Dissolved", b"diss"));
}
layers.push(empty("Empty", b"norm"));
}
for k in (0..=LEVELS).rev() {
let g = group("Group", if pass(k) { b"pass" } else { b"norm" });
layers.push(if k == 0 { g } else { knockout(g, 1, 255) });
}
psdlayers::WALKS.set((0, layers.len()));
let imported = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 1 << 20, cms);
let (walked, _) = psdlayers::WALKS.replace((0, usize::MAX));
let (doc, warnings) = imported.unwrap().unwrap();
assert!(walked <= layers.len(), "{case}: {walked} walks for {} records", layers.len());
assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Outside", "Group"], "{case}");
let mut expected = warned;
expected.push(vectorcraft_doc::depth::merged_note());
assert_eq!(warnings, expected, "{case}");
}
}
#[test]
fn what_doesnt_come_in_is_said() {
let mut text = layer("Words", [0, 0, 2, 2], [0, 0, 0, 255]);
+1 -1
View File
@@ -305,7 +305,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Live Shape Properties",
[],
None,
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint)} (Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
has_selection,
set_live_shape
),
+31 -4
View File
@@ -202,6 +202,16 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
// A polygon's Polygon Properties: its angle, radius or side length, Make Sides Equal.
let (polygon_angle, polygon_radius, side) = (angle("polygonAngle")?, length("polygonRadius")?, length("sideLength")?);
let equal = p.get("makeSidesEqual").and_then(Value::as_bool) == Some(true);
// A rectangle's Rectangle Angle and an ellipse's Ellipse Angle, as `polygonAngle` turns a polygon.
let (rectangle_angle, ellipse_angle) = (angle("rectangleAngle")?, angle("ellipseAngle")?);
// Whether a shape at `now` already stands at `a`: a turn the rounding of an earlier one left
// (89.999999999°, or 359.9999999999° against 0°) counts as no change.
let at_angle = |now: Option<f64>, a: f64| {
now.is_some_and(|n| {
let d = (n - a).rem_euclid(360.0);
d.min(360.0 - d) < 1e-9
})
};
// A line's Line Properties: its length (its first end stays) and its angle (about its midpoint).
// A line's length can reach across the whole canvas, past `MAX_COORD`: its ends are checked below.
let line_length = number("lineLength", |x| x > 0.0, "a length in points above 0")?;
@@ -249,12 +259,15 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
Some(l @ LiveShape::Polygon { sides: now, .. })
if !(sides.is_none_or(|n| n.clamp(3, 1000) == u64::from(*now))
&& (!equal || l.polygon_sides_equal())
&& polygon_angle.is_none_or(|a| l.polygon_angle() == Some(a))
&& polygon_angle.is_none_or(|a| at_angle(l.polygon_angle(), a))
&& side.and_then(|len| l.polygon_radius_for_side(len)).or(polygon_radius).is_none_or(|r| l.polygon_radius() == Some(r))) =>
{
return false;
}
Some(LiveShape::Ellipse { pie, .. }) if pie_of(*pie) != *pie => return false,
Some(l @ LiveShape::Ellipse { pie, .. }) if pie_of(*pie) != *pie || ellipse_angle.is_some_and(|a| !at_angle(l.shape_angle(), a)) => {
return false;
}
Some(l @ LiveShape::Rectangle { .. }) if rectangle_angle.is_some_and(|a| !at_angle(l.shape_angle(), a)) => return false,
_ => {}
}
if relative_radii.is_some_and(|on| live.as_deref().map(|l| l.radii_relative()) != Some(on)) {
@@ -298,9 +311,18 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
}
*path = l.to_path();
}
if let Some(l @ LiveShape::Ellipse { .. }) = live.as_deref_mut()
&& (pie_start.is_some() || pie_end.is_some() || invert)
if let Some(a) = rectangle_angle
&& let Some(l @ LiveShape::Rectangle { .. }) = live.as_deref_mut()
{
l.set_shape_angle(a);
*path = l.to_path();
}
if let Some(l @ LiveShape::Ellipse { .. }) = live.as_deref_mut()
&& (pie_start.is_some() || pie_end.is_some() || invert || ellipse_angle.is_some())
{
if let Some(a) = ellipse_angle {
l.set_shape_angle(a);
}
if let LiveShape::Ellipse { pie, .. } = l {
*pie = pie_of(*pie);
}
@@ -339,6 +361,11 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
for id in &ids {
super::pixelgrid::resnap(d, *id);
}
// A shape named in `ids` and not selected is not checked after the edit: one that a turn or
// a new radius would take past the coordinate limit is an error here, and nothing changes.
if !crate::sanity::objects_in_range(d, &ids) {
return Err(bad("object.setLiveShape", format!("coordinate out of range (limit ±{MAX_COORD} pt)")));
}
Ok(())
})?;
ok()
+114 -1
View File
@@ -9,12 +9,13 @@
//! **Repeat** objects are live nodes (`NodeKind::Repeat`) holding the source art and the
//! arrangement; `vectorcraft_doc::pattern` evaluates the instances.
use std::collections::HashSet;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::Paint;
use vectorcraft_doc::pattern::{self, Overlap, PATTERN_EDIT_LAYER, PatternDef, PatternEdit, RepeatKind, RepeatSpec, TileType, pattern_paint};
use vectorcraft_doc::swatches::PaintFn;
use vectorcraft_doc::swatches::{PaintFn, graph_paints, node_paints, override_paints, walk_with_masks};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Selection};
use vectorcraft_geom::{Point, Rect};
@@ -37,6 +38,15 @@ pub fn specs() -> Vec<CommandSpec> {
can_make_pattern,
pattern_make
),
cmd!(
"object.pattern.replaceArt",
"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}",
can_replace_pattern_art,
pattern_replace_art
),
cmd!(
"object.pattern.edit",
"Edit Pattern",
@@ -198,6 +208,12 @@ fn has_selection_or_ids(s: &Session) -> std::result::Result<(), String> {
has_doc(s)
}
/// Replace Pattern Art: a document, and no pattern is being edited.
fn can_replace_pattern_art(s: &Session) -> std::result::Result<(), String> {
has_doc(s)?;
if editing(s).is_some() { Err("finish editing the pattern first".into()) } else { Ok(()) }
}
/// The repeats of the selection: selected ones, and those around a selected object. None while
/// an object of a dynamic symbol instance's art is selected.
fn selected_repeats(s: &Session) -> Vec<NodeId> {
@@ -412,6 +428,103 @@ pub(crate) fn finish_edit(d: &mut Document, sel: &mut Selection) -> Result<Strin
Ok(pe.pattern)
}
/// Give pattern `name` fresh-id copies of the selected art (or of `ids`) as its tile art, as one
/// undo step (`object.pattern.replaceArt`). The pattern keeps its name, swatch, tile and options,
/// and its tile fits the new art when its Size Tile to Art is on; paints refer to a pattern by
/// name, so every fill and stroke of it draws the new tile. The art stays where it is, selected as
/// before. Art that matches the tile art already records nothing.
fn pattern_replace_art(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.pattern.replaceArt";
let name = text_param(p, "name", C)?.ok_or_else(|| bad(C, "missing name"))?.to_string();
let roots = roots(s, p, C)?;
let d = &s.doc()?.doc;
let old = d.pattern(&name).map(|def| def.art.clone()).ok_or_else(|| bad(C, format!("no pattern `{name}`")))?;
if roots.is_empty() {
return Err(bad(C, "select the art for the pattern tile"));
}
let src: Vec<Arc<Node>> = roots.iter().filter_map(|id| d.node(*id).cloned()).map(Arc::new).collect();
if paints_pattern(d, &src, &name) {
return Err(bad(C, format!("art painted with `{name}` can't be its tile")));
}
// Copies made from the same next id are equal when the art matches the tile art.
let fresh = |art: &[Arc<Node>]| copies(&mut Document::clone(d), art);
if fresh(&old) == fresh(&src) {
return Ok(json!({ "name": name }));
}
s.edit("Replace Pattern Art", |d, _| {
let art: Vec<Arc<Node>> = copies(d, &src).into_iter().map(Arc::new).collect();
if let Some(def) = d.pattern_mut(&name) {
def.art = art;
if def.size_tile_to_art {
def.fit_tile_to_art();
}
}
Ok(())
})?;
Ok(json!({ "name": name }))
}
/// What a piece of art uses by name, for [`paints_pattern`].
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
enum Uses<'a> {
Symbol(&'a str),
Pattern(&'a str),
GraphDesign(&'a str),
Brush(&'a str),
}
/// Does `art` paint pattern `name`, itself or through the symbols (of its instances and of the
/// inline graphics in its type), patterns, graph designs and brushes it uses? A graph's stored
/// series and label paints count, since its marks and labels take them each time it is drawn again.
fn paints_pattern(d: &Document, art: &[Arc<Node>], name: &str) -> bool {
let brushes = vectorcraft_brush::library(d);
// What was already looked into, and the art left to look at.
let mut seen: HashSet<Uses> = HashSet::new();
let mut left: Vec<&Node> = art.iter().map(|a| &**a).collect();
while let Some(n) = left.pop() {
let mut used = vec![];
walk_with_masks(n, &mut |c| {
match &c.kind {
NodeKind::SymbolInstance { symbol, .. } => used.push(Uses::Symbol(symbol.as_str())),
// The symbol of every inline graphic in type counts, overset or not.
NodeKind::Text(t) => used.extend(t.runs.iter().filter_map(|r| r.inline.as_ref()).map(|a| Uses::Symbol(a.symbol.as_str()))),
_ => {}
}
for it in &c.appearance.items {
if let vectorcraft_doc::AppearanceItem::Stroke(sk) = it
&& let Some(b) = &sk.brush
{
used.push(Uses::Brush(b.as_str()));
}
}
for p in node_paints(c).chain(override_paints(c)).chain(graph_paints(c)) {
if let Paint::Pattern { pattern, .. } = p {
used.push(Uses::Pattern(pattern.as_str()));
}
}
if let Some(g) = c.extras().graph.as_deref() {
used.extend(g.series_markers.iter().flatten().map(|m| Uses::GraphDesign(m.as_str())));
used.extend(g.series_columns.iter().flatten().map(|c| Uses::GraphDesign(c.design.as_str())));
}
});
for u in used {
if u == Uses::Pattern(name) {
return true;
}
if !seen.insert(u) {
continue;
}
match u {
Uses::Symbol(symbol) => left.extend(d.symbols.iter().find(|x| x.name == symbol).map(|x| &*x.art)),
Uses::Pattern(pattern) => left.extend(d.pattern(pattern).into_iter().flat_map(|x| x.art.iter().map(|a| &**a))),
Uses::GraphDesign(design) => left.extend(d.graph_designs.iter().find(|x| x.name == design).map(|x| &*x.art)),
Uses::Brush(brush) => left.extend(brushes.iter().filter(|x| x.name == brush).flat_map(|x| x.art())),
}
}
}
false
}
/// Leave pattern editing mode, discarding the changes (`object.pattern.cancel`). An existing
/// pattern gets its definition back, its name included when Pattern Options renamed it while it was
/// edited and no other pattern, swatch or color group has taken that name since. A new pattern is
@@ -363,6 +363,7 @@ pub(super) const ALLOWED: &[&str] = &[
"object.pattern.done",
"object.pattern.edit",
"object.pattern.make",
"object.pattern.replaceArt",
"object.puppetWarp",
"object.puppetWarp.pins",
"object.rasterize",
+25
View File
@@ -119,6 +119,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
"energy-beams",
"dry-media",
"tech-circuit",
"engraving",
"arrows",
"image-brush"
]
@@ -272,6 +273,30 @@ fn black_stroke() -> vectorcraft_doc::StrokeLayer {
vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0)
}
#[test]
fn engraving_library_draws_fine_parallel_strokes_and_survives_save() {
let mut s = session();
let listed = run(&mut s, "brush.libraries", json!({}));
let entry = listed["libraries"].as_array().unwrap().iter().find(|l| l["id"] == "engraving").unwrap();
assert_eq!((entry["name"].as_str(), entry["category"].as_str(), entry["count"].as_u64()), (Some("Engraving"), Some("builtIn"), Some(4)));
let (_, lib) = cmd::brushlib::library(&s, "Engraving").unwrap();
for b in &lib.brushes {
for length in [2.0, 200.0] {
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(length), &black_stroke());
let pts = anchors(&pieces.iter().collect::<Vec<_>>());
assert!(!pts.is_empty() && pts.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{} at {length} pt", b.name);
}
}
let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 20, "x2": 210, "y2": 20}))["id"].as_u64().unwrap();
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "engraving", "name": "Fine Hatching", "apply": true, "ids": [path]}));
assert_eq!(strs(&added["added"]), ["Fine Hatching"]);
assert_eq!(added["applied"], json!([path]));
let saved = run(&mut s, "brush.saveLibrary", json!({"names": ["Fine Hatching"]}));
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
let reopened = vectorcraft_format::load(&bytes).unwrap();
assert_eq!(vectorcraft_brush::find(&reopened, "Fine Hatching").unwrap(), lib.brushes[0]);
}
#[test]
fn stipple_library_draws_dot_textures_and_survives_save() {
let mut s = session();
+100
View File
@@ -585,6 +585,106 @@ fn a_polygon_takes_its_angle_radius_side_length_and_equal_sides() {
}
}
/// Rectangle Angle and Ellipse Angle: `rectangleAngle` and `ellipseAngle` turn each selected live
/// rectangle or ellipse about its own center, keeping its size, corners and pie, as one undo step.
/// The angle it already has records no step, each key leaves the other kind as it is, and a value
/// that is not a number is an error.
#[test]
fn a_rectangle_and_an_ellipse_take_their_angle() {
let (mut s, rect) = session();
run(&mut s, json!({"radius": 8}));
let ellipse = NodeId(s.execute("shape.ellipse", &json!({"x": 200, "y": 200, "width": 120, "height": 80})).unwrap()["id"].as_u64().unwrap());
run(&mut s, json!({"pieStart": 30, "pieEnd": 120}));
let live = |s: &Session, id: NodeId| {
let n = s.doc().unwrap().doc.node(id).unwrap();
(n.live_shape().unwrap().clone(), n.geometric_bounds().unwrap())
};
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let close = |a: f64, b: f64| (a - b).abs() < 1e-6;
let angle = |s: &Session, id: NodeId| live(s, id).0.shape_angle().unwrap();
// The ellipse's center: the middle of its untransformed box, wherever its pie leaves the path.
let ellipse_center = |s: &Session| match live(s, ellipse).0 {
LiveShape::Ellipse { w, h, xf, .. } => xf * vectorcraft_geom::Point::new(w / 2.0, h / 2.0),
l => panic!("{l:?}"),
};
let center = ellipse_center(&s);
s.execute("select.set", &json!({"ids": [rect.0]})).unwrap();
let n = steps(&s);
run(&mut s, json!({"rectangleAngle": 90}));
let (l, b) = live(&s, rect);
assert!(close(angle(&s, rect), 90.0), "{l:?}");
// 100 × 60 at (10, 10) turned about (60, 40): 60 wide, 100 tall, same center.
assert!(close(b.width(), 60.0) && close(b.height(), 100.0) && close(b.center().x, 60.0) && close(b.center().y, 40.0), "{b:?}");
let LiveShape::Rectangle { w, h, radii, .. } = &l else { panic!("{l:?}") };
assert!(close(*w, 100.0) && close(*h, 60.0) && *radii == [8.0; 4], "{w} {h} {radii:?}");
assert_eq!(steps(&s), n + 1, "one undo step");
for same in [json!({"rectangleAngle": 90}), json!({"rectangleAngle": 450}), json!({"rectangleAngle": -270}), json!({"ellipseAngle": 10})] {
run(&mut s, same.clone());
assert_eq!(steps(&s), n + 1, "{same} records no undo step");
}
// A turn the field gives back rounded is the angle the shape has: typing it again records no step.
run(&mut s, json!({"rectangleAngle": 33.3}));
let now = angle(&s, rect);
run(&mut s, json!({"rectangleAngle": now}));
run(&mut s, json!({"rectangleAngle": 33.3}));
assert_eq!(steps(&s), n + 2);
for bad in [json!({"rectangleAngle": "left"}), json!({"ellipseAngle": "up"}), json!({"rectangleAngle": true})] {
assert!(s.execute("object.setLiveShape", &bad).is_err(), "{bad}");
assert_eq!(steps(&s), n + 2, "{bad} changes nothing");
}
// The ellipse turns about its center and keeps its pie.
s.execute("select.set", &json!({"ids": [ellipse.0]})).unwrap();
run(&mut s, json!({"ellipseAngle": 90}));
let (l, b) = live(&s, ellipse);
assert!(close(angle(&s, ellipse), 90.0), "{l:?}");
let LiveShape::Ellipse { pie, .. } = &l else { panic!("{l:?}") };
assert_eq!(*pie, (30.0, 120.0));
let now = ellipse_center(&s);
assert!(close(now.x, center.x) && close(now.y, center.y), "{center:?} → {now:?}");
assert!(b.width() < b.height(), "120 × 80 turned a quarter turn: {b:?}");
// Both selected: each key turns its own kind only, each about its own center.
s.execute("select.set", &json!({"ids": [rect.0, ellipse.0]})).unwrap();
run(&mut s, json!({"rectangleAngle": 45}));
assert!(close(angle(&s, rect), 45.0) && close(angle(&s, ellipse), 90.0));
let b = live(&s, rect).1;
assert!(close(b.center().x, 60.0) && close(b.center().y, 40.0), "{b:?}");
s.execute("edit.undo", &json!({})).unwrap();
assert!(close(angle(&s, rect), 33.3));
// A reflected rectangle takes the angle too, about its center.
s.execute("select.set", &json!({"ids": [rect.0]})).unwrap();
s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap();
let before = live(&s, rect).1.center();
run(&mut s, json!({"rectangleAngle": 20}));
let after = live(&s, rect).1.center();
assert!(close(angle(&s, rect), 20.0) && close(before.x, after.x) && close(before.y, after.y), "{before:?} → {after:?}");
}
/// A shape named in `ids` that a turn would take past the coordinate limit (±4,000,000 pt) is an
/// error that changes nothing, whether or not it is selected.
#[test]
fn a_turn_past_the_coordinate_limit_is_an_error() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let mut add = |cmd: &str, p: Value| s.execute(cmd, &p).unwrap()["id"].as_u64().unwrap();
// Each reaches within 10 pt of the limit and past it when turned.
let rect = add("shape.rectangle", json!({"x": 3_999_890, "y": 100, "width": 100, "height": 100}));
let ellipse = add("shape.ellipse", json!({"x": 3_999_950, "y": 100, "width": 40, "height": 100}));
let polygon = add("shape.polygon", json!({"cx": 3_999_955, "cy": 200, "radius": 50, "sides": 6}));
for (id, key, angle) in [(rect, "rectangleAngle", 45), (ellipse, "ellipseAngle", 90), (polygon, "polygonAngle", 90)] {
for selected in [false, true] {
s.execute("select.set", &json!({"ids": if selected { vec![id] } else { vec![] }})).unwrap();
let (doc, steps) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
let e = s.execute("object.setLiveShape", &json!({"ids": [id], key: angle})).unwrap_err();
assert!(e.to_string().contains("out of range"), "{key}, selected {selected}: {e}");
assert!(*s.doc().unwrap().doc == *doc && s.doc().unwrap().history.undo.len() == steps, "{key}, selected {selected}: changed");
}
}
}
/// A live line's Line Properties: Line Length keeps its first end in place, Line Angle (degrees
/// counterclockwise, any finite value brought into 0 to 360) turns it about its midpoint, the
/// length applies before the angle, every selected line takes them in one undo step, and a value
+147
View File
@@ -212,6 +212,153 @@ fn cancel_new_pattern_removes_it() {
assert_eq!(doc(&s).layers.len(), 1);
}
/// A 30×40 blue rectangle at (100, 100) with no stroke, selected.
fn blue_rect(s: &mut Session) -> NodeId {
let b = rect(s, 100.0, 100.0, 30.0, 40.0);
s.execute("paint.setFill", &json!({"ids": [b.0], "color": "#0000ff"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [b.0], "none": true})).unwrap();
sel(s, &[b]);
b
}
/// Replace Pattern Art gives the pattern copies of the selected art as its tile art in one undo
/// step: the pattern keeps its name, swatch, place, tile and options, art painted with it keeps the
/// paint, and the selected art stays on the canvas, selected. Undo and Redo swap the two tiles.
#[test]
fn replace_art_gives_a_pattern_new_tile_art() {
let mut s = session();
let red = make_dots(&mut s);
let filled = rect(&mut s, 200.0, 200.0, 100.0, 100.0);
s.execute("paint.setFill", &json!({"ids": [filled.0], "swatch": "Dots"})).unwrap();
s.execute("pattern.options", &json!({"name": "Dots", "tileType": "hexByRow"})).unwrap();
let blue = blue_rect(&mut s);
let old = doc(&s).pattern("Dots").unwrap().clone();
let place = |s: &Session| doc(s).swatches_iter().position(|w| w.name == "Dots");
let (at, swatches, steps) = (place(&s), doc(&s).swatches_iter().count(), s.doc().unwrap().history.undo.len());
let v = s.execute("object.pattern.replaceArt", &json!({"name": "Dots"})).unwrap();
assert_eq!(v["name"], "Dots");
let d = doc(&s);
let def = d.pattern("Dots").unwrap();
assert_eq!(def.art.len(), 1);
assert_eq!(def.art[0].kind, node(&s, blue).kind, "the tile art is the blue rectangle");
assert_eq!(def.art[0].appearance, node(&s, blue).appearance);
assert_ne!(def.art[0].id, blue, "a copy with an id of its own");
assert_eq!((def.tile, def.tile_type, &def.name), (old.tile, old.tile_type, &old.name), "the tile and options stay");
assert_eq!((d.patterns.len(), place(&s), d.swatches_iter().count()), (1, at, swatches), "no new pattern or swatch");
assert!(is_pattern(&node(&s, filled).appearance.fill_paint(), "Dots"), "the filled art keeps the pattern");
assert!(d.node(blue).is_some() && d.node(red).is_some(), "the art stays");
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), vec![blue], "the art stays selected");
let st = s.doc().unwrap();
assert_eq!((st.history.undo.len(), st.history.undo.last().map(|e| e.label.as_str())), (steps + 1, Some("Replace Pattern Art")));
let new = def.art.clone();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(doc(&s).pattern("Dots").unwrap(), &old, "Undo gives the old tile art back");
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(doc(&s).pattern("Dots").unwrap().art, new, "Redo gives the new tile art");
}
/// With Size Tile to Art on, the tile fits the new art (and its spacing); `ids` names the art.
#[test]
fn replace_art_fits_the_tile_when_size_tile_to_art_is_on() {
let mut s = session();
make_dots(&mut s);
s.execute("pattern.options", &json!({"name": "Dots", "sizeTileToArt": true, "hSpacing": 4, "vSpacing": 6})).unwrap();
let blue = blue_rect(&mut s);
s.execute("select.set", &json!({"ids": []})).unwrap();
s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [blue.0]})).unwrap();
assert_eq!(doc(&s).pattern("Dots").unwrap().tile, Rect::new(98.0, 97.0, 132.0, 143.0));
}
/// Art that matches the tile art already, its own ids aside, records no undo step.
#[test]
fn replace_art_that_matches_the_tile_art_records_nothing() {
let mut s = session();
make_dots(&mut s);
blue_rect(&mut s);
s.execute("object.pattern.replaceArt", &json!({"name": "Dots"})).unwrap();
let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len());
s.execute("object.pattern.replaceArt", &json!({"name": "Dots"})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
assert_eq!(doc(&s), &before);
}
/// Replace Pattern Art is refused, changing nothing, for a missing name or pattern, with no art,
/// while a pattern is edited, and for art painted with the pattern itself, directly, through
/// another pattern, through a symbol, through the paints a graph stores, through a graph design a
/// graph draws its columns with, through the art of a brush on a stroke and through the symbol of an
/// inline graphic in type.
#[test]
fn replace_art_is_refused_without_changing_anything() {
let mut s = session();
make_dots(&mut s);
// "Holds dots": a pattern whose tile is painted with Dots.
let other = rect(&mut s, 100.0, 100.0, 10.0, 10.0);
s.execute("paint.setFill", &json!({"ids": [other.0], "swatch": "Dots"})).unwrap();
sel(&mut s, &[other]);
s.execute("object.pattern.make", &json!({"name": "Holds dots", "edit": false})).unwrap();
let via = rect(&mut s, 150.0, 150.0, 10.0, 10.0);
s.execute("paint.setFill", &json!({"ids": [via.0], "swatch": "Holds dots"})).unwrap();
let stroked = rect(&mut s, 200.0, 200.0, 10.0, 10.0);
s.execute("paint.setStroke", &json!({"ids": [stroked.0], "swatch": "Dots"})).unwrap();
sel(&mut s, &[stroked]);
let instance = id_of(&s.execute("symbol.new", &json!({"name": "Dotted"})).unwrap());
let graph = graph_painted_with(&mut s, "Dots");
// A graph whose stored columns name design "Dotted columns", drawn with Dots, before it is drawn
// again.
let design = rect(&mut s, 300.0, 300.0, 10.0, 10.0);
s.execute("paint.setFill", &json!({"ids": [design.0], "swatch": "Dots"})).unwrap();
s.execute("graph.design", &json!({"new": "Dotted columns", "ids": [design.0]})).unwrap();
let v = s.execute("graph.create", &json!({"type": "column", "x": 300, "y": 200, "width": 60, "height": 40, "csv": ",2024\nQ1,3"}));
let designed = id_of(&v.unwrap());
let mut extras = doc_mut(&mut s).node_mut(designed).unwrap().extras_mut();
extras.graph.as_mut().unwrap().series_columns =
vec![Some(vectorcraft_doc::ColumnDesign { design: "Dotted columns".into(), ..Default::default() })];
drop(extras);
// A path stroked with an art brush whose art is filled with Dots.
let brush_art = rect(&mut s, 300.0, 350.0, 20.0, 5.0);
s.execute("paint.setFill", &json!({"ids": [brush_art.0], "swatch": "Dots"})).unwrap();
s.execute("brush.new", &json!({"type": "art", "name": "Dotted brush", "ids": [brush_art.0]})).unwrap();
let brushed = rect(&mut s, 300.0, 380.0, 40.0, 10.0);
s.execute("paint.setFill", &json!({"ids": [brushed.0], "none": true})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [brushed.0], "color": "#000000"})).unwrap();
s.execute("brush.apply", &json!({"name": "Dotted brush", "ids": [brushed.0]})).unwrap();
// Type that shows symbol "Dotted" as an inline graphic.
let typed = id_of(&s.execute("text.create", &json!({"x": 20, "y": 420, "text": "Hi"})).unwrap());
s.execute("text.insertInline", &json!({"id": typed.0, "at": 0, "symbol": "Dotted"})).unwrap();
let plain = blue_rect(&mut s);
let unchanged = |s: &Session, before: &vectorcraft_doc::Document, steps: usize, case: &str| {
assert_eq!(doc(s), before, "{case}: the document stays");
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{case}: no undo step");
};
let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len());
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()),
("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()),
("through a graph's paints", json!({"name": "Dots", "ids": [graph.0]}), "art painted with `Dots` can't be its tile".into()),
("through a graph design", json!({"name": "Dots", "ids": [designed.0]}), "art painted with `Dots` can't be its tile".into()),
("through a brush", json!({"name": "Dots", "ids": [brushed.0]}), "art painted with `Dots` can't be its tile".into()),
("through an inline graphic", json!({"name": "Dots", "ids": [typed.0]}), "art painted with `Dots` can't be its tile".into()),
] {
let err = s.execute("object.pattern.replaceArt", &p).unwrap_err();
assert!(err.to_string().contains(&why), "{case}: {err}");
unchanged(&s, &before, steps, case);
}
s.execute("select.set", &json!({"ids": []})).unwrap();
let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len());
let err = s.execute("object.pattern.replaceArt", &json!({"name": "Dots"})).unwrap_err();
assert!(err.to_string().contains("select the art for the pattern tile"), "nothing selected: {err}");
unchanged(&s, &before, steps, "nothing selected");
s.execute("object.pattern.edit", &json!({"name": "Holds dots"})).unwrap();
let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len());
let err = s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [plain.0]})).unwrap_err();
assert!(matches!(&err, EngineError::Disabled(_, w) if w == "finish editing the pattern first"), "while editing: {err}");
unchanged(&s, &before, steps, "while editing");
}
fn doc_mut(s: &mut Session) -> &mut vectorcraft_doc::Document {
Arc::make_mut(&mut s.doc_mut().unwrap().doc)
}
+15
View File
@@ -836,6 +836,21 @@ fn a_null_in_group_colors_removes_that_swatch_and_the_ones_after_it_keep_their_p
assert_eq!(link(&s, green), ("#00ff00".into(), Some(names[2].clone())), "art linked to a swatch that stays keeps its link");
}
/// "keep" in `groupColors` leaves the group's swatch at its place as it is, without Global Adjust,
/// and past the group's swatches it adds none.
#[test]
fn keep_in_group_colors_leaves_that_swatch_as_it_is() {
let mut s = session();
run(&mut s, "swatch.newGroup", json!({"name": "Brand", "colors": ["#2878f0", "#ff0000"]}));
let p = json!({"map": [], "group": "Brand", "groupColors": ["keep", "#00ff00", "keep"], "globalAdjust": {"brightness": -50}});
run(&mut s, "recolor.apply", p);
let g = &s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Brand").unwrap().swatches;
let g: Vec<String> = g.iter().map(|w| w.paint.color().unwrap().to_hex()).collect();
assert_eq!(g.len(), 2, "{g:?}");
assert_eq!(g[0], "#2878f0", "the kept swatch takes no Global Adjust");
assert_ne!(g[1], "#00ff00", "the other new color takes it");
}
/// A gradient or pattern swatch of the group keeps its place and its paint when `recolor.apply`
/// rewrites the group: the group's colors, from the rows or from `groupColors`, go to its color
/// swatches in order.
+4 -2
View File
@@ -12,12 +12,14 @@ use crate::*;
const DENIED: &str = "Script file access denied";
/// A fresh folder for test `name`, with a `main` folder inside it for the script.
/// A fresh folder for test `name`, with a `main` folder inside it for the script, by its real
/// path: kept grants hold real paths, and a path named through a link (macOS's `/var` is
/// `/private/var`) is refused by its names alone.
fn folder(name: &str) -> PathBuf {
let base = std::env::temp_dir().join(format!("vc-script-io-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(base.join("main")).unwrap();
base
std::fs::canonicalize(&base).unwrap()
}
fn write(path: &Path, bytes: &[u8]) {
+31
View File
@@ -160,6 +160,37 @@ fn save_and_load_round_trip_keeps_cmyk_spot_and_groups() {
assert!(s.execute("swatch.library.save", &json!({"user": true})).is_err(), "no user folder in a headless session");
}
/// A library color group that holds a gradient comes into the document whole, the gradient at its
/// place in the group, as a `.ai` library's pattern swatch comes in its color group.
#[test]
fn add_brings_a_library_color_group_holding_a_gradient_whole() {
let mut s = session();
run(&mut s, "swatch.newGroup", json!({"name": "Brand", "colors": ["#123456", "#abcdef"]}));
let r = run(&mut s, "swatch.library.save", json!({"names": ["Brand", "Sunset"], "name": "Mixed"}));
// Move the Sunset gradient into the library's Brand group, as a hand-edited file can.
let mut lib: Value = serde_json::from_str(r["data"].as_str().unwrap()).unwrap();
let swatches = lib["swatches"].as_array_mut().unwrap();
let at = swatches.iter().position(|w| w["name"] == "Sunset").unwrap();
let sunset = swatches.remove(at);
lib["groups"][0]["swatches"].as_array_mut().unwrap().insert(1, sunset);
let r = run(&mut s, "swatch.library.load", json!({"data": lib.to_string(), "name": "mixed.vcswatches"}));
let id = r["library"].as_str().unwrap().to_string();
let (_, loaded) = cmd::swatchlib::library(&s, &id).unwrap();
assert!(matches!(loaded.groups[0].swatches[1].paint, Paint::Gradient(_)), "the reader keeps the gradient in the group");
run(&mut s, "swatch.delete", json!({"names": ["Brand", "Sunset"]}));
for p in [json!({"library": id}), json!({"library": id, "names": ["Brand"]})] {
let undo = undo_len(&s);
let r = run(&mut s, "swatch.library.add", p.clone());
assert!(r["added"].as_array().unwrap().iter().any(|n| n == "Sunset"), "{p}: {r}");
let brand = doc(&s).swatch_groups.iter().find(|g| g.name == "Brand").map(|g| g.swatches.clone()).unwrap_or_default();
let kinds: Vec<(&str, bool)> = brand.iter().map(|w| (w.name.as_str(), matches!(w.paint, Paint::Gradient(_)))).collect();
assert_eq!(kinds.len(), 3, "{p}: {kinds:?}");
assert_eq!(kinds[1], ("Sunset", true), "{p}: the gradient keeps its place in the group");
assert_eq!(undo_len(&s), undo + 1, "{p}: one undo step");
run(&mut s, "edit.undo", json!({}));
}
}
/// The swatch library commands, and the graphic style library save and load that share their file
/// handling, refuse a parameter of the wrong form, such as `user: "true"` or `names: "Grays"`, with
/// an error that names it; the document keeps its swatches and no undo step is recorded. A null
+33
View File
@@ -1278,6 +1278,39 @@ fn polygon_properties_junk() {
assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n"));
}
/// A live rectangle's and ellipse's Rectangle and Ellipse Angle with junk values, drawn plain,
/// scaled unevenly, flattened to nothing and sheared: never a panic, and the document stays sound.
#[test]
fn rectangle_and_ellipse_angle_junk() {
let mut failures = vec![];
for (shape, key) in [("shape.rectangle", "rectangleAngle"), ("shape.ellipse", "ellipseAngle")] {
for xf in [
None,
Some(("object.scale", json!({"sx": 300, "sy": 20}))),
Some(("object.scale", json!({"sx": 1e-300, "sy": 100}))),
Some(("object.shear", json!({"angle": 40}))),
] {
for v in junk_values() {
let p = json!({ key: v });
let mut s = Fixture::Multi.session();
let Ok(_) = no_panic(s.execute(shape, &json!({"x": 60, "y": 60, "width": 80, "height": 50}))) else { continue };
if let Some((cmd, q)) = &xf {
let _ = no_panic(s.execute(cmd, q));
}
match catch_quiet(|| no_panic(s.execute("object.setLiveShape", &p))) {
Err(m) => failures.push(format!("PANIC object.setLiveShape {p} [{xf:?}]: {m}")),
Ok(_) => {
if let Err(e) = catch_quiet(|| check_all(&mut s)).unwrap_or_else(|m| Err(format!("panic in checks: {m}"))) {
failures.push(format!("object.setLiveShape {p} [{xf:?}]: {e}"));
}
}
}
}
}
}
assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n"));
}
/// A live line's Line Properties with junk values (the fixtures have no line), on a line, a line
/// whose ends meet and one at the coordinate limit: never a panic, and the document stays sound.
#[test]
+62
View File
@@ -118,6 +118,68 @@ fn each_arrow_style_draws_its_stroke_arrowhead_at_both_ends() {
}
}
/// `arrowHead` draws any built-in stroke arrowhead at both ends of the dimension line, and the
/// native file keeps it. The saved `arrowStyle` stays one of the four values versions without
/// `arrowHead` read, and a dimension saved without `arrowHead` draws its arrow style. Options
/// without a stroke head are saved without `arrowHead`. A custom arrowhead, an unknown name and an
/// overlong name are refused.
#[test]
fn every_stroke_arrowhead_draws_as_a_dimension_arrowhead() {
use vectorcraft_doc::{Arrowhead, dimension::ArrowStyle};
let ends = |s: &Session, id: u64| -> Vec<_> {
let n = s.doc().unwrap().doc.node(NodeId(id)).unwrap();
let children = n.children().unwrap();
let strokes = children.iter().filter_map(|n| n.appearance.stroke().map(|s| (s.start_arrow.clone(), s.end_arrow.clone())));
strokes.filter(|(a, b)| a.is_some() || b.is_some()).collect()
};
let mut s = session();
let mut made = vec![];
for head in Arrowhead::ALL {
let name = serde_json::to_value(&head).unwrap();
let id = run(&mut s, "dimension.create", json!({"a":[0,0],"b":[72,0],"options":{"arrowHead":name}}))["id"].as_u64().unwrap();
let drawn = ends(&s, id);
assert!(!drawn.is_empty() && drawn.iter().all(|h| *h == (Some(head.clone()), Some(head.clone()))), "{name}: {drawn:?}");
let saved = serde_json::to_value(&recipe(&s, id).options).unwrap();
assert_eq!((&saved["arrowStyle"], &saved["arrowHead"]), (&json!("filled"), &name));
made.push((id, head));
}
let bytes = vectorcraft_format::save(&s.doc().unwrap().doc, false);
let mut reopened = Session::new();
reopened.add_document(vectorcraft_format::load(&bytes).unwrap(), None);
for (id, head) in made {
assert_eq!(recipe(&reopened, id).options.arrowhead(), Some(head));
}
// A dimension saved before `arrowHead` existed.
let id = run(&mut s, "dimension.create", json!({"a":[0,0],"b":[72,0],"options":{"arrowStyle":"open"}}))["id"].as_u64().unwrap();
let mut file: Value = serde_json::from_slice(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
fn drop_head(v: &mut Value) {
match v {
Value::Object(m) => {
m.remove("arrowHead");
m.values_mut().for_each(drop_head);
}
Value::Array(a) => a.iter_mut().for_each(drop_head),
_ => {}
}
}
drop_head(&mut file);
let mut older = Session::new();
older.add_document(vectorcraft_format::load(&serde_json::to_vec(&file).unwrap()).unwrap(), None);
let o = recipe(&older, id).options;
assert_eq!((o.arrow_style, o.arrow_head.clone(), o.arrowhead()), (ArrowStyle::Open, None, Some(Arrowhead::TriangleOpen)));
// Without a stroke head, the saved and recorded options carry no `arrowHead`, and a null one
// is still taken.
let saved = serde_json::to_value(&recipe(&s, id).options).unwrap();
assert!(saved.get("arrowHead").is_none(), "{saved}");
assert!(s.execute("dimension.create", &json!({"a":[0,0],"b":[72,0],"options":{"arrowHead":null}})).is_ok());
let custom = json!({"Custom":{"name":"Dot","path":{"subpaths":[]}}});
for bad in [json!("Custom"), json!("Arrowhead"), json!("barbed"), json!(3), json!("Barbed".repeat(20)), custom] {
let p = json!({"a":[0,0],"b":[72,0],"options":{"arrowHead":bad}});
assert!(s.execute("dimension.create", &p).is_err(), "{bad}");
}
assert!(s.execute("dimension.create", &json!({"a":[0,0],"b":[72,0],"options":{"arrowStyle":"Barbed"}})).is_err());
}
#[test]
fn dimension_angles_circles_arcs_and_curves() {
let mut s = session();
+9
View File
@@ -29,6 +29,10 @@ impl Default for Headless {
}
}
/// Desktop UI commands that the app refuses for every control and MCP request, because each one
/// opens another app (`refuse_automation` in `vectorcraft-ui-egui`). `--connect` does not run them.
const KEYBOARD_ONLY: &[&str] = &["attributes.openUrl", "file.export.svg.browser", "file.saveForWeb.browser", "file.showPackage"];
/// Commands the desktop app adds on top of the engine; the headless backend implements them too so
/// `run_command` behaves the same in both modes.
const HOST_COMMANDS: &[(&str, &str, &str)] = &[
@@ -157,6 +161,11 @@ impl Headless {
None if vectorcraft_engine::find_command(id).is_some() => {
self.session.check_params(id, params).map_err(|e| e.to_string())?;
}
None if KEYBOARD_ONLY.contains(&id) => {
return Err(format!(
"`{id}` opens another app: only the person at the keyboard can run it in the desktop app; control and MCP requests are refused, `--connect` included"
));
}
None if crate::ui_catalog::UI_COMMANDS.iter().any(|(cid, ..)| *cid == id) => {
return Err(format!(
"`{id}` is a desktop UI command (`ui: true`); start `vectorcraft --control 7979` and use `vectorcraft-cli mcp --connect`"
+17
View File
@@ -338,6 +338,23 @@ fn headless_command_list_includes_ui_commands() {
assert!(text_of(&r).contains("--connect"), "{r}");
}
/// Desktop commands that the app refuses for every automated request are not offered through
/// `--connect`: the headless error says only the person at the keyboard can run them.
#[test]
fn headless_does_not_send_keyboard_only_commands_to_connect() {
let mut s = server();
rpc(&mut s, 1, "initialize", json!({"protocolVersion": PROTOCOL_VERSION}));
s.handle_line(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#);
for (n, id) in ["attributes.openUrl", "file.export.svg.browser", "file.saveForWeb.browser", "file.showPackage"].iter().enumerate() {
assert!(crate::ui_catalog::UI_COMMANDS.iter().any(|(cid, ..)| cid == id), "{id} is not a desktop UI command");
let r = call(&mut s, 10 + n as u64, "command_run", json!({"id": id, "params": {}}));
assert_eq!(r["isError"], true, "{id}: {r}");
let text = text_of(&r);
assert!(text.contains("only the person at the keyboard"), "{id}: {r}");
assert!(!text.contains("start `vectorcraft --control"), "{id}: {r}");
}
}
// ---------- headless end-to-end ----------
#[test]
+1 -1
View File
@@ -10,7 +10,7 @@ workspace = true
[dependencies]
# The shared font catalog from craft-libs main (it has the outline, bidi and caret helpers used here).
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3", default-features = false }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", default-features = false }
vectorcraft-geom = { workspace = true }
vectorcraft-doc = { workspace = true }
kurbo = { workspace = true }
+113 -5
View File
@@ -27,8 +27,12 @@
//! Brush Options' Key Color eyedropper sets `brushKeyColor` and `stop`: the next click samples into
//! the open dialog (`brushKeyColor` UI request) and switches back.
//!
//! Escape ends either pick without sampling and switches back to that tool. With neither pick
//! Escape ends an armed pick without sampling and switches back to that tool. With no pick
//! armed, Escape is left to the application.
//!
//! Image Trace's Ignore Color eyedropper passes its bound document point to the panel, which
//! samples the original image pixels and ends the pick only when a color is accepted. A miss
//! stays armed; this tool changes neither paint nor selection.
use std::collections::HashSet;
@@ -51,6 +55,8 @@ pub struct EyedropperTool {
text_selection: crate::text::TypeTool,
/// Brush Options › Key Color (Hue Shift): sample into the dialog, then [`Self::stop`].
brush_key_color: bool,
/// Image Trace > Ignore Color: the panel's opaque document/object/revision binding.
image_trace_ignore_color: Option<Value>,
/// The gradient mesh points the tool switched from had picked, each a mesh and a point index.
mesh_points: Vec<(NodeId, usize)>,
}
@@ -512,6 +518,11 @@ impl Tool for EyedropperTool {
if ev.kind != PointerKind::Down {
return vec![];
}
if let Some(binding) = &self.image_trace_ignore_color {
// The panel knows whether this hits an opaque source pixel. It clears the binding
// and restores the previous tool only after accepting a color, not on a miss.
return vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({ "binding": binding, "point": [ev.pos.x, ev.pos.y] }))];
}
let opts = sample_options(cx);
if self.brush_key_color {
let Some(c) = sample_color_at(cx, ev.pos) else { return vec![] };
@@ -573,6 +584,9 @@ impl Tool for EyedropperTool {
if let Some(o) = options.as_object_mut() {
o.insert("stop".into(), json!(self.stop));
o.insert("brushKeyColor".into(), json!(self.brush_key_color));
if let Some(binding) = &self.image_trace_ignore_color {
o.insert("imageTraceIgnoreColor".into(), binding.clone());
}
if !self.mesh_points.is_empty() {
let points: Vec<Value> = self.mesh_points.iter().map(|(id, index)| json!({"id": id.0, "index": index})).collect();
o.insert("meshPoints".into(), Value::Array(points));
@@ -587,6 +601,7 @@ impl Tool for EyedropperTool {
match key {
"stop" => self.stop = value.as_str().map(str::to_string),
"brushKeyColor" => self.brush_key_color = value.as_bool().unwrap_or(false),
"imageTraceIgnoreColor" => self.image_trace_ignore_color = (!value.is_null()).then(|| value.clone()),
"meshPoints" => self.mesh_points = crate::meshedit::points_of(value),
"textSelection" => self.text_selection.set_option(key, value),
_ => {}
@@ -621,12 +636,15 @@ impl Tool for EyedropperTool {
Cursor::Eyedropper
}
/// Escape ends a gradient stop's or Key Color's pick without sampling and switches back to the
/// tool that armed it.
/// Escape ends the armed pick without sampling; Image Trace receives its cancellation reply.
fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec<Action> {
if key != ToolKey::Escape || !self.picking() {
return vec![];
}
if let Some(binding) = self.image_trace_ignore_color.take() {
let back = self.stop.take().unwrap_or_else(|| "selection".to_string());
return vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({ "binding": binding, "cancel": true })), Action::SwitchTool(back)];
}
let back = self.stop.take().unwrap_or_else(|| "selection".to_string());
self.brush_key_color = false;
vec![Action::SwitchTool(back)]
@@ -648,9 +666,9 @@ impl Tool for EyedropperTool {
}
impl EyedropperTool {
/// Is a one-shot pick armed (a gradient stop's or Brush Options' Key Color)?
/// Is a gradient stop, Brush Key Color or Image Trace Ignore Color pick armed?
fn picking(&self) -> bool {
self.stop.is_some() || self.brush_key_color
self.stop.is_some() || self.brush_key_color || self.image_trace_ignore_color.is_some()
}
}
@@ -869,6 +887,96 @@ mod tests {
assert_eq!(t.options(), json!({ "stop": null, "brushKeyColor": false }));
}
#[test]
fn image_trace_sampling_keeps_forwarding_its_binding_until_the_panel_accepts_a_color() {
let (d, id) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = cx(&d, &s, &p);
let binding = json!({"doc": 7, "target": id.0, "revision": 11});
for mods in [Mods::default(), Mods { alt: true, ..Default::default() }, Mods { alt: true, shift: true, ..Default::default() }] {
let mut t = EyedropperTool::default();
t.set_option("stop", &json!("gradient"));
t.set_option("imageTraceIgnoreColor", &binding);
assert_eq!(t.options()["imageTraceIgnoreColor"], binding);
assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Move, -25.5, 400.25)).is_empty());
assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, -25.5, 400.25)).is_empty());
assert_eq!(
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, -25.5, 400.25).with_mods(mods)),
vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({"binding": binding, "point": [-25.5, 400.25]}))]
);
assert_eq!(t.options()["imageTraceIgnoreColor"], binding, "a point is only a request until the panel accepts its source color");
assert_eq!(t.options()["stop"], "gradient");
assert!(t.claims_key(&cx, ToolKey::Escape));
assert!(t.ends_on_escape(&cx));
let next = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 10.0, 20.0));
assert_eq!(next, vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({"binding": binding, "point": [10.0, 20.0]}))]);
t.set_option("imageTraceIgnoreColor", &Value::Null);
t.set_option("stop", &Value::Null);
assert_eq!(t.options(), json!({"stop": null, "brushKeyColor": false}));
assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty());
}
}
#[test]
fn image_trace_escape_cancels_its_binding_and_restores_the_tool_once() {
let (d, id) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = cx(&d, &s, &p);
let binding = json!({"doc": 7, "target": id.0, "revision": 11});
let mut t = EyedropperTool::default();
assert!(!t.claims_key(&cx, ToolKey::Escape));
assert!(!t.ends_on_escape(&cx));
assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty());
t.set_option("stop", &json!("selection"));
t.set_option("imageTraceIgnoreColor", &binding);
assert!(t.claims_key(&cx, ToolKey::Escape));
assert!(t.ends_on_escape(&cx));
assert!(!t.claims_key(&cx, ToolKey::Enter));
assert!(t.key(&cx, ToolKey::Enter, Mods::default()).is_empty());
assert_eq!(t.options()["imageTraceIgnoreColor"], binding);
assert!(t.drop_press(&cx).is_empty(), "a dropped press leaves this pick waiting too");
assert_eq!(t.options()["imageTraceIgnoreColor"], binding);
assert_eq!(
t.key(&cx, ToolKey::Escape, Mods::default()),
vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({"binding": binding, "cancel": true})), Action::SwitchTool("selection".into())]
);
assert_eq!(t.options(), json!({"stop": null, "brushKeyColor": false}));
assert!(!t.claims_key(&cx, ToolKey::Escape));
assert!(!t.ends_on_escape(&cx));
assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty());
// A binding without a saved tool still claims its one Escape and returns to Selection.
t.set_option("imageTraceIgnoreColor", &binding);
assert!(t.claims_key(&cx, ToolKey::Escape) && t.ends_on_escape(&cx));
assert_eq!(
t.key(&cx, ToolKey::Escape, Mods::default()),
vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({"binding": binding, "cancel": true})), Action::SwitchTool("selection".into())]
);
assert!(!t.claims_key(&cx, ToolKey::Escape) && !t.ends_on_escape(&cx));
}
#[test]
fn clearing_image_trace_sampling_preserves_existing_brush_and_stop_options() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = cx(&d, &s, &p);
let mut t = EyedropperTool::default();
t.set_option("brushKeyColor", &json!(true));
t.set_option("stop", &json!("selection"));
let original = t.options();
t.set_option("imageTraceIgnoreColor", &json!({"doc": 7, "target": 8, "revision": 11}));
t.set_option("imageTraceIgnoreColor", &Value::Null);
assert_eq!(t.options(), original);
// Clearing Trace leaves the ordinary Brush pick armed, including its upstream Escape.
assert!(t.claims_key(&cx, ToolKey::Escape));
assert!(t.ends_on_escape(&cx));
assert!(t.key(&cx, ToolKey::Enter, Mods::default()).is_empty());
assert_eq!(t.options(), original);
assert_eq!(
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 150.0, 150.0)),
vec![Action::Dialog("brushKeyColor".into(), json!({"color": color_json(&Color::WHITE)})), Action::SwitchTool("selection".into())]
);
}
/// The hex of the colour a `paint.sampleColor` action samples.
fn sampled_hex(a: &[Action]) -> String {
let [Action::Exec(c, p)] = a else { panic!("one action: {a:?}") };
+1
View File
@@ -519,6 +519,7 @@ impl VectorcraftApp {
}
self.ui.flyout = None;
switched?;
crate::panels::image_trace::cancel_ignore_sampler(self, false);
if let Some(g) = vectorcraft_tools::catalog::group_of(id)
&& let Some(slot) = self.ui.group_tool.get_mut(g)
{
+1
View File
@@ -181,6 +181,7 @@ impl VectorcraftApp {
/// injected until the batch was actually applied, so a burst of hidden ticks cannot queue
/// several steps of a drag or replay them together later.
pub fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
crate::canvas::capture_pointer_before_input(ctx, raw.viewport_id);
self.fill_raw_input(ctx, raw);
crate::font_menu::sync_wheel_target(self, ctx, raw.viewport_id);
crate::font_menu::take_raw_wheel(ctx, raw);
+271 -3
View File
@@ -251,6 +251,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
// The meshes of the tools' shared paths. Likewise, a frame that does not draw the tools'
// overlays drops them.
let mut shared_paths = std::mem::take(&mut app.canvas.shared_paths);
let sampler_cancelled = crate::panels::image_trace::refresh_ignore_sampler(app);
// A release ends the Image Trace panel's eye-button hold, also when the panel is no longer
// drawn, so a later press elsewhere does not show the source image.
if app.ui.trace_hold_source.is_some() && !ui.input(|i| i.pointer.any_down()) {
@@ -263,7 +264,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
if app.ui.home.is_some_and(|k| k != crate::menus::home_key(app)) {
app.ui.home = None;
}
if crate::menus::home_showing(app) {
let home_showing = crate::menus::home_showing(app);
observe_hidden_ignore_sampler_pointer(app, ui, home_showing);
if home_showing {
// No IME owner this pass (`ime_caret_rect` stays None): the end-of-pass observation marks
// the context absent and keeps any marked text as typed.
home(app, ui, full);
@@ -298,7 +301,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
scroll_bars(app, ui, rect, outer, &t);
}
let resp = ui.interact(rect, egui::Id::unique("canvas"), Sense::click_and_drag());
canvas_input(app, ui, &resp, rect);
input_after_sampler_refresh(app, ui, &resp, rect, sampler_cancelled);
let v = *app.view().unwrap_or(&View::default());
let xf = Xf::at(rect, &v, app.canvas_ui_zoom);
// While the view pans, zooms or turns under the pointer, the art under it isn't hit-tested.
@@ -470,6 +473,272 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
}
}
#[derive(Clone, Copy, Default)]
struct CanvasClick {
count: u8,
at: Option<Pos2>,
}
fn pointer_before_input_id(viewport: egui::ViewportId) -> egui::Id {
egui::Id::unique("canvas-pointer-before-input").with(viewport)
}
/// The existing host hook calls this before egui updates the pointer for this batch.
pub(crate) fn capture_pointer_before_input(ctx: &egui::Context, viewport: egui::ViewportId) {
let pointer = ctx.input_for(viewport, |i| i.pointer.clone());
ctx.data_mut(|data| data.insert_temp(pointer_before_input_id(viewport), pointer));
}
/// Each release keeps egui's own qualification, including earlier releases in this batch.
fn canvas_pointer_releases(ui: &Ui) -> Vec<IgnoreSamplerRelease> {
let previous = ui.data(|data| data.get_temp::<egui::PointerState>(pointer_before_input_id(ui.ctx().viewport_id()))).unwrap_or_default();
let options = ui.ctx().options(|o| o.input_options);
let pixels_per_point = ui.ctx().pixels_per_point();
ui.input(|i| {
let mut counts = [0usize; egui::NUM_POINTER_BUTTONS];
for event in &i.events {
if let egui::Event::PointerButton { button, pressed: false, .. } = event {
counts[*button as usize] += 1;
}
}
i.events
.iter()
.enumerate()
.filter_map(|(index, event)| {
let egui::Event::PointerButton { pos, button, pressed: false, .. } = event else { return None };
let clicked = if counts[*button as usize] == 1 {
i.pointer.button_clicked(*button)
} else {
// Aggregated flags cannot identify a later non-click release. Replay only
// an ambiguous button's prefix, before its Up, through egui's public API.
let mut before = i.clone();
before.pointer = previous.clone();
let raw = egui::RawInput { time: Some(i.time), events: i.events[..index].to_vec(), ..i.raw.clone() };
before.begin_pass(raw, false, pixels_per_point, options).pointer.could_any_button_be_click()
};
Some(IgnoreSamplerRelease { button: *button, at: *pos, clicked })
})
.collect()
})
}
/// Two non-sampler clicks replace egui's last two click times after a consumed pick.
#[derive(Clone, Copy, Default)]
struct IgnoreSamplerClicks {
last: Option<(f64, Pos2)>,
remaining: u8,
}
fn ignore_sampler_primary_id(id: egui::Id) -> egui::Id {
id.with("image-trace-consumed-primary")
}
fn ignore_sampler_owns_primary(ui: &Ui, id: egui::Id) -> bool {
ui.data(|data| data.get_temp::<bool>(ignore_sampler_primary_id(id)).unwrap_or(false))
}
fn reset_ignore_sampler_clicks(ui: &Ui, id: egui::Id) {
ui.data_mut(|data| data.insert_temp(id.with("image-trace-clicks"), IgnoreSamplerClicks { last: None, remaining: 2 }));
}
/// Reclassify only the two clicks whose raw history can still contain a consumed pick.
/// Other widgets' clicks count too, as they do in egui; its pointer state stays untouched.
fn ignore_sampler_clicks(ui: &Ui, id: egui::Id, consumed: bool, releases: &[IgnoreSamplerRelease]) {
ui.data_mut(|data| data.remove::<CanvasClick>(id.with("image-trace-click-count")));
if !releases.iter().any(|release| release.clicked) {
return;
}
if consumed {
reset_ignore_sampler_clicks(ui, id);
return;
}
let time = ui.input(|i| i.time);
for release in releases.iter().filter(|release| release.clicked) {
record_ignore_sampler_click(ui, id, release.at, time, release.button == egui::PointerButton::Primary);
}
}
fn record_ignore_sampler_click(ui: &Ui, id: egui::Id, at: Pos2, time: f64, primary: bool) {
let (delay, distance) = ui.ctx().options(|o| (o.input_options.max_double_click_delay, o.input_options.max_click_dist));
ui.data_mut(|data| {
let history_id = id.with("image-trace-clicks");
let Some(mut clicks) = data.remove_temp::<IgnoreSamplerClicks>(history_id) else {
if primary {
data.remove::<CanvasClick>(id.with("image-trace-click-count"));
}
return;
};
let double = clicks.last.is_some_and(|(last, pos)| time - last < delay && pos.distance_sq(at) < distance * distance);
if primary {
data.insert_temp(id.with("image-trace-click-count"), CanvasClick { count: if double { 2 } else { 1 }, at: Some(at) });
}
clicks.last = Some((time, at));
clicks.remaining -= 1;
if clicks.remaining != 0 {
data.insert_temp(history_id, clicks);
}
});
}
fn primary_click(ui: &Ui, resp: &egui::Response) -> CanvasClick {
if !resp.clicked_by(egui::PointerButton::Primary) {
return CanvasClick::default();
}
ui.data(|data| data.get_temp::<CanvasClick>(resp.id.with("image-trace-click-count"))).unwrap_or_else(|| {
let count = if resp.triple_clicked() {
3
} else if resp.double_clicked() {
2
} else {
1
};
let at = ui.data(|data| data.get_temp::<Pos2>(resp.id.with("canvas-qualified-primary-release")));
CanvasClick { count, at }
})
}
fn primary_click_count(ui: &Ui, resp: &egui::Response) -> u8 {
primary_click(ui, resp).count
}
/// Remove only the pointer sequence acquired by this sampler, never a view or tool drag.
fn clear_ignore_sampler_gesture(ui: &Ui, id: egui::Id) {
ui.data_mut(|data| {
data.remove::<bool>(ignore_sampler_primary_id(id));
if matches!(data.get_temp::<Drag>(drag::drag_id()), Some(Drag::Gesture)) {
data.remove::<Drag>(drag::drag_id());
data.remove::<Pos2>(drag::drag_pos_id());
data.remove::<Point>(drag::tool_drag_doc_id());
data.remove::<Point>(drag::tool_press_doc_id());
}
});
}
#[derive(Clone, Copy)]
struct IgnoreSamplerRelease {
button: egui::PointerButton,
at: Pos2,
clicked: bool,
}
#[derive(Default)]
struct IgnoreSamplerPointer {
owned: bool,
replaced: bool,
ordinary_pressed: bool,
consumed_release: bool,
releases: Vec<IgnoreSamplerRelease>,
}
/// Attribute a fresh press after an owned release before egui's per-frame flags lose their order.
fn ignore_sampler_pointer_frame(ui: &Ui, id: egui::Id, cancelled: bool, releases: &[IgnoreSamplerRelease]) -> IgnoreSamplerPointer {
let owned = ignore_sampler_owns_primary(ui, id);
if !owned && !cancelled {
return IgnoreSamplerPointer::default();
}
ui.input(|i| {
let mut frame = IgnoreSamplerPointer { owned, ..Default::default() };
let mut first_press_owned = cancelled;
let mut releases = releases.iter();
for event in &i.events {
if let egui::Event::PointerButton { pos, button, pressed, .. } = event {
if *pressed {
if *button == egui::PointerButton::Primary {
frame.replaced |= frame.owned;
// An observed old Up ends that cancelled sequence; without it,
// a fresh invalid press keeps the existing cancellation gate.
frame.owned = first_press_owned && !frame.consumed_release;
first_press_owned = false;
frame.ordinary_pressed |= !frame.owned;
}
} else {
let clicked = releases.next().is_some_and(|release| release.clicked);
ignore_sampler_release(&mut frame, *button, *pos, clicked);
}
}
}
frame
})
}
fn ignore_sampler_release(frame: &mut IgnoreSamplerPointer, button: egui::PointerButton, at: Pos2, clicked: bool) {
if button == egui::PointerButton::Primary && frame.owned {
frame.consumed_release = true;
frame.releases.clear();
} else if frame.consumed_release {
frame.releases.push(IgnoreSamplerRelease { button, at, clicked });
}
}
fn ignore_sampler_frame_clicks(ui: &Ui, id: egui::Id, frame: &IgnoreSamplerPointer, consumed: bool, releases: &[IgnoreSamplerRelease]) {
if !frame.consumed_release || !frame.ordinary_pressed {
ignore_sampler_clicks(ui, id, consumed, releases);
return;
}
// Consume the old sequence, then classify only subsequent ordinary releases. A new Down
// still reaches the tool when the last release belongs to the consumed sequence.
reset_ignore_sampler_clicks(ui, id);
ui.data_mut(|data| data.insert_temp(id.with("image-trace-click-count"), CanvasClick::default()));
let time = ui.input(|i| i.time);
for release in &frame.releases {
let primary = release.button == egui::PointerButton::Primary;
if release.clicked {
record_ignore_sampler_click(ui, id, release.at, time, primary);
}
}
}
fn begin_ignore_sampler_pointer(ui: &Ui, id: egui::Id, cancelled: bool) -> (bool, bool) {
let releases = canvas_pointer_releases(ui);
ui.data_mut(|data| {
let position_id = id.with("canvas-qualified-primary-release");
data.remove::<Pos2>(position_id);
if let Some(release) = releases.iter().rev().find(|release| release.clicked && release.button == egui::PointerButton::Primary) {
data.insert_temp(position_id, release.at);
}
});
let frame = ignore_sampler_pointer_frame(ui, id, cancelled, &releases);
if frame.replaced {
// This also replaces an abandoned sampler Down whose release was not observed.
clear_ignore_sampler_gesture(ui, id);
}
if frame.owned {
ui.data_mut(|data| data.insert_temp(ignore_sampler_primary_id(id), true));
}
let consumed = frame.owned && ui.input(|i| i.pointer.primary_pressed() || i.pointer.primary_released() || i.pointer.primary_down());
ignore_sampler_frame_clicks(ui, id, &frame, consumed, &releases);
(consumed, frame.ordinary_pressed)
}
fn end_ignore_sampler_pointer(ui: &Ui, id: egui::Id) {
// A valid Down can acquire ownership and complete in the same frame.
if ignore_sampler_owns_primary(ui, id) && !ui.input(|i| i.pointer.primary_down()) {
if ui.input(|i| i.pointer.button_clicked(egui::PointerButton::Primary)) {
reset_ignore_sampler_clicks(ui, id);
}
clear_ignore_sampler_gesture(ui, id);
}
}
fn observe_hidden_ignore_sampler_pointer(app: &VectorcraftApp, ui: &Ui, home_showing: bool) {
if home_showing || app.session.active().is_none() {
// Home and the empty window still advance egui's click history. Observe the same
// correction there so it retires after the two ordinary clicks that replace a pick.
let id = egui::Id::unique("canvas");
begin_ignore_sampler_pointer(ui, id, false);
end_ignore_sampler_pointer(ui, id);
}
}
/// A sampler press keeps its release, even if its Down completes or its binding expires held.
fn input_after_sampler_refresh(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect: egui::Rect, cancelled: bool) {
let (consumed, ordinary_pressed) = begin_ignore_sampler_pointer(ui, resp.id, cancelled);
if !consumed && (ordinary_pressed || !cancelled || !ui.input(|i| i.pointer.any_pressed())) {
canvas_input(app, ui, resp, rect);
}
end_ignore_sampler_pointer(ui, resp.id);
}
/// The pointer on the canvas: the tool's input, unless the context menu or the 3D gizmo has the press.
pub(crate) fn canvas_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect: egui::Rect) {
if app.ui.dialog.as_ref().is_some_and(crate::dialogs::revolve_gizmo::active) {
@@ -643,7 +912,6 @@ fn cache_key(
rich_black: app.session.prefs.black_on_screen == "rich",
// A tool's drag on the canvas, during an interaction (not a dialog's preview).
dragging: app.session.in_interaction() && ui.data(|d| d.get_temp::<Drag>(drag_id())) == Some(Drag::Tool),
// The Image Trace panel's eye button, while it is held.
trace_source: app.ui.trace_hold_source.clone(),
// Preferences › Performance › Use Monitor Profile for Canvas.
display: app.display_profile.key(app.session.prefs.monitor_profile_display),
+21 -2
View File
@@ -380,6 +380,9 @@ pub(crate) fn end_art_move(app: &mut VectorcraftApp, ctx: &egui::Context) {
/// Send a pointer event to the active tool and act on UI requests (dialogs, tool switches).
pub fn dispatch(app: &mut VectorcraftApp, ev: &PointerEvent, view: vectorcraft_engine::ViewInfo) {
if ev.kind == PointerKind::Down && crate::panels::image_trace::discard_stale_ignore_click(app) {
return;
}
// A press lent to a selection tool (Cmd/Ctrl held) does not use the tool of a held key.
if ev.kind == PointerKind::Down && app.session.lent_tool_id(&ev.mods).is_none() {
crate::shortcuts::note_tool_use(app);
@@ -422,11 +425,27 @@ fn pressed_with(app: &mut VectorcraftApp, index: Option<usize>, pos: Point, tool
pub fn apply_requests(app: &mut VectorcraftApp, r: vectorcraft_engine::Result<Vec<vectorcraft_engine::UiRequest>>) {
match r {
Ok(reqs) => {
let mut sampler_return = None;
for r in reqs {
match r {
vectorcraft_engine::UiRequest::Dialog(kind, p) => crate::dialogs::open_tool_dialog(app, &kind, p),
vectorcraft_engine::UiRequest::Dialog(kind, p) => {
let back = if kind == "imageTraceIgnoreColor" && p["cancel"] == true {
app.ui.trace_ignore_sampler.as_ref().map(|sampler| sampler.back.clone())
} else {
None
};
crate::dialogs::open_tool_dialog(app, &kind, p);
// A matching callback must actually consume the active sampler.
sampler_return = back.filter(|_| app.ui.trace_ignore_sampler.is_none());
}
vectorcraft_engine::UiRequest::Panel(panel) => activate_panel(app, &panel),
vectorcraft_engine::UiRequest::SwitchTool(t) => app.select_tool(&t),
vectorcraft_engine::UiRequest::SwitchTool(t) => {
if sampler_return.take().is_some_and(|back| back == t) {
app.return_to_tool(&t);
} else {
app.select_tool(&t);
}
}
vectorcraft_engine::UiRequest::Status(msg) => app.status(msg),
vectorcraft_engine::UiRequest::Place(p) => crate::place::place_from_cursor(app, &p),
// In the document the press was made in, which may no longer be the active one.
+32 -12
View File
@@ -140,7 +140,7 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo
drag_held(app, ui, &f, d, p);
} else {
// The drag ends where its button went up: the moves after the release in this frame are hover.
drag_released(app, ui, &f, d, release_pos(ui, button).unwrap_or(p));
drag_released(app, ui, &f, d, release_pos(ui, button, false).unwrap_or(p));
}
} else if let Some(p) = hover_tool
// A press on an artboard's name starts no drag: the moves while it is held are not hover.
@@ -190,15 +190,18 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo
.unwrap_or(m.shift);
select_named_artboard(app, i, shift || release_shift);
}
if resp.double_clicked()
let click = super::primary_click(ui, resp);
if !super::ignore_sampler_owns_primary(ui, resp.id)
&& click.count == 2
&& !f.modal
&& let Some(p) = at
&& let Some(p) = click.at.or(at)
{
double_click(app, ui, &f, p);
}
if resp.triple_clicked()
if !super::ignore_sampler_owns_primary(ui, resp.id)
&& click.count == 3
&& !f.modal
&& let Some(p) = at
&& let Some(p) = click.at.or(at)
{
triple_click(app, ui, &f, p);
}
@@ -339,7 +342,7 @@ fn begin_drag(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) {
Drag::RotateView { start_angle: (p.y - c.y).atan2(p.x - c.x) as f64, start_rot: v.rotation, snaps: !space }
} else {
// Cmd with another tool drags with the selection tool used last (the session lends it).
let ev = PointerEvent {
let mut ev = PointerEvent {
kind: PointerKind::Down,
pos: xf.to_doc(p),
mods: mods(m, space),
@@ -347,9 +350,25 @@ fn begin_drag(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) {
pressure: pen_pressure(ui, app, true),
pen: pen_pose(app, &xf),
};
// Only a Down actually sent to this sampler owns the gesture. Cmd/Ctrl's borrowed
// selection press keeps the ordinary tool path.
let sampler = app.ui.trace_ignore_sampler.is_some() && tool == "eyedropper" && app.session.lent_tool_id(&ev.mods).is_none();
if sampler {
// A later hover move is not the source pixel that was pressed.
let pressed = ui.input(|i| {
i.events.iter().find_map(|event| match event {
egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, .. } => Some(*pos),
_ => None,
})
});
if let Some(pressed) = pressed {
ev.pos = xf.to_doc(pressed);
}
ui.data_mut(|data| data.insert_temp(super::ignore_sampler_primary_id(resp.id), true));
}
dispatch(app, &ev, view);
crate::document_drag::begin(app, ui.ctx(), ev.pos);
Drag::Tool
if sampler { Drag::Gesture } else { Drag::Tool }
};
// A drag of the Zoom, Hand or Rotate View tool uses the tool of a held shortcut; held Space's
// view tools are not that tool.
@@ -611,7 +630,7 @@ fn drag_released(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Po
// The second click of a double-click: don't fit another artboard on this release.
// A double-click on an object does not open Artboard Options. Empty artboard
// space still does.
if resp.double_clicked() && app.session.tool_id() == "artboard" {
if super::primary_click_count(ui, resp) == 2 && app.session.tool_id() == "artboard" {
app.session.set_tool_option("suppressFitClick", &json!(true));
}
// A move that came in the release's own frame shapes the preview first: the
@@ -714,13 +733,14 @@ fn triple_click(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) {
dispatch(app, &ev, view);
}
/// Where `button` went up in this frame, if it did.
fn release_pos(ui: &Ui, button: egui::PointerButton) -> Option<Pos2> {
/// Where `button` went up: the first release ends a drag, the last classifies this frame's click.
fn release_pos(ui: &Ui, button: egui::PointerButton, last: bool) -> Option<Pos2> {
ui.input(|i| {
i.events.iter().find_map(|e| match e {
let mut releases = i.events.iter().filter_map(|e| match e {
egui::Event::PointerButton { pos, button: b, pressed: false, .. } if *b == button => Some(*pos),
_ => None,
})
});
if last { releases.next_back() } else { releases.next() }
})
}
+22 -17
View File
@@ -1011,6 +1011,19 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
}
}
/// The Control bar's object label, `label`, while the bar has room for it. For one selected image
/// (`image`: Linked File or Embedded) it is an underlined link, and a click opens the Links panel on
/// the image with its Link Info.
fn object_label(app: &mut VectorcraftApp, ui: &mut Ui, label: egui::RichText, image: bool) {
if ui.available_width() < widgets::text_width(ui, label.clone()) {
left_out(ui);
} else if !image {
ui.label(label);
} else if ui.link(label.underline()).clicked() {
crate::panels::links::show_selected_image(app, ui.ctx());
}
}
/// The Control bar's gripper, controls and panel menu, in the bar `bar`. A `floating` bar clips its
/// controls to the room left of the panel menu button, and always shows the button.
fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, dock_room: egui::Rect, floating: bool) {
@@ -1043,30 +1056,22 @@ fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect,
let units = app.session.general_unit();
let first = st.selection.objects.first().and_then(|id| st.doc.node(*id));
let anchors = anchor_controls(app);
let label = match first {
_ if app.session.tool_id() == "artboard" => tl!("Artboard"),
Some(_) if count == 1 && anchors != AnchorControls::None => {
tl!("Anchor Point")
}
// The label, and whether it names one selected image.
let (label, image) = match first {
_ if app.session.tool_id() == "artboard" => (tl!("Artboard"), false),
Some(_) if count == 1 && anchors != AnchorControls::None => (tl!("Anchor Point"), false),
Some(vectorcraft_doc::Node { kind: NodeKind::Image(im), .. }) if count == 1 => {
if im.link.is_some() {
tl!("Linked File")
(tl!("Linked File"), true)
} else {
tl!("Embedded")
(tl!("Embedded"), true)
}
}
Some(n) if count == 1 && crate::panels::image_trace::is_trace(n) => {
tl!("Image Tracing")
}
_ => tl!(crate::panels::appearance::summary(app, ui.ctx()).map_or("No Selection", |s| s.label)),
Some(n) if count == 1 && crate::panels::image_trace::is_trace(n) => (tl!("Image Tracing"), false),
_ => (tl!(crate::panels::appearance::summary(app, ui.ctx()).map_or("No Selection", |s| s.label)), false),
};
let has_first = first.is_some();
let label = egui::RichText::new(label).font(theme::semibold(12.0)).color(t.text);
if ui.available_width() >= widgets::text_width(ui, label.clone()) {
ui.label(label);
} else {
left_out(ui);
}
object_label(app, ui, egui::RichText::new(label).font(theme::semibold(12.0)).color(t.text), image);
// With the Artboard tool in use, the bar shows the active artboard's controls in place
// of the object controls.
let (artboard_options, transform) = (group_on(app, "artboardOptions"), group_on(app, "transform"));
+52
View File
@@ -4304,6 +4304,58 @@ fn select_similar_stays_out_while_an_image_control_is_left_out() {
assert!(seen, "a wide bar shows the button after the image's controls");
}
/// A click on the Control bar's Linked File or Embedded label shows the Links panel, in an expanded
/// dock and in one collapsed to icons; the label of any other object stays plain text.
#[test]
fn the_linked_file_and_embedded_labels_open_the_links_panel() {
crate::i18n::set_current(crate::i18n::Lang::EN);
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 200})).unwrap();
let img = image::RgbaImage::from_pixel(20, 20, image::Rgba([0, 0, 0, 255]));
let mut png = vec![];
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let dir = vectorcraft_testkit::temp_dir("control-bar-image-label");
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("square.png");
std::fs::write(&path, &png).unwrap();
use crate::tests_removeanchors::{at, click_control, control_frame};
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let links = crate::panels::links::ID;
// Closes the Links panel, clicks `name` on the bar and answers whether the panel shows.
let click = |app: &mut crate::VectorcraftApp, name: &str| {
app.run("window.panel.close", json!({"panel": links})).ok();
app.ui.open_panel = None;
assert!(!crate::panel_docking::visible(&app.ui, links), "{name}: the panel is closed first");
let pos = at(&control_frame(app, &ctx, vec![]), name);
click_control(app, &ctx, pos);
crate::panel_docking::visible(&app.ui, links)
};
let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap()["id"].clone();
let linked = app.run("file.place", json!({"path": path, "link": true})).unwrap()["ids"].clone();
let embedded = app.run("file.place", json!({"path": path, "link": false})).unwrap()["ids"].clone();
// The default layout floats Links: dock it beside Layers so that both passes reach a docked panel.
app.run("window.panel", json!({"panel": links})).unwrap();
app.run("window.panel.dock", json!({"panel": links, "onto": "layers"})).unwrap();
// Whether Links floats, and whether its dock column is collapsed to icons.
let placed = |app: &crate::VectorcraftApp| {
let layout = crate::panel_docking::layout_of(&app.ui);
(layout.floating.iter().any(|w| w.panels().any(|p| p == links)), crate::panel_docking::in_iconic_column(&layout, links))
};
for collapsed in [false, true] {
app.run("window.collapseDock", json!({ "collapsed": collapsed })).unwrap();
app.run("select.set", json!({ "ids": linked })).unwrap();
assert!(click(&mut app, "Linked File"), "collapsed {collapsed}, status: {}", app.ui.status);
assert_eq!(placed(&app), (false, collapsed), "Links opened in its dock, collapsed {collapsed}");
app.run("select.set", json!({ "ids": embedded })).unwrap();
assert!(click(&mut app, "Embedded"), "collapsed {collapsed}, status: {}", app.ui.status);
assert_eq!(placed(&app), (false, collapsed), "Links opened in its dock, collapsed {collapsed}");
app.run("select.set", json!({ "ids": [id] })).unwrap();
let name = crate::panels::appearance::object_label(&app);
assert!(!click(&mut app, name), "collapsed {collapsed}: a rectangle's label opens nothing");
}
}
/// The Anchor Points group holds Convert and Anchors for direct-selected anchors; off, the bar keeps
/// its Anchor Point label.
#[test]
+5 -1
View File
@@ -627,7 +627,8 @@ pub fn accepts_field(d: &Dialog, field: &str) -> bool {
/// A Graph Data Column Width set this way sets every column, as Cell Style's does. A Width Point
/// Edit side width set this way for several points sets it on every point, as typing it does. An
/// Import PDF `allPages` set this way to the other pick sets Import PDF pages as links back to its
/// default.
/// default. A Dimension Tool Options `arrowStyle` set this way clears `arrowHead`, and a built-in
/// `arrowHead` set this way sets both values of its Arrow Style entry, as that menu does.
pub fn set_field(d: &mut Dialog, field: String, value: Value) {
if d.kind == brush_options::KIND {
brush_art_options::note_set(d, &field);
@@ -641,6 +642,9 @@ pub fn set_field(d: &mut Dialog, field: String, value: Value) {
if d.kind == import_pdf::KIND {
import_pdf::note_set(d, &field, &value);
}
if d.kind == dimension::KIND && dimension::note_set(d, &field, &value) {
return;
}
if d.kind == "preferences" {
crate::prefs_dialog::note_set(d, &field, &value);
}
+135 -22
View File
@@ -4,6 +4,7 @@ use super::DialogSpec;
use crate::{VectorcraftApp, state::Dialog, theme::Tokens, widgets};
use egui::{RichText, Ui};
use serde_json::{Value, json};
use vectorcraft_doc::Arrowhead;
use vectorcraft_doc::dimension::{ArrowStyle, DimensionOptions};
pub const KIND: &str = "dimensionOptions";
@@ -14,6 +15,8 @@ pub(super) const SPEC: DialogSpec = DialogSpec {
ok: Some("Save"),
min_width: 520.0,
max_width: Some(560.0),
// The saved options leave `arrowHead` out when it is null.
inputs: |_| &["arrowHead"],
..DialogSpec::FORM
};
@@ -31,11 +34,33 @@ const UNITS: Choices = &[
("yd", "Yards"),
];
const LINE_TYPES: Choices = &[("solid", "Solid"), ("dashed", "Dashed"), ("dotted", "Dotted")];
const ARROWS: Choices = &[("filled", "Filled"), ("open", "Open"), ("tick", "Tick"), ("none", "None")];
/// The style of each `ARROWS` entry, in the same order.
const ARROW_STYLES: [ArrowStyle; 4] = [ArrowStyle::Filled, ArrowStyle::Open, ArrowStyle::Tick, ArrowStyle::None];
/// The size of an Arrow Style preview: a line with the head at its right end.
const ARROW_PREVIEW: egui::Vec2 = egui::vec2(40.0, 16.0);
/// The size of an Arrow Style preview: a line with the head at its right end. Line Arrow, the widest
/// head, spreads 20 pt across at the preview's head weight.
const ARROW_PREVIEW: egui::Vec2 = egui::vec2(40.0, 22.0);
/// One Arrow Style entry: the `arrowStyle` and `arrowHead` values it sets, and its name.
struct ArrowChoice {
style: ArrowStyle,
head: Option<Arrowhead>,
name: &'static str,
}
impl ArrowChoice {
/// The arrowhead the dimension line draws with this entry.
fn drawn(&self) -> Option<Arrowhead> {
self.head.clone().or_else(|| self.style.arrowhead())
}
}
/// The Arrow Style entries: Filled, Open, Tick and None, then the other built-in stroke arrowheads
/// in the Stroke panel's order. A stroke arrowhead keeps `filled` as its `arrowStyle`, the head that
/// versions which do not read `arrowHead` draw when they draw the dimension again.
fn arrow_choices() -> Vec<ArrowChoice> {
let named = [(ArrowStyle::Filled, "Filled"), (ArrowStyle::Open, "Open"), (ArrowStyle::Tick, "Tick"), (ArrowStyle::None, "None")];
let heads = Arrowhead::ALL.into_iter().filter(|h| !named.iter().any(|(s, _)| s.arrowhead().as_ref() == Some(h)));
named
.into_iter()
.map(|(style, name)| ArrowChoice { style, head: None, name })
.chain(heads.map(|h| ArrowChoice { style: ArrowStyle::Filled, name: h.label(), head: Some(h) }))
.collect()
}
const POSITIONS: Choices = &[("away", "Away from the Line"), ("between", "Between Line and Object")];
const ALIGNMENTS: Choices = &[("left", "Left"), ("center", "Center"), ("right", "Right")];
@@ -51,6 +76,37 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
Ok(json!({"dialog":KIND}))
}
/// For `ui.dialog.set`, as the Arrow Style menu sets them: an `arrowStyle` set alone draws that
/// style's own head, and a built-in head set as `arrowHead` sets both values of its Arrow Style
/// entry (`tick` with no `arrowHead` for `Slash`, `filled` with `Barbed` for `Barbed`). Returns
/// whether it set the field itself.
pub(super) fn note_set(d: &mut Dialog, field: &str, value: &Value) -> bool {
match field {
"arrowStyle" => {
d.fields.insert("arrowHead".into(), Value::Null);
false
}
"arrowHead" => {
let head = built_in_head(value);
if let Some(ch) = arrow_choices().into_iter().find(|ch| head.is_some() && ch.drawn() == head)
&& let (Ok(style), Ok(head)) = (serde_json::to_value(ch.style), serde_json::to_value(&ch.head))
{
d.fields.insert("arrowStyle".into(), style);
d.fields.insert("arrowHead".into(), head);
return true;
}
false
}
_ => false,
}
}
/// The built-in stroke arrowhead `value` names. Only a short name is read: a draft may hold anything.
fn built_in_head(value: &Value) -> Option<Arrowhead> {
let name = value.as_str().filter(|name| name.len() <= 64)?;
serde_json::from_value::<Arrowhead>(Value::String(name.into())).ok().filter(|h| !matches!(h, Arrowhead::Custom(_)))
}
fn read(fields: &serde_json::Map<String, Value>) -> Result<DimensionOptions, String> {
let o: DimensionOptions = serde_json::from_value(Value::Object(fields.clone())).map_err(|e| e.to_string())?;
o.validate()?;
@@ -73,24 +129,34 @@ fn choose(ui: &mut Ui, fields: &mut serde_json::Map<String, Value>, key: &str, l
});
changed
}
/// The Arrow Style dropdown: each style shows a drawn preview of its arrowhead before its name, in
/// the open list and in the closed field.
/// The Arrow Style dropdown: Filled, Open, Tick and None, then the other built-in stroke
/// arrowheads. Each style shows a drawn preview of its arrowhead before its name, in the open list
/// and in the closed field.
fn arrow_style(ui: &mut Ui, fields: &mut serde_json::Map<String, Value>, id: &str) -> bool {
const KEY: &str = "arrowStyle";
const STYLE: &str = "arrowStyle";
const HEAD: &str = "arrowHead";
let mut changed = false;
widgets::label_row(ui, tl!("Arrow Style:"), 96.0, |ui| {
let current = fields.get(KEY).and_then(Value::as_str).unwrap_or_default();
let shown = ARROWS.iter().position(|(v, _)| *v == current);
let names: Vec<&str> = ARROWS.iter().map(|(_, s)| tl!(*s)).collect();
let choices = arrow_choices();
let style = fields.get(STYLE).cloned().and_then(|v| serde_json::from_value::<ArrowStyle>(v).ok());
let head = fields.get(HEAD).and_then(built_in_head);
let current = style.map(|s| head.or_else(|| s.arrowhead()));
let shown = current.and_then(|c| choices.iter().position(|ch| ch.drawn() == c));
let names: Vec<&str> = choices.iter().map(|ch| crate::panels::stroke::builtin_arrow_name(ch.name)).collect();
let icon = |ui: &Ui, rect: egui::Rect, i: usize, ink: egui::Color32, _: bool| {
if let Some(style) = ARROW_STYLES.get(i) {
crate::panels::stroke::paint_arrow(ui, rect, style.arrowhead().as_ref(), false, ink);
// Only the rows in view render their previews.
if ui.is_rect_visible(rect)
&& let Some(ch) = choices.get(i)
{
crate::panels::stroke::paint_arrow(ui, rect, ch.drawn().as_ref(), false, ink);
}
};
if let Some((value, _)) =
widgets::dropdown_icon_names_sized(ui, ("dimension", id), shown, &names, 150.0, ARROW_PREVIEW, icon).and_then(|i| ARROWS.get(i))
if let Some(ch) =
widgets::dropdown_icon_names_sized(ui, ("dimension", id), shown, &names, 150.0, ARROW_PREVIEW, icon).and_then(|i| choices.get(i))
&& let (Ok(style), Ok(head)) = (serde_json::to_value(ch.style), serde_json::to_value(&ch.head))
{
fields.insert(KEY.into(), json!(value));
fields.insert(STYLE.into(), style);
fields.insert(HEAD.into(), head);
changed = true;
}
});
@@ -387,9 +453,13 @@ mod tests {
assert!(text.contains(label), "{label}: {text}");
}
let d = app.ui.dialog.as_mut().unwrap();
// The default style has no `arrowHead`, and the dialog still takes one.
assert!(!d.fields.contains_key("arrowHead") && super::super::accepts_field(d, "arrowHead"));
d.fields.insert("scale".into(), json!("1:10"));
d.fields.insert("units".into(), json!("pc"));
d.fields.insert("arrowHead".into(), json!("Barbed"));
super::super::confirm(&mut app).unwrap();
assert_eq!(app.session.tool_options_of("dimension")["style"]["arrowHead"], "Barbed");
assert_eq!(app.session.tool_options_of("dimension")["style"]["scale"], "1:10");
assert_eq!(app.session.tool_options_of("dimension")["style"]["units"], "pc");
open(&mut app).unwrap();
@@ -397,6 +467,28 @@ mod tests {
assert!(super::super::confirm(&mut app).is_err());
app.ui.dialog = None;
assert_eq!(app.session.tool_options_of("dimension")["style"]["scale"], "1:10");
// An arrow style set by `ui.dialog.set` replaces the Barbed head, as the menu does.
open(&mut app).unwrap();
super::super::set_field(app.ui.dialog.as_mut().unwrap(), "arrowStyle".into(), json!("none"));
super::super::confirm(&mut app).unwrap();
let style = serde_json::from_value::<DimensionOptions>(app.session.tool_options_of("dimension")["style"].clone()).unwrap();
assert_eq!((style.arrow_style, style.arrowhead()), (ArrowStyle::None, None));
// A stroke head set by `ui.dialog.set` keeps Filled as the arrow style, as the menu does; an
// unknown name leaves the arrow style as it was.
open(&mut app).unwrap();
let d = app.ui.dialog.as_mut().unwrap();
super::super::set_field(d, "arrowStyle".into(), json!("tick"));
super::super::set_field(d, "arrowHead".into(), json!("Nope"));
assert_eq!(d.fields["arrowStyle"], "tick");
super::super::set_field(d, "arrowHead".into(), json!("Barbed"));
super::super::confirm(&mut app).unwrap();
let style = serde_json::from_value::<DimensionOptions>(app.session.tool_options_of("dimension")["style"].clone()).unwrap();
assert_eq!((style.arrow_style, style.arrowhead()), (ArrowStyle::Filled, Some(Arrowhead::Barbed)));
// The head of an older style sets that style and no `arrowHead`, as its menu entry does.
open(&mut app).unwrap();
let d = app.ui.dialog.as_mut().unwrap();
super::super::set_field(d, "arrowHead".into(), json!("Slash"));
assert_eq!((&d.fields["arrowStyle"], &d.fields["arrowHead"]), (&json!("tick"), &Value::Null));
}
/// A selected dimension shows its style in Properties, with Apply to All and Set as Default.
@@ -436,7 +528,10 @@ mod tests {
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
ctx.run_ui(egui::RawInput::default(), |ui| f(app, ui)).textures_delta.clear();
ctx.run_ui(egui::RawInput::default(), |ui| f(app, ui))
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| f(app, ui));
// Previews of rows that come into view in this frame load now.
out.textures_delta.clear();
out
}
/// The Arrow Style field of the Tool Options and of Properties shows the style's arrowhead,
@@ -454,12 +549,30 @@ mod tests {
assert!(picture_before(&out, "Tick"), "Properties");
}
/// Each Arrow Style entry previews the style its value names.
/// A dimension drawn with a stroke arrowhead shows that head's name and preview in its Arrow
/// Style field (#3222).
#[test]
fn arrow_previews_follow_the_listed_styles() {
assert_eq!(ARROWS.len(), ARROW_STYLES.len());
for ((value, _), style) in ARROWS.iter().zip(ARROW_STYLES) {
assert_eq!(serde_json::to_value(style).unwrap(), json!(value));
fn arrow_style_shows_a_stroke_arrowhead() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("dimension.create", json!({"a":[10,10],"b":[110,10],"options":{"arrowHead":"HalfArrowLeft"}})).unwrap();
let out = frame(&mut app, properties_section);
assert!(picture_before(&out, "Half Arrow (left)"), "Properties");
}
/// The Arrow Style list names each arrowhead once, with the four older styles first, and each
/// stroke arrowhead keeps Filled as its `arrowStyle`.
#[test]
fn arrow_style_list_names_each_style_once() {
let choices = arrow_choices();
let names: Vec<&str> = choices.iter().map(|c| c.name).collect();
assert_eq!(names[..4], ["Filled", "Open", "Tick", "None"]);
for name in ["Triangle", "Triangle (open)", "Slash"] {
assert!(!names.contains(&name), "{name} is listed as Filled, Open or Tick");
}
assert_eq!(names.len(), Arrowhead::ALL.len() + 1, "None and each built-in head: {names:?}");
let drawn: Vec<_> = choices.iter().map(|c| format!("{:?}", c.drawn())).collect();
assert_eq!(drawn.iter().collect::<std::collections::HashSet<_>>().len(), drawn.len(), "{drawn:?}");
assert!(choices[4..].iter().all(|c| c.style == ArrowStyle::Filled && c.head.is_some()));
}
}
+627 -50
View File
@@ -31,10 +31,17 @@
//! Color too. The base color can't be removed. A removed color's row goes, unless it has current
//! colors and art or a group is open: it then keeps them, with no new color, so that art keeps its
//! colors and the group's swatch at that place goes. Under the tools, a button switches both wheels
//! to hue and brightness (black at the center, full brightness at the edge, at the base color's
//! to hue and brightness (black at the center, full brightness at the edge, at the selected color's
//! saturation; a marker drag sets hue and brightness, Add Color adds the hue and brightness clicked
//! at the base color's saturation, and the slider under the wheel is a Saturation slider) and back;
//! switching changes no color, and the dialog opens on hue and saturation. With art, the Prominent Colors bar under the wheel shows the new
//! at the selected color's saturation, and the slider under the wheel is a Saturation slider) and
//! back; switching changes no color, and the dialog opens on hue and saturation. The base color is the one the harmony rules
//! build from, drawn with the larger marker; it stays the base when another color is selected for
//! the sliders. A right-click on a marker or a color bar offers Set As Base Color, Select Shade (a
//! grid of the color's hue at 7 saturations by 7 brightnesses; a click moves the marker there as a
//! drag would), Color Picker and Remove Color; a right-click elsewhere on the wheel offers Add New
//! Color, which adds the hue and saturation there as the Add Color tool does, and a color added on
//! the line from the center to a marker moves with that marker when the colors are unlinked. Set
//! Current Color As Base Color, before the color chips, makes the selected color the base. With art, the Prominent Colors bar under the wheel shows the new
//! colors, each part as wide as its row's share of the art's uses, the largest first; dragging the
//! edge between two parts moves width between them, and when the drag ends the rows' current
//! colors move toward those widths (`recolor.weigh`), and the art previews them. The New Color
@@ -78,7 +85,10 @@
//!
//! Fields (`ui.dialog.set`): `rows` ([{from: [keys], to: key, exclude?, tint?: percent of a spot
//! color, added?}]; a row with no current colors, `from: []`, recolors no art, and with `added: true`
//! (a color the Add Color tool added) adds its new color to the color group; `to: null`, no new color), `colors` (null: Auto, or a count), `method`, `preserveWhite`, `preserveBlack`,
//! (a color the Add Color tool added) adds its new color to the color group; `to: null`, no new color;
//! `base: true`, the base color, else the first color the Edit tab shows; `tie: n` on a marker and
//! `follows: n` on a color added on its line, which moves with it; the dialog sends `recolor.apply`
//! the rows without these three), `colors` (null: Auto, or a count), `method`, `preserveWhite`, `preserveBlack`,
//! `preserveGrays`, `limitTo` (library id, "document" for the document's swatches, "" for none),
//! `group`, `groupName`, `tab` (`assign` or `edit`), `rule` (harmony id), `linked`, `preview`,
//! `sliderMode` (`hsb`, `rgb`, `cmyk`, `lab` or `tint`; unset: the row color's own model, HSB for
@@ -213,7 +223,8 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
None => String::new(),
};
// Without art the rows are the group's colours, as they are.
let start: Vec<Value> = if art { vec![] } else { assign.iter().map(|k| json!({"from": [k], "to": k})).collect() };
let mut start: Vec<Value> = if art { vec![] } else { assign.iter().map(|k| json!({"from": [k], "to": k})).collect() };
number_slots(&mut start);
// The Preserve checkboxes as they were last confirmed (#2960).
let kept = |k: &str, default: bool| app.ui.recolor_preserve.get(k).and_then(Value::as_bool).unwrap_or(default);
let fields = json!({
@@ -276,6 +287,7 @@ fn sync(app: &mut VectorcraftApp, d: &mut Dialog) {
for (row, to) in rows.iter_mut().zip(assign) {
row["to"] = to;
}
number_slots(&mut rows);
snap(app, d, &mut rows);
d.fields.insert("rows".into(), Value::Array(rows));
// Find dims the preserved colors with the rows that aren't selected.
@@ -335,7 +347,9 @@ fn sync_weights(app: &mut VectorcraftApp, d: &mut Dialog) {
match app.session.execute("recolor.weigh", &json!({"map": rows(d), "weights": w})) {
Ok(r) => {
if let Some(m) = r["map"].as_array() {
d.fields.insert("rows".into(), Value::Array(m.clone()));
let mut m = m.clone();
keep_marks(&rows(d), &mut m);
d.fields.insert("rows".into(), Value::Array(m));
}
}
Err(e) => app.status(e.to_string()),
@@ -451,14 +465,14 @@ fn group_colors<'a>(app: &VectorcraftApp, d: &Dialog, rs: impl Iterator<Item = &
}
/// The New Color Group menu's request: save the new colors of the rows that aren't excluded and
/// hold current colors or were added on the Edit tab (Save All Colors, in row order; a row without one gives its first current
/// color) or of the Prominent Colors bar (Save Prominent Colors, in its order) as a new color
/// group, a step of its own (`swatch.newGroup`).
/// hold current colors or were added on the Edit tab (Save All Colors, in row order) or of the
/// Prominent Colors bar (Save Prominent Colors, in its order) as a new color group, a step of its
/// own (`swatch.newGroup`). Either way a row whose new color was removed gives none.
fn save_group(app: &mut VectorcraftApp, d: &mut Dialog, which: &str) -> Result<(), String> {
let rs = rows(d);
let order: Vec<usize> = match which {
"prominent" => prominent_parts(d, &rs).into_iter().map(|p| p.0).collect(),
_ => (0..rs.len()).filter(|&i| in_group(&rs[i])).collect(),
"prominent" => prominent_parts(d, &rs).into_iter().map(|p| p.0).filter(|&i| to_color(&rs[i]).is_some()).collect(),
_ => (0..rs.len()).filter(|&i| in_group(&rs[i]) && to_color(&rs[i]).is_some()).collect(),
};
let colors = group_colors(app, d, order.iter().filter_map(|&i| rs.get(i)));
if colors.is_empty() {
@@ -541,6 +555,7 @@ fn select_group(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String>
d.fields.remove(REDUCED);
} else {
let mut rs: Vec<Value> = assign.iter().map(|k| json!({"from": [k], "to": k})).collect();
number_slots(&mut rs);
snap(app, d, &mut rs);
d.fields.insert("rows".into(), Value::Array(rs));
d.fields.insert("__sel".into(), json!([]));
@@ -601,7 +616,7 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res
// An excluded row leaves its swatch the color it has now, as OK's `"keep"` does: with
// art, the swatch's color in `__assign`; without art, the swatch's color in the group,
// which an earlier Save Changes may have changed.
let filled: Vec<&Value> = rs.iter().filter(|r| !no_current(r)).collect();
let filled = by_place(&rs);
let rest: Vec<Value> =
p["groupColors"].as_array().map(|a| a.iter().skip(filled.len()).map(|k| json!({"from": [k], "to": k})).collect()).unwrap_or_default();
let assign: Vec<Value> =
@@ -1169,7 +1184,7 @@ fn apply_params(d: &Dialog) -> Value {
.chain(added)
.collect()
} else {
let filled: Vec<&Value> = rs.iter().filter(|r| !no_current(r)).collect();
let filled = by_place(&rs);
let rest = assign.get(filled.len()..).unwrap_or_default();
let took = filled.iter().map(|r| if excluded(r) { &keep } else { &r["to"] });
took.chain(rest).chain(added).collect()
@@ -1177,8 +1192,10 @@ fn apply_params(d: &Dialog) -> Value {
};
Some(json!({"group": g, "groupColors": colors, "rename": rename}))
});
// A row edited with the sliders carries `model: "new"`: its art takes the mode they showed.
let mut p = json!({"map": rs, "method": d.str("method"), "limitTo": d.str("limitTo")});
// A row edited with the sliders carries `model: "new"`: its art takes the mode they showed. The
// Edit tab's own marks (the base color, colors tied to a marker) stay in the dialog.
let map: Vec<Value> = rs.iter().map(without_marks).collect();
let mut p = json!({"map": map, "method": d.str("method"), "limitTo": d.str("limitTo")});
// The Global Adjust amounts, kept while the sliders show another mode; at 0% they are left out.
let values = adjust_values(d);
if values.iter().any(|v| *v != 0.0) {
@@ -1406,7 +1423,7 @@ fn main(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> Option<(usize,
}
let mut rs = rows(d);
let top = ui.cursor().top();
let (changed, pick) = if d.str("tab") == "edit" { (edit_tab(app, ui, d, &mut rs), None) } else { assign_tab(app, ui, d, &mut rs) };
let (changed, pick) = if d.str("tab") == "edit" { edit_tab(app, ui, d, &mut rs) } else { assign_tab(app, ui, d, &mut rs) };
if d.str("tab") != "edit" {
ui.add_space((TAB_H - (ui.cursor().top() - top)).max(0.0));
}
@@ -1663,7 +1680,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
r?;
}
if d.bool("__newGroup") {
let colors = group_colors(app, &d, rows(&d).iter().filter(|r| in_group(r)));
let colors = group_colors(app, &d, rows(&d).iter().filter(|r| in_group(r) && to_color(r).is_some()));
let r = form::commit_preview(app, "swatch.newGroup", json!({"name": d.str("groupName"), "colors": colors, "keepModel": true}))?;
app.ui.recolor_history = History::default();
return Ok(r);
@@ -1897,7 +1914,9 @@ fn assign_tab(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut
let p = json!({"map": rows, "order": !sb, "saturationBrightness": sb, "seed": seed});
match app.session.execute("recolor.randomize", &p) {
Ok(r) => {
*rows = r["map"].as_array().cloned().unwrap_or_default();
let mut shuffled = r["map"].as_array().cloned().unwrap_or_default();
keep_marks(rows, &mut shuffled);
*rows = shuffled;
if !sb {
d.fields.insert(SHUFFLED.into(), json!(true));
}
@@ -2264,6 +2283,21 @@ fn merge(rows: &mut Vec<Value>, sel: &[usize]) {
for &i in rest.iter().rev() {
let row = rows.remove(i);
moved.splice(0..0, row["from"].as_array().cloned().unwrap_or_default());
// The base color merged into another row makes that row the base, and the colors that
// followed the merged row's marker follow that row's.
if row[BASE] == json!(true) {
rows[first][BASE] = json!(true);
}
if let Some(t) = row[TIE].as_u64() {
match rows[first][TIE].as_u64() {
Some(to) => {
for r in rows.iter_mut().filter(|r| r[FOLLOWS].as_u64() == Some(t)) {
r[FOLLOWS] = json!(to);
}
}
None => rows[first][TIE] = json!(t),
}
}
}
if let Some(dst) = rows[first]["from"].as_array_mut() {
dst.extend(moved);
@@ -2275,7 +2309,17 @@ fn separate(rows: &mut Vec<Value>, sel: &[usize]) {
let mut out = vec![];
for (i, row) in rows.drain(..).enumerate() {
match row["from"].as_array() {
Some(a) if sel.contains(&i) && a.len() > 1 => out.extend(a.iter().map(|k| json!({"from": [k], "to": k}))),
Some(a) if sel.contains(&i) && a.len() > 1 => {
let at = out.len();
out.extend(a.iter().map(|k| json!({"from": [k], "to": k})));
// A separated row's marks (the base color, a marker's tie, a color it follows, its place) go
// to the row of its first color.
for k in [BASE, TIE, FOLLOWS, SLOT] {
if let Some(v) = row.get(k) {
out[at][k] = v.clone();
}
}
}
_ => out.push(row),
}
}
@@ -2306,13 +2350,29 @@ fn edit_slider_row(d: &Dialog, rows: &[Value], active: &[usize], base: Option<us
}
/// Set row `i`'s new colour to hue/saturation/brightness `hsb` ([`move_on_wheel`]: with `linked`
/// the other rows keep their relation to it). Excluded rows stay.
/// the other rows keep their relation to it; unlinked, the colors added on its marker's line, which
/// follow its `tie`, and those that follow theirs, keep theirs). Excluded rows stay.
fn move_color(rows: &mut [Value], i: usize, hsb: [f32; 3], linked: bool) {
let active = active_rows(rows);
let all = active_rows(rows);
let active: Vec<usize> = if linked {
all
} else {
// Row `i` and the rows that follow it, directly or through another follower.
let mut moving = vec![i];
let mut n = 0;
while let Some(&j) = moving.get(n) {
if let Some(t) = rows.get(j).and_then(|r| r[TIE].as_u64()) {
let next: Vec<usize> = all.iter().copied().filter(|&k| rows[k][FOLLOWS].as_u64() == Some(t) && !moving.contains(&k)).collect();
moving.extend(next);
}
n += 1;
}
all.into_iter().filter(|j| moving.contains(j)).collect()
};
let Some(k) = active.iter().position(|&j| j == i) else { return };
let before: Vec<Color> = active.iter().filter_map(|&j| to_color(&rows[j])).collect();
let mut colors = before.clone();
move_on_wheel(&mut colors, k, hsb, linked);
move_on_wheel(&mut colors, k, hsb, true);
for ((&j, c), old) in active.iter().zip(&colors).zip(&before) {
if key(c) != key(old) {
set_to(&mut rows[j], c);
@@ -2337,7 +2397,7 @@ fn wheel_axes(d: &Dialog) -> widgets::WheelAxes {
/// The new color the Add Color tool gives a click at hue `h` (degrees) and `t`, the saturation (or
/// with [`widgets::WheelAxes::HueBrightness`] the brightness) clicked: with the other component of
/// `base` (the base color, whose other component the wheel shows; full without one), the segmented
/// `base` (the selected color, whose other component the wheel shows; full without one), the segmented
/// wheel's patch color with `segmented`, in `base`'s model.
fn added_color(base: Option<Color>, h: f32, t: f32, segmented: bool, axes: widgets::WheelAxes) -> Color {
let o = base.map_or(1.0, |b| b.to_hsb()[axes.other()]);
@@ -2391,16 +2451,244 @@ fn removed(d: &mut Dialog, base: usize) {
d.fields.remove(COMPS);
}
/// The Edit tab. Returns true when the rows changed.
fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut Vec<Value>) -> bool {
/// A row's mark as the base color, the color the harmony rules build from (`true`).
const BASE: &str = "base";
/// A row's number on a marker that the colors added on its line follow.
const TIE: &str = "tie";
/// A row's mark as a color added on a marker's line: the marker's `tie`, which it moves with.
const FOLLOWS: &str = "follows";
/// A row's place when the rows were made (the group swatch it took), which it keeps when it moves.
const SLOT: &str = "slot";
/// Give each row its place in `rows` as its [`SLOT`].
fn number_slots(rows: &mut [Value]) {
for (i, r) in rows.iter_mut().enumerate() {
r[SLOT] = json!(i);
}
}
/// The rows with current colors in the order of their group swatches: each row takes the swatch at
/// its [`SLOT`], so a row moved among the color bars keeps its swatch; rows that don't all carry a
/// place go in row order.
fn by_place(rs: &[Value]) -> Vec<&Value> {
let mut filled: Vec<&Value> = rs.iter().filter(|r| !no_current(r)).collect();
if filled.iter().all(|r| r[SLOT].is_u64()) {
filled.sort_by_key(|r| r[SLOT].as_u64());
}
filled
}
/// The target of the wheel's right-click menu: `{marker, line, hs}` (row indexes and the hue and
/// saturation clicked).
const MENU_AT: &str = "__wheelMenu";
/// Select Shade's grid: saturations across, from 0% to 100%, and brightnesses down, from 100%.
const SHADE_COLS: usize = 7;
const SHADE_ROWS: usize = 7;
const SHADE_CELL: f32 = 16.0;
/// The base color's row: the row of `active` (the rows the Edit tab shows) marked `base`, else
/// the first of them.
fn base_row(rows: &[Value], active: &[usize]) -> Option<usize> {
active.iter().copied().find(|&i| rows[i][BASE] == json!(true)).or(active.first().copied())
}
/// Whether Set As Base Color would change anything for row `i`: it is shown on the Edit tab, and it
/// isn't the base already, or it is the base only because the marked row is hidden (excluded, or
/// with no new color), whose mark would make it the base again once shown.
fn can_set_base(rows: &[Value], i: usize) -> bool {
let active = active_rows(rows);
active.contains(&i) && (base_row(rows, &active) != Some(i) || rows.iter().enumerate().any(|(k, r)| k != i && r[BASE] == json!(true)))
}
/// Make row `i` the base color (Set As Base Color). Returns false when that changes nothing
/// ([`can_set_base`]).
fn set_base(rows: &mut [Value], i: usize) -> bool {
if !can_set_base(rows, i) {
return false;
}
for r in rows.iter_mut() {
if let Some(o) = r.as_object_mut() {
o.remove(BASE);
}
}
rows[i][BASE] = json!(true);
true
}
/// Make row `follower` move with the marker of row `leader`: the leader keeps its `tie` (a new
/// number, past every `tie` and `follows`, when it has none, so that colors left from a removed
/// marker follow no other) and the follower takes it as `follows`.
fn tie_to(rows: &mut [Value], leader: usize, follower: usize) {
if leader == follower || leader >= rows.len() || follower >= rows.len() {
return;
}
let used = rows.iter().flat_map(|r| [r[TIE].as_u64(), r[FOLLOWS].as_u64()]).flatten().max();
let t = rows[leader][TIE].as_u64().unwrap_or_else(|| used.map_or(1, |m| m.saturating_add(1)));
rows[leader][TIE] = json!(t);
rows[follower][FOLLOWS] = json!(t);
}
/// Give each row of `after` the base, tie and follows marks of the row at its place in `before`,
/// when the two have as many rows (the engine's `recolor.randomize` and `recolor.weigh` keep the
/// rows in order and return them without the dialog's own marks).
fn keep_marks(before: &[Value], after: &mut [Value]) {
if before.len() != after.len() {
return;
}
for (a, b) in after.iter_mut().zip(before) {
for k in [BASE, TIE, FOLLOWS, SLOT] {
if a.get(k).is_none()
&& let Some(v) = b.get(k)
{
a[k] = v.clone();
}
}
}
}
/// `row` without the dialog's base, tie, follows and place marks.
fn without_marks(row: &Value) -> Value {
let mut r = row.clone();
if let Some(o) = r.as_object_mut() {
for k in [BASE, TIE, FOLLOWS, SLOT] {
o.remove(k);
}
}
r
}
/// The saturation and brightness of Select Shade's cell in column `col` and row `row`.
fn shade_at(col: usize, row: usize) -> [f32; 2] {
[col as f32 / (SHADE_COLS - 1) as f32, 1.0 - row as f32 / SHADE_ROWS as f32]
}
/// Select Shade's grid of `c`'s hue, the cell nearest `c` framed. Returns the saturation and
/// brightness of the cell clicked.
fn shade_grid(ui: &mut Ui, c: &Color) -> Option<[f32; 2]> {
let t = Tokens::get(ui.ctx());
let [h, s0, v0] = c.to_hsb();
let near = ((s0 * (SHADE_COLS - 1) as f32).round() as usize, (((1.0 - v0) * SHADE_ROWS as f32).round() as usize).min(SHADE_ROWS - 1));
let mut out = None;
egui::Grid::new("recolor-shades").spacing([2.0, 2.0]).show(ui, |ui| {
for row in 0..SHADE_ROWS {
for col in 0..SHADE_COLS {
let [s, v] = shade_at(col, row);
let (r, resp) = ui.allocate_exact_size(vec2(SHADE_CELL, SHADE_CELL), Sense::click());
ui.painter().rect_filled(r, 1.0, c32(&Color::from_hsb(h, s, v)));
if (col, row) == near {
ui.painter().rect_stroke(r, 1.0, egui::Stroke::new(1.5, t.accent), egui::StrokeKind::Outside);
}
let name = format!("{} {}%, {} {}%", tl!("Saturation"), (s * 100.0).round(), tl!("Brightness"), (v * 100.0).round());
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &name));
if resp.clicked() {
out = Some([s, v]);
ui.close();
}
}
ui.end_row();
}
});
out
}
/// What a marker's or a color bar's right-click menu, or the wheel's, chose.
enum MenuChoice {
/// Set As Base Color for the row.
Base(usize),
/// Select Shade: the row's color at this saturation and brightness.
Shade(usize, [f32; 2]),
/// Color Picker for the row.
Picker(usize),
/// Remove Color for the row.
Remove(usize),
/// Add New Color at this hue and saturation, moving with the marker of the row on whose line
/// it is.
Add([f32; 2], Option<usize>),
}
/// A marker's or a color bar's right-click menu for row `i`: Set As Base Color and Remove Color
/// (neither for the base color `base`), Select Shade and Color Picker.
fn color_menu(ui: &mut Ui, rows: &[Value], i: usize, base: Option<usize>) -> Option<MenuChoice> {
let mut choice = None;
if widgets::menu_item_name(ui, tl!("Set As Base Color"), can_set_base(rows, i), false) {
choice = Some(MenuChoice::Base(i));
}
if let Some(c) = rows.get(i).and_then(to_color) {
// Indented like the items beside it (their check column).
ui.menu_button(format!(" {}", tl!("Select Shade")), |ui| {
if let Some(sv) = shade_grid(ui, &c) {
choice = Some(MenuChoice::Shade(i, sv));
}
});
}
if widgets::menu_item_name(ui, tl!("Color Picker"), true, false) {
choice = Some(MenuChoice::Picker(i));
}
if widgets::menu_item_name(ui, tl!("Remove Color"), Some(i) != base, false) {
choice = Some(MenuChoice::Remove(i));
}
choice
}
/// Carry out a right-click menu's `choice` on the rows (`base`: the base color's row; `shown`: the
/// color whose brightness the wheel shows; `segmented`: the menu was on the segmented wheel).
/// Returns whether the rows changed and the row whose new color the Color Picker is to edit.
fn choose(
d: &mut Dialog,
rows: &mut Vec<Value>,
choice: MenuChoice,
base: Option<usize>,
shown: Option<Color>,
segmented: bool,
axes: widgets::WheelAxes,
) -> (bool, Option<usize>) {
match choice {
MenuChoice::Base(i) => (set_base(rows, i), None),
MenuChoice::Shade(i, [s, v]) => {
let Some(h) = rows.get(i).and_then(to_color).map(|c| c.to_hsb()[0]) else { return (false, None) };
let before = rows.clone();
move_color(rows, i, [h, s, v], d.bool("linked"));
d.fields.insert("__sel".into(), json!([i]));
d.fields.remove(COMPS);
(*rows != before, None)
}
MenuChoice::Picker(i) => {
d.fields.insert("__sel".into(), json!([i]));
(false, Some(i))
}
MenuChoice::Remove(i) => match remove_color(rows, i, base, keeps_rows(d)) {
Some(b) => {
removed(d, b);
(true, None)
}
None => (false, None),
},
MenuChoice::Add([h, s], line) => {
let i = add_color(rows, &added_color(shown, h, s, segmented, axes));
if let Some(l) = line {
tie_to(rows, l, i);
}
d.fields.insert("__sel".into(), json!([i]));
d.fields.remove(COMPS);
(true, None)
}
}
}
/// The Edit tab. Returns whether the rows changed and the row whose new color a right-click menu's
/// Color Picker is to edit.
fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut Vec<Value>) -> (bool, Option<(usize, bool)>) {
let top = ui.cursor().top();
let t = Tokens::get(ui.ctx());
let mut changed = false;
let mut pick = None;
let linked = d.bool("linked");
let active = active_rows(rows);
let base = selection(d).into_iter().find(|i| active.contains(i)).or(active.first().copied());
let slider_row = edit_slider_row(d, rows, &active, base);
let target = SliderTarget::at(app, d, rows, slider_row);
// The harmony rules build from the base color; the sliders and the Brightness slider edit the
// selected color (the base color when the tab does not show the first selected row).
let base = base_row(rows, &active);
let sel = edit_slider_row(d, rows, &active, base);
let target = SliderTarget::at(app, d, rows, sel);
ui.horizontal(|ui| {
ui.label(egui::RichText::new(tl!("Harmony Rules:")).color(t.text_dim));
let rule = Harmony::parse(&d.str("rule")).unwrap_or(Harmony::Complementary);
@@ -2421,9 +2709,9 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut Vec<Va
}
// New Color Group: save the wheel's colors or the Prominent Colors as a color group.
let button = widgets::icon_button(ui, "dc-folder", tl!("New Color Group"), false, 24.0);
let prominent = d.bool("__art") && !prominent_parts(d, rows).is_empty();
let prominent = d.bool("__art") && prominent_parts(d, rows).iter().any(|p| rows.get(p.0).and_then(to_color).is_some());
let saved = egui::Popup::menu(&button).show(|ui| {
if widgets::menu_item_name(ui, tl!("Save All Colors"), rows.iter().any(in_group), false) {
if widgets::menu_item_name(ui, tl!("Save All Colors"), rows.iter().any(|r| in_group(r) && to_color(r).is_some()), false) {
return Some("all");
}
widgets::menu_item_name(ui, tl!("Save Prominent Colors"), prominent, false).then_some("prominent")
@@ -2445,6 +2733,9 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut Vec<Va
}
let colors: Vec<Color> = active.iter().filter_map(|&i| to_color(&rows[i])).collect();
let marked = base.and_then(|b| active.iter().position(|&i| i == b));
let selected = sel.and_then(|s| active.iter().position(|&i| i == s));
let shown = sel.and_then(|s| to_color(&rows[s]));
let mut choice = None;
let display = d.str("display");
let tool = d.str(WHEEL_TOOL);
let axes = wheel_axes(d);
@@ -2482,15 +2773,56 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut Vec<Va
}
});
ui.vertical(|ui| match display.as_str() {
"bars" => changed |= color_bars(ui, d, rows, &active, base),
_ => w = widgets::wheel_of(ui, "recolor-wheel", WHEEL, &colors, marked, display == "segmented", axes),
"bars" => {
let (moved, chosen) = color_bars(ui, d, rows, &active, base);
changed |= moved;
choice = chosen;
}
_ => w = widgets::recolor_wheel(ui, "recolor-wheel", WHEEL, &colors, marked, selected, display == "segmented", axes),
});
});
// A right-click on the wheel: a marker's menu, or Add New Color elsewhere. Its target is kept
// while the menu stays open.
if let Some((hit, line, hs)) = w.secondary {
d.fields.insert(MENU_AT.into(), json!({"marker": hit.map(|k| active[k]), "line": line.map(|k| active[k]), "hs": hs}));
} else if w.response.as_ref().is_some_and(egui::Response::secondary_clicked) {
// A right-click off the wheel (in a corner of its square) targets nothing: its menu's Add
// New Color is off, and no earlier marker is changed.
d.fields.remove(MENU_AT);
}
if let Some(resp) = &w.response {
let at = d.fields.get(MENU_AT).cloned().unwrap_or_default();
let row = |k: &str| at[k].as_u64().map(|i| i as usize).filter(|i| active.contains(i));
let hs = at["hs"].as_array().and_then(|a| Some([a.first()?.as_f64()? as f32, a.get(1)?.as_f64()? as f32]));
resp.context_menu(|ui| match row("marker") {
Some(i) => choice = color_menu(ui, rows, i, base),
None => {
if widgets::menu_item_name(ui, tl!("Add New Color"), hs.is_some(), false)
&& let Some(hs) = hs
{
choice = Some(MenuChoice::Add(hs, row("line")));
}
}
});
}
// A menu's choice changes the rows the wheel's indexes were for, so the wheel's own clicks and
// drags of this frame are left alone.
let chosen = choice.is_some();
if let Some(c) = choice {
let (did, picked) = choose(d, rows, c, base, shown, display == "segmented", axes);
changed |= did;
pick = picked.map(|i| (i, false));
}
if chosen {
w.pressed = None;
w.moved = None;
w.clicked = None;
}
// A click with a wheel tool adds a color there, or removes the color of the marker clicked.
let clicked = w.clicked.filter(|_| on_wheel && matches!(tool.as_str(), "add" | "remove"));
if let Some((hit, [h, out])) = clicked {
if tool == "add" {
let c = added_color(base.and_then(|b| to_color(&rows[b])), h, out, display == "segmented", axes);
let c = added_color(shown, h, out, display == "segmented", axes);
let i = add_color(rows, &c);
d.fields.insert("__sel".into(), json!([i]));
d.fields.remove(COMPS);
@@ -2534,43 +2866,57 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut Vec<Va
}
// A color added or removed above changed the rows, so the sliders and chips read them afresh.
let active = active_rows(rows);
let base = selection(d).into_iter().find(|i| active.contains(i)).or(active.first().copied());
let base = base_row(rows, &active);
let sel = edit_slider_row(d, rows, &active, base);
if d.str("sliderMode") == GLOBAL {
let sample = base.and_then(|b| to_color(&rows[b])).unwrap_or(Color::rgb(0.8, 0.45, 0.25));
let sample = sel.and_then(|b| to_color(&rows[b])).unwrap_or(Color::rgb(0.8, 0.45, 0.25));
global_sliders(ui, d, sample);
} else {
changed |= sliders(app, ui, d, rows, slider_row);
changed |= sliders(app, ui, d, rows, sel);
}
// The new colours: click one to make it the base colour.
// The new colours: click one to select it; Set Current Color As Base Color, before them, makes
// the selected one the base color, which carries a double ring as its marker does.
let min_height = (TAB_H - (ui.cursor().top() - top)).max(0.0);
let mut make_base = None;
super::modal::scrolled_rows(ui, "recolor-edit-colors", |ui| {
// Keep the usual tab height when it fits; the empty space scrolls with the chips.
ui.set_min_height(min_height);
ui.horizontal_wrapped(|ui| {
let can = sel.is_some_and(|s| can_set_base(rows, s));
if widgets::icon_button_enabled(ui, "circle-dot", tl!("Set Current Color As Base Color"), false, can, 20.0).clicked() {
make_base = sel;
}
for &i in &active {
let (r, resp) = ui.allocate_exact_size(vec2(28.0, 20.0), Sense::click());
chip(ui, r, to_color(&rows[i]).unwrap_or_default(), false);
if Some(i) == base {
if Some(i) == sel {
ui.painter().rect_stroke(r.expand(1.5), 2.0, egui::Stroke::new(1.5, t.accent), egui::StrokeKind::Outside);
}
if Some(i) == base {
ui.painter().circle_stroke(r.center(), 4.0, egui::Stroke::new(1.5, egui::Color32::WHITE));
ui.painter().circle_stroke(r.center(), 5.5, egui::Stroke::new(1.0, egui::Color32::BLACK));
}
if resp.on_hover_text(rows[i]["to"].as_str().unwrap_or_default()).clicked() {
d.fields.insert("__sel".into(), json!([i]));
}
}
});
});
changed
if let Some(i) = make_base {
changed |= set_base(rows, i);
}
(changed, pick)
}
/// The Edit tab's color bars: a solid bar per row of `active` with its new color, in row order, the
/// base row's framed, scrolling past the wheel's height. A click on a bar selects its row (the
/// sliders under it edit that row's new color); a drag moves the bar's row to where the line under
/// the pointer shows, keeping every new color. A bar's right-click menu has Remove Color (not for the
/// base row's). Returns true when the rows moved or a color was removed.
fn color_bars(ui: &mut Ui, d: &mut Dialog, rows: &mut Vec<Value>, active: &[usize], base: Option<usize>) -> bool {
/// the pointer shows, keeping every new color. A bar's right-click menu is a marker's
/// ([`color_menu`]). Returns true when the rows moved, and the menu's choice.
fn color_bars(ui: &mut Ui, d: &mut Dialog, rows: &mut [Value], active: &[usize], base: Option<usize>) -> (bool, Option<MenuChoice>) {
let t = Tokens::get(ui.ctx());
let mut rects: Vec<Rect> = Vec::with_capacity(active.len());
let (mut dragging, mut released, mut dropped, mut remove) = (None, None, None, None);
let (mut dragging, mut released, mut dropped, mut choice) = (None, None, None, None);
// The area is given its full height first: in the row beside the display buttons a scroll area
// alone is only as tall as the room the row has.
let area = vec2(ui.available_width(), BARS_H);
@@ -2603,8 +2949,8 @@ fn color_bars(ui: &mut Ui, d: &mut Dialog, rows: &mut Vec<Value>, active: &[usiz
rects.push(r);
let resp = resp.on_hover_text(rows[i]["to"].as_str().unwrap_or_default());
resp.context_menu(|ui| {
if widgets::menu_item_name(ui, tl!("Remove Color"), Some(i) != base, false) {
remove = Some(i);
if let Some(c) = color_menu(ui, rows, i, base) {
choice = Some(c);
}
});
}
@@ -2621,15 +2967,14 @@ fn color_bars(ui: &mut Ui, d: &mut Dialog, rows: &mut Vec<Value>, active: &[usiz
dropped = released.zip(at);
});
});
if let Some(b) = remove.and_then(|i| remove_color(rows, i, base, keeps_rows(d))) {
removed(d, b);
return true;
if choice.is_some() {
return (false, choice);
}
let Some(moved) = dropped.and_then(|(n, to)| move_bar(rows, active, n, to)) else { return false };
let Some(moved) = dropped.and_then(|(n, to)| move_bar(rows, active, n, to)) else { return (false, None) };
d.fields.insert("__sel".into(), json!([moved]));
// The slider values held are those of a row index that may now hold another row.
d.fields.remove(COMPS);
true
(true, None)
}
/// Move the row of the `from`th active row (of `active`, ascending row indexes) to before the
@@ -2790,6 +3135,67 @@ mod tests {
assert_eq!(apply_params(&d)["groupColors"], json!(["rgb 1 1 1", null, "rgb 3 3 3"]));
}
/// An excluded row with current colors keeps the group's swatch at its place as it is, even
/// after its new color was edited or removed, and with Global Adjust on.
#[test]
fn an_excluded_row_keeps_its_group_swatch() {
let mut d = Dialog::new(KIND, json!({"group": "G", "groupName": "G", "__art": true, "__assign": ["rgb 1 1 1", "rgb 2 2 2", "rgb 3 3 3"]}));
let rs = json!([
{"from": ["rgb 255 0 0"], "to": "rgb 7 7 7", "exclude": true},
{"from": ["rgb 0 0 255"], "to": null, "exclude": true},
{"from": ["rgb 0 255 0"], "to": "rgb 8 8 8"},
]);
d.fields.insert("rows".into(), rs);
assert_eq!(apply_params(&d)["groupColors"], json!(["keep", "keep", "rgb 8 8 8"]));
// Without art the rows are the group's colors.
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
app.run("swatch.newGroup", json!({"name": "G", "colors": ["#2878f0", "#ff0000"]})).unwrap();
app.run("ui.recolorDialog", json!({"group": "G"})).unwrap();
let mut d = app.ui.dialog.clone().unwrap();
let mut rs = super::rows(&d);
rs[0]["to"] = json!("#00ff00");
rs[0]["exclude"] = json!(true);
rs[1]["to"] = json!("#0000ff");
d.fields.insert("rows".into(), json!(rs));
d.fields.insert("globalAdjust".into(), json!({"brightness": -50}));
confirm(&mut app, &d).unwrap();
let g = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "G").unwrap();
let hex: Vec<String> = g.swatches.iter().map(|w| w.paint.color().unwrap().to_hex()).collect();
assert_eq!(hex[0], "#2878f0", "{hex:?}");
assert_ne!(hex[1], "#ff0000", "{hex:?}");
}
/// A row moved among the color bars keeps the group swatch it took when the rows were made, so
/// an excluded row's swatch stays as it is and the other swatches keep their places.
#[test]
fn a_moved_row_keeps_its_group_swatch() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
app.run("swatch.newGroup", json!({"name": "G", "colors": ["#ff0000", "#0000ff", "#00ff00"]})).unwrap();
app.run("ui.recolorDialog", json!({"group": "G"})).unwrap();
let mut d = app.ui.dialog.clone().unwrap();
let mut rs = super::rows(&d);
rs[1]["exclude"] = json!(true);
rs[2]["to"] = json!("#ffff00");
let active = active_rows(&rs);
assert_eq!(active, [0, 2]);
// Drag the last bar (green, now yellow) above the first (red).
assert_eq!(move_bar(&mut rs, &active, 1, 0), Some(0));
d.fields.insert("rows".into(), json!(rs));
let colors = &apply_params(&d)["groupColors"];
assert_eq!(colors[1], json!("keep"), "{colors}");
confirm(&mut app, &d).unwrap();
let g = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "G").unwrap();
let hex: Vec<String> = g.swatches.iter().map(|w| w.paint.color().unwrap().to_hex()).collect();
assert_eq!(hex, ["#ff0000", "#0000ff", "#ffff00"]);
// Rows reduced from art carry their place too, and `recolor.apply` gets none.
let mut rows = vec![json!({"from": ["rgb 255 0 0"], "to": "rgb 1 1 1"}), json!({"from": ["rgb 0 0 255"], "to": "rgb 2 2 2"})];
number_slots(&mut rows);
assert_eq!(rows.iter().map(|r| r[SLOT].clone()).collect::<Vec<_>>(), [json!(0), json!(1)]);
assert!(without_marks(&rows[0]).get(SLOT).is_none());
}
#[test]
fn merge_and_separate_rows() {
let mut r = rows();
@@ -2927,6 +3333,117 @@ mod tests {
assert_eq!([&r[0]["to"], &r[1]["to"], &r[2]["to"]], ["rgb 255 0 0", "rgb 0 255 0", "rgb 0 0 255"]);
}
/// The base color is the row marked `base`, else the first row shown; Set As Base Color moves the
/// mark, and does nothing for the base row already or a row the Edit tab doesn't show.
#[test]
fn set_base_moves_the_base_mark() {
let mut r = rows();
assert_eq!(base_row(&r, &active_rows(&r)), Some(0));
assert!(!set_base(&mut r, 0), "the first row is the base already");
assert!(set_base(&mut r, 2));
assert_eq!(base_row(&r, &active_rows(&r)), Some(2));
assert!(set_base(&mut r, 1));
assert_eq!(r.iter().filter(|x| x[BASE] == json!(true)).count(), 1, "one base mark: {r:?}");
assert!(!set_base(&mut r, 1));
r[2]["exclude"] = json!(true);
assert!(!set_base(&mut r, 2), "an excluded row isn't shown");
assert!(!set_base(&mut r, 9));
// An excluded base row leaves the first row shown as the base.
r[1]["exclude"] = json!(true);
assert_eq!(base_row(&r, &active_rows(&r)), Some(0));
// Setting that row as the base keeps it the base once the marked row is shown again.
assert!(set_base(&mut r, 0), "the hidden row's mark moves to it");
r[1]["exclude"] = json!(false);
assert_eq!(base_row(&r, &active_rows(&r)), Some(0), "{r:?}");
}
/// Merge and Separate keep the base mark on a row of the base color's colors; Randomize's rows
/// (as the engine returns them) take the marks at their places again; `recolor.apply` gets no marks.
#[test]
fn the_base_mark_follows_merge_separate_and_randomize() {
let mut r = rows();
set_base(&mut r, 2);
merge(&mut r, &[0, 2]);
assert_eq!(r[0][BASE], json!(true), "merged into the first row: {r:?}");
let mut r = rows();
set_base(&mut r, 1);
separate(&mut r, &[1]);
assert_eq!(r.len(), 4);
assert_eq!((r[1][BASE].clone(), r[2].get(BASE)), (json!(true), None), "{r:?}");
// A marker's tie goes with it too.
let mut t = rows();
t[1][TIE] = json!(1);
separate(&mut t, &[1]);
assert_eq!((t[1][TIE].clone(), t[2].get(TIE)), (json!(1), None));
let mut t = rows();
t[0][TIE] = json!(1);
t[2][TIE] = json!(3);
t.push(json!({"from": [], "to": "rgb 1 2 3", "follows": 3}));
merge(&mut t, &[0, 2]);
assert_eq!((t[0][TIE].clone(), t[2][FOLLOWS].clone()), (json!(1), json!(1)), "its follower follows the row merged into: {t:?}");
let before = r.clone();
let mut shuffled: Vec<Value> = r.iter().map(without_marks).collect();
assert!(shuffled.iter().all(|x| x.get(BASE).is_none()));
keep_marks(&before, &mut shuffled);
assert_eq!(shuffled, before);
let mut fewer = vec![json!({"from": [], "to": "rgb 1 1 1"})];
keep_marks(&before, &mut fewer);
assert!(fewer[0].get(BASE).is_none(), "rows of another count take no marks");
let mut d = Dialog::new(KIND, json!({}));
d.fields.insert("rows".into(), json!(before));
assert!(apply_params(&d)["map"].as_array().unwrap().iter().all(|x| x.get(BASE).is_none()));
}
/// A color added on a marker's line moves with that marker when the colors are unlinked; it
/// moves alone itself, and linked colors all move together as before.
#[test]
fn a_color_added_on_a_markers_line_moves_with_it() {
let hue = |r: &[Value], i: usize| to_color(&r[i]).unwrap().to_hsb()[0];
let mut r = rows();
let added = add_color(&mut r, &Color::from_hsb(240.0, 0.5, 1.0));
tie_to(&mut r, 1, added);
assert_eq!((r[1][TIE].clone(), r[added][FOLLOWS].clone()), (json!(1), json!(1)));
move_color(&mut r, 1, [270.0, 1.0, 1.0], false);
assert!((hue(&r, added) - 270.0).abs() < 0.5, "the added color turns with its marker: {}", hue(&r, added));
assert!((hue(&r, 0) - 0.0).abs() < 0.5 && (hue(&r, 2) - 120.0).abs() < 0.5, "the others stay");
move_color(&mut r, added, [300.0, 0.5, 1.0], false);
assert!((hue(&r, 1) - 270.0).abs() < 0.5, "its marker stays");
// A second color tied to the same marker shares its number.
let next = add_color(&mut r, &Color::from_hsb(270.0, 0.2, 1.0));
tie_to(&mut r, 1, next);
assert_eq!(r[next][FOLLOWS], json!(1));
let other = add_color(&mut r, &Color::from_hsb(0.0, 0.2, 1.0));
tie_to(&mut r, 0, other);
assert_eq!(r[0][TIE], json!(2), "another marker takes a new number");
tie_to(&mut r, 0, 0);
assert!(r[0].get(FOLLOWS).is_none(), "a row isn't tied to itself");
// Colors left from a removed marker follow no marker tied later.
let mut r = rows();
let added = add_color(&mut r, &Color::from_hsb(240.0, 0.5, 1.0));
tie_to(&mut r, 1, added);
r.remove(1);
let next = add_color(&mut r, &Color::from_hsb(0.0, 0.5, 1.0));
tie_to(&mut r, 0, next);
assert_eq!(r[0][TIE], json!(2), "{r:?}");
// A color added on an added color's line moves with the first marker too.
let mut r = rows();
let added = add_color(&mut r, &Color::from_hsb(240.0, 0.5, 1.0));
tie_to(&mut r, 1, added);
let chained = add_color(&mut r, &Color::from_hsb(240.0, 0.25, 1.0));
tie_to(&mut r, added, chained);
move_color(&mut r, 1, [250.0, 1.0, 1.0], false);
assert!((hue(&r, chained) - 250.0).abs() < 0.5, "{r:?}");
}
/// Select Shade's grid runs from 0% to 100% saturation across and from 100% brightness down.
#[test]
fn the_shade_grid_spans_saturation_and_brightness() {
assert_eq!(shade_at(0, 0), [0.0, 1.0]);
assert_eq!(shade_at(SHADE_COLS - 1, 0)[0], 1.0);
let last = shade_at(0, SHADE_ROWS - 1)[1];
assert!(last > 0.0 && last < 0.2, "{last}");
}
/// A row made with New Row is not on the Edit tab while it is empty: a harmony rule gives it
/// no color and a linked move leaves its new color as it is.
#[test]
@@ -3407,6 +3924,41 @@ mod tests {
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 2, "a step for each group");
}
/// A color removed on the Edit tab leaves its row with no new color, and neither Save All
/// Colors, Save Prominent Colors nor OK on colors opened alone puts the row's current color in
/// the new color group.
#[test]
fn a_removed_color_joins_no_saved_color_group() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
let ctx = egui::Context::default();
prominent_setup(&mut app, &ctx);
let last = |app: &VectorcraftApp| -> Vec<String> {
let doc = &app.session.doc().unwrap().doc;
doc.swatch_groups.last().unwrap().swatches.iter().map(|w| w.paint.color().unwrap().to_hex()).collect()
};
let d = app.ui.dialog.as_mut().unwrap();
d.fields.insert("rows".into(), json!([{"from": [BLUE], "to": null}, {"from": [RED, PURPLE], "to": "rgb 0 255 0"}]));
d.fields.insert(SAVE_GROUP.into(), json!("all"));
frame(&mut app, &ctx, 0.1, vec![], 0);
frame(&mut app, &ctx, 0.11, vec![], 0);
assert_eq!(last(&app), ["#00ff00"], "Save All Colors");
let n = app.session.doc().unwrap().doc.swatch_groups.len();
app.ui.dialog.as_mut().unwrap().fields.insert(SAVE_GROUP.into(), json!("prominent"));
frame(&mut app, &ctx, 0.2, vec![], 0);
frame(&mut app, &ctx, 0.21, vec![], 0);
assert_eq!(app.session.doc().unwrap().doc.swatch_groups.len(), n + 1, "Save Prominent Colors makes a group");
assert_eq!(last(&app), ["#00ff00"], "Save Prominent Colors");
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
app.run("ui.recolorDialog", json!({"colors": ["#ff0000", "#0000ff"]})).unwrap();
let d = app.ui.dialog.as_mut().unwrap();
d.fields.insert("rows".into(), json!([{"from": ["rgb 255 0 0"], "to": "rgb 255 0 0"}, {"from": ["rgb 0 0 255"], "to": null}]));
let d = d.clone();
confirm(&mut app, &d).unwrap();
assert_eq!(last(&app), ["#ff0000"], "OK on colors opened alone");
}
/// Save All Colors leaves out a row made with New Row while it is empty; with only empty rows
/// it saves no group and records no step.
#[test]
@@ -3794,6 +4346,31 @@ mod tests {
assert_eq!(group_hex(&app, "A"), Some(vec!["#ff0000".into(), "#00ff00".into()]), "other groups are left as they are");
}
/// Without art: rows of a group picked in the list keep their swatches when a color bar moves,
/// at OK and at Save Changes, and an excluded row's swatch stays as it is.
#[test]
fn a_moved_row_of_a_listed_group_keeps_its_swatch_at_save_changes() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
app.run("swatch.newGroup", json!({"name": "A", "colors": ["#000000"], "keepModel": true})).unwrap();
app.run("swatch.newGroup", json!({"name": "G", "colors": ["#ff0000", "#0000ff", "#00ff00"], "keepModel": true})).unwrap();
app.run("ui.recolorDialog", json!({"group": "A"})).unwrap();
set(&mut app, "group", json!("G")).unwrap();
let d = app.ui.dialog.as_mut().unwrap();
let mut rs = super::rows(d);
rs[1]["exclude"] = json!(true);
rs[2]["to"] = json!("#ffff00");
let active = active_rows(&rs);
// Drag the last bar (green, now yellow) above the first (red).
assert_eq!(move_bar(&mut rs, &active, 1, 0), Some(0));
d.fields.insert("rows".into(), Value::Array(rs));
assert_eq!(apply_params(d)["groupColors"][1], json!("keep"));
act(&mut app, &ctx, 0.1, "save").unwrap();
assert_eq!(group_hex(&app, "G"), Some(vec!["#ff0000".into(), "#0000ff".into(), "#ffff00".into()]));
}
/// Without art: selecting another color group in the list and Save Changes leave Undo Changes
/// and Redo Changes no step to go to, so OK gives the selected group the rows read for it.
#[test]
+20 -1
View File
@@ -232,7 +232,7 @@ pub(crate) fn browser_preview(app: &mut VectorcraftApp, p: &Value) -> Result<Val
o.insert("path".into(), json!(path));
o.insert("output".into(), json!("html"));
}
let r = app.run("document.exportForWeb", q)?;
let r = app.run("document.exportForWeb", q).inspect_err(|_| remove_preview_folder(&dir))?;
app.open_url(&io::file_url(&path));
if has_warnings(&r) {
io::report_saved(app, &path, &r);
@@ -257,9 +257,28 @@ fn temp_folder() -> Result<String, String> {
/// `root` ([`preview_folder_under`]).
#[cfg(not(target_arch = "wasm32"))]
pub(super) fn temp_folder_under(root: &str) -> Result<String, String> {
#[cfg(test)]
if let Some(tmp) = TEST_TMP.with_borrow(Clone::clone) {
return preview_folder_under(&tmp, root, PREVIEW_KEEP);
}
preview_folder_under(&std::env::temp_dir(), root, PREVIEW_KEEP)
}
#[cfg(all(test, not(target_arch = "wasm32")))]
thread_local! {
/// The folder this test thread's browser previews go to instead of the system's temporary
/// folder, when set.
pub(super) static TEST_TMP: std::cell::RefCell<Option<std::path::PathBuf>> = const { std::cell::RefCell::new(None) };
}
/// Remove the folder `dir` made for a browser preview whose files could not all be written, so
/// a failed preview leaves no folder behind. The log says when it can't be removed.
pub(super) fn remove_preview_folder(dir: &str) {
if let Err(e) = std::fs::remove_dir_all(dir) {
log::warn!("vectorcraft: the browser preview folder {dir} can't be removed: {e}");
}
}
/// A new folder for a Save for Web browser preview in the temporary folder `tmp`
/// ([`preview_folder_under`] with `VectorCraft Save for Web`).
#[cfg(all(test, not(target_arch = "wasm32")))]
+30 -4
View File
@@ -354,7 +354,8 @@ fn encode_page<'a>(
/// the default browser (desktop) → `{path, warnings}`. Nothing is written to the chosen
/// destination, and the document, its path and the remembered choices are left as they were.
/// When the export has warnings, the status bar shows them as [`io::report_saved`] shows a save's
/// notes. Nothing opens when a check, the encoding or a write fails.
/// notes. Nothing opens when a check, the encoding or a write fails, and a failed write removes
/// the new folder.
pub(crate) fn browser_preview(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
if io::is_web(app) {
return Err("no file system here".into());
@@ -370,7 +371,7 @@ pub(crate) fn browser_preview(app: &mut VectorcraftApp, p: &Value) -> Result<Val
let target = format!("{dir}/{}.svg", super::save_for_web::preview_name(&stem));
let named = enc.named(&doc, &target);
for (p, bytes) in &named {
io::write_to(&mut app.services, p, bytes)?;
io::write_to(&mut app.services, p, bytes).inspect_err(|_| super::save_for_web::remove_preview_folder(&dir))?;
}
(named.first().map_or(target, |(p, _)| p.clone()), enc.notes())
};
@@ -480,8 +481,12 @@ mod tests {
type Opened = Rc<RefCell<Vec<String>>>;
/// [`app`] whose browser records each URL it is asked to open.
/// [`app`] whose browser records each URL it is asked to open. Its previews go to a temporary
/// folder of the test's own ([`preview_tmp`]), not the system's.
fn browsing(picked: &str) -> (VectorcraftApp, Written, Opened) {
static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let tmp = vectorcraft_testkit::temp_dir(&format!("svg-browser-{}", N.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
super::super::save_for_web::TEST_TMP.set(Some(tmp));
let (mut app, written) = app(picked);
let opened = Opened::default();
let o = opened.clone();
@@ -489,6 +494,13 @@ mod tests {
(app, written, opened)
}
/// The SVG preview folder inside this test's temporary folder ([`browsing`]), with `/` between
/// its parts.
fn preview_tmp() -> String {
let tmp = super::super::save_for_web::TEST_TMP.with_borrow(Clone::clone).expect("browsing sets the temporary folder");
tmp.join(PREVIEW_ROOT).to_string_lossy().replace('\\', "/")
}
/// Show in Browser for the open dialog's current choices, as its button runs it.
fn show_in_browser(app: &mut VectorcraftApp) -> Result<Value, String> {
let p = preview_params(app.ui.dialog.as_ref().expect("SVG Options open"));
@@ -510,7 +522,7 @@ mod tests {
let remembered = app.ui.svg_options.clone();
let r = show_in_browser(&mut app).unwrap_or_else(|e| panic!("{e}"));
let path = r["path"].as_str().unwrap().to_string();
assert!(path.contains("/VectorCraft SVG Preview/") && path.ends_with("/Untitled-1.svg"), "{path}");
assert!(path.starts_with(&format!("{}/", preview_tmp())) && path.ends_with("/Untitled-1.svg"), "{path}");
assert_eq!(*opened.borrow(), [io::file_url(&path)]);
assert_eq!(written.borrow().len(), 1);
assert_eq!(written.borrow()[0].0, path);
@@ -538,6 +550,18 @@ mod tests {
assert!(app.ui.dialog.is_some());
}
/// A write that fails opens nothing and removes the folder made for that preview.
#[test]
fn show_in_browser_removes_its_folder_when_a_write_fails() {
let (mut app, _, opened) = browsing("/tmp/out.svg");
app.services.write = Some(Box::new(|_: &str, _: &[u8]| Err("disk full".to_string())));
app.run("file.export.svg", Value::Null).unwrap();
assert!(show_in_browser(&mut app).unwrap_err().contains("disk full"));
assert!(opened.borrow().is_empty());
let left: Vec<_> = std::fs::read_dir(preview_tmp()).map(|d| d.flatten().map(|e| e.file_name()).collect()).unwrap_or_default();
assert!(left.is_empty(), "{left:?}");
}
/// Under Export Selection the preview is the selection alone, cropped to it, as OK writes it.
#[test]
fn show_in_browser_under_export_selection_shows_the_selection() {
@@ -606,7 +630,9 @@ mod tests {
app.ui.answering_control = true;
assert!(show_in_browser(&mut app).unwrap_err().contains("opens another app"));
app.ui.answering_control = false;
assert!(crate::menus::enabled(&app, BROWSER));
app.services.download = Some(Box::new(|_: &str, _: &[u8]| Ok(())));
assert!(!crate::menus::enabled(&app, BROWSER), "the command palette and menus show it disabled on the web");
assert!(show_in_browser(&mut app).is_err());
assert!(written.borrow().is_empty() && opened.borrow().is_empty());
}
@@ -385,6 +385,8 @@ fn the_web_downloads_and_has_no_browser_preview() {
let log = log.borrow().clone();
assert!(log[0].starts_with("download Untitled-1.html ") && log[1].starts_with("download Untitled-1.png "), "{log:?}");
assert!(app.run("file.saveForWeb.browser", json!({})).is_err());
assert!(crate::menus::enabled(&app, "file.saveForWeb"));
assert!(!crate::menus::enabled(&app, "file.saveForWeb.browser"), "the command palette and menus show it disabled on the web");
}
#[test]
@@ -414,6 +416,19 @@ fn preview_in_browser_opens_the_page() {
assert!(log.last().unwrap().starts_with("open file://") && log.last().unwrap().ends_with("Untitled-1.html"), "{log:?}");
}
/// A preview whose export fails opens nothing and removes the folder made for it.
#[test]
fn a_failed_browser_preview_removes_its_folder() {
let tmp = vectorcraft_testkit::temp_dir("sfw-browser-failed");
save_for_web::TEST_TMP.set(Some(tmp.clone()));
let (mut app, log) = app(&tmp, false);
assert!(app.run("file.saveForWeb.browser", json!({"format": "bogus"})).is_err());
assert!(!log.borrow().iter().any(|l| l.starts_with("open ")), "{:?}", log.borrow());
let left: Vec<_> =
std::fs::read_dir(tmp.join("VectorCraft Save for Web")).map(|d| d.flatten().map(|e| e.file_name()).collect()).unwrap_or_default();
assert!(left.is_empty(), "{left:?}");
}
/// Each preview has its own folder: a second one, from another app or the same one, leaves the
/// first page and its image as they were.
#[test]
+5
View File
@@ -124,6 +124,11 @@ pub fn open_tool_dialog(app: &mut VectorcraftApp, kind: &str, p: Value) {
}
// Double-clicking a stop on the gradient annotator: its popover, next to the stop's chip.
"gradientStop" => Dialog::new(kind, json!({"index": p.get("index").cloned().unwrap_or(json!(0)), "x": x, "y": y, "tab": "color"})),
// Image Trace's Ignore Color eyedropper updates the panel, not the document's paint.
"imageTraceIgnoreColor" => {
crate::panels::image_trace::apply_ignore_color_sample(app, &p);
return;
}
// Brush Options › Key Color eyedropper: update the open dialog, do not replace it.
"brushKeyColor" => {
if let Some(c) = p.get("color") {
+12
View File
@@ -1630,6 +1630,10 @@ font-technology Variable Променливи
Add Color Tool Инструмент „Добавяне на цвят“
Remove Color Tool Инструмент „Премахване на цвят“
Remove Color Премахване на цвят
Set As Base Color Задаване като основен цвят
Select Shade Избор на нюанс
Add New Color Добавяне на нов цвят
Set Current Color As Base Color Задаване на текущия цвят като основен
Find the selected colors in the artwork Намиране на избраните цветове в илюстрацията
Harmony Sets Набори от хармонии
Height Височина
@@ -2014,6 +2018,7 @@ font-technology Variable Променливи
Limit to Library: Ограничаване до библиотека:
Limit: Ограничение:
Line Линия
Line Arrow Линейна стрелка
Line Art and Text Resolution: Разделителна способност на линеарна графика и текст:
Line Breaks Паузи на редове
Line Color Цвят на линията
@@ -5848,6 +5853,7 @@ lighting Light Светлина
B5 B5
Bar Лента
Barbed С кукички
arrowhead Feather Перо
Baseline (Standard) Основна линия (стандартна)
Baseline Optimized Оптимизирана основна линия
Basic Основен
@@ -7451,6 +7457,7 @@ breakText Glyphs Глифи
Remove Strokes Премахване на щрихи
Place Brush Art Поставяне на графика на четка
Replace Brush Art Замяна на графика на четка
Replace Pattern Art Замяна на графика на мостра
Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Щрихи използват тази четка. Да се приложи ли новата графика към тези щрихи, или те да останат както са и да се добави копие на четката с новата графика?
Apply to Strokes Прилагане към щрихите
Leave Strokes Оставяне на щрихите
@@ -7866,6 +7873,11 @@ breakText Glyphs Глифи
@msg A joint does not close by {gap} pt. Една връзка не се затваря с {gap} pt.
@msg Two panels pass through each other. Два панела минават един през друг.
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer трябва да е "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine"
Engraving Гравюра
Fine Hatching Фино щриховане
Dense Hatching Гъсто щриховане
Tapered Hatching Изтъняващо щриховане
Broken Hatching Прекъснато щриховане
Image Brush Четки за изображения
Soft Bloom Мек цъфтеж
Halftone Field Полутоново поле
Can't render this file because it is too large.
+12
View File
@@ -3106,6 +3106,10 @@ digits Malayalam Malajalam
Add Color Tool Alat za dodavanje boje
Remove Color Tool Alat za uklanjanje boje
Remove Color Ukloni boju
Set As Base Color Postavi kao osnovnu boju
Select Shade Odaberi nijansu
Add New Color Dodaj novu boju
Set Current Color As Base Color Postavi trenutnu boju kao osnovnu
Find the selected colors in the artwork Pronađi odabrane boje u crtežu
Harmony Rules Pravila harmonije
Keep this row's colors (exclude) Zadrži boje ovog reda (isključi)
@@ -6053,6 +6057,7 @@ imageTrace Outline Obris
Arrow Strelica
Arrow (open) Strelica (otvorena)
Barbed Bodljikavo
arrowhead Feather Pero
Half Arrow (left) Polustrelica (lijevo)
Half Arrow (right) Polustrelica (desno)
Concave Konkavno
@@ -6080,6 +6085,7 @@ imageTrace Outline Obris
Kite Zmaj
Triangle to Bar Trougao u traku
Oval Oval
Line Arrow Linijska strelica
Complementary Komplementarne
Complementary 2 Komplementarne 2
Split Complementary Podijeljene komplementarne
@@ -7500,6 +7506,7 @@ shape Open Otvoren
Remove Strokes Ukloni poteze
Place Brush Art Postavi crtež četkice
Replace Brush Art Zamijeni crtež četkice
Replace Pattern Art Zamijeni crtež uzorka
Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Potezi koriste ovu četkicu. Primijeniti novi crtež na te poteze ili ih ostaviti kakvi jesu i dodati kopiju četkice s novim crtežom?
Apply to Strokes Primijeni na poteze
Leave Strokes Ostavi poteze
@@ -7921,6 +7928,11 @@ shape Open Otvoren
@msg A joint does not close by {gap} pt. Spoj se ne zatvara za {gap} pt.
@msg Two panels pass through each other. Dva panela prolaze jedan kroz drugi.
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer mora biti "singleLine", "everyLine", "standardSingleLine" ili "standardEveryLine"
Engraving Gravura
Fine Hatching Fino šrafiranje
Dense Hatching Gusto šrafiranje
Tapered Hatching Suženo šrafiranje
Broken Hatching Isprekidano šrafiranje
Image Brush Slikovni kistovi
Soft Bloom Meko cvjetanje
Halftone Field Polutonsko polje
Can't render this file because it contains an unexpected character in line 2 and column 73.
+14
View File
@@ -456,6 +456,8 @@ antiAlias Sharp Nítid
Bar Barra
Bar Graph Tool Eina de gràfic de barres
Barbed Amb pues
arrowhead Feather Ploma
arrowhead Target Diana
Bas Relief Baix relleu
Bas Relief… Baix relleu…
Base Along: Base al llarg de:
@@ -2199,6 +2201,10 @@ digits Malayalam Malaiàlam
Add Color Tool Eina Afegeix color
Remove Color Tool Eina Elimina color
Remove Color Elimina el color
Set As Base Color Defineix com a color base
Select Shade Selecciona el to
Add New Color Afegeix un color nou
Set Current Color As Base Color Defineix el color actual com a color base
Find the selected colors in the artwork Troba els colors seleccionats a l’obra
Harmony Sets Conjunts d’harmonia
HDTV 1080p HDTV 1080p
@@ -2610,6 +2616,7 @@ digits Malayalam Malaiàlam
Limit: Límit:
Limited Limitat
Line Línia
Line Arrow Fletxa de línies
Line Art Art lineal
Line Art and Text Resolution: Resolució de l’art lineal i del text:
Line Breaks Salts de línia
@@ -6841,6 +6848,7 @@ liquify-list-end {0}, {1} {0} i {1}
@msg no native format no hi ha format natiu
@msg no pages no hi ha pàgines
@msg no pattern `{name}` no hi ha el motiu `{name}`
@msg art painted with `{name}` can't be its tile un art pintat amb `{name}` no pot ser el seu mosaic
@msg no pattern swatch `{name}` no hi ha la mostra de motiu `{name}`
@msg no perspective grid preset named `{name}` no hi ha cap preajust de quadrícula de perspectiva anomenat `{name}`
@msg no plug-in {0} is installed no hi ha instal·lat el complement {0}
@@ -8317,6 +8325,7 @@ breakText Glyphs Glifs
Remove Strokes Elimina els traços
Place Brush Art Col·loca l’art del pinzell
Replace Brush Art Substitueix l’art del pinzell
Replace Pattern Art Substitueix l’art del motiu
Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Hi ha traços que fan servir aquest pinzell. Voleu aplicar l’art nou a aquests traços, o deixar-los com estan i afegir una còpia del pinzell amb l’art nou?
Apply to Strokes Aplica als traços
Leave Strokes Deixa els traços
@@ -8896,6 +8905,11 @@ breakText Glyphs Glifs
@msg A joint does not close by {gap} pt. Una unió no es tanca per {gap} pt.
@msg Two panels pass through each other. Dos panells es travessen l’un a l’altre.
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer ha de ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine"
Engraving Gravat
Fine Hatching Ratllat fi
Dense Hatching Ratllat dens
Tapered Hatching Ratllat afilat
Broken Hatching Ratllat interromput
Image Brush Pinzells d'imatge
Soft Bloom Floració suau
Halftone Field Camp de semitons
Can't render this file because it is too large.
+13
View File
@@ -3189,6 +3189,10 @@ digits Malayalam Malajálamské
Add Color Tool Nástroj Přidat barvu
Remove Color Tool Nástroj Odstranit barvu
Remove Color Odstranit barvu
Set As Base Color Nastavit jako základní barvu
Select Shade Vybrat odstín
Add New Color Přidat novou barvu
Set Current Color As Base Color Nastavit aktuální barvu jako základní
Find the selected colors in the artwork Najít vybrané barvy v kresbě
Harmony Rules Pravidla harmonie
Keep this row's colors (exclude) Ponechat barvy tohoto řádku (vyloučit)
@@ -5717,6 +5721,7 @@ liquify-list-end {0}, {1} {0} a {1}
@msg no native format chybí nativní formát
@msg no pages žádné stránky
@msg no pattern `{name}` vzorek `{name}` neexistuje
@msg art painted with `{name}` can't be its tile kresba vybarvená vzorkem `{name}` nemůže být jeho dlaždicí
@msg no perspective grid preset named `{name}` přednastavení perspektivní mřížky s názvem `{name}` neexistuje
@msg no plug-in {0} is installed zásuvný modul {0} není nainstalován
@msg no plug-in {id} is installed zásuvný modul {id} není nainstalován
@@ -6504,6 +6509,7 @@ variable-list-end {0}, {1} {0} a {1}
Arrow Šipka
Arrow (open) Šipka (otevřená)
Barbed S protihroty
arrowhead Feather Pírko
Half Arrow (left) Poloviční šipka (vlevo)
Half Arrow (right) Poloviční šipka (vpravo)
Concave Vkleslá
@@ -6531,6 +6537,7 @@ variable-list-end {0}, {1} {0} a {1}
Kite Deltoid
Triangle to Bar Trojúhelník k příčce
Oval Ovál
Line Arrow Čárová šipka
# Colour harmony rules (Color Guide, Recolor Artwork, Color Themes)
Complementary Komplementární
Complementary 2 Komplementární 2
@@ -8299,6 +8306,7 @@ breakText Glyphs Glyfy
Remove Strokes Odebrat tahy
Place Brush Art Umístit kresbu štětce
Replace Brush Art Nahradit kresbu štětce
Replace Pattern Art Nahradit kresbu vzorku
Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Tahy používají tento štětec. Použít novou kresbu na tyto tahy, nebo je ponechat beze změny a přidat kopii štětce s novou kresbou?
Apply to Strokes Použít na tahy
Leave Strokes Ponechat tahy
@@ -10721,6 +10729,11 @@ breakText Glyphs Glyfy
@msg A panel is not joined to the rest by a crease. Panel není se zbytkem spojen žádnou linií bigu.
@msg A fold line is on a non-printing layer. Linie skladu je na netisknutelné vrstvě.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panely: {panels}, panty: {hinges}, chyby: {errors}, upozornění: {warnings}
Engraving Rytina
Fine Hatching Jemné šrafování
Dense Hatching Husté šrafování
Tapered Hatching Zúžené šrafování
Broken Hatching Přerušované šrafování
Image Brush Obrazové štětce
Soft Bloom Jemný květ
Halftone Field Polotónové pole
Can't render this file because it is too large.
+13
View File
@@ -5713,6 +5713,10 @@ digits Malayalam Malayalam
Add Color Tool Værktøjet Tilføj farve
Remove Color Tool Værktøjet Fjern farve
Remove Color Fjern farve
Set As Base Color Angiv som grundfarve
Select Shade Vælg nuance
Add New Color Tilføj ny farve
Set Current Color As Base Color Angiv aktuel farve som grundfarve
Find the selected colors in the artwork Find de valgte farver i grafikken
Harmony Rules Harmoniregler
Keep this row's colors (exclude) Behold farverne i denne række (ekskludér)
@@ -7911,6 +7915,7 @@ imageTrace Outline Kontur
@msg no native format intet indbygget format
@msg no pages ingen sider
@msg no pattern `{name}` intet mønster `{name}`
@msg art painted with `{name}` can't be its tile grafik malet med `{name}` kan ikke være dens flise
@msg no perspective grid preset named `{name}` ingen perspektivgitterforudindstilling med navnet `{name}`
@msg no plug-in {0} is installed plug-in'et {0} er ikke installeret
@msg no plug-in {id} is installed plug-in'et {id} er ikke installeret
@@ -8580,6 +8585,7 @@ imageTrace Outline Kontur
Arrow Pil
Arrow (open) Pil (åben)
Barbed Modhager
arrowhead Feather Fjer
Half Arrow (left) Halvpil (venstre)
Half Arrow (right) Halvpil (højre)
Concave Konkav
@@ -8607,6 +8613,7 @@ imageTrace Outline Kontur
Kite Drage
Triangle to Bar Trekant til bjælke
Oval Oval
Line Arrow Stregpil
Complementary Komplementær
Complementary 2 Komplementær 2
Split Complementary Delt komplementær
@@ -10355,6 +10362,7 @@ breakText Glyphs Glyffer
Remove Strokes Fjern streger
Place Brush Art Placér penselgrafik
Replace Brush Art Erstat penselgrafik
Replace Pattern Art Erstat mønstergrafik
Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Streger bruger denne pensel. Anvend den nye grafik på stregerne, eller lad dem være, som de er, og tilføj en kopi af penslen med den nye grafik?
Apply to Strokes Anvend på streger
Leave Strokes Bevar streger
@@ -10783,6 +10791,11 @@ breakText Glyphs Glyffer
@msg A joint does not close by {gap} pt. En samling lukker ikke med {gap} pt.
@msg Two panels pass through each other. To paneler går gennem hinanden.
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer skal være "singleLine", "everyLine", "standardSingleLine" eller "standardEveryLine"
Engraving Gravering
Fine Hatching Fin skravering
Dense Hatching Tæt skravering
Tapered Hatching Tilspidset skravering
Broken Hatching Afbrudt skravering
Image Brush Billedpensler
Soft Bloom Blød blomstring
Halftone Field Halvtonefelt
Can't render this file because it is too large.
+41
View File
@@ -1694,6 +1694,10 @@ file-filter Templates Vorlagen
Add Color Tool Farbe-hinzufügen-Werkzeug
Remove Color Tool Farbe-entfernen-Werkzeug
Remove Color Farbe entfernen
Set As Base Color Als Grundfarbe festlegen
Select Shade Schattierung auswählen
Add New Color Neue Farbe hinzufügen
Set Current Color As Base Color Aktuelle Farbe als Grundfarbe festlegen
Find the selected colors in the artwork Ausgewählte Farben in der Grafik finden
Harmony Sets Harmoniesätze
Height Höhe
@@ -5294,6 +5298,7 @@ liquify-list-end {0}, {1} {0} und {1}
@msg no native format kein natives Format
@msg no pages keine Seiten
@msg no pattern `{name}` kein Muster `{name}`
@msg art painted with `{name}` can't be its tile mit `{name}` gefärbtes Bildmaterial kann nicht dessen Kachel sein
@msg no perspective grid preset named `{name}` keine Vorgabe für Perspektivenraster namens `{name}`
@msg no plug-in {0} is installed es ist kein Plug-in {0} installiert
@msg no plug-in {id} is installed es ist kein Plug-in {id} installiert
@@ -7605,6 +7610,36 @@ anchor Points: Punkte:
@msg `{id}` is not a colour adjustment `{id}` ist keine Farbkorrektur
@msg missing `effect` `effect` fehlt
@msg `params` must be an object `params` muss ein Objekt sein
# Stroke arrowheads (Stroke panel, Dimension Tool Options and Properties › Arrow Style).
Triangle (open) Dreieck (offen)
Circle (open) Kreis (offen)
Square (open) Quadrat (offen)
Arrow (open) Pfeil (offen)
Barbed Mit Widerhaken
arrowhead Feather Feder
Half Arrow (left) Halber Pfeil (links)
Half Arrow (right) Halber Pfeil (rechts)
Double Bar Doppelbalken
Dot on Bar Punkt auf Balken
Chevron Winkel
Plus Plus
Hexagon (open) Sechseck (offen)
Tag Etikett
Tag (open) Etikett (offen)
Half Circle Halbkreis
Drop Tropfen
Slash Schrägstrich
Double Slash Doppelter Schrägstrich
Diamond (open) Raute (offen)
Reverse Triangle Umgekehrtes Dreieck
Swallowtail Schwalbenschwanz
Bracket Klammer
Fork Gabel
Leaf Blatt
Kite Drachen
Triangle to Bar Dreieck zu Balken
Oval Oval
Line Arrow Linienpfeil
# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages.
Path Precision Tools Pfad-Präzisionswerkzeuge
Anchor Eraser Brush Ankerpunkt-Radierpinsel
@@ -7895,6 +7930,7 @@ breakText Glyphs Glyphen
Remove Strokes Konturen entfernen
Place Brush Art Pinselgrafik platzieren
Replace Brush Art Pinselgrafik ersetzen
Replace Pattern Art Mustergrafik ersetzen
Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Konturen verwenden diesen Pinsel. Die neue Grafik auf diese Konturen anwenden oder sie unverändert lassen und eine Kopie des Pinsels mit der neuen Grafik hinzufügen?
Apply to Strokes Auf Konturen anwenden
Leave Strokes Konturen beibehalten
@@ -10334,6 +10370,11 @@ breakText Glyphs Glyphen
@msg A panel is not joined to the rest by a crease. Ein Feld ist durch keine Rilllinie mit den übrigen verbunden.
@msg A fold line is on a non-printing layer. Eine Faltlinie liegt auf einer nicht druckbaren Ebene.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Felder: {panels}, Scharniere: {hinges}, Fehler: {errors}, Warnungen: {warnings}
Engraving Gravur
Fine Hatching Feine Schraffur
Dense Hatching Dichte Schraffur
Tapered Hatching Verjüngte Schraffur
Broken Hatching Unterbrochene Schraffur
Image Brush Bildpinsel
Soft Bloom Sanfte Blüte
Halftone Field Rasterfeld
Can't render this file because it is too large.
+13
View File
@@ -1617,6 +1617,10 @@ font-technology Variable Μεταβλητές
Add Color Tool Εργαλείο προσθήκης χρώματος
Remove Color Tool Εργαλείο αφαίρεσης χρώματος
Remove Color Αφαίρεση χρώματος
Set As Base Color Ορισμός ως βασικό χρώμα
Select Shade Επιλογή απόχρωσης
Add New Color Προσθήκη νέου χρώματος
Set Current Color As Base Color Ορισμός τρέχοντος χρώματος ως βασικού
Find the selected colors in the artwork Εύρεση των επιλεγμένων χρωμάτων στο σχέδιο
Harmony Sets Σύνολα χρωματικής αρμονίας
Height Ύψος
@@ -1976,6 +1980,7 @@ font-technology Variable Μεταβλητές
Lighten Φώτισμα
Lightness Φωτεινότητα
Line Γραμμή
Line Arrow Γραμμικό βέλος
Line Segment Tool Ευθύγραμμο τμήμα (Line Segment Tool)
Linear Gradient Γραμμικό ντεγκραντέ
Lines Γραμμές
@@ -5353,6 +5358,7 @@ digits Malayalam Μαλαγιάλαμ
@msg no native format δεν υπάρχει εγγενής μορφή
@msg no pages δεν υπάρχουν σελίδες
@msg no pattern `{name}` δεν υπάρχει μοτίβο `{name}`
@msg art painted with `{name}` can't be its tile σχέδιο βαμμένο με `{name}` δεν μπορεί να είναι το πλακίδιό του
@msg no perspective grid preset named `{name}` δεν υπάρχει προεπιλογή πλέγματος προοπτικής με όνομα `{name}`
@msg no plug-in {0} is installed δεν είναι εγκατεστημένο το πρόσθετο {0}
@msg no plug-in {id} is installed δεν είναι εγκατεστημένο το πρόσθετο {id}
@@ -6290,6 +6296,7 @@ variable-list-end {0}, {1} {0} και {1}
Auto Size Αυτόματο μέγεθος
Bar Ράβδος
Barbed Αγκιστρωτό
arrowhead Feather Φτερό
Baseline (Standard) Γραμμή βάσης (τυπική)
Baseline Optimized Βελτιστοποιημένο για γραμμή βάσης
Black Outline Μαύρο περίγραμμα
@@ -8290,6 +8297,7 @@ breakText Glyphs Γλύφοι
Remove Strokes Αφαίρεση περιγραμμάτων
Place Brush Art Τοποθέτηση σχεδίου πινέλου
Replace Brush Art Αντικατάσταση σχεδίου πινέλου
Replace Pattern Art Αντικατάσταση σχεδίου μοτίβου
Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Περιγράμματα χρησιμοποιούν αυτό το πινέλο. Να εφαρμοστεί το νέο σχέδιο σε αυτά τα περιγράμματα ή να μείνουν ως έχουν και να προστεθεί αντίγραφο του πινέλου με το νέο σχέδιο;
Apply to Strokes Εφαρμογή στα περιγράμματα
Leave Strokes Διατήρηση περιγραμμάτων
@@ -8870,6 +8878,11 @@ breakText Glyphs Γλύφοι
@msg A joint does not close by {gap} pt. Μια ένωση δεν κλείνει κατά {gap} pt.
@msg Two panels pass through each other. Δύο πάνελ διαπερνούν το ένα το άλλο.
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" το composer πρέπει να είναι "singleLine", "everyLine", "standardSingleLine" ή "standardEveryLine"
Engraving Χαρακτική
Fine Hatching Λεπτή διαγράμμιση
Dense Hatching Πυκνή διαγράμμιση
Tapered Hatching Κωνική διαγράμμιση
Broken Hatching Διακεκομμένη διαγράμμιση
Image Brush Πινέλα εικόνας
Soft Bloom Απαλό άνθος
Halftone Field Πεδίο ημιτόνων
Can't render this file because it is too large.
+14
View File
@@ -1707,6 +1707,10 @@ font-technology Variable Variables
Add Color Tool Herramienta Añadir color
Remove Color Tool Herramienta Eliminar color
Remove Color Eliminar color
Set As Base Color Establecer como color base
Select Shade Seleccionar matiz
Add New Color Añadir nuevo color
Set Current Color As Base Color Establecer el color actual como color base
Find the selected colors in the artwork Buscar los colores seleccionados en la ilustración
Harmony Sets Conjuntos de armonía
Height Altura
@@ -5405,6 +5409,7 @@ liquify-list-end {0}, {1} {0}, {1}
@msg no native format no hay formato nativo
@msg no pages no hay páginas
@msg no pattern `{name}` no existe el motivo `{name}`
@msg art painted with `{name}` can't be its tile una ilustración pintada con `{name}` no puede ser su azulejo
@msg no perspective grid preset named `{name}` no hay ningún preajuste de cuadrícula de perspectiva llamado `{name}`
@msg no plug-in {0} is installed no hay ningún plugin {0} instalado
@msg no plug-in {id} is installed no hay ningún plugin {id} instalado
@@ -6457,6 +6462,8 @@ effect Regular Regular
Arrow Flecha
Arrow (open) Flecha (abierta)
Barbed Con púas
arrowhead Feather Emplumado
arrowhead Target Diana
Half Arrow (left) Media flecha (izquierda)
Half Arrow (right) Media flecha (derecha)
Concave Cóncava
@@ -6484,6 +6491,7 @@ effect Regular Regular
Kite Cometa
Triangle to Bar Triángulo a barra
Oval Óvalo
Line Arrow Flecha de líneas
Complementary Complementario
Complementary 2 Complementario 2
Split Complementary Complementario dividido
@@ -8275,6 +8283,7 @@ breakText Glyphs Glifos
Remove Strokes Quitar trazos
Place Brush Art Colocar ilustración del pincel
Replace Brush Art Reemplazar ilustración del pincel
Replace Pattern Art Reemplazar ilustración del motivo
Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Algunos trazos usan este pincel. ¿Aplicar la nueva ilustración a esos trazos, o dejarlos como están y añadir una copia del pincel con la nueva ilustración?
Apply to Strokes Aplicar a los trazos
Leave Strokes Dejar los trazos
@@ -10613,6 +10622,11 @@ breakText Glyphs Glifos
@msg A joint does not close by {gap} pt. Una unión no cierra por {gap} pt.
@msg Two panels pass through each other. Dos paneles se atraviesan entre sí.
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer debe ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine"
Engraving Grabado
Fine Hatching Rayado fino
Dense Hatching Rayado denso
Tapered Hatching Rayado afilado
Broken Hatching Rayado discontinuo
Image Brush Pinceles de imagen
Soft Bloom Flor suave
Halftone Field Campo de semitonos
Can't render this file because it is too large.
+13
View File
@@ -3131,6 +3131,10 @@ digits Malayalam Malajalam
Add Color Tool Lisää väri -työkalu
Remove Color Tool Poista väri -työkalu
Remove Color Poista väri
Set As Base Color Aseta perusväriksi
Select Shade Valitse sävy
Add New Color Lisää uusi väri
Set Current Color As Base Color Aseta nykyinen väri perusväriksi
Find the selected colors in the artwork Etsi valitut värit kuvituksesta
Harmony Rules Harmoniasäännöt
Keep this row's colors (exclude) Säilytä tämän rivin värit (jätä pois)
@@ -5638,6 +5642,7 @@ liquify-list-end {0}, {1} {0} ja {1}
@msg no native format ei omaa tiedostomuotoa
@msg no pages ei sivuja
@msg no pattern `{name}` ei kuviota `{name}`
@msg art painted with `{name}` can't be its tile kuviolla `{name}` maalattu kuvitus ei voi olla sen ruutu
@msg no perspective grid preset named `{name}` ei perspektiiviruudukon esiasetusta nimeltä `{name}`
@msg no plug-in {0} is installed laajennusta {0} ei ole asennettu
@msg no plug-in {id} is installed laajennusta {id} ei ole asennettu
@@ -6419,6 +6424,7 @@ variable-list-end {0}, {1} {0} ja {1}
Arrow Nuoli
Arrow (open) Nuoli (avoin)
Barbed Väkänen
arrowhead Feather Sulka
Half Arrow (left) Puolinuoli (vasen)
Half Arrow (right) Puolinuoli (oikea)
Concave Kovera
@@ -6446,6 +6452,7 @@ variable-list-end {0}, {1} {0} ja {1}
Kite Leija
Triangle to Bar Kolmiosta palkkiin
Oval Soikio
Line Arrow Viivanuoli
Complementary Vastaväri
Complementary 2 Vastaväri 2
Split Complementary Jaettu vastaväri
@@ -8366,6 +8373,7 @@ breakText Glyphs Merkit
Remove Strokes Poista viivat
Place Brush Art Sijoita siveltimen kuvitus
Replace Brush Art Korvaa siveltimen kuvitus
Replace Pattern Art Korvaa kuvion kuvitus
Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Viivat käyttävät tätä sivellintä. Käytetäänkö uutta kuvitusta näissä viivoissa, vai jätetäänkö ne ennalleen ja lisätään siveltimestä kopio, jossa on uusi kuvitus?
Apply to Strokes Käytä viivoihin
Leave Strokes Jätä viivat ennalleen
@@ -8953,6 +8961,11 @@ breakText Glyphs Merkit
@msg A joint does not close by {gap} pt. Liitos ei sulkeudu, rako {gap} pt.
@msg Two panels pass through each other. Kaksi paneelia kulkee toistensa läpi.
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer on oltava "singleLine", "everyLine", "standardSingleLine" tai "standardEveryLine"
Engraving Kaiverrus
Fine Hatching Hieno viivoitus
Dense Hatching Tiheä viivoitus
Tapered Hatching Kapeneva viivoitus
Broken Hatching Katkoviivoitus
Image Brush Kuvasiveltimet
Soft Bloom Pehmeä kukinta
Halftone Field Rasterikenttä
Can't render this file because it is too large.
+13
View File
@@ -1696,6 +1696,10 @@ font-technology Variable Variables
Add Color Tool Outil Ajouter une couleur
Remove Color Tool Outil Supprimer une couleur
Remove Color Supprimer la couleur
Set As Base Color Définir comme couleur de base
Select Shade Sélectionner une nuance
Add New Color Ajouter une nouvelle couleur
Set Current Color As Base Color Définir la couleur actuelle comme couleur de base
Find the selected colors in the artwork Rechercher les couleurs sélectionnées dans l’illustration
Harmony Rules: Règles d’harmonie :
Harmony Sets Ensembles d’harmonies
@@ -5364,6 +5368,7 @@ liquify-list-end {0}, {1} {0} et {1}
@msg no native format aucun format natif
@msg no pages aucune page
@msg no pattern `{name}` aucun motif `{name}`
@msg art painted with `{name}` can't be its tile une illustration peinte avec `{name}` ne peut pas être son carreau
@msg no perspective grid preset named `{name}` aucun paramètre prédéfini de grille de perspective nommé `{name}`
@msg no plug-in {0} is installed aucun plug-in {0} n’est installé
@msg no plug-in {id} is installed aucun plug-in {id} n’est installé
@@ -6491,6 +6496,7 @@ lighting Light Lumière
B5 B5
Bar Barre
Barbed Barbelée
arrowhead Feather Empennage
Baseline (Standard) De base (standard)
Baseline Optimized De base optimisé
Basic De base
@@ -6619,6 +6625,7 @@ lighting Light Lumière
Letterhead A4 Papier à en-tête A4
Letterhead Letter Papier à en-tête Lettre US
Line Art Dessin au trait
Line Arrow Flèche filaire
Linear Linéaire
Logo 1000×1000 Logo 1000×1000
Low Fidelity Photo Photo basse fidélité
@@ -8295,6 +8302,7 @@ breakText Glyphs Glyphes
Remove Strokes Supprimer les contours
Place Brush Art Placer l’illustration de la forme
Replace Brush Art Remplacer l’illustration de la forme
Replace Pattern Art Remplacer l’illustration du motif
Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Des contours utilisent cette forme. Appliquer la nouvelle illustration à ces contours, ou les laisser tels quels et ajouter une copie de la forme avec la nouvelle illustration ?
Apply to Strokes Appliquer aux contours
Leave Strokes Conserver les contours
@@ -10684,6 +10692,11 @@ breakText Glyphs Glyphes
@msg A joint does not close by {gap} pt. Un joint ne se ferme pas, avec un écart de {gap} pt.
@msg Two panels pass through each other. Deux panneaux se traversent.
@msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} pixels, c’est trop grand pour le GIF (65535 pixels par côté au plus) : réduisez la résolution
Engraving Gravure
Fine Hatching Hachures fines
Dense Hatching Hachures denses
Tapered Hatching Hachures effilées
Broken Hatching Hachures interrompues
Image Brush Pinceaux d’image
Soft Bloom Floraison douce
Halftone Field Champ de demi-teintes
Can't render this file because it is too large.
+41
View File
@@ -3156,6 +3156,37 @@
Remove Effect ઇફેક્ટ દૂર કરો
Remove Effects ઇફેક્ટ્સ દૂર કરો
Remove Gaps ગેપ દૂર કરો
# Stroke arrowheads (Stroke panel, Dimension Tool Options and Properties › Arrow Style).
Triangle (open) ત્રિકોણ (ખુલ્લો)
Circle (open) વર્તુળ (ખુલ્લું)
Square (open) ચોરસ (ખુલ્લો)
Arrow (open) તીર (ખુલ્લું)
Barbed કાંટાળું
arrowhead Feather પીંછું
Half Arrow (left) અડધું તીર (ડાબે)
Half Arrow (right) અડધું તીર (જમણે)
Double Bar બેવડી પટ્ટી
Dot on Bar પટ્ટી પર બિંદુ
Chevron શેવરોન
Cross ક્રોસ
Plus પ્લસ
Hexagon (open) ષટ્કોણ (ખુલ્લો)
Tag ટૅગ
Tag (open) ટૅગ (ખુલ્લો)
Half Circle અર્ધવર્તુળ
Drop ટીપું
Slash સ્લૅશ
Double Slash બેવડો સ્લૅશ
Diamond (open) ડાયમંડ (ખુલ્લો)
Reverse Triangle ઊંધો ત્રિકોણ
Swallowtail અબાબીલની પૂંછડી
Bracket કૌંસ
Fork કાંટો
Leaf પાંદડું
Kite પતંગ
Triangle to Bar ત્રિકોણથી પટ્ટી
Oval અંડાકાર
Line Arrow રેખા તીર
# Path Precision Tools add-on: Common Tangents.
Common Tangents… સામાન્ય સ્પર્શરેખાઓ…
Common Tangents સામાન્ય સ્પર્શરેખાઓ
@@ -3957,6 +3988,10 @@
Add Color Tool રંગ ઉમેરો સાધન
Remove Color Tool રંગ દૂર કરો સાધન
Remove Color રંગ દૂર કરો
Set As Base Color આધાર રંગ તરીકે સેટ કરો
Select Shade છાયા પસંદ કરો
Add New Color નવો રંગ ઉમેરો
Set Current Color As Base Color વર્તમાન રંગને આધાર રંગ તરીકે સેટ કરો
Find the selected colors in the artwork પસંદ કરેલા રંગો આર્ટવર્કમાં શોધો
Show handles when multiple anchors are selected બહુવિધ એન્કર પસંદ હોય ત્યારે હૅન્ડલ બતાવો
Show in Folder ફોલ્ડરમાં બતાવો
@@ -5059,6 +5094,7 @@ antiAlias Sharp શાર્પ
Composition કમ્પોઝિશન
Place Brush Art બ્રશ આર્ટ પ્લેસ કરો
Replace Brush Art બ્રશ આર્ટ બદલો
Replace Pattern Art પેટર્ન આર્ટ બદલો
Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? સ્ટ્રોક્સ આ બ્રશ વાપરે છે. તે સ્ટ્રોક્સ પર નવી આર્ટ લાગુ કરવી છે કે તેમને જેમ છે તેમ રાખીને નવી આર્ટવાળી બ્રશની નકલ ઉમેરવી છે?
Apply to Strokes સ્ટ્રોક્સ પર લાગુ કરો
Leave Strokes સ્ટ્રોક્સ જેમ છે તેમ રાખો
@@ -5580,6 +5616,11 @@ swatch [Registration] [રજિસ્ટ્રેશન]
Standard Single-line Composer સ્ટાન્ડર્ડ સિંગલ-લાઇન કમ્પોઝર
Standard Every-line Composer સ્ટાન્ડર્ડ એવરી-લાઇન કમ્પોઝર
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer આમાંથી એક હોવું જોઈએ: "singleLine", "everyLine", "standardSingleLine" અથવા "standardEveryLine"
Engraving કોતરણી
Fine Hatching ઝીણી રેખાઓ
Dense Hatching ગાઢ રેખાઓ
Tapered Hatching પાતળી થતી રેખાઓ
Broken Hatching તૂટક રેખાઓ
Image Brush છબી બ્રશ
Soft Bloom નરમ ફૂલ
Halftone Field હાફટોન ક્ષેત્ર
Can't render this file because it contains an unexpected character in line 72 and column 5.
+13
View File
@@ -811,6 +811,7 @@ antiAlias Sharp शार्प
Bar बार
Bar Graph Tool बार ग्राफ़ टूल
Barbed कंटीले
arrowhead Feather पंख
Bas Relief बास रिलीफ़
Bas Relief… बास रिलीफ़…
Base Along: आधार के साथ:
@@ -3117,6 +3118,7 @@ antiAlias Sharp शार्प
Limit: सीमा:
Limited लिमिटेड
Line लाइन
Line Arrow लाइन तीर
line {line} लाइन {line}
Line {line} लाइन {line}
Line {line}: {name}: {status} लाइन {line}: {name}: {status}
@@ -4495,6 +4497,7 @@ antiAlias Sharp शार्प
Remove Strokes स्ट्रोक हटाएँ
Place Brush Art ब्रश आर्टवर्क रखें
Replace Brush Art ब्रश आर्टवर्क बदलें
Replace Pattern Art पैटर्न आर्टवर्क बदलें
Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? स्ट्रोक्स इस ब्रश का उपयोग कर रहे हैं। नया आर्टवर्क उन स्ट्रोक्स पर लागू करें, या उन्हें जैसा है वैसा छोड़कर नए आर्टवर्क वाले ब्रश की एक कॉपी जोड़ें?
Apply to Strokes स्ट्रोक्स पर लागू करें
Leave Strokes स्ट्रोक्स जैसे हैं वैसे छोड़ें
@@ -5338,6 +5341,10 @@ antiAlias Sharp शार्प
Add Color Tool रंग जोड़ें टूल
Remove Color Tool रंग हटाएँ टूल
Remove Color रंग हटाएँ
Set As Base Color आधार रंग के रूप में सेट करें
Select Shade शेड चुनें
Add New Color नया रंग जोड़ें
Set Current Color As Base Color वर्तमान रंग को आधार रंग के रूप में सेट करें
Find the selected colors in the artwork चयनित रंगों को आर्टवर्क में खोजें
Show Color Groups रंग समूह दिखाएँ
Show Color Swatches रंग स्वॉचेस दिखाएँ
@@ -8394,6 +8401,7 @@ liquify-list-end {0}, {1} {0} और {1}
@msg no parent layer कोई अभिभावक लेयर नहीं
@msg no Pathfinder operation applied yet अभी तक कोई पाथफाइंडर ऑपरेशन लागू नहीं है
@msg no pattern `{name}` कोई पैटर्न `{name}` नहीं
@msg art painted with `{name}` can't be its tile `{name}` से रंगी कला उसकी टाइल नहीं हो सकती
@msg no pattern named `{choice}` `{choice}` नाम का कोई पैटर्न नहीं
@msg no pattern swatch `{name}` कोई पैटर्न स्वॉच `{name}` नहीं
@msg no PDF preset named `{n}` कोई PDF प्रीसेट नहीं है जिसका नाम `{n}` है
@@ -10327,6 +10335,11 @@ theme Appearance अपीयरेंस
@msg A panel is not joined to the rest by a crease. कोई पैनल किसी क्रीज़ लाइन से बाकी से जुड़ा नहीं है।
@msg A fold line is on a non-printing layer. एक फ़ोल्ड लाइन नॉन-प्रिंटिंग लेयर पर है।
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} पैनल: {panels}, हिंज: {hinges}, एरर: {errors}, वॉर्निंग: {warnings}
Engraving नक्काशी
Fine Hatching बारीक रेखांकन
Dense Hatching घना रेखांकन
Tapered Hatching पतला होता रेखांकन
Broken Hatching टूटा रेखांकन
Image Brush छवि ब्रश
Soft Bloom कोमल खिलावट
Halftone Field हाफ़टोन क्षेत्र
Can't render this file because it is too large.
+14
View File
@@ -409,6 +409,8 @@ font-technology Variable Változó
Bar Vonal
Bar Graph Tool Sávdiagram
Barbed Szakállas
arrowhead Feather Tollazat
arrowhead Target Céltábla
Baseline Alapvonal
Baseline (Standard) Alapvonali (szabványos)
Baseline Optimized Alapvonali, optimalizált
@@ -2118,6 +2120,10 @@ file-filter Templates Sablonok
Add Color Tool Szín hozzáadása eszköz
Remove Color Tool Szín eltávolítása eszköz
Remove Color Szín eltávolítása
Set As Base Color Beállítás alapszínként
Select Shade Árnyalat kiválasztása
Add New Color Új szín hozzáadása
Set Current Color As Base Color Aktuális szín beállítása alapszínként
Find the selected colors in the artwork A kijelölt színek keresése a grafikában
Harmony Sets Harmóniakészletek
HDTV 1080p HDTV 1080p
@@ -2609,6 +2615,7 @@ file-filter Templates Sablonok
Limit: Határ:
Limited Korlátozott
Line Vonal
Line Arrow Vonalas nyíl
Line Art Vonalas rajz
Line Art and Text Resolution: Vonalas grafika és szöveg felbontása:
Line Breaks Sortörések
@@ -6095,6 +6102,7 @@ liquify-list-end {0}, {1} {0} és {1}
@msg no native format nincs natív formátum
@msg no pages nincsenek oldalak
@msg no pattern `{name}` nincs ilyen mintázat: `{name}`
@msg art painted with `{name}` can't be its tile a(z) `{name}` mintázattal festett grafika nem lehet annak csempéje
@msg no perspective grid preset named `{name}` nincs ilyen nevű perspektivikusrács-előbeállítás: `{name}`
@msg no plug-in {0} is installed nincs telepítve ilyen bővítmény: {0}
@msg no plug-in {id} is installed nincs telepítve ilyen bővítmény: {id}
@@ -8284,6 +8292,7 @@ breakText Glyphs Glifák
Remove Strokes Körvonalak eltávolítása
Place Brush Art Ecsetgrafika elhelyezése
Replace Brush Art Ecsetgrafika cseréje
Replace Pattern Art Mintázatgrafika cseréje
Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Körvonalak használják ezt az ecsetet. Alkalmazod az új grafikát ezekre a körvonalakra, vagy változatlanul hagyod őket, és hozzáadod az ecset egy másolatát az új grafikával?
Apply to Strokes Alkalmazás a körvonalakra
Leave Strokes Körvonalak megtartása
@@ -10709,6 +10718,11 @@ breakText Glyphs Glifák
@msg A panel is not joined to the rest by a crease. Egy panelt egyetlen bigvonal sem köt a többihez.
@msg A fold line is on a non-printing layer. Egy hajtásvonal nem nyomtatható rétegen van.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelek: {panels}, zsanérok: {hinges}, hibák: {errors}, figyelmeztetések: {warnings}
Engraving Metszet
Fine Hatching Finom vonalkázás
Dense Hatching Sűrű vonalkázás
Tapered Hatching Elvékonyodó vonalkázás
Broken Hatching Szaggatott vonalkázás
Image Brush Képecsetek
Soft Bloom Lágy virágzás
Halftone Field Féltónusmező
Can't render this file because it is too large.
+12
View File
@@ -3585,6 +3585,10 @@ digits Malayalam Malayalam
Add Color Tool Alat Tambah Warna
Remove Color Tool Alat Hapus Warna
Remove Color Hapus Warna
Set As Base Color Atur sebagai Warna Dasar
Select Shade Pilih Corak
Add New Color Tambah Warna Baru
Set Current Color As Base Color Atur Warna Saat Ini sebagai Warna Dasar
Find the selected colors in the artwork Temukan warna yang dipilih di karya seni
Harmony Rules Aturan harmoni
Keep this row's colors (exclude) Pertahankan warna baris ini (kecualikan)
@@ -6383,6 +6387,7 @@ imageTrace Outline Kontur
Arrow Panah
Arrow (open) Panah (terbuka)
Barbed Berduri
arrowhead Feather Bulu
Half Arrow (left) Setengah panah (kiri)
Half Arrow (right) Setengah panah (kanan)
Concave Cekung
@@ -6410,6 +6415,7 @@ imageTrace Outline Kontur
Kite Layang-layang
Triangle to Bar Segitiga ke batang
Oval Oval
Line Arrow Panah garis
Complementary Komplementer
Complementary 2 Komplementer 2
Split Complementary Komplementer terpisah
@@ -8149,6 +8155,7 @@ breakText Glyphs Glif
Remove Strokes Hapus Stroke
Place Brush Art Tempatkan karya seni kuas
Replace Brush Art Ganti karya seni kuas
Replace Pattern Art Ganti karya seni pola
Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Stroke menggunakan kuas ini. Terapkan karya seni baru ke stroke tersebut, atau biarkan apa adanya dan tambahkan salinan kuas dengan karya seni baru?
Apply to Strokes Terapkan ke Stroke
Leave Strokes Biarkan Stroke
@@ -8564,6 +8571,11 @@ breakText Glyphs Glif
@msg A joint does not close by {gap} pt. Sebuah sambungan tidak menutup sejauh {gap} pt.
@msg Two panels pass through each other. Dua panel saling menembus.
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer harus "singleLine", "everyLine", "standardSingleLine", atau "standardEveryLine"
Engraving Ukiran
Fine Hatching Arsiran halus
Dense Hatching Arsiran rapat
Tapered Hatching Arsiran meruncing
Broken Hatching Arsiran terputus
Image Brush Kuas gambar
Soft Bloom Mekar lembut
Halftone Field Bidang halftone
Can't render this file because it is too large.
+42
View File
@@ -1731,6 +1731,10 @@ file-filter Templates Modelli
Add Color Tool Strumento Aggiungi colore
Remove Color Tool Strumento Rimuovi colore
Remove Color Rimuovi colore
Set As Base Color Imposta come colore base
Select Shade Seleziona sfumatura
Add New Color Aggiungi nuovo colore
Set Current Color As Base Color Imposta il colore corrente come colore base
Find the selected colors in the artwork Trova i colori selezionati nella grafica
Harmony Sets Gruppi di armonia
Height Altezza
@@ -5431,6 +5435,7 @@ liquify-list-end {0}, {1} {0} e {1}
@msg no native format nessun formato nativo
@msg no pages nessuna pagina
@msg no pattern `{name}` nessun motivo `{name}`
@msg art painted with `{name}` can't be its tile una grafica dipinta con `{name}` non può esserne la porzione
@msg no perspective grid preset named `{name}` nessun preset di griglia prospettica denominato `{name}`
@msg no plug-in {0} is installed nessun plug-in {0} installato
@msg no plug-in {id} is installed nessun plug-in {id} installato
@@ -7642,6 +7647,37 @@ anchor Points: Punti:
@msg `{id}` is not a colour adjustment `{id}` non è una regolazione del colore
@msg missing `effect` manca `effect`
@msg `params` must be an object `params` deve essere un oggetto
# Stroke arrowheads (Stroke panel, Dimension Tool Options and Properties › Arrow Style).
Triangle (open) Triangolo (aperto)
Circle (open) Cerchio (aperto)
Square (open) Quadrato (aperto)
Arrow (open) Freccia (aperta)
Barbed Uncinata
arrowhead Feather Piuma
arrowhead Target Bersaglio
Half Arrow (left) Mezza freccia (sinistra)
Half Arrow (right) Mezza freccia (destra)
Double Bar Doppia barra
Dot on Bar Punto su barra
Chevron Gallone
Plus Più
Hexagon (open) Esagono (aperto)
Tag Etichetta
Tag (open) Etichetta (aperta)
Half Circle Semicerchio
Drop Goccia
Slash Barra obliqua
Double Slash Doppia barra obliqua
Diamond (open) Rombo (aperto)
Reverse Triangle Triangolo invertito
Swallowtail Coda di rondine
Bracket Parentesi
Fork Forcella
Leaf Foglia
Kite Aquilone
Triangle to Bar Da triangolo a barra
Oval Ovale
Line Arrow Freccia a linee
# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages.
Path Precision Tools Strumenti di precisione per tracciati
Anchor Eraser Brush Pennello gomma punti di ancoraggio
@@ -7932,6 +7968,7 @@ breakText Glyphs Glifi
Remove Strokes Rimuovi tracce
Place Brush Art Inserisci grafica del pennello
Replace Brush Art Sostituisci grafica del pennello
Replace Pattern Art Sostituisci grafica del motivo
Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Alcune tracce usano questo pennello. Applicare la nuova grafica a queste tracce, o lasciarle come sono e aggiungere una copia del pennello con la nuova grafica?
Apply to Strokes Applica alle tracce
Leave Strokes Lascia le tracce
@@ -10367,6 +10404,11 @@ breakText Glyphs Glifi
@msg A panel is not joined to the rest by a crease. Un pannello non è unito al resto da alcuna linea di cordonatura.
@msg A fold line is on a non-printing layer. Una linea di piega si trova su un livello non stampabile.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Pannelli: {panels}, cerniere: {hinges}, errori: {errors}, avvisi: {warnings}
Engraving Incisione
Fine Hatching Tratteggio fine
Dense Hatching Tratteggio fitto
Tapered Hatching Tratteggio affusolato
Broken Hatching Tratteggio spezzato
Image Brush Pennelli immagine
Soft Bloom Fioritura morbida
Halftone Field Campo mezzitoni
Can't render this file because it is too large.
+41
View File
@@ -2119,6 +2119,10 @@ antiAlias Sharp シャープ
Add Color Tool カラー追加ツール
Remove Color Tool カラー削除ツール
Remove Color カラーを削除
Set As Base Color ベースカラーに設定
Select Shade シェードを選択
Add New Color 新規カラーを追加
Set Current Color As Base Color 現在のカラーをベースカラーに設定
Find the selected colors in the artwork 選択したカラーをアートワーク内で検索
Height 高さ
Height: 高さ:
@@ -5197,6 +5201,7 @@ variable-list-end {0}, {1} {0}、{1}
@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} の結果が空になりました。領域を囲まない直線などのオープンパスがあります。含めるには、先にそのパスに「オブジェクト › パス › パスのアウトライン」を適用してください
@msg already editing a pattern すでにパターンを編集中です
@msg no pattern `{name}` パターン `{name}` が見つかりません
@msg art painted with `{name}` can't be its tile `{name}` でペイントされたアートはそのタイルにできません
@msg not in pattern editing mode パターン編集モードではありません
@msg finish editing the pattern first 先にパターンの編集を終了してください
@msg pattern missing パターンが見つかりません
@@ -9532,6 +9537,36 @@ anchor Points: ポイント:
@msg `{id}` is not a colour adjustment `{id}` はカラー補正ではありません
@msg missing `effect` `effect` が指定されていません
@msg `params` must be an object `params` にはオブジェクトを指定してください
# Stroke arrowheads (Stroke panel, Dimension Tool Options and Properties › Arrow Style).
Triangle (open) 三角形 (白抜き)
Circle (open) 円 (白抜き)
Square (open) 正方形 (白抜き)
Arrow (open) 矢印 (白抜き)
Barbed かえし付き
arrowhead Feather 矢羽根
Half Arrow (left) 片矢印 (左)
Half Arrow (right) 片矢印 (右)
Double Bar 二重バー
Dot on Bar バー上のドット
Chevron 山形
Plus プラス
Hexagon (open) 六角形 (白抜き)
Tag タグ
Tag (open) タグ (白抜き)
Half Circle 半円
Drop しずく
Slash スラッシュ
Double Slash 二重スラッシュ
Diamond (open) ひし形 (白抜き)
Reverse Triangle 逆三角形
Swallowtail 燕尾
Bracket 角かっこ
Fork フォーク
Leaf 葉
Kite カイト
Triangle to Bar 三角形からバー
Oval 楕円
Line Arrow 線矢印
# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages.
Path Precision Tools パス精密ツール
Anchor Eraser Brush アンカーポイント消去ブラシ
@@ -9822,6 +9857,7 @@ breakText Glyphs 字形
Remove Strokes 線を削除
Place Brush Art ブラシのアートを配置
Replace Brush Art ブラシのアートを置き換え
Replace Pattern Art パターンのアートを置き換え
Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? このブラシは線で使われています。新しいアートをそれらの線に適用しますか?それとも線をそのままにして、新しいアートを持つブラシのコピーを追加しますか?
Apply to Strokes 線に適用
Leave Strokes 線を保持
@@ -10431,6 +10467,11 @@ breakText Glyphs 字形
@msg A panel is not joined to the rest by a crease. パネルがどの筋入れ線でも他とつながっていません。
@msg A fold line is on a non-printing layer. 折り線が印刷しないレイヤーにあります。
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} パネル: {panels}、ヒンジ: {hinges}、エラー: {errors}、警告: {warnings}
Engraving 彫刻
Fine Hatching 細いハッチング
Dense Hatching 密なハッチング
Tapered Hatching 先細りハッチング
Broken Hatching 途切れたハッチング
Image Brush 画像ブラシ
Soft Bloom やわらかな花
Halftone Field ハーフトーンの面
Can't render this file because it is too large.
+13
View File
@@ -5071,6 +5071,10 @@ digits Malayalam მალაიალამური
Add Color Tool ფერის დამატების ხელსაწყო
Remove Color Tool ფერის წაშლის ხელსაწყო
Remove Color ფერის წაშლა
Set As Base Color საბაზო ფერად დაყენება
Select Shade ელფერის არჩევა
Add New Color ახალი ფერის დამატება
Set Current Color As Base Color მიმდინარე ფერის საბაზო ფერად დაყენება
Find the selected colors in the artwork მონიშნული ფერების ძებნა ნახატში
Keep this row's colors (exclude) ამ სტრიქონის ფერების შენარჩუნება (გამორიცხვა)
Limit to Library: ბიბლიოთეკით შეზღუდვა:
@@ -7172,6 +7176,7 @@ font-technology Variable ცვლადი
@msg no native format საკუთარი ფორმატი არ არის
@msg no pages გვერდები არ არის
@msg no pattern `{name}` პატერნი `{name}` არ არის
@msg art painted with `{name}` can't be its tile `{name}`-ით შეღებილი ნახატი მისი ფილა ვერ იქნება
@msg no perspective grid preset named `{name}` პერსპექტივის ბადის პრესეტი სახელით `{name}` არ არის
@msg no plug-in {0} is installed პლაგინი {0} დაინსტალირებული არ არის
@msg no plug-in {id} is installed პლაგინი {id} დაინსტალირებული არ არის
@@ -7874,6 +7879,7 @@ font-technology Variable ცვლადი
Arrow ისარი
Arrow (open) ისარი (ღია)
Barbed წვეტიანი
arrowhead Feather ბუმბული
Half Arrow (left) ნახევარი ისარი (მარცხენა)
Half Arrow (right) ნახევარი ისარი (მარჯვენა)
Concave ჩაზნექილი
@@ -7901,6 +7907,7 @@ font-technology Variable ცვლადი
Kite ფრანი
Triangle to Bar სამკუთხედიდან ზოლამდე
Oval ოვალი
Line Arrow ხაზოვანი ისარი
Complementary დამატებითი
Complementary 2 დამატებითი 2
Split Complementary გაყოფილი დამატებითი
@@ -10473,6 +10480,7 @@ breakText Glyphs გლიფები
Remove Strokes კონტურების მოხსნა
Place Brush Art ფუნჯის ნახატის განთავსება
Replace Brush Art ფუნჯის ნახატის ჩანაცვლება
Replace Pattern Art პატერნის ნახატის ჩანაცვლება
Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? კონტურები იყენებს ამ ფუნჯს. გამოყენებულ იქნას ახალი ნახატი ამ კონტურებზე, თუ დარჩეს ისინი როგორც არის და დაემატოს ფუნჯის ასლი ახალი ნახატით?
Apply to Strokes კონტურებზე გამოყენება
Leave Strokes კონტურების დატოვება
@@ -11007,6 +11015,11 @@ font-script Japanese იაპონური
@msg A joint does not close by {gap} pt. შეერთება არ იხურება {gap} pt-ით.
@msg Two panels pass through each other. ორი პანელი ერთმანეთში გადის.
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer უნდა იყოს "singleLine", "everyLine", "standardSingleLine" ან "standardEveryLine"
Engraving გრავიურა
Fine Hatching წვრილი შტრიხები
Dense Hatching მჭიდრო შტრიხები
Tapered Hatching შევიწროებული შტრიხები
Broken Hatching წყვეტილი შტრიხები
Image Brush გამოსახულების ფუნჯები
Soft Bloom რბილი ყვავილი
Halftone Field ნახევარტონური ველი
Can't render this file because it is too large.
+42
View File
@@ -2109,6 +2109,10 @@ antiAlias Sharp 날카롭게
Add Color Tool 색상 추가 도구
Remove Color Tool 색상 제거 도구
Remove Color 색상 제거
Set As Base Color 기본 색상으로 설정
Select Shade 음영 선택
Add New Color 새 색상 추가
Set Current Color As Base Color 현재 색상을 기본 색상으로 설정
Find the selected colors in the artwork 선택한 색상을 아트웍에서 찾기
Height 높이
Height: 높이:
@@ -5126,6 +5130,7 @@ variable-list-end {0}, {1} {0} 및 {1}
@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label}의 결과가 비어 있습니다. 선이나 기타 열린 패스가 영역을 둘러싸지 않습니다. 포함하려면 먼저 개체 › 패스 › 선 윤곽선화를 적용하세요
@msg already editing a pattern 이미 패턴을 편집 중입니다
@msg no pattern `{name}` `{name}` 패턴이 없습니다
@msg art painted with `{name}` can't be its tile `{name}` 패턴으로 칠한 아트웍은 그 타일이 될 수 없습니다
@msg not in pattern editing mode 패턴 편집 모드가 아닙니다
@msg finish editing the pattern first 먼저 패턴 편집을 마치세요
@msg pattern missing 패턴이 없습니다
@@ -7614,6 +7619,37 @@ anchor Points: 포인트:
@msg `{id}` is not a colour adjustment `{id}`은(는) 색상 조정이 아닙니다
@msg missing `effect` `effect`이 없습니다
@msg `params` must be an object `params`는 개체여야 합니다
# Stroke arrowheads (Stroke panel, Dimension Tool Options and Properties › Arrow Style).
Triangle (open) 삼각형 (윤곽)
Circle (open) 원 (윤곽)
Square (open) 사각 (윤곽)
Arrow (open) 화살표 (윤곽)
Barbed 미늘
arrowhead Feather 깃털
arrowhead Target 과녁
Half Arrow (left) 반쪽 화살표 (왼쪽)
Half Arrow (right) 반쪽 화살표 (오른쪽)
Double Bar 이중 막대
Dot on Bar 막대 위 점
Chevron 갈매기형
Plus 더하기
Hexagon (open) 육각형 (윤곽)
Tag 태그
Tag (open) 태그 (윤곽)
Half Circle 반원
Drop 물방울
Slash 슬래시
Double Slash 이중 슬래시
Diamond (open) 다이아몬드 (윤곽)
Reverse Triangle 역삼각형
Swallowtail 제비 꼬리
Bracket 대괄호
Fork 포크
Leaf 잎
Kite 연
Triangle to Bar 삼각형에서 막대
Oval 타원
Line Arrow 선 화살표
# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages.
Path Precision Tools 패스 정밀 도구
Anchor Eraser Brush 앵커 포인트 지우개 브러시
@@ -7904,6 +7940,7 @@ breakText Glyphs 글리프
Remove Strokes 선 제거
Place Brush Art 브러시 아트 배치
Replace Brush Art 브러시 아트 바꾸기
Replace Pattern Art 패턴 아트 바꾸기
Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? 선에서 이 브러시를 사용합니다. 새 아트를 해당 선에 적용하시겠습니까, 아니면 선을 그대로 두고 새 아트로 브러시 사본을 추가하시겠습니까?
Apply to Strokes 선에 적용
Leave Strokes 선 유지
@@ -10330,6 +10367,11 @@ breakText Glyphs 글리프
@msg A panel is not joined to the rest by a crease. 패널이 어떤 오시선으로도 나머지와 연결되어 있지 않습니다.
@msg A fold line is on a non-printing layer. 접는 선이 인쇄되지 않는 레이어에 있습니다.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 패널: {panels}, 힌지: {hinges}, 오류: {errors}, 경고: {warnings}
Engraving 판화
Fine Hatching 가는 해칭
Dense Hatching 촘촘한 해칭
Tapered Hatching 가늘어지는 해칭
Broken Hatching 끊긴 해칭
Image Brush 이미지 브러시
Soft Bloom 부드러운 꽃
Halftone Field 하프톤 필드
Can't render this file because it is too large.
+13
View File
@@ -3584,6 +3584,10 @@ digits Malayalam Malayalam
Add Color Tool Gereedschap Kleur toevoegen
Remove Color Tool Gereedschap Kleur verwijderen
Remove Color Kleur verwijderen
Set As Base Color Instellen als basiskleur
Select Shade Schakering selecteren
Add New Color Nieuwe kleur toevoegen
Set Current Color As Base Color Huidige kleur instellen als basiskleur
Find the selected colors in the artwork De geselecteerde kleuren zoeken in de artwork
Harmony Rules Harmonieregels
Keep this row's colors (exclude) De kleuren van deze rij behouden (uitsluiten)
@@ -5787,6 +5791,7 @@ imageTrace Outline Contour
@msg no native format geen eigen indeling
@msg no pages geen pagina's
@msg no pattern `{name}` geen patroon `{name}`
@msg art painted with `{name}` can't be its tile illustratie die met `{name}` is geverfd, kan niet de tegel ervan zijn
@msg no perspective grid preset named `{name}` geen perspectiefrastervoorinstelling met de naam `{name}`
@msg no plug-in {0} is installed er is geen plug-in {0} geïnstalleerd
@msg no plug-in {id} is installed er is geen plug-in {id} geïnstalleerd
@@ -8293,6 +8298,7 @@ imageTrace Outline Contour
Arrow Pijl
Arrow (open) Pijl (open)
Barbed Weerhaak
arrowhead Feather Veer
Half Arrow (left) Halve pijl (links)
Half Arrow (right) Halve pijl (rechts)
Concave Concaaf
@@ -8320,6 +8326,7 @@ imageTrace Outline Contour
Kite Vlieger
Triangle to Bar Driehoek naar balk
Oval Ovaal
Line Arrow Lijnpijl
Complementary Complementair
Complementary 2 Complementair 2
Split Complementary Gesplitst complementair
@@ -10193,6 +10200,7 @@ breakText Glyphs Glyphs
Remove Strokes Contouren verwijderen
Place Brush Art Penseelillustratie plaatsen
Replace Brush Art Penseelillustratie vervangen
Replace Pattern Art Patroonillustratie vervangen
Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Contouren gebruiken dit penseel. De nieuwe illustratie op deze contouren toepassen, of ze laten zoals ze zijn en een kopie van het penseel met de nieuwe illustratie toevoegen?
Apply to Strokes Op contouren toepassen
Leave Strokes Contouren behouden
@@ -10760,6 +10768,11 @@ breakText Glyphs Glyphs
@msg A panel is not joined to the rest by a crease. Een paneel is door geen rillijn met de rest verbonden.
@msg A fold line is on a non-printing layer. Een vouwlijn staat op een laag die niet wordt afgedrukt.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelen: {panels}, scharnieren: {hinges}, fouten: {errors}, waarschuwingen: {warnings}
Engraving Gravure
Fine Hatching Fijne arcering
Dense Hatching Dichte arcering
Tapered Hatching Taps toelopende arcering
Broken Hatching Onderbroken arcering
Image Brush Afbeeldingspenselen
Soft Bloom Zachte bloei
Halftone Field Halftoonveld
Can't render this file because it is too large.
+13
View File
@@ -3099,6 +3099,10 @@ digits Malayalam Malajalam
Add Color Tool Narzędzie Dodaj kolor
Remove Color Tool Narzędzie Usuń kolor
Remove Color Usuń kolor
Set As Base Color Ustaw jako kolor bazowy
Select Shade Wybierz odcień
Add New Color Dodaj nowy kolor
Set Current Color As Base Color Ustaw bieżący kolor jako bazowy
Find the selected colors in the artwork Znajdź zaznaczone kolory w kompozycji
Keep this row's colors (exclude) Zachowaj kolory tego wiersza (wyklucz)
Limit to Library: Ogranicz do biblioteki:
@@ -5534,6 +5538,7 @@ liquify-list-end {0}, {1} {0} i {1}
@msg no native format brak formatu natywnego
@msg no pages brak stron
@msg no pattern `{name}` brak wzorka `{name}`
@msg art painted with `{name}` can't be its tile kompozycja malowana wzorkiem `{name}` nie może być jego kafelkiem
@msg no perspective grid preset named `{name}` brak ustawienia siatki perspektywy o nazwie `{name}`
@msg no plug-in {0} is installed wtyczka {0} nie jest zainstalowana
@msg no plug-in {id} is installed wtyczka {id} nie jest zainstalowana
@@ -6356,6 +6361,7 @@ variable-list-end {0}, {1} {0} i {1}
Arrow Strzałka
Arrow (open) Strzałka (otwarta)
Barbed Zadziorowata
arrowhead Feather Pióro
Half Arrow (left) Pół strzałki (lewa)
Half Arrow (right) Pół strzałki (prawa)
Concave Wklęsła
@@ -6383,6 +6389,7 @@ variable-list-end {0}, {1} {0} i {1}
Kite Latawiec
Triangle to Bar Trójkąt z kreską
Oval Owal
Line Arrow Strzałka liniowa
Complementary Dopełniające
Complementary 2 Dopełniające 2
Split Complementary Rozdzielone dopełniające
@@ -8156,6 +8163,7 @@ breakText Glyphs Glify
Remove Strokes Usuń obrysy
Place Brush Art Umieść kompozycję pędzla
Replace Brush Art Zastąp kompozycję pędzla
Replace Pattern Art Zastąp kompozycję wzorka
Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Obrysy używają tego pędzla. Zastosować nową kompozycję do tych obrysów, czy pozostawić je bez zmian i dodać kopię pędzla z nową kompozycją?
Apply to Strokes Zastosuj do obrysów
Leave Strokes Pozostaw obrysy
@@ -10584,6 +10592,11 @@ breakText Glyphs Glify
@msg A panel is not joined to the rest by a crease. Panel nie jest połączony z resztą żadną linią bigowania.
@msg A fold line is on a non-printing layer. Linia zgięcia znajduje się na warstwie niedrukowanej.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panele: {panels}, zawiasy: {hinges}, błędy: {errors}, ostrzeżenia: {warnings}
Engraving Grawerowanie
Fine Hatching Drobne kreskowanie
Dense Hatching Gęste kreskowanie
Tapered Hatching Zwężane kreskowanie
Broken Hatching Przerywane kreskowanie
Image Brush Pędzle obrazkowe
Soft Bloom Miękki kwiat
Halftone Field Pole półtonów
Can't render this file because it is too large.
+13
View File
@@ -1481,6 +1481,10 @@ antiAlias Sharp Nítido
Add Color Tool Ferramenta Adicionar cor
Remove Color Tool Ferramenta Remover cor
Remove Color Remover cor
Set As Base Color Definir como cor base
Select Shade Selecionar tonalidade
Add New Color Adicionar nova cor
Set Current Color As Base Color Definir cor atual como cor base
Find the selected colors in the artwork Localizar as cores selecionadas na arte
Harmony Sets Conjuntos de Harmonia
Height Altura
@@ -4679,6 +4683,7 @@ axis Both Ambos
@msg no native format sem formato nativo
@msg no pages sem páginas
@msg no pattern `{name}` nenhum padrão `{name}`
@msg art painted with `{name}` can't be its tile uma arte pintada com `{name}` não pode ser o ladrilho dele
@msg no perspective grid preset named `{name}` nenhuma predefinição de grade de perspectiva chamada `{name}`
@msg no plug-in {0} is installed o plug-in {0} não está instalado
@msg no plug-in {id} is installed o plug-in {id} não está instalado
@@ -6439,6 +6444,7 @@ effect Regular Regular
Arrow Seta
Arrow (open) Seta (aberta)
Barbed Farpada
arrowhead Feather Pena
Half Arrow (left) Meia Seta (esquerda)
Half Arrow (right) Meia Seta (direita)
Concave Côncava
@@ -6466,6 +6472,7 @@ effect Regular Regular
Kite Pipa
Triangle to Bar Triângulo para Barra
Oval Oval
Line Arrow Seta de Linha
Complementary Complementar
Complementary 2 Complementar 2
Split Complementary Complementar Dividida
@@ -8318,6 +8325,7 @@ breakText Glyphs Glifos
Remove Strokes Remover Traçados
Place Brush Art Colocar Arte do Pincel
Replace Brush Art Substituir Arte do Pincel
Replace Pattern Art Substituir Arte do Padrão
Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Traçados usam este pincel. Aplicar a nova arte a esses traçados, ou deixá-los como estão e adicionar uma cópia do pincel com a nova arte?
Apply to Strokes Aplicar aos Traçados
Leave Strokes Manter Traçados
@@ -10793,6 +10801,11 @@ swatch Yellow Green Verde-amarelado
@msg A panel is not joined to the rest by a crease. Um painel não está unido ao restante por nenhuma linha de vinco.
@msg A fold line is on a non-printing layer. Uma linha de dobra está em uma camada não imprimível.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Painéis: {panels}, dobradiças: {hinges}, erros: {errors}, avisos: {warnings}
Engraving Gravura
Fine Hatching Hachuras finas
Dense Hatching Hachuras densas
Tapered Hatching Hachuras afiladas
Broken Hatching Hachuras interrompidas
Image Brush Pincéis de imagem
Soft Bloom Flor suave
Halftone Field Campo de meios-tons
Can't render this file because it is too large.
+14
View File
@@ -1717,6 +1717,10 @@ file-filter Templates Шаблоны
Add Color Tool Инструмент «Добавить цвет»
Remove Color Tool Инструмент «Удалить цвет»
Remove Color Удалить цвет
Set As Base Color Сделать базовым цветом
Select Shade Выбрать оттенок
Add New Color Добавить новый цвет
Set Current Color As Base Color Сделать текущий цвет базовым
Find the selected colors in the artwork Найти выбранные цвета в рисунке
Harmony Sets Наборы гармонии
Height Высота
@@ -2134,6 +2138,7 @@ file-filter Templates Шаблоны
Limit to Library: Ограничить библиотекой:
Limit: Предел:
Line Линия
Line Arrow Линейная стрелка
Line Art and Text Resolution: Разрешение штрихового рисунка и текста:
Line Breaks Разрывы строк
Line Color Цвет линии
@@ -5426,6 +5431,7 @@ liquify-list-end {0}, {1} {0} и {1}
@msg no native format нет собственного формата
@msg no pages нет страниц
@msg no pattern `{name}` нет узора `{name}`
@msg art painted with `{name}` can't be its tile графика, окрашенная узором `{name}`, не может быть его плиткой
@msg no perspective grid preset named `{name}` нет набора сетки перспективы с именем `{name}`
@msg no plug-in {0} is installed модуль {0} не установлен
@msg no plug-in {id} is installed модуль {id} не установлен
@@ -7596,6 +7602,8 @@ axis Y Axis Ось Y
Auto Size Авторазмер
Bar Черта
Barbed С зазубриной
arrowhead Feather Перо
arrowhead Target Мишень
Baseline (Standard) Базовый (стандартный)
Baseline Optimized Базовый оптимизированный
Bicubic Бикубическая
@@ -8289,6 +8297,7 @@ breakText Glyphs Глифы
Remove Strokes Убрать обводки
Place Brush Art Поместить рисунок кисти
Replace Brush Art Заменить рисунок кисти
Replace Pattern Art Заменить рисунок узора
Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Обводки используют эту кисть. Применить новый рисунок к этим обводкам или оставить их как есть и добавить копию кисти с новым рисунком?
Apply to Strokes Применить к обводкам
Leave Strokes Оставить обводки
@@ -10776,6 +10785,11 @@ shape Open Открытый
@msg Two panels pass through each other. Две панели проходят друг сквозь друга.
@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} пикселей — слишком большой размер для PSD (не более {MAX_SIDE} пикселей по стороне): уменьшите разрешение
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer должен быть "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine"
Engraving Гравировка
Fine Hatching Тонкая штриховка
Dense Hatching Плотная штриховка
Tapered Hatching Сужающаяся штриховка
Broken Hatching Прерывистая штриховка
Image Brush Кисти изображений
Soft Bloom Мягкое цветение
Halftone Field Полутоновое поле
Can't render this file because it is too large.
+13
View File
@@ -1654,6 +1654,10 @@ font-technology Variable Variabla
Add Color Tool Verktyget Lägg till färg
Remove Color Tool Verktyget Ta bort färg
Remove Color Ta bort färg
Set As Base Color Ange som grundfärg
Select Shade Välj nyans
Add New Color Lägg till ny färg
Set Current Color As Base Color Ange aktuell färg som grundfärg
Find the selected colors in the artwork Hitta de markerade färgerna i teckningen
Harmony Sets Harmoniuppsättningar
Height Höjd
@@ -2036,6 +2040,7 @@ font-technology Variable Variabla
Limit to Library: Begränsa till bibliotek:
Limit: Gränsvärde:
Line Linje
Line Arrow Linjepil
Line Art and Text Resolution: Upplösning för streckteckning och text:
Line Breaks Radbrytningar
Line Color Linjefärg
@@ -5291,6 +5296,7 @@ liquify-list-end {0}, {1} {0} och {1}
@msg no native format inget eget format
@msg no pages inga sidor
@msg no pattern `{name}` inget mönster `{name}`
@msg art painted with `{name}` can't be its tile grafik målad med `{name}` kan inte vara dess ruta
@msg no perspective grid preset named `{name}` ingen förinställning för perspektivrutnät med namnet `{name}`
@msg no plug-in {0} is installed inget plugin {0} är installerat
@msg no plug-in {id} is installed inget plugin {id} är installerat
@@ -6404,6 +6410,7 @@ lighting Light Ljus
B5 B5
Bar Lodstreck
Barbed Hullingförsedd
arrowhead Feather Fjäder
Baseline (Standard) Baseline (standard)
Baseline Optimized Baseline optimerad
Basic Grundläggande
@@ -8334,6 +8341,7 @@ breakText Glyphs Glyfer
Remove Strokes Ta bort konturer
Place Brush Art Placera penselgrafik
Replace Brush Art Ersätt penselgrafik
Replace Pattern Art Ersätt mönstergrafik
Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Konturer använder den här penseln. Använd den nya grafiken på konturerna, eller låt dem vara som de är och lägg till en kopia av penseln med den nya grafiken?
Apply to Strokes Använd på konturer
Leave Strokes Behåll konturer
@@ -10814,6 +10822,11 @@ digits Hindi Hindi
@msg A joint does not close by {gap} pt. En fog sluter inte med {gap} pt.
@msg Two panels pass through each other. Två paneler går igenom varandra.
@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pixlar är för stort för PSD (högst {MAX_SIDE} pixlar per sida): sänk upplösningen
Engraving Gravyr
Fine Hatching Fin skraffering
Dense Hatching Tät skraffering
Tapered Hatching Avsmalnande skraffering
Broken Hatching Bruten skraffering
Image Brush Bildpenslar
Soft Bloom Mjuk blomning
Halftone Field Halvtonsfält
Can't render this file because it is too large.
+15
View File
@@ -770,6 +770,21 @@ fn built_in_library_style_names_are_in_complete_catalogs() {
assert!(bad.is_empty(), "{}", bad.join("\n"));
}
/// The Stroke panel and the Dimension tool's Arrow Style list the built-in arrowheads by name, so
/// each name has a row in each complete catalog: an `arrowhead` row, or a plain one. Feather needs
/// its `arrowhead` row, since its plain row may name the Feather effect.
#[test]
fn built_in_arrowhead_names_are_in_complete_catalogs() {
use vectorcraft_doc::Arrowhead;
let names = distinct(Arrowhead::ALL.iter().map(|h| h.label().to_string()).collect());
assert_eq!(names.len(), 41, "{names:?}");
// Spanish's plain Target row names a destination; its arrowhead row names the shape.
let es = crate::i18n::Lang::from_code("es").expect("es registered");
assert_eq!(crate::i18n::tr_ctx(es, "arrowhead", "Target"), "Diana");
let bad = lacking(&names, |c, n| c.contextual("arrowhead", n).is_some() || (n != "Feather" && c.plain(n).is_some()));
assert!(bad.is_empty(), "{}", bad.join("\n"));
}
/// A built-in symbol library's panel lists its symbols in the UI language, so every symbol of
/// every built-in library has a row in each complete catalog.
#[test]
+13
View File
@@ -1617,6 +1617,10 @@ font-technology Variable Değişken
Add Color Tool Renk Ekle aracı
Remove Color Tool Renk Kaldır aracı
Remove Color Rengi kaldır
Set As Base Color Temel renk olarak ayarla
Select Shade Ton seç
Add New Color Yeni renk ekle
Set Current Color As Base Color Geçerli rengi temel renk olarak ayarla
Find the selected colors in the artwork Seçili renkleri resimde bul
Harmony Sets Armoni Setleri
Height Yükseklik
@@ -1929,6 +1933,7 @@ font-technology Variable Değişken
Limit to Library: Kütüphaneyle Sınırlama:
Limit: Sınır:
Line Hat
Line Arrow Çizgi Ok
Line Art and Text Resolution: Çizgi Sanatı ve Metin Çözünürlüğü:
Line Breaks Satır Sonları
Line Color Çizgi Rengi
@@ -5114,6 +5119,7 @@ liquify-list-end {0}, {1} {0} ve {1}
@msg no native format yerel format yok
@msg no pages sayfa yok
@msg no pattern `{name}` `{name}` deseni yok
@msg art painted with `{name}` can't be its tile `{name}` ile boyanmış resim onun döşemesi olamaz
@msg no perspective grid preset named `{name}` `{name}` adında perspektif ızgarası ön ayarı yok
@msg no plug-in {0} is installed {0} eklentisi kurulu değil
@msg no plug-in {id} is installed {id} eklentisi kurulu değil
@@ -6253,6 +6259,7 @@ lighting Light Işık
B5 B5
Bar Bar
Barbed Dikenli
arrowhead Feather Tüy
Baseline (Standard) Temel (Standart)
Baseline Optimized Temel Optimize Edilmiş
Basic Temel
@@ -10189,6 +10196,7 @@ breakText Glyphs Glifler
Remove Strokes Konturları Kaldır
Place Brush Art Fırça Çizimini Yerleştir
Replace Brush Art Fırça Çizimini Değiştir
Replace Pattern Art Desen Çizimini Değiştir
Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Konturlar bu fırçayı kullanıyor. Yeni çizim bu konturlara uygulansın mı, yoksa konturlar olduğu gibi bırakılıp fırçanın yeni çizimli bir kopyası mı eklensin?
Apply to Strokes Konturlara Uygula
Leave Strokes Konturları Bırak
@@ -10679,6 +10687,11 @@ breakText Glyphs Glifler
@msg A panel is not joined to the rest by a crease. Bir panel geri kalanlara hiçbir pilyaj çizgisiyle bağlı değil.
@msg A fold line is on a non-printing layer. Bir katlama çizgisi yazdırılmayan bir katmanda.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneller: {panels}, menteşeler: {hinges}, hatalar: {errors}, uyarılar: {warnings}
Engraving Gravür
Fine Hatching İnce tarama
Dense Hatching Yoğun tarama
Tapered Hatching İncelen tarama
Broken Hatching Kesikli tarama
Image Brush Görsel Fırçaları
Soft Bloom Yumuşak Çiçek
Halftone Field Yarı Ton Alanı
Can't render this file because it is too large.
+42
View File
@@ -1725,6 +1725,10 @@ file-filter Templates Шаблони
Add Color Tool Інструмент «Додати колір»
Remove Color Tool Інструмент «Вилучити колір»
Remove Color Вилучити колір
Set As Base Color Зробити базовим кольором
Select Shade Вибрати відтінок
Add New Color Додати новий колір
Set Current Color As Base Color Зробити поточний колір базовим
Find the selected colors in the artwork Знайти вибрані кольори в малюнку
Harmony Sets Набори гармонії
Height Висота
@@ -5415,6 +5419,7 @@ liquify-list-end {0}, {1} {0} і {1}
@msg no native format немає власного формату
@msg no pages немає сторінок
@msg no pattern `{name}` немає візерунка `{name}`
@msg art painted with `{name}` can't be its tile графіка, зафарбована візерунком `{name}`, не може бути його плиткою
@msg no perspective grid preset named `{name}` немає набору сітки перспективи з ім’ям `{name}`
@msg no plug-in {0} is installed модуль {0} не встановлений
@msg no plug-in {id} is installed модуль {id} не встановлений
@@ -7624,6 +7629,37 @@ anchor Points: Точки:
@msg `{id}` is not a colour adjustment `{id}` не є корекцією кольору
@msg missing `effect` відсутня `effect`
@msg `params` must be an object `params` має бути об’єктом
# Stroke arrowheads (Stroke panel, Dimension Tool Options and Properties › Arrow Style).
Triangle (open) Трикутник (контурний)
Circle (open) Коло (контурне)
Square (open) Квадрат (контурний)
Arrow (open) Стрілка (контурна)
Barbed Зазубрена
arrowhead Feather Оперення
arrowhead Target Мішень
Half Arrow (left) Половина стрілки (ліворуч)
Half Arrow (right) Половина стрілки (праворуч)
Double Bar Подвійна смуга
Dot on Bar Крапка на смузі
Chevron Шеврон
Plus Плюс
Hexagon (open) Шестикутник (контурний)
Tag Ярлик
Tag (open) Ярлик (контурний)
Half Circle Півколо
Drop Крапля
Slash Скісна риска
Double Slash Подвійна скісна риска
Diamond (open) Ромб (контурний)
Reverse Triangle Обернений трикутник
Swallowtail Ластівчин хвіст
Bracket Дужка
Fork Вилка
Leaf Листок
Kite Дельтоїд
Triangle to Bar Трикутник до смуги
Oval Овал
Line Arrow Лінійна стрілка
# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages.
Path Precision Tools Інструменти точного редагування контурів
Anchor Eraser Brush Пензель-гумка опорних точок
@@ -7914,6 +7950,7 @@ breakText Glyphs Гліфи
Remove Strokes Забрати обведення
Place Brush Art Розмістити малюнок пензля
Replace Brush Art Замінити малюнок пензля
Replace Pattern Art Замінити малюнок візерунка
Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Обведення використовують цей пензель. Застосувати новий малюнок до цих обведень чи залишити їх як є і додати копію пензля з новим малюнком?
Apply to Strokes Застосувати до обведень
Leave Strokes Залишити обведення
@@ -10343,6 +10380,11 @@ breakText Glyphs Гліфи
@msg A panel is not joined to the rest by a crease. Панель не з’єднана з рештою жодною лінією біговки.
@msg A fold line is on a non-printing layer. Лінія згину лежить на шарі, що не друкується.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панелі: {panels}, шарніри: {hinges}, помилки: {errors}, попередження: {warnings}
Engraving Гравіювання
Fine Hatching Тонке штрихування
Dense Hatching Щільне штрихування
Tapered Hatching Звужене штрихування
Broken Hatching Переривчасте штрихування
Image Brush Пензлі зображень
Soft Bloom М’яке цвітіння
Halftone Field Напівтонове поле
Can't render this file because it is too large.
+41
View File
@@ -1968,6 +1968,10 @@ file-filter Templates Mẫu
Add Color Tool Công cụ Thêm màu
Remove Color Tool Công cụ Xóa màu
Remove Color Xóa màu
Set As Base Color Đặt làm màu cơ sở
Select Shade Chọn sắc độ
Add New Color Thêm màu mới
Set Current Color As Base Color Đặt màu hiện tại làm màu cơ sở
Find the selected colors in the artwork Tìm các màu đã chọn trong tác phẩm
Harmony Sets Bộ hài hòa màu
Height Chiều cao
@@ -5794,6 +5798,7 @@ liquify-list-end {0}, {1} {0} và {1}
@msg no native format không có định dạng gốc
@msg no pages không có trang
@msg no pattern `{name}` không có họa tiết `{name}`
@msg art painted with `{name}` can't be its tile đối tượng được tô bằng `{name}` không thể làm ô của nó
@msg no perspective grid preset named `{name}` không có thiết lập sẵn lưới phối cảnh tên `{name}`
@msg no plug-in {0} is installed plug-in {0} chưa được cài đặt
@msg no plug-in {id} is installed plug-in {id} chưa được cài đặt
@@ -7671,6 +7676,36 @@ anchor Points: Điểm:
@msg `{id}` is not a colour adjustment `{id}` không phải là điều chỉnh màu
@msg missing `effect` thiếu `effect`
@msg `params` must be an object `params` phải là một đối tượng
# Stroke arrowheads (Stroke panel, Dimension Tool Options and Properties › Arrow Style).
Triangle (open) Tam giác (rỗng)
Circle (open) Hình tròn (rỗng)
Square (open) Hình vuông (rỗng)
Arrow (open) Mũi tên (rỗng)
Barbed Có ngạnh
arrowhead Feather Lông vũ
Half Arrow (left) Nửa mũi tên (trái)
Half Arrow (right) Nửa mũi tên (phải)
Double Bar Thanh đôi
Dot on Bar Chấm trên thanh
Chevron Hình chữ V
Plus Dấu cộng
Hexagon (open) Lục giác (rỗng)
Tag Nhãn
Tag (open) Nhãn (rỗng)
Half Circle Nửa hình tròn
Drop Giọt nước
Slash Gạch chéo
Double Slash Gạch chéo đôi
Diamond (open) Hình thoi (rỗng)
Reverse Triangle Tam giác ngược
Swallowtail Đuôi én
Bracket Ngoặc
Fork Chạc
Leaf Chiếc lá
Kite Hình diều
Triangle to Bar Tam giác đến thanh
Oval Hình bầu dục
Line Arrow Mũi tên nét
# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages.
Path Precision Tools Công cụ chính xác cho đường dẫn
Anchor Eraser Brush Cọ tẩy điểm neo
@@ -7961,6 +7996,7 @@ breakText Glyphs Glyph
Remove Strokes Gỡ nét
Place Brush Art Đặt đối tượng của cọ
Replace Brush Art Thay đối tượng của cọ
Replace Pattern Art Thay đối tượng của họa tiết
Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Có nét đang dùng cọ này. Áp dụng đối tượng mới cho các nét đó, hay giữ nguyên chúng và thêm một bản sao của cọ với đối tượng mới?
Apply to Strokes Áp dụng cho nét
Leave Strokes Giữ nguyên nét
@@ -8541,6 +8577,11 @@ breakText Glyphs Glyph
@msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} điểm ảnh quá lớn cho Targa (tối đa 65535 điểm ảnh mỗi cạnh): hãy giảm độ phân giải
@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} điểm ảnh quá lớn cho PSD (tối đa {MAX_SIDE} điểm ảnh mỗi cạnh): hãy giảm độ phân giải
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer phải là "singleLine", "everyLine", "standardSingleLine" hoặc "standardEveryLine"
Engraving Khắc nét
Fine Hatching Nét gạch mảnh
Dense Hatching Nét gạch dày
Tapered Hatching Nét gạch thuôn
Broken Hatching Nét gạch đứt
Image Brush Cọ hình ảnh
Soft Bloom Hoa nở mềm
Halftone Field Vùng bán sắc
Can't render this file because it is too large.
+41
View File
@@ -1659,6 +1659,10 @@ file-filter Templates 模板
Add Color Tool 添加颜色工具
Remove Color Tool 删除颜色工具
Remove Color 删除颜色
Set As Base Color 设为基色
Select Shade 选择色调
Add New Color 添加新颜色
Set Current Color As Base Color 将当前颜色设为基色
Find the selected colors in the artwork 在图稿中查找所选颜色
Harmony Sets 色彩调和组
Height 高度
@@ -4883,6 +4887,7 @@ imageTrace Outline 轮廓
@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} 生成了空结果:直线或其他开放路径不围成区域;要包含它,请先对其应用“对象 › 路径 › 轮廓化描边”
@msg already editing a pattern 已在编辑图案
@msg no pattern `{name}` 没有图案 `{name}`
@msg art painted with `{name}` can't be its tile 使用 `{name}` 上色的图稿不能作为它的拼贴
@msg not in pattern editing mode 不在图案编辑模式中
@msg finish editing the pattern first 请先完成图案编辑
@msg pattern missing 缺少图案
@@ -7851,6 +7856,36 @@ anchor Points: 点:
@msg `{id}` is not a colour adjustment `{id}` 不是颜色调整
@msg missing `effect` 缺少 `effect`
@msg `params` must be an object `params` 必须是对象
# Stroke arrowheads (Stroke panel, Dimension Tool Options and Properties › Arrow Style).
Triangle (open) 三角 (空心)
Circle (open) 圆形 (空心)
Square (open) 正方形 (空心)
Arrow (open) 箭头 (空心)
Barbed 倒钩
arrowhead Feather 羽毛
Half Arrow (left) 半箭头 (左)
Half Arrow (right) 半箭头 (右)
Double Bar 双条形
Dot on Bar 条形上的圆点
Chevron 人字形
Plus 加号
Hexagon (open) 六边形 (空心)
Tag 标签
Tag (open) 标签 (空心)
Half Circle 半圆
Drop 水滴
Slash 斜线
Double Slash 双斜线
Diamond (open) 菱形 (空心)
Reverse Triangle 倒三角
Swallowtail 燕尾
Bracket 括号
Fork 叉形
Leaf 叶形
Kite 风筝形
Triangle to Bar 三角至条形
Oval 椭圆
Line Arrow 线条箭头
# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages.
Path Precision Tools 路径精确工具
Anchor Eraser Brush 锚点橡皮擦画笔
@@ -8140,6 +8175,7 @@ breakText Glyphs 字形
Remove Strokes 移除描边
Place Brush Art 置入画笔图稿
Replace Brush Art 替换画笔图稿
Replace Pattern Art 替换图案图稿
Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? 有描边使用了此画笔。要将新图稿应用到这些描边,还是保留描边不变并添加一个使用新图稿的画笔副本?
Apply to Strokes 应用于描边
Leave Strokes 保留描边
@@ -10536,6 +10572,11 @@ breakText Glyphs 字形
@msg A joint does not close by {gap} pt. 有一处接缝相差 {gap} pt 未闭合。
@msg Two panels pass through each other. 两个面板相互穿插。
@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} 像素对 PSD 而言过大 (每边最多 {MAX_SIDE} 像素):请降低分辨率
Engraving 雕刻
Fine Hatching 细线排线
Dense Hatching 密集排线
Tapered Hatching 渐细排线
Broken Hatching 断续排线
Image Brush 图像画笔
Soft Bloom 柔和花朵
Halftone Field 半色调区域
Can't render this file because it is too large.
+41
View File
@@ -1696,6 +1696,10 @@ file-filter Templates 範本
Add Color Tool 新增顏色工具
Remove Color Tool 移除顏色工具
Remove Color 移除顏色
Set As Base Color 設為基色
Select Shade 選取色調
Add New Color 新增顏色
Set Current Color As Base Color 將目前顏色設為基色
Find the selected colors in the artwork 在圖稿中尋找所選顏色
Harmony Sets 色彩調和組
Height 高度
@@ -2266,6 +2270,7 @@ file-filter Templates 範本
@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} 產生了空的結果:直線或其他開放路徑不圍成區域;若要納入,請先對其套用「物件 › 路徑 › 外框筆畫」
@msg already editing a pattern 已在編輯圖樣
@msg no pattern `{name}` 沒有圖樣 `{name}`
@msg art painted with `{name}` can't be its tile 以 `{name}` 上色的圖稿不能作為它的拼貼
@msg not in pattern editing mode 不在圖樣編輯模式中
@msg finish editing the pattern first 請先完成圖樣編輯
@msg pattern missing 找不到圖樣
@@ -7673,6 +7678,36 @@ anchor Points: 點:
@msg `{id}` is not a colour adjustment `{id}` 不是顏色調整
@msg missing `effect` 未提供 `effect`
@msg `params` must be an object `params` 必須是物件
# Stroke arrowheads (Stroke panel, Dimension Tool Options and Properties › Arrow Style).
Triangle (open) 三角 (空心)
Circle (open) 圓形 (空心)
Square (open) 正方形 (空心)
Arrow (open) 箭頭 (空心)
Barbed 倒鉤
arrowhead Feather 羽毛
Half Arrow (left) 半箭頭 (左)
Half Arrow (right) 半箭頭 (右)
Double Bar 雙長條
Dot on Bar 長條上的圓點
Chevron 人字形
Plus 加號
Hexagon (open) 六邊形 (空心)
Tag 標籤
Tag (open) 標籤 (空心)
Half Circle 半圓
Drop 水滴
Slash 斜線
Double Slash 雙斜線
Diamond (open) 菱形 (空心)
Reverse Triangle 倒三角
Swallowtail 燕尾
Bracket 括號
Fork 叉形
Leaf 葉形
Kite 風箏形
Triangle to Bar 三角至長條
Oval 橢圓
Line Arrow 線條箭頭
# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages.
Path Precision Tools 路徑精確工具
Anchor Eraser Brush 錨點橡皮擦筆刷
@@ -7963,6 +7998,7 @@ breakText Glyphs 字符
Remove Strokes 移除筆畫
Place Brush Art 置入筆刷圖稿
Replace Brush Art 取代筆刷圖稿
Replace Pattern Art 取代圖樣圖稿
Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? 有筆畫使用了此筆刷。要將新圖稿套用到這些筆畫,還是保留筆畫不變並加入一個使用新圖稿的筆刷複本?
Apply to Strokes 套用至筆畫
Leave Strokes 保留筆畫
@@ -10351,6 +10387,11 @@ breakText Glyphs 字符
@msg A joint does not close by {gap} pt. 有一處接縫相差 {gap} pt 未閉合。
@msg Two panels pass through each other. 兩個面板相互穿插。
@msg {what} would print on more than {MAX_TILES} tiles: scale it down {what} 會列印在超過 {MAX_TILES} 個拼貼上:請縮小
Engraving 雕刻
Fine Hatching 細線排線
Dense Hatching 密集排線
Tapered Hatching 漸細排線
Broken Hatching 斷續排線
Image Brush 影像筆刷
Soft Bloom 柔和花朵
Halftone Field 半色調區域
Can't render this file because it is too large.
+3 -1
View File
@@ -334,7 +334,9 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool {
"ui.packageDialog" | "docInfo.save" => app.session.active().is_some(),
"ui.batchDialog" => !app.ui.action_sets.is_empty() && app.ui.action_sets.iter().any(|s| !s.actions.is_empty()),
"ui.epsOptionsDialog" | "ui.hpglOptionsDialog" => app.session.active().is_some(),
"file.saveForWeb" | "file.saveForWeb.browser" | "file.export.svg.browser" => app.session.active().is_some(),
"file.saveForWeb" => app.session.active().is_some(),
// A browser preview opens a file, and the web build has none to open.
"file.saveForWeb.browser" | "file.export.svg.browser" => app.session.active().is_some() && !crate::io::is_web(app),
"file.exportSelection" => app.session.active().is_some_and(|d| !d.selection.is_empty()),
"css.copy" | "css.exportFile" => app.session.active().is_some(),
"print.printerSetup" => app.services.print.as_ref().is_some_and(|s| s.has_setup()),
+18 -2
View File
@@ -429,11 +429,27 @@ fn restore_hidden_group(app: &mut VectorcraftApp, panel: &str) -> Result<Value,
Ok(result)
}
/// The tab in front of the group that holds `panel` in a dock column collapsed to icons.
fn flyout_tab(layout: &Layout<String>, panel: &str) -> Option<String> {
dock_columns(layout)
.into_iter()
.filter(|column| column.iconic)
.flat_map(|column| &column.groups)
.find(|group| group.panels.iter().any(|p| p == panel))
.and_then(|group| group.active_panel())
.map(|front| front.to_string())
}
/// Show `panel` as `window.panel` does, but leave it be when it can be seen already ([`visible`]):
/// a command that opens a panel to work in (Edit › Color Settings…) never puts it away. In
/// Presentation Mode the panel comes to the front of its group and shows when the mode ends.
/// a command that opens a panel to work in (Edit › Color Settings…) never puts it away. A flyout
/// keeps the name of the icon that opened it after another of its tabs is clicked, so a panel whose
/// flyout is open with another tab in front comes to the front of it. In Presentation Mode the
/// panel comes to the front of its group and shows when the mode ends.
pub(crate) fn reveal_panel(app: &mut VectorcraftApp, panel: &str) -> Result<Value, String> {
if visible(&app.ui, panel) {
if app.ui.docking.is_some() && flyout_tab(&layout_of(&app.ui), panel).is_some_and(|front| front != panel) {
gesture(app, Action::Activate { panel: panel.to_string() })?;
}
return Ok(json!({"open": panel}));
}
let id = normalize(panel).ok_or_else(|| format!("unknown panel `{panel}`"))?;
+22
View File
@@ -397,6 +397,28 @@ fn a_collapsed_dock_uses_the_flyouts_active_tab_for_thumbnail_work() {
assert!(!thumbnail_panel_showing(&h.app.ui, &h.ctx), "a Properties tab under the Layers icon does not need thumbnails");
}
/// Revealing a panel whose flyout is open with another tab of its group in front brings that panel
/// to the front and keeps the flyout open.
#[test]
fn reveal_brings_the_panel_to_the_front_of_its_open_flyout() {
let mut h = Harness::new();
h.app.run("window.collapseDock", json!({"collapsed": true})).unwrap();
h.app.ui.docking = Some(layout_of(&h.app.ui));
h.app.run("window.panel", json!({"panel": "properties"})).unwrap();
h.frame(vec![]);
gesture(&mut h.app, Action::Activate { panel: "layers".into() }).unwrap();
h.frame(vec![]);
assert_eq!(h.app.ui.open_panel.as_deref(), Some("properties"), "the flyout is still named for its opening icon");
assert_eq!(flyout_tab(&layout_of(&h.app.ui), "properties").as_deref(), Some("layers"), "Layers is in front");
reveal_panel(&mut h.app, "properties").unwrap();
h.frame(vec![]);
assert_eq!(h.app.ui.open_panel.as_deref(), Some("properties"), "the flyout stays open");
assert_eq!(flyout_tab(&layout_of(&h.app.ui), "properties").as_deref(), Some("properties"), "Properties is in front");
// Revealed again while in front, the panel stays as it is.
reveal_panel(&mut h.app, "properties").unwrap();
assert_eq!(h.app.ui.open_panel.as_deref(), Some("properties"));
}
/// A Character field shortcut with the Character panel in front of its floating window brings
/// that window forward and leaves the panel showing.
#[test]
+197 -19
View File
@@ -172,28 +172,17 @@ thread_local! {
static TARGET_LOOKUPS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
}
/// The object Trace acts on: the first selected image or Image Trace object in paint order, as
/// `imageTrace.make` takes it, else the first selected object. Only the selected images and Image
/// Trace objects are put in paint order.
/// The image or Image Trace object `imageTrace.make` takes from the selected roots, else the
/// first selected non-traceable object's metadata. Release and Expand keep their own selection scope.
fn find_target(app: &VectorcraftApp) -> Target {
let Some(st) = app.session.active() else { return Target::default() };
#[cfg(test)]
TARGET_LOOKUPS.with(|n| n.set(n.get() + 1));
let mut any_trace = false;
let traceable: Vec<NodeId> = st
.selection
.objects
.iter()
.copied()
.filter(|id| {
st.doc.node(*id).is_some_and(|n| {
let trace = is_trace(n);
any_trace |= trace;
trace || matches!(n.kind, NodeKind::Image(_))
})
})
.collect();
let node = st.doc.paint_order(traceable).into_iter().find_map(|id| st.doc.node(id)).or_else(|| first_node(app));
let any_trace = st.selection.objects.iter().any(|id| st.doc.node(*id).is_some_and(is_trace));
let node = vectorcraft_engine::cmd::image_trace_target(&app.session, &Value::Null)
.ok()
.and_then(|id| st.doc.node(id))
.or_else(|| first_node(app).filter(|n| !is_trace(n) && !matches!(n.kind, NodeKind::Image(_))));
let Some(n) = node else { return Target { any_trace, ..Target::default() } };
Target {
object: Some((st.uid, n.id)),
@@ -320,6 +309,175 @@ fn hold_source(app: &mut VectorcraftApp, ctx: &egui::Context, down: bool) {
}
}
/// The retained original image of a live trace, or the selected placed image itself.
fn source_image(n: &Node) -> Option<&vectorcraft_doc::ImageObject> {
let source = if is_trace(n) { n.children()?.first()?.as_ref() } else { n };
match &source.kind {
NodeKind::Image(image) => Some(image),
_ => None,
}
}
fn sampler_binding(s: &crate::state::TraceIgnoreSampler) -> Value {
json!({ "doc": s.doc, "target": s.target.0, "revision": s.revision })
}
fn sampler_valid(app: &VectorcraftApp, s: &crate::state::TraceIgnoreSampler) -> bool {
let Some(doc) = app.session.active() else { return false };
doc.uid == s.doc
&& doc.revision == s.revision
&& find_target(app).object == Some((s.doc, s.target))
&& doc.doc.node(s.target).and_then(source_image).is_some_and(|image| doc.doc.images.contains_key(&image.key))
}
fn sampler_tool_active(app: &VectorcraftApp, s: &crate::state::TraceIgnoreSampler) -> bool {
app.session.tool_id() == "eyedropper" && app.session.tool_options()["imageTraceIgnoreColor"] == sampler_binding(s)
}
/// Clear only this temporary mode. An explicit tool choice keeps the tool the user chose.
pub(crate) fn cancel_ignore_sampler(app: &mut VectorcraftApp, restore: bool) {
let Some(s) = app.ui.trace_ignore_sampler.take() else { return };
// This UI session owns these transient fields even while Cmd/Ctrl parks the eyedropper
// behind a borrowed selection tool. The named setter also updates that stored lender.
let options = serde_json::Map::from_iter([("imageTraceIgnoreColor".into(), Value::Null), ("stop".into(), Value::Null)]);
app.session.set_tool_options(Some("eyedropper"), &options);
if restore && app.session.tool_id() == "eyedropper" {
app.return_to_tool(&s.back);
}
if let Some(ctx) = &app.ui_ctx {
ctx.request_repaint();
}
}
/// Presets and restored panel settings can turn Ignore Color off without its checkbox.
fn cancel_disabled_ignore_sampler(app: &mut VectorcraftApp, params: &Value) {
if params["ignoreWhite"] != true {
cancel_ignore_sampler(app, true);
}
}
/// Also runs when the panel is closed: document changes and tool changes end the pick.
pub(crate) fn refresh_ignore_sampler(app: &mut VectorcraftApp) -> bool {
let Some(s) = app.ui.trace_ignore_sampler.as_ref() else { return false };
if !sampler_valid(app, s) {
cancel_ignore_sampler(app, true);
} else if !sampler_tool_active(app, s) {
cancel_ignore_sampler(app, false);
} else {
return false;
}
true
}
/// A stale sampler's click must not become a paint/selection click in the restored tool.
pub(crate) fn discard_stale_ignore_click(app: &mut VectorcraftApp) -> bool {
let Some(s) = app.ui.trace_ignore_sampler.as_ref() else { return false };
if sampler_valid(app, s) && sampler_tool_active(app, s) {
return false;
}
let restore = app.session.tool_id() == "eyedropper";
cancel_ignore_sampler(app, restore);
true
}
fn start_ignore_sampler(app: &mut VectorcraftApp, ctx: &egui::Context) {
if app.ui.trace_ignore_sampler.is_some() {
cancel_ignore_sampler(app, true);
return;
}
let Some((doc, target)) = target(app, ctx).object else { return };
let Some(revision) = app.session.active().map(|d| d.revision) else { return };
let s = crate::state::TraceIgnoreSampler { doc, target, revision, back: app.session.tool_id().to_string() };
if !sampler_valid(app, &s) {
return;
}
if let Err(e) = app.try_select_tool("eyedropper") {
app.status(e);
return;
}
if !sampler_valid(app, &s) {
app.return_to_tool(&s.back);
return;
}
app.session.set_tool_option("imageTraceIgnoreColor", &sampler_binding(&s));
app.session.set_tool_option("stop", &json!(s.back.as_str()));
// Bind the reply to this panel's state, also when it is drawn without the full app frame.
app.ui_ctx = Some(ctx.clone());
app.ui.trace_ignore_sampler = Some(s);
if let Some(ctx) = &app.ui_ctx {
ctx.request_repaint();
}
}
/// Match Image Trace's input bytes, not the current canvas result or the working-space colour.
fn sampled_ignore_color(app: &VectorcraftApp, s: &crate::state::TraceIgnoreSampler, p: &Value) -> Option<String> {
let point = vectorcraft_geom::Point::new(p["point"][0].as_f64()?, p["point"][1].as_f64()?);
if !point.x.is_finite() || !point.y.is_finite() {
return None;
}
let doc = &app.session.active()?.doc;
let image = source_image(doc.node(s.target)?)?;
if image.xf.determinant().abs() < 1e-12 {
return None;
}
let pixel = image.xf.inverse() * point;
if !pixel.x.is_finite()
|| !pixel.y.is_finite()
|| pixel.x < 0.0
|| pixel.y < 0.0
|| pixel.x >= f64::from(image.width.max(1))
|| pixel.y >= f64::from(image.height.max(1))
{
return None;
}
let [r, g, b, alpha] = doc.images.get(&image.key)?.sample_object(pixel.x, pixel.y, (image.width, image.height), 1)?;
(alpha != 0).then(|| format!("#{r:02x}{g:02x}{b:02x}"))
}
/// A miss keeps the pick armed; only a valid source color, Escape or invalid binding ends it.
pub(crate) fn apply_ignore_color_sample(app: &mut VectorcraftApp, p: &Value) {
let Some(s) = app.ui.trace_ignore_sampler.as_ref() else { return };
if p["binding"] != sampler_binding(s) {
return;
}
if p["cancel"] == true {
// Escape already carries its one deferred SwitchTool request.
cancel_ignore_sampler(app, false);
return;
}
if !sampler_valid(app, s) {
cancel_ignore_sampler(app, true);
return;
}
// Outside the source or over a transparent pixel there is no color to accept. Keep the
// binding and previous tool so the next canvas click can still complete this pick.
let Some(color) = sampled_ignore_color(app, s, p) else { return };
let s = s.clone();
// The canvas UI establishes this context before a real panel click can arm the sampler.
let Some(ctx) = app.ui_ctx.clone() else { return };
cancel_ignore_sampler(app, false);
let all = presets(app, &ctx);
let mut st: TraceUi = pstate(&ctx, "image-trace");
let Target { is_trace, stored, .. } = target(app, &ctx);
follow_preset_changes(app, &mut st, &all);
let changes: Vec<&TracePresetChange> = app.session.trace_preset_changes_since(0).collect();
sync_with_object(&mut st, stored, Some((s.doc, s.target)), &all, &changes);
st.params["ignoreColor"] = json!(color);
st.preset = "Custom".into();
let preview = app.ui.image_trace_preview;
if is_trace || !preview {
st.preview_off = !preview;
}
if is_trace && preview {
trace(app, &ctx, &mut st);
}
set_pstate(&ctx, "image-trace", st);
ctx.request_repaint();
// Complete the temporary tool without treating its return as a fresh explicit tool choice.
// A miss above has no switch request and remains armed.
app.return_to_tool(&s.back);
}
/// The selected Image Trace object's View row (Control bar, Properties).
pub(crate) fn view_row(app: &mut VectorcraftApp, ui: &mut Ui, current: TraceView, width: f32) {
widgets::dim_label(ui, tl!("View:"));
@@ -895,17 +1053,36 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
ui.horizontal(|ui| {
let on = st.params["ignoreWhite"].as_bool().unwrap_or(false);
if widgets::check(ui, tl!("Ignore Color"), on, true) {
if on {
cancel_ignore_sampler(app, true);
}
st.params["ignoreWhite"] = json!(!on);
st.preset = "Custom".into();
retrace = true;
}
if on {
let mut rgb = ignore_color(&st.params);
if ui.color_edit_button_srgb(&mut rgb).changed() {
let picker = ui.color_edit_button_srgb(&mut rgb);
if picker.clicked() {
cancel_ignore_sampler(app, true);
}
if picker.changed() {
st.params["ignoreColor"] = json!(format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2]));
st.preset = "Custom".into();
retrace = true;
}
if widgets::icon_button_enabled(
ui,
"pipette",
tl!("Eyedropper: click the source image to sample the ignored color"),
app.ui.trace_ignore_sampler.is_some(),
is_trace || is_image,
22.0,
)
.clicked()
{
start_ignore_sampler(app, ui.ctx());
}
}
});
}
@@ -943,6 +1120,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
if is_trace || !preview {
st.preview_off = !preview;
}
cancel_disabled_ignore_sampler(app, &st.params);
if retrace && is_trace && preview {
trace(app, ui.ctx(), &mut st);
}
+33 -3
View File
@@ -1763,7 +1763,8 @@ fn lookup_fixture() -> (VectorcraftApp, std::collections::HashMap<&'static str,
/// The panel's lookup gives what putting the whole selection in paint order gave, field for field,
/// for every kind of selection: images in either selection order, an Image Trace object with its
/// own image, a clipping group named Image Trace, nested groups, hidden and locked images, two
/// layers, repeated ids, ids the document lacks, and nothing selected. The result kept for a
/// layers, repeated ids, ids the document lacks, and nothing selected. Selected ancestors with
/// their descendants have separate canonical-root expectations below. The result kept for a
/// revision follows each change of the selection, an edit, Undo and a switch of document.
#[test]
fn the_target_lookup_matches_sorting_the_whole_selection() {
@@ -1779,10 +1780,8 @@ fn the_target_lookup_matches_sorting_the_whole_selection() {
&["trace image", "trace"],
&["rect", "trace image"],
&["clip"],
&["clip", "clipped"],
&["rect", "clipped"],
&["outer"],
&["outer", "deep"],
&["inner", "rect"],
&["deep", "back"],
&["hidden", "locked"],
@@ -1838,6 +1837,37 @@ fn the_target_lookup_matches_sorting_the_whole_selection() {
assert_eq!(target(&none, &ctx), Target::default());
}
/// Trace only accepts selected roots: a selected parent blocks its image descendant.
/// Missing implicit-selection ids are dropped, while explicit ids are validated.
#[test]
fn the_target_lookup_obeys_canonical_roots_and_explicit_id_validation() {
let (mut app, ids) = lookup_fixture();
let ctx = egui::Context::default();
for (parent, child) in [("clip", "clipped"), ("outer", "deep")] {
select_as_is(&mut app, &[ids[parent], ids[child]]);
let uid = app.session.active().unwrap().uid;
let expected = Target { object: Some((uid, ids[parent])), ..Default::default() };
assert_eq!(find_target(&app), expected, "the selected {parent} supplies metadata, not its pruned image");
assert_eq!(target(&app, &ctx), expected);
assert_eq!(target(&app, &ctx), expected, "the canonical result is also cached");
assert!(vectorcraft_engine::cmd::image_trace_target(&app.session, &Value::Null).is_err());
let document = app.session.active().unwrap().doc.clone();
assert!(app.run("imageTrace.make", json!({})).is_err(), "Trace rejects that non-image root");
assert_eq!(app.session.active().unwrap().doc, document);
select_as_is(&mut app, &[ids[child]]);
assert_eq!(vectorcraft_engine::cmd::image_trace_target(&app.session, &Value::Null).unwrap(), ids[child], "the image alone remains eligible");
}
let stale = NodeId(u64::MAX);
select_as_is(&mut app, &[stale, ids["front"]]);
assert_eq!(target(&app, &ctx).object.map(|(_, id)| id), Some(ids["front"]), "implicit stale entries do not hide a valid image");
assert_eq!(vectorcraft_engine::cmd::image_trace_target(&app.session, &Value::Null).unwrap(), ids["front"]);
let explicit = json!({"ids": [stale.0, ids["front"].0]});
let document = app.session.active().unwrap().doc.clone();
assert!(vectorcraft_engine::cmd::image_trace_target(&app.session, &explicit).is_err(), "explicit missing ids are invalid");
assert!(app.run("imageTrace.make", explicit).is_err());
assert_eq!(app.session.active().unwrap().doc, document);
}
/// The panel and its menu look the object Trace acts on up once for each revision of the document,
/// however many frames show it, and again once the revision moves.
#[test]
+41 -2
View File
@@ -82,6 +82,26 @@ fn set_options(ctx: &egui::Context, f: impl FnOnce(&mut Options)) {
set_pstate(ctx, "links-options", o);
}
/// Show the Links panel on the selected image (the Control bar's Linked File or Embedded label),
/// wherever the panel is docked or floats; a panel that is already shown stays where it is. The
/// Link Info section opens, and when the panel next draws the list, a Show filter that leaves out
/// the image's row goes back to Show All and the list scrolls to the row ([`show`]). The sort,
/// thumbnail size and DCS option keep their settings.
pub(crate) fn show_selected_image(app: &mut VectorcraftApp, ctx: &egui::Context) {
let first = selected_images(app).first().copied();
let request = app.session.active().map(|st| st.uid).zip(first);
set_pstate(ctx, "links-scroll-to", request);
// The list drawn next is read after this request, so a row a file change has just brought
// into the Show filter is there to scroll to.
let mut c: std::sync::Arc<Cache> = pstate(ctx, "links-cache");
std::sync::Arc::make_mut(&mut c).at = f64::NEG_INFINITY;
set_pstate(ctx, "links-cache", c);
set_options(ctx, |o| o.info = true);
if let Err(e) = crate::panel_docking::reveal_panel(app, ID) {
app.status(e);
}
}
/// The rows to show (cached per document revision, the files looked at again every [`RECHECK`]
/// seconds) and the Link Info of the first selected image when the section is open. A frame that
/// fetches nothing returns the stored cache without copying it and stores nothing.
@@ -577,12 +597,28 @@ fn click(app: &mut VectorcraftApp, ctx: &egui::Context, rows: &[Value], id: u64,
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let t = Tokens::get(ui.ctx());
let o = options(ui.ctx());
let mut o = options(ui.ctx());
super::layers::show_thumbs_of(app.session.active().map(|st| st.uid));
let Some(cache) = cached(app, ui.ctx(), &o) else {
let Some(mut cache) = cached(app, ui.ctx(), &o) else {
widgets::dim_label(ui, tl!("No document"));
return;
};
// The row that `show_selected_image` asks for, used by this draw only and only in the document
// it was asked in. A Show filter that leaves the row out goes back to Show All, decided from the
// rows this frame draws and scrolls through.
let request: Option<(u64, u64)> = pstate(ui.ctx(), "links-scroll-to");
if request.is_some() {
set_pstate::<Option<(u64, u64)>>(ui.ctx(), "links-scroll-to", None);
}
let uid = app.session.active().map(|st| st.uid);
let scroll_to = request.filter(|(doc, _)| Some(*doc) == uid).map(|(_, id)| id);
let listed = |cache: &Cache, id: u64| cache.list["links"].as_array().is_some_and(|rows| rows.iter().any(|r| r["id"].as_u64() == Some(id)));
if scroll_to.filter(|id| o.show != "all" && !listed(&cache, *id)).is_some() {
set_options(ui.ctx(), |o| o.show = "all");
o = options(ui.ctx());
let Some(all) = cached(app, ui.ctx(), &o) else { return };
cache = all;
}
let Some(st) = app.session.active() else { return };
let doc = st.doc.clone();
let thumbs = super::layers::ThumbSource::of(app, st, &doc);
@@ -606,6 +642,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
for r in rows {
let Some(id) = r["id"].as_u64() else { continue };
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click());
if scroll_to == Some(id) {
ui.scroll_to_rect(rect, Some(egui::Align::Center));
}
if !ui.is_rect_visible(rect) {
continue;
}
+7 -1
View File
@@ -109,10 +109,16 @@ fn arrow_label(a: Option<&Arrowhead>) -> &'static str {
fn arrow_name(a: Option<&Arrowhead>) -> String {
match a {
Some(Arrowhead::Custom(c)) => c.name.clone(),
_ => tl!(arrow_label(a)).to_string(),
_ => builtin_arrow_name(arrow_label(a)).to_string(),
}
}
/// A built-in arrowhead's name `label` in the interface language. Its `arrowhead` row comes first,
/// so a name that is also an effect's (Feather) can be translated for each one.
pub(crate) fn builtin_arrow_name(label: &str) -> &str {
crate::i18n::tr_ctx(crate::i18n::current(), "arrowhead", label)
}
/// The preview cache key of `a`: its name, and for a custom head its art.
fn arrow_key(a: Option<&Arrowhead>) -> String {
match a {
+110 -53
View File
@@ -65,8 +65,10 @@ pub(super) enum Drop {
/// nor a tint swatch. With Cmd/Ctrl held (`spot`), a solid color other than Registration
/// becomes a spot color swatch.
New { paint: Paint, target: Option<String>, replace: bool, spot: bool },
/// Art dragged off the canvas becomes a pattern swatch made of a copy of it (the art stays).
Pattern { ids: Vec<u64> },
/// Art dragged off the canvas becomes a pattern swatch made of a copy of it (the art stays);
/// with Alt held (`replace`) over pattern swatch `target`, a copy of it becomes that pattern's
/// tile art instead.
Pattern { ids: Vec<u64>, target: Option<String>, replace: bool },
}
impl Drop {
@@ -81,16 +83,42 @@ impl Drop {
Some(Drop::Move { names: r.names.clone(), target, after, with })
}
PanelDrag::Paint { paint, .. } => Some(Drop::New { paint: paint.clone(), target, replace, spot }),
PanelDrag::Art(ids) => Some(Drop::Pattern { ids: ids.iter().map(|id| id.0).collect() }),
PanelDrag::Art(ids) => Some(Drop::Pattern { ids: ids.iter().map(|id| id.0).collect(), target, replace }),
_ => None,
}
}
}
/// The drag held over `resp`, if the panel takes it (paints and art dragged off the canvas, not the
/// Appearance panel's thumbnail).
/// Whether the panel takes drag `d`: paints and art dragged off the canvas, not the Appearance
/// panel's thumbnail.
fn takes(d: &PanelDrag) -> bool {
matches!(d, PanelDrag::Paint { .. } | PanelDrag::Art(_))
}
/// The drag held over `resp`, if the panel takes it ([`takes`]).
fn held(resp: &Response) -> Option<std::sync::Arc<PanelDrag>> {
resp.dnd_hover_payload::<PanelDrag>().filter(|d| matches!(**d, PanelDrag::Paint { .. } | PanelDrag::Art(_)))
resp.dnd_hover_payload::<PanelDrag>().filter(|d| takes(d))
}
/// The drag in progress, if the panel takes it ([`takes`]), wherever the pointer is.
fn dragged(ui: &Ui) -> Option<std::sync::Arc<PanelDrag>> {
egui::DragAndDrop::payload::<PanelDrag>(ui.ctx()).filter(|d| takes(d))
}
/// Where the primary button came up this frame and the modifiers held then, when that was over
/// `resp` with no other layer on top (the test [`egui::Context::rect_contains_pointer`] makes of the
/// pointer). A drop lands there with those modifiers, even when the pointer moved on or a key was
/// let go later in the same frame.
fn released_over(ui: &Ui, resp: &Response) -> Option<(egui::Pos2, egui::Modifiers)> {
let up = ui.input(|i| {
i.events.iter().find_map(|e| match e {
egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers } => Some((*pos, *modifiers)),
_ => None,
})
})?;
let ctx = ui.ctx();
let rect = ctx.layer_transform_to_global(resp.layer_id).map_or(resp.interact_rect, |t| t * resp.interact_rect);
(rect.is_positive() && rect.contains(up.0) && ctx.layer_id_at(up.0) == Some(resp.layer_id)).then_some(up)
}
/// The drag a tile or row of `e` starts, moving rows `names`. Colour groups have no paint of their
@@ -157,64 +185,80 @@ pub(super) fn tile_input(ui: &Ui, resp: Response, e: &Entry, items: &[Entry], se
}
/// A drag held over the tile or row `resp` of entry `e` shows where it would land (before or after
/// it by the pointer's half, or into a folder); a release there sets the drop.
/// it by the pointer's half, or into a folder), by where the pointer is and the keys held now. A
/// release over it ([`released_over`]) sets the drop, by where the button came up and the keys held
/// then.
fn tile_drop(ui: &Ui, resp: &Response, e: &Entry, list: bool, ev: &mut TileEvents) {
let Some(d) = held(resp) else { return };
let PanelDrag::Paint { rows, .. } = &*d else { return };
let name = e.name();
ev.over = true;
// Swatches dropped on one of themselves stay where they are.
if rows.as_ref().is_some_and(|r| r.names.iter().any(|n| n == name)) {
resp.dnd_release_payload::<PanelDrag>();
let up = released_over(ui, resp);
let hover = held(resp);
let Some(d) = hover.clone().or_else(|| up.and_then(|_| dragged(ui))) else { return };
let take = || egui::DragAndDrop::take_payload::<PanelDrag>(ui.ctx()).is_some();
// Art held with Alt over a pattern swatch would replace its tile art, and the swatch is
// outlined; other art goes to the list (see [`zone_input`]).
if let PanelDrag::Art(_) = &*d {
if !matches!(e, Entry::Swatch { paint: Paint::Pattern { .. }, .. }) {
return;
}
if hover.is_some() && crate::panels::alt_held(ui) {
ev.over = true;
let t = Tokens::get(ui.ctx());
ui.painter().rect_stroke(resp.rect.expand(1.0), 0.0, Stroke::new(1.5, t.accent), StrokeKind::Outside);
}
if up.is_some_and(|(_, m)| m.alt) && take() {
ev.drop = Drop::of(&d, Some(e.name().to_string()), false, true, false);
}
return;
}
let t = Tokens::get(ui.ctx());
let r = resp.rect;
let at = ui.input(|i| i.pointer.interact_pos()).unwrap_or(r.center());
let after = if list { at.y > r.center().y } else { at.x > r.center().x };
// A paint from elsewhere, or swatches over a folder, go into it; otherwise a bar marks the slot.
if rows.as_ref().is_none_or(|d| e.is_folder() && !d.groups) {
ui.painter().rect_stroke(r.expand(1.0), 0.0, Stroke::new(1.5, t.accent), StrokeKind::Outside);
} else if list {
let y = if after { r.bottom() } else { r.top() };
ui.painter().line_segment([pos2(r.left(), y), pos2(r.right(), y)], Stroke::new(2.0, t.accent));
} else {
let x = if after { r.right() + 0.75 } else { r.left() - 0.75 };
ui.painter().line_segment([pos2(x, r.top() - 1.0), pos2(x, r.bottom() + 1.0)], Stroke::new(2.0, t.accent));
let PanelDrag::Paint { rows, .. } = &*d else { return };
let name = e.name();
if hover.is_some() {
ev.over = true;
}
if resp.dnd_release_payload::<PanelDrag>().is_some() {
let m = release_modifiers(ui);
ev.drop = Drop::of(&d, Some(name.to_string()), after, m.alt, m.command);
// Swatches dropped on one of themselves stay where they are.
if rows.as_ref().is_some_and(|r| r.names.iter().any(|n| n == name)) {
if up.is_some() {
take();
}
return;
}
let r = resp.rect;
let side = |at: egui::Pos2| if list { at.y > r.center().y } else { at.x > r.center().x };
if hover.is_some() {
let t = Tokens::get(ui.ctx());
let after = side(ui.input(|i| i.pointer.interact_pos()).unwrap_or(r.center()));
// A paint from elsewhere, or swatches over a folder, go into it; otherwise a bar marks the slot.
if rows.as_ref().is_none_or(|d| e.is_folder() && !d.groups) {
ui.painter().rect_stroke(r.expand(1.0), 0.0, Stroke::new(1.5, t.accent), StrokeKind::Outside);
} else if list {
let y = if after { r.bottom() } else { r.top() };
ui.painter().line_segment([pos2(r.left(), y), pos2(r.right(), y)], Stroke::new(2.0, t.accent));
} else {
let x = if after { r.right() + 0.75 } else { r.left() - 0.75 };
ui.painter().line_segment([pos2(x, r.top() - 1.0), pos2(x, r.bottom() + 1.0)], Stroke::new(2.0, t.accent));
}
}
if let Some((at, m)) = up
&& take()
{
ev.drop = Drop::of(&d, Some(name.to_string()), side(at), m.alt, m.command);
}
}
/// Drops between and after the tiles (`zone`: the list's viewport) go to the end of the ungrouped
/// swatches (colour groups to the end of the groups); the list is outlined while one is held there.
/// A tile that took the release first leaves nothing to drop here.
pub(super) fn zone_input(ui: &Ui, zone: &Response, ev: &mut TileEvents) {
let Some(d) = held(zone) else { return };
if !ev.over {
if held(zone).is_some() && !ev.over {
ui.painter().rect_stroke(zone.rect, 0.0, Stroke::new(1.5, Tokens::get(ui.ctx()).accent), StrokeKind::Inside);
}
if zone.dnd_release_payload::<PanelDrag>().is_some() {
ev.drop = Drop::of(&d, None, false, false, release_modifiers(ui).command);
if let Some((_, m)) = released_over(ui, zone)
&& let Some(d) = dragged(ui)
&& egui::DragAndDrop::take_payload::<PanelDrag>(ui.ctx()).is_some()
{
ev.drop = Drop::of(&d, None, false, false, m.command);
}
}
/// The modifiers (Alt; Cmd on macOS, Ctrl on Windows and Linux) held when the primary button was
/// released this frame, as the release event carries them, so a key let go later in the same frame
/// does not change the drop. Without such an event, the modifiers held at the end of the frame.
fn release_modifiers(ui: &Ui) -> egui::Modifiers {
ui.input(|i| {
i.events
.iter()
.find_map(|e| match e {
egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: false, modifiers, .. } => Some(*modifiers),
_ => None,
})
.unwrap_or(i.modifiers)
})
}
/// The colour group `name` is, or the one swatch `name` belongs to.
pub(super) fn group_of(d: &Document, name: &str) -> Option<String> {
if d.swatch_groups.iter().any(|g| g.name == name) {
@@ -270,6 +314,14 @@ fn replaces(d: &Document, with: &str, target: &str) -> bool {
}
}
/// The pattern swatch `name` paints with.
fn swatch_pattern(d: &Document, name: &str) -> Option<String> {
match &d.swatch(name)?.paint {
Paint::Pattern { pattern, .. } => Some(pattern.clone()),
_ => None,
}
}
/// `paint` as swatch params. A solid color other than Registration is sent as the color the drag
/// carries, not as its base swatch and tint, which the command would resolve again at the drop.
fn shown_color_params(paint: &Paint) -> Value {
@@ -280,10 +332,11 @@ fn shown_color_params(paint: &Paint) -> Value {
}
/// Run a drop on the panel: move the swatches, give the paint of a swatch Alt-dropped on another of
/// its kind to that one, or make a swatch of the proxy's paint (a color dropped on a folder or a
/// its kind to that one, make a swatch of the proxy's paint (a color dropped on a folder or a
/// grouped swatch joins that group; a color Cmd/Ctrl-dropped becomes a new spot color of the color
/// the drag shows, tints included). With Alt also held, a color dropped on a swatch it can replace
/// replaces that swatch's color with the color the drag shows and makes no spot color.
/// the drag shows, tints included), or make a pattern swatch of art (Alt-dropped on a pattern
/// swatch: the art becomes that pattern's tile art). With Alt also held, a color dropped on a swatch
/// it can replace replaces that swatch's color with the color the drag shows and makes no spot color.
pub(super) fn apply_drop(app: &mut VectorcraftApp, drop: Drop) {
let Some(d) = app.session.active().map(|st| &st.doc) else { return };
let (cmd, params) = match drop {
@@ -315,7 +368,11 @@ pub(super) fn apply_drop(app: &mut VectorcraftApp, drop: Drop) {
}
("swatch.new", p)
}
Drop::Pattern { ids } => ("object.pattern.make", json!({"ids": ids, "edit": false})),
// Alt: over a pattern swatch, the art becomes that pattern's tile art.
Drop::Pattern { ids, target, replace } => match target.filter(|_| replace).and_then(|t| swatch_pattern(d, &t)) {
Some(name) => ("object.pattern.replaceArt", json!({"name": name, "ids": ids})),
None => ("object.pattern.make", json!({"ids": ids, "edit": false})),
},
};
if let Err(e) = app.run(cmd, params) {
app.status(e);
@@ -1021,6 +1021,92 @@ fn art_dropped_on_the_panel_becomes_a_pattern_swatch() {
assert!(egui::DragAndDrop::payload::<PanelDrag>(&ctx).is_none());
}
/// Art released with Alt held over a pattern swatch becomes that pattern's tile art in one undo
/// step: no pattern or swatch is added and the art stays. With Alt over a color swatch, or without
/// Alt over the pattern swatch, the art becomes a new pattern swatch as before.
#[test]
fn art_alt_dropped_on_a_pattern_swatch_replaces_its_tile_art() {
let mut app = app();
let square = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
app.run("object.pattern.make", json!({"ids": [square], "name": "Dots", "edit": false})).unwrap();
let id = app.run("shape.star", json!({"cx": 50, "cy": 50, "radius1": 20, "radius2": 9, "points": 5})).unwrap()["id"].as_u64().unwrap();
let star = vectorcraft_doc::NodeId(id);
let count = |app: &mut VectorcraftApp| app.run("pattern.list", json!({})).unwrap()["patterns"].as_array().map(Vec::len);
let tile_art = |app: &VectorcraftApp| app.session.doc().unwrap().doc.pattern("Dots").map(|p| p.art.clone());
let ctx = context();
let drop = |app: &mut VectorcraftApp, on: &str, modifiers: Modifiers, time: f64| {
frame(app, &ctx, vec![], time, show);
let at = tile_center(&ctx, on);
egui::DragAndDrop::set_payload(&ctx, PanelDrag::Art(vec![star]));
let release = Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers };
frame_with(app, &ctx, vec![Event::PointerMoved(at), release], modifiers, time + 0.5, show);
assert!(egui::DragAndDrop::payload::<PanelDrag>(&ctx).is_none(), "{on}: the drop is taken");
};
let (before, undo, star_before) = (tile_art(&app), undo_steps(&app), app.session.doc().unwrap().doc.node(star).cloned());
drop(&mut app, "Dots", Modifiers::ALT, 0.0);
let art = tile_art(&app).expect("Dots stays");
assert_ne!(Some(&art), before.as_ref(), "{}", app.ui.status);
assert_eq!(art.len(), 1);
assert_eq!(Some(&art[0].kind), star_before.as_ref().map(|n| &n.kind), "the star is the tile art");
assert_eq!(count(&mut app), Some(1), "no new pattern");
assert_eq!(undo_steps(&app), undo + 1, "one undo step");
assert_eq!(app.session.doc().unwrap().doc.node(star).cloned(), star_before, "the star stays as it was");
// Alt over a color swatch: a new pattern.
drop(&mut app, "Bright Red", Modifiers::ALT, 1.0);
assert_eq!(count(&mut app), Some(2), "Alt over a color swatch makes a pattern");
// No Alt over the pattern swatch: a new pattern, and Dots keeps its art.
drop(&mut app, "Dots", Modifiers::NONE, 2.0);
assert_eq!(count(&mut app), Some(3), "a plain drop on a pattern swatch makes a pattern");
assert_eq!(tile_art(&app), Some(art), "Dots keeps its tile art");
}
/// A drop lands where the button came up, with the keys held then. Art released with Alt held
/// over pattern swatch Dots replaces the tile art of Dots when Alt is let go, or the pointer moves
/// on to pattern swatch Stripes, later in the same frame. Art released over Dots without Alt makes
/// a new pattern when Alt is pressed later in that frame. A color released with Alt held over Red
/// gives Red that color when Alt is let go later in the frame.
#[test]
fn a_drop_lands_where_the_button_came_up_with_the_keys_held_then() {
let mut app = app();
for (x, name) in [(0, "Dots"), (20, "Stripes")] {
let id = app.run("shape.rectangle", json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
app.run("object.pattern.make", json!({"ids": [id], "name": name, "edit": false})).unwrap();
}
let id = app.run("shape.star", json!({"cx": 50, "cy": 50, "radius1": 20, "radius2": 9, "points": 5})).unwrap()["id"].as_u64().unwrap();
let star = vectorcraft_doc::NodeId(id);
let star_kind = app.session.doc().unwrap().doc.node(star).map(|n| n.kind.clone());
let tile_kind =
|app: &VectorcraftApp, name: &str| app.session.doc().unwrap().doc.pattern(name).and_then(|p| p.art.first().map(|n| n.kind.clone()));
let count = |app: &mut VectorcraftApp| app.run("pattern.list", json!({})).unwrap()["patterns"].as_array().map(Vec::len);
let ctx = context();
// In one frame: release over `on` with `up` held, then hold `then` and move over `to`.
let drop = |app: &mut VectorcraftApp, payload: PanelDrag, on: &str, up: Modifiers, then: Modifiers, to: &str, time: f64| {
frame(app, &ctx, vec![], time, show);
let (at, next) = (tile_center(&ctx, on), tile_center(&ctx, to));
egui::DragAndDrop::set_payload(&ctx, payload);
let release = Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: up };
let events = vec![Event::PointerMoved(at), release, Event::ModifiersChanged(then), Event::PointerMoved(next)];
frame_with(app, &ctx, events, up, time + 0.5, show);
assert!(egui::DragAndDrop::payload::<PanelDrag>(&ctx).is_none(), "{on}: the drop is taken");
};
let stripes = tile_kind(&app, "Stripes");
drop(&mut app, PanelDrag::Art(vec![star]), "Dots", Modifiers::ALT, Modifiers::NONE, "Dots", 0.0);
assert_eq!(tile_kind(&app, "Dots"), star_kind, "Alt let go after the release: {}", app.ui.status);
assert_eq!(count(&mut app), Some(2), "no new pattern");
app.run("edit.undo", json!({})).unwrap();
drop(&mut app, PanelDrag::Art(vec![star]), "Dots", Modifiers::ALT, Modifiers::ALT, "Stripes", 1.0);
assert_eq!(tile_kind(&app, "Dots"), star_kind, "the pointer moved on to Stripes after the release");
assert_eq!(tile_kind(&app, "Stripes"), stripes, "Stripes keeps its tile art");
app.run("edit.undo", json!({})).unwrap();
let dots = tile_kind(&app, "Dots");
drop(&mut app, PanelDrag::Art(vec![star]), "Dots", Modifiers::NONE, Modifiers::ALT, "Dots", 2.0);
assert_eq!(count(&mut app), Some(3), "Alt pressed after a plain release makes a pattern");
assert_eq!(tile_kind(&app, "Dots"), dots, "Dots keeps its tile art");
let rgb = Color::from_hex("#2a6fb0").unwrap();
drop(&mut app, PanelDrag::paint(Paint::solid(rgb)), "Red", Modifiers::ALT, Modifiers::NONE, "Red", 3.0);
assert_eq!(app.session.doc().unwrap().doc.swatch("Red").map(|w| w.paint.color()), Some(Some(rgb)), "Alt let go after the release on Red");
}
#[test]
fn a_proxy_dropped_on_the_panel_becomes_a_swatch() {
let mut app = app();
@@ -204,6 +204,7 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() {
json!("energy-beams"),
json!("dry-media"),
json!("tech-circuit"),
json!("engraving"),
json!("arrows"),
json!("image-brush")
]
+152
View File
@@ -136,6 +136,158 @@ fn the_panel_lists_the_images_with_link_info_for_the_selected_one() {
}
}
/// Click the flyout item `name`, checked or not (frames at `time` and just after).
fn click_menu_item(app: &mut VectorcraftApp, ctx: &egui::Context, name: &str, time: f64) {
let frame = |app: &mut VectorcraftApp, events: Vec<egui::Event>, time: f64| {
super::tests_appearance::frame_raw(ctx, app, egui::RawInput { events, time: Some(time), ..Default::default() }, super::links::menu)
};
let texts = frame(app, vec![], time);
let item = texts.iter().find(|(t, _)| t.trim_start_matches('✓').trim() == name);
let at = item.unwrap_or_else(|| panic!("`{name}` not drawn: {texts:?}")).1.center();
let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
for (i, e) in [egui::Event::PointerMoved(at), button(true), button(false)].into_iter().enumerate() {
frame(app, vec![e], time + 0.01 * (i + 1) as f64);
}
}
/// Opening the panel on the selected image (the Control bar's Linked File or Embedded label) opens
/// Link Info when it was closed, and sets a Show filter that leaves out the image's row back to
/// Show All; a filter that lists the row stays.
#[test]
fn opening_the_panel_on_the_selected_image_shows_its_row_and_link_info() {
let dir = Folder::new("show-selected");
let (mut app, linked, embedded) = app(&dir);
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let text = |app: &mut VectorcraftApp, time: f64| {
let raw = egui::RawInput { time: Some(time), ..Default::default() };
let texts = super::tests_appearance::frame_raw(&ctx, app, raw, super::links::show);
texts.into_iter().map(|(t, _)| t).collect::<Vec<_>>().join("\n")
};
app.run("select.set", json!({"ids": [linked]})).unwrap();
click_menu_item(&mut app, &ctx, "Show Link Info", 1.0);
click_menu_item(&mut app, &ctx, "Show Embedded", 2.0);
let before = text(&mut app, 3.0);
assert!(!before.contains("linked.png") && !before.contains("Location"), "the filter hides the row, Link Info is closed: {before}");
app.run("window.panel.close", json!({"panel": super::links::ID})).ok();
super::links::show_selected_image(&mut app, &ctx);
assert!(crate::panel_docking::visible(&app.ui, super::links::ID), "status: {}", app.ui.status);
let after = text(&mut app, 4.0);
assert!(after.contains("linked.png") && after.contains("embedded.png"), "Show All lists every row: {after}");
assert!(after.contains("Location") && after.contains("300 × 200 px"), "Link Info shows the linked image: {after}");
// An embedded image under Show Embedded keeps the filter.
app.run("select.set", json!({"ids": [embedded]})).unwrap();
click_menu_item(&mut app, &ctx, "Show Link Info", 5.0);
click_menu_item(&mut app, &ctx, "Show Embedded", 6.0);
super::links::show_selected_image(&mut app, &ctx);
assert!(crate::panel_docking::visible(&app.ui, super::links::ID), "an open panel stays open");
let embedded_only = text(&mut app, 7.0);
assert!(embedded_only.contains("embedded.png") && !embedded_only.contains("linked.png"), "Show Embedded stays: {embedded_only}");
assert!(embedded_only.contains("Effective PPI"), "Link Info shows the embedded image: {embedded_only}");
}
/// Opening the panel on the selected image scrolls the list to the image's row when it is out of
/// view.
#[test]
fn opening_the_panel_on_the_selected_image_scrolls_to_its_row() {
let dir = Folder::new("show-selected-scroll");
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
// The panel lists the image placed first last, below the list's view.
let mut first = None;
for i in 0..20 {
let path = dir.file(&format!("img{i:02}.png"), &png(10, 10));
let id = app.run("file.place", json!({"path": path, "at": [10 + 15 * i, 100]})).unwrap()["ids"][0].as_u64().unwrap();
first.get_or_insert(id);
}
app.run("select.set", json!({"ids": [first]})).unwrap();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
// How many times the first image's name is drawn: its row while in view, and Link Info.
let drawn = |app: &mut VectorcraftApp, time: f64| {
let raw = egui::RawInput { time: Some(time), ..Default::default() };
let texts = super::tests_appearance::frame_raw(&ctx, app, raw, super::links::show);
texts.iter().filter(|(t, _)| t == "img00.png").count()
};
let before = drawn(&mut app, 1.0);
assert_eq!(drawn(&mut app, 2.0), before, "the list stays at the top");
super::links::show_selected_image(&mut app, &ctx);
// The list scrolls over the frames after the one that asks.
for time in [3.0, 4.0, 5.0] {
drawn(&mut app, time);
}
assert_eq!(drawn(&mut app, 6.0), before + 1, "the row scrolled into view");
}
/// Opening the panel on the selected image draws a list read after the request, so a row that a
/// file change brought into the Show filter since the list was last read is there to scroll to.
#[test]
fn opening_the_panel_on_the_selected_image_reads_the_list_again() {
let dir = Folder::new("show-selected-fresh");
let (mut app, linked, _) = app(&dir);
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
// How many times the linked image's name is drawn: its row, and Link Info.
let drawn = |app: &mut VectorcraftApp, time: f64| {
let raw = egui::RawInput { time: Some(time), ..Default::default() };
let texts = super::tests_appearance::frame_raw(&ctx, app, raw, super::links::show);
texts.iter().filter(|(t, _)| t == "linked.png").count()
};
app.run("select.set", json!({"ids": [linked]})).unwrap();
click_menu_item(&mut app, &ctx, "Show Missing", 1.0);
assert_eq!(drawn(&mut app, 2.0), 1, "Link Info only: nothing is missing yet");
std::fs::remove_file(dir.0.join("linked.png")).unwrap();
// Within the time the panel keeps its list before it looks at the files again.
super::links::show_selected_image(&mut app, &ctx);
assert_eq!(drawn(&mut app, 2.1), 2, "the missing image's row and its Link Info are drawn");
}
/// The Show filter is set back to Show All from the rows the panel draws, not from the files as
/// they were when the panel was asked to open: a missing image restored before the list is drawn
/// still gets its row.
#[test]
fn opening_the_panel_on_the_selected_image_decides_the_filter_from_the_drawn_rows() {
let dir = Folder::new("show-selected-drawn");
let (mut app, linked, _) = app(&dir);
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let drawn = |app: &mut VectorcraftApp, time: f64| {
let raw = egui::RawInput { time: Some(time), ..Default::default() };
let texts = super::tests_appearance::frame_raw(&ctx, app, raw, super::links::show);
texts.iter().filter(|(t, _)| t == "linked.png").count()
};
app.run("select.set", json!({"ids": [linked]})).unwrap();
click_menu_item(&mut app, &ctx, "Show Missing", 1.0);
let bytes = std::fs::read(dir.0.join("linked.png")).unwrap();
std::fs::remove_file(dir.0.join("linked.png")).unwrap();
super::links::show_selected_image(&mut app, &ctx);
std::fs::write(dir.0.join("linked.png"), bytes).unwrap();
assert_eq!(drawn(&mut app, 2.0), 2, "the restored image's row and its Link Info are drawn");
assert_eq!(super::pstate::<Option<(u64, u64)>>(&ctx, "links-scroll-to"), None, "the scroll request is used on the row");
}
/// A request to show the selected image applies only in the document it was made in: drawn for
/// another document, the panel keeps its Show filter and drops the request.
#[test]
fn opening_the_panel_on_the_selected_image_leaves_another_document_alone() {
let dir = Folder::new("show-selected-other-doc");
let (mut app, linked, _) = app(&dir);
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let text = |app: &mut VectorcraftApp, time: f64| {
let raw = egui::RawInput { time: Some(time), ..Default::default() };
let texts = super::tests_appearance::frame_raw(&ctx, app, raw, super::links::show);
texts.into_iter().map(|(t, _)| t).collect::<Vec<_>>().join("\n")
};
app.run("select.set", json!({"ids": [linked]})).unwrap();
click_menu_item(&mut app, &ctx, "Show Missing", 1.0);
super::links::show_selected_image(&mut app, &ctx);
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let other = text(&mut app, 2.0);
assert!(other.contains("Nothing matches the Show filter."), "the other document keeps Show Missing: {other}");
assert_eq!(super::pstate::<Option<(u64, u64)>>(&ctx, "links-scroll-to"), None, "the request is dropped");
}
/// A frame that fetches nothing keeps the stored rows and Link Info as they are, without a copy; the
/// two-second recheck, another first selected image and an edit each store a new cache.
#[test]
+54 -1
View File
@@ -441,6 +441,8 @@ pub(crate) fn live_shape_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, l
if headed {
widgets::subheader(ui, tl!("Rectangle Properties:"));
}
let fw = super::field_width(ui);
shape_angle_row(app, ui, live, &format!("{id}-rectangle"), "rectangleAngle", fw);
corner_radius_row(app, ui, n, &format!("{id}-radius"));
}
LiveShape::Polygon { .. } => {
@@ -451,6 +453,7 @@ pub(crate) fn live_shape_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, l
}
LiveShape::Ellipse { pie, .. } => {
widgets::subheader(ui, tl!("Ellipse Properties:"));
shape_angle_row(app, ui, live, &format!("{id}-ellipse"), "ellipseAngle", 60.0);
pie_rows(app, ui, *pie, &format!("{id}-pie"));
}
LiveShape::Line { .. } => return line_rows(app, ui, live, &format!("{id}-line")),
@@ -459,6 +462,55 @@ pub(crate) fn live_shape_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, l
true
}
/// A live rectangle's or ellipse's Angle row (Rectangle and Ellipse Angle, counterclockwise): the
/// angle the selected shapes of its kind share, blank when they differ. `key` is the
/// `object.setLiveShape` param an edit sets, which turns each of them about its own center.
fn shape_angle_row(app: &mut VectorcraftApp, ui: &mut Ui, live: &LiveShape, id: &str, key: &str, width: f32) {
let angle = shared_shape_angle(app, ui.ctx(), live);
ui.horizontal(|ui| {
widgets::dim_label(ui, tl!("Angle:"));
if let Some(a) = widgets::mixed_field_named(ui, (id, "angle"), Some(tl!("Angle:")), angle, "°", 1, width) {
app.run("object.setLiveShape", json!({ key: a })).ok();
}
});
}
/// The selected live shapes of `live`'s kind, the document uid and revision they were read at, and
/// the angle they share.
type SharedAngle = Option<((u64, u64, std::mem::Discriminant<LiveShape>), Option<f64>)>;
/// The angle ([`LiveShape::shape_angle`]) every selected live shape of `live`'s kind shares, `None`
/// when they differ or none is selected. Measured once per (document uid, revision) and kind: the
/// panels read it every frame, and Select All can select hundreds of thousands of shapes.
fn shared_shape_angle(app: &VectorcraftApp, ctx: &egui::Context, live: &LiveShape) -> Option<f64> {
let st = app.session.active()?;
let key = (st.uid, st.revision, std::mem::discriminant(live));
if let Some((k, angle)) = pstate::<SharedAngle>(ctx, "shape-angle")
&& k == key
{
return angle;
}
let mut angles = st
.selection
.objects
.iter()
.filter_map(|id| st.doc.node(*id)?.live_shape())
.filter(|l| std::mem::discriminant(*l) == key.2)
.filter_map(LiveShape::shape_angle);
// With no shape of its kind selected, the panel shows `live`'s own angle.
let angle = match angles.next() {
None => live.shape_angle(),
Some(first) => angles
.all(|a| {
let d = (a - first).rem_euclid(360.0);
d.min(360.0 - d) < 1e-9
})
.then_some(first),
};
set_pstate::<SharedAngle>(ctx, "shape-angle", Some((key, angle)));
angle
}
/// Whether every selected object is a live line (and one is selected).
fn only_lines_selected(app: &VectorcraftApp) -> bool {
let Some(st) = app.session.active() else { return false };
@@ -546,6 +598,7 @@ pub(crate) fn polygon_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live
let side = radius.map(|r| 2.0 * r * (std::f64::consts::PI / f64::from((*sides).max(3))).sin());
let kind = super::corner_style(app, n).1;
let kinds: Vec<&str> = CornerKind::ALL.iter().map(|k| corner_kind(*k)).collect();
let angle = shared_shape_angle(app, ui.ctx(), live);
// The `object.setLiveShape` param an edited field sets.
let mut set = None;
egui::Grid::new((id, "grid")).num_columns(2).spacing([6.0, 6.0]).show(ui, |ui| {
@@ -555,7 +608,7 @@ pub(crate) fn polygon_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live
}
ui.end_row();
widgets::dim_label(ui, tl!("Angle:"));
if let Some(a) = widgets::plain_field_named(ui, (id, "angle"), Some(tl!("Angle:")), live.polygon_angle().unwrap_or(0.0), "°", 1, fw) {
if let Some(a) = widgets::mixed_field_named(ui, (id, "angle"), Some(tl!("Angle:")), angle, "°", 1, fw) {
set = Some(("polygonAngle", json!(a)));
}
ui.end_row();
@@ -154,6 +154,56 @@ fn an_ellipse_shows_its_pie_properties() {
assert!(shown.iter().any(|s| s == "30°") && shown.iter().any(|s| s == "120°"), "{shown:?}");
}
/// A live rectangle and a live ellipse show their own angle (Rectangle and Ellipse Angle) in the
/// Transform panel and the Properties panel's Transform section, apart from the Rotate field's box
/// angle, which Reset Bounding Box squares to the page. Selected shapes of one kind at different
/// angles show a blank angle.
#[test]
fn a_rectangle_and_an_ellipse_show_their_angle() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
for (shape, heading) in [("shape.rectangle", "Rectangle Properties:"), ("shape.ellipse", "Ellipse Properties:")] {
let mut ids = vec![];
for (y, angle) in [(20, 30), (200, 60)] {
let id = app.run(shape, json!({"x": 50, "y": y, "width": 100, "height": 50})).unwrap()["id"].as_u64().unwrap();
app.run("object.rotate", json!({"angle": angle, "absolute": true})).unwrap();
app.run("object.resetBoundingBox", json!({})).unwrap();
ids.push(id);
}
app.run("select.set", json!({"ids": [ids[0]]})).unwrap();
for (draw, rotate) in [(show as fn(&mut VectorcraftApp, &mut Ui), "Rotate"), (crate::panels::properties::transform_section, "Rotation")] {
assert_eq!(field_text(&mut app, draw, rotate), "0°", "{shape}: {rotate}");
assert_eq!(field_text(&mut app, draw, "Angle:"), "30°", "{shape}: {rotate}");
}
assert!(texts(&mut app, show).iter().any(|s| s == heading), "{heading}");
app.run("select.set", json!({"ids": ids})).unwrap();
assert_eq!(field_text(&mut app, show, "Angle:"), "", "{shape}: mixed angles");
app.run("select.set", json!({"ids": [ids[1]]})).unwrap();
assert_eq!(field_text(&mut app, show, "Angle:"), "60°", "{shape}");
}
}
/// The text in `draw`'s input named `label`, read from the accessibility tree of a headless frame.
fn field_text(app: &mut VectorcraftApp, draw: fn(&mut VectorcraftApp, &mut Ui), label: &str) -> String {
use egui_kittest::kittest::Queryable;
let state = std::mem::replace(app, VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()));
let mut fonts = false;
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(320.0, 900.0)).with_accessibility_check(false).build_ui_state(
move |ui, app: &mut VectorcraftApp| {
if !std::mem::replace(&mut fonts, true) {
crate::theme::install_fonts(ui.ctx());
return;
}
draw(app, ui);
},
state,
);
h.run_steps(3);
let text = h.get_by_role_and_label(egui::accesskit::Role::TextInput, label).value().unwrap_or_default();
*app = h.into_state();
text
}
/// Ellipse Properties' Constrain Pie Angle link, in the Transform panel and the Properties panel's
/// Transform section: off at first, a click or Space with the keyboard on it toggles it, and while
/// it is on a typed Pie Start or End Angle moves the other angle by as much, keeping the span, in
+13
View File
@@ -6,6 +6,15 @@ use vectorcraft_geom::Point;
use crate::theme::Brightness;
/// A one-shot Image Trace Ignore Color sampler, bound to the unchanged selected source.
#[derive(Clone, Debug)]
pub struct TraceIgnoreSampler {
pub doc: u64,
pub target: vectorcraft_doc::NodeId,
pub revision: u64,
pub back: String,
}
/// A Brush Options Key Color click, owned by its dialog and document until release or cancel.
#[derive(Clone, Debug)]
pub struct BrushKeyColorPick {
@@ -928,6 +937,9 @@ pub struct UiState {
/// panel's eye button is held down ([`vectorcraft_render::RenderOptions::trace_source`]).
#[serde(skip)]
pub trace_hold_source: Option<std::sync::Arc<Vec<vectorcraft_doc::NodeId>>>,
/// Ignore Color's one-shot canvas sampler; independent of the eye button's press lifetime.
#[serde(skip)]
pub trace_ignore_sampler: Option<TraceIgnoreSampler>,
/// Layers panel › Panel Options… (row size, thumbnails, Show Layers Only, Locate Selected Objects).
#[serde(default)]
pub layers_panel: crate::panels::layers::PanelOptions,
@@ -1372,6 +1384,7 @@ impl Default for UiState {
psd_import: Value::Null,
home: None,
trace_hold_source: None,
trace_ignore_sampler: None,
layers_panel: Default::default(),
navigator_panel: Default::default(),
attributes_panel: Default::default(),
+3 -1
View File
@@ -1310,7 +1310,9 @@ fn ui_inspect_script_report_leaves_out_files_outside_the_read_root() {
std::fs::write(base.join("outside/bad.jsxinc"), "\nthrow new Error('stopped here');\n").unwrap();
finish(&mut app, json!({"path": s(base.join("outside/run.jsx"))}));
let person = crate::control::inspect(&app, &ctx);
assert_eq!(person["scriptReport"]["file"], json!(s(base.join("outside/bad.jsxinc"))), "{person}");
// The report names the file by its real path (on macOS the temp folder is reached through a link).
let bad = std::fs::canonicalize(base.join("outside/bad.jsxinc")).unwrap();
assert_eq!(person["scriptReport"]["file"], json!(s(bad)), "{person}");
let r = request(&mut app, &tx, "ui.inspect", json!({}));
assert_eq!(r["result"]["scriptReport"]["file"], "bad.jsxinc", "{r}");
assert!(r["result"]["scriptReport"]["console"].to_string().contains("bad.jsxinc:2:"), "{r}");
+163
View File
@@ -1496,6 +1496,169 @@ fn a_color_bars_menu_removes_its_color() {
assert_eq!(field(h.state(), "__sel"), json!([0]));
}
/// Right-clicks the point `at`.
fn right_click_at(h: &mut egui_kittest::Harness<'_, VectorcraftApp>, at: Pos2) {
h.event(Event::PointerMoved(at));
h.event(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE });
h.event(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE });
h.run_steps(2);
}
/// The smaller angle between hues `a` and `b`, in degrees.
fn hue_gap(a: f32, b: f32) -> f32 {
(a - b).rem_euclid(360.0).min((b - a).rem_euclid(360.0))
}
/// A marker's right-click menu has Set As Base Color, Select Shade, Color Picker and Remove Color.
/// Set As Base Color marks the row as the base, whose menu then has neither Set As Base Color nor
/// Remove Color; with another color selected, a harmony rule builds from the base color, and OK
/// recolors the art.
#[test]
fn a_markers_menu_sets_the_base_color_that_the_rules_build_from() {
let mut h = edit_harness(&["#ff0000", "#0000ff", "#00ff00"]);
let hsb = new_hsb(h.state());
let at = wheel_at(&h, hsb[1][0], hsb[1][1]);
right_click_at(&mut h, at);
for item in [" Set As Base Color", " Select Shade", " Color Picker", " Remove Color"] {
assert!(h.query_by_label(item).is_some(), "{item}");
}
h.get_by_label(" Set As Base Color").click();
h.run_steps(3);
let rows = field(h.state(), "rows");
assert_eq!(rows[1]["base"], json!(true), "{rows}");
assert!(rows[0].get("base").is_none() && rows[2].get("base").is_none());
right_click_at(&mut h, at);
assert!(h.get_by_label(" Set As Base Color").accesskit_node().is_disabled(), "it is the base already");
assert!(h.get_by_label(" Remove Color").accesskit_node().is_disabled(), "the base color can't be removed");
h.key_press(egui::Key::Escape);
h.run_steps(2);
// The selected color is another one; the rule still builds from the base.
set(h.state_mut(), "__sel", json!([0]));
h.run_steps(3);
h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Harmony Rules:").click();
h.run_steps(2);
h.get_by_label("Triad").click();
h.run_steps(3);
let now = new_hsb(h.state());
assert!(hue_gap(now[1][0], hsb[1][0]) < 1.0, "the base color keeps its hue: {hsb:?} -> {now:?}");
assert!(hue_gap(now[0][0], now[1][0]) > 110.0 && hue_gap(now[2][0], now[1][0]) > 110.0, "the others are a triad from it: {now:?}");
assert_eq!(field(h.state(), "rows")[1]["base"], json!(true), "the rule keeps the base mark");
let before = fills(h.state());
let app = h.state_mut();
dialogs::confirm(app).unwrap();
assert_eq!(fills(app), before, "OK keeps the previewed colors");
}
/// Select Shade on a marker's menu shows a grid of the color's hue; a click on a cell gives the color
/// that saturation and brightness, keeping its hue, and closes the menu. Unlinked, the other colors
/// stay; linked, they move as a drag would move them.
#[test]
fn select_shade_gives_a_marker_the_shade_clicked() {
for linked in [false, true] {
let mut h = edit_harness(&["rgb 200 100 100", "rgb 100 200 200"]);
set(h.state_mut(), "linked", json!(linked));
h.run_steps(3);
let hsb = new_hsb(h.state());
let at = wheel_at(&h, hsb[0][0], hsb[0][1]);
right_click_at(&mut h, at);
h.get_by_label(" Select Shade").click();
h.run_steps(2);
let cell = "Saturation 50%, Brightness 57%";
h.get_by_label(cell).click();
h.run_steps(3);
let now = new_hsb(h.state());
assert!(hue_gap(now[0][0], hsb[0][0]) < 1.0 && (now[0][1] - 0.5).abs() < 0.01 && (now[0][2] - 4.0 / 7.0).abs() < 0.01, "{now:?}");
let other_moved = (now[1][2] - hsb[1][2]).abs() > 0.01;
assert_eq!(other_moved, linked, "linked {linked}: {hsb:?} -> {now:?}");
assert!(h.query_by_label(cell).is_none(), "the menu closes");
assert_eq!(field(h.state(), "__sel"), json!([0]));
}
}
/// Color Picker on a marker's menu opens the Color Picker for that color.
#[test]
fn a_markers_menu_opens_the_color_picker() {
let mut h = edit_harness(&["rgb 200 100 100", "rgb 100 200 200"]);
let hsb = new_hsb(h.state());
let at = wheel_at(&h, hsb[1][0], hsb[1][1]);
right_click_at(&mut h, at);
h.get_by_label(" Color Picker").click();
h.run_steps(3);
assert_eq!(h.state().ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("colorPicker"));
}
/// A right-click on the wheel away from the markers offers Add New Color, which adds the hue and
/// saturation there as a new color. A color added on the line from the center to a marker moves
/// with that marker when the colors are unlinked, and the others stay.
#[test]
fn add_new_color_on_a_markers_line_moves_with_that_marker() {
let mut h = edit_harness(&["rgb 200 100 100", "rgb 100 200 200"]);
set(h.state_mut(), "linked", json!(false));
set(h.state_mut(), "__sel", json!([0]));
h.run_steps(4);
let hsb = new_hsb(h.state());
let at = wheel_at(&h, 90.0, 0.6);
right_click_at(&mut h, at);
assert!(h.query_by_label(" Set As Base Color").is_none(), "no marker there");
h.get_by_label(" Add New Color").click();
h.run_steps(3);
let rows = field(h.state(), "rows");
assert_eq!(rows.as_array().unwrap().len(), 3, "{rows}");
assert_eq!((&rows[2]["from"], &rows[2]["added"]), (&json!([]), &json!(true)));
assert!(rows[2].get("follows").is_none(), "off every marker's line");
let [hue, s, v] = new_hsb(h.state())[2];
assert!((hue - 90.0).abs() < 1.0 && (s - 0.6).abs() < 0.01 && (v - hsb[0][2]).abs() < 0.01, "{:?}", [hue, s, v]);
assert_eq!(field(h.state(), "__sel"), json!([2]));
// Halfway along the second color's line.
let on_line = wheel_at(&h, hsb[1][0], hsb[1][1] / 2.0);
right_click_at(&mut h, on_line);
h.get_by_label(" Add New Color").click();
h.run_steps(3);
let rows = field(h.state(), "rows");
assert_eq!(rows.as_array().unwrap().len(), 4);
assert!(rows[1]["tie"].is_u64() && rows[3]["follows"] == rows[1]["tie"], "{rows}");
// Drag the second color's marker a little way round: the color on its line turns with it.
let before = new_hsb(h.state());
let start = wheel_at(&h, before[1][0], before[1][1]);
h.hover_at(start);
h.run_steps(1);
h.drag_at(start);
h.run_steps(1);
let mut p = start;
for k in 1..=6 {
p = wheel_at(&h, before[1][0] + 5.0 * k as f32, before[1][1]);
h.hover_at(p);
h.run_steps(1);
}
h.drop_at(p);
h.run_steps(2);
let after = new_hsb(h.state());
let turned = hue_gap(after[1][0], before[1][0]);
assert!(turned > 20.0, "the marker turned: {before:?} -> {after:?}");
assert!((hue_gap(after[3][0], before[3][0]) - turned).abs() < 1.0, "the color on its line turned as far: {before:?} -> {after:?}");
assert!(hue_gap(after[0][0], before[0][0]) < 0.5 && hue_gap(after[2][0], before[2][0]) < 0.5, "the others stay: {before:?} -> {after:?}");
}
/// Set Current Color As Base Color makes the selected color the base; it is off while the selected
/// color is the base. A color bar's menu has Set As Base Color too.
#[test]
fn set_current_color_as_base_color_marks_the_selected_color() {
let mut h = edit_harness(&["#ff0000", "#0000ff", "#00ff00"]);
let name = "Set Current Color As Base Color";
assert!(h.get_by_role_and_label(egui::accesskit::Role::Button, name).accesskit_node().is_disabled(), "the base color is the selected one");
set(h.state_mut(), "__sel", json!([2]));
h.run_steps(3);
click_button(&mut h, name);
assert_eq!(field(h.state(), "rows")[2]["base"], json!(true));
assert!(h.get_by_role_and_label(egui::accesskit::Role::Button, name).accesskit_node().is_disabled());
show_display(&mut h, "Show color bars");
right_click_bar(&mut h, "Color 1");
h.get_by_label(" Set As Base Color").click();
h.run_steps(3);
let rows = field(h.state(), "rows");
assert_eq!((&rows[0]["base"], rows[2].get("base")), (&json!(true), None), "{rows}");
}
// Optional local visual QA; these captures are not committed assets.
fn capture_recolor(h: &mut egui_kittest::Harness<'_, VectorcraftApp>, name: &str) {
if let Some(dir) = std::env::var_os("VECTORCRAFT_RECOLOR_CAPTURE_DIR") {
+2 -2
View File
@@ -39,8 +39,8 @@ pub use chips::{ProxyClicks, chip_button, chip_button_named, fill_stroke_proxy,
pub use color::{
FieldAxis, Live, MarkerResponse, RingResponse, SliderValue, WheelAxes, WheelResponse, channel_slider, channel_slider_named,
channel_slider_stepped, channel_slider_valued, color_field, color_mesh, color_slider, color_slider_named, color_slider_stepped,
color_slider_valued, harmony_wheel, hex_field, hex_field_named, hsb32, hue_ring, region_texture, ring_markers, ring_square, segment_color,
segment_color_on, segmented_wheel, stepped_area, wheel_of,
color_slider_valued, harmony_wheel, hex_field, hex_field_named, hsb32, hue_ring, recolor_wheel, region_texture, ring_markers, ring_square,
segment_color, segment_color_on, segmented_wheel, stepped_area, wheel_of,
};
pub(crate) use color::{HEX_FIELD_CHARS, focus_by_pointer, hex_text, pointer_phase};
pub use drag::{
+69 -9
View File
@@ -1097,6 +1097,12 @@ pub struct WheelResponse {
/// A click on the wheel: the color whose marker is within reach of it (if any), and the hue
/// (degrees) and the saturation (or brightness) under the pointer (1 past the wheel's edge).
pub clicked: Option<(Option<usize>, [f32; 2])>,
/// A right-click on the wheel, or on a marker past its edge: the color whose marker is within
/// reach of it (if any), the color on whose line from the center it is (when it is on no
/// marker), and the hue (degrees) and saturation under the pointer.
pub secondary: Option<(Option<usize>, Option<usize>, [f32; 2])>,
/// The wheel's own response, for a right-click menu.
pub response: Option<egui::Response>,
}
/// The harmony wheel of Recolor Artwork's Edit tab and the Color Themes panel: a hue and saturation
@@ -1104,25 +1110,60 @@ pub struct WheelResponse {
/// marker per colour joined to the centre (the selected colour, `base`, larger) and a Brightness
/// slider for the selected colour below it.
pub fn harmony_wheel(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: Option<usize>) -> WheelResponse {
wheel_of(ui, id, size, colors, base, false, WheelAxes::HueSaturation)
wheel_of(ui, id, size, colors, base, base, false, WheelAxes::HueSaturation)
}
/// [`harmony_wheel`] drawn as solid patches (24 hues by 5 saturations, each in its
/// [`segment_color`]). The markers sit at their colors' own hue and
/// Recolor Artwork's wheel: [`harmony_wheel`] with the base color's marker (`base`) larger and the
/// selected color's (`selected`, when another) ringed, at the selected color's brightness, with the
/// Brightness slider for it. With `segmented` it is drawn as solid patches (24 hues by 5
/// saturations, each in its [`segment_color`]); the markers sit at their colors' own hue and
/// saturation, and a drag moves them as freely as on the smooth wheel.
pub fn segmented_wheel(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: Option<usize>) -> WheelResponse {
wheel_of(ui, id, size, colors, base, true, WheelAxes::HueSaturation)
#[allow(clippy::too_many_arguments)]
pub fn recolor_wheel(
ui: &mut Ui,
id: &str,
size: f32,
colors: &[Color],
base: Option<usize>,
selected: Option<usize>,
segmented: bool,
axes: WheelAxes,
) -> WheelResponse {
wheel_of(ui, id, size, colors, base, selected.or(base), segmented, axes)
}
/// [`harmony_wheel`], or with `segmented` [`segmented_wheel`], showing `axes`. With
/// The distance from `p` to the segment from `a` to `b`.
fn segment_distance(p: egui::Pos2, a: egui::Pos2, b: egui::Pos2) -> f32 {
let ab = b - a;
let len2 = ab.length_sq();
let t = if len2 > 0.0 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 };
p.distance(a + ab * t)
}
pub fn segmented_wheel(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: Option<usize>) -> WheelResponse {
wheel_of(ui, id, size, colors, base, base, true, WheelAxes::HueSaturation)
}
/// [`harmony_wheel`], [`recolor_wheel`], or with `segmented` [`segmented_wheel`], showing `axes`. The
/// big marker is `base`'s, and the wheel's background and the slider under it are `selected`'s. With
/// [`WheelAxes::HueBrightness`] the distance from the center is brightness (black at the center,
/// full brightness at the edge, a ring of patches per 20% on the segmented wheel), the wheel is drawn
/// at the selected colour's saturation (full without one), a marker drag sets hue and brightness,
/// and the slider under the wheel is a Saturation slider.
pub fn wheel_of(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: Option<usize>, segmented: bool, axes: WheelAxes) -> WheelResponse {
#[allow(clippy::too_many_arguments)]
pub fn wheel_of(
ui: &mut Ui,
id: &str,
size: f32,
colors: &[Color],
base: Option<usize>,
selected: Option<usize>,
segmented: bool,
axes: WheelAxes,
) -> WheelResponse {
let t = Tokens::get(ui.ctx());
let mut out = WheelResponse::default();
let base_hsb = base.and_then(|b| colors.get(b)).map(Color::to_hsb);
let base_hsb = selected.and_then(|b| colors.get(b)).map(Color::to_hsb);
let (radial, other) = (axes.radial(), axes.other());
// The component the wheel does not show: the slider's value, and the wheel's background at it.
let o = base_hsb.map_or(1.0, |c| c[other]);
@@ -1144,6 +1185,24 @@ pub fn wheel_of(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: Option
painter.line_segment([c, p], Stroke::new(1.0, Color32::from_white_alpha(160)));
painter.circle(p, if big { 8.0 } else { 5.5 }, crate::panels::c32(col), Stroke::new(1.5, Color32::WHITE));
painter.circle_stroke(p, if big { 9.0 } else { 6.5 }, Stroke::new(1.0, Color32::BLACK));
if Some(i) == selected && selected != base {
painter.circle_stroke(p, 8.5, Stroke::new(1.5, t.accent));
}
}
// A right-click: the marker under it, or else the line from the center to a marker.
if resp.secondary_clicked()
&& let Some(p) = resp.interact_pointer_pos()
{
let near = colors.iter().map(at).enumerate().map(|(i, m)| (i, m.distance(p))).filter(|x| x.1 <= 14.0).min_by(|a, b| a.1.total_cmp(&b.1));
let dv = p - c;
if dv.length() <= r || near.is_some() {
let line = near.is_none().then(|| {
let on = colors.iter().map(at).enumerate().map(|(i, m)| (i, segment_distance(p, c, m))).filter(|x| x.1 <= 4.0);
on.min_by(|a, b| a.1.total_cmp(&b.1)).map(|x| x.0)
});
let h = (-dv.y).atan2(dv.x).to_degrees().rem_euclid(360.0);
out.secondary = Some((near.map(|x| x.0), line.flatten(), [h, (dv.length() / r).clamp(0.0, 1.0)]));
}
}
// Drag a marker: the nearest one within reach of the press.
let drag = ui.scope_id().with((id, "drag"));
@@ -1173,6 +1232,7 @@ pub fn wheel_of(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: Option
}
let name = if segmented { tl!("Segmented color wheel") } else { tl!("Color wheel") };
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Slider, ui.is_enabled(), name));
out.response = Some(resp);
});
ui.add_space(6.0);
ui.horizontal(|ui| {
@@ -1181,7 +1241,7 @@ pub fn wheel_of(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: Option
ui.add_sized([70.0, 22.0], egui::Label::new(egui::RichText::new(name).color(t.text_dim)));
// Screen readers get the value in percent, as the Color panel's HSB fields show it.
let shown = SliderValue::field((f64::from(o) * 100.0).round(), 0.0..=100.0, "%", 0);
if let (Some(b), Some(hsb)) = (base, base_hsb)
if let (Some(b), Some(hsb)) = (selected, base_hsb)
&& let (Some(nv), _) = color_slider_valued(ui, (id, key), name, Some(shown), o, size, &|x| {
let [h, s, v] = axes.hsb(hsb[0], hsb[radial], x);
crate::panels::c32(&Color::from_hsb(h, s, v))
File diff suppressed because it is too large Load Diff
+18 -6
View File
@@ -300,18 +300,30 @@ luminosity}`, percent from -100 to 100, 0 by default). The dialog sends a non-ze
colors; colors opened alone are saved as a group with the change. `display` sets how the Edit tab shows the new
colors: `smooth` (the smooth wheel, also when unset; each opening starts there), `segmented` (a wheel of solid patches,
24 hues by 5 saturations, whose markers move as freely) or `bars` (a solid bar per recolored color in row order; a click
selects its row for the sliders and a drag moves the row without changing a color). `wheelTool` turns on a wheel tool
on either wheel: `add` (the Add Color tool) adds a click as a new color, the hue and saturation clicked at the base
color's brightness (the patch's color on the segmented wheel), in a new row with no current colors (`from: []`) and
selects its row for the sliders and a drag moves the row without changing a color; the moved row keeps the color group
swatch it took). `wheelTool` turns on a wheel tool
on either wheel: `add` (the Add Color tool) adds a click as a new color, the hue and saturation clicked at the selected
color's brightness (the base color's when none is selected; the patch's color on the segmented wheel), in a new row with no current colors (`from: []`) and
`added: true` that becomes the selected row; `remove` (the Remove Color tool) removes the color of the marker clicked.
`wheelAxes: "hueBrightness"` makes both wheels show hue and brightness: brightness runs from black at the center to
full at the edge, the wheel is drawn at the base color's saturation, a marker drag sets hue and brightness, the slider
under the wheel sets saturation, and Add Color adds the hue and brightness clicked at the base color's saturation.
full at the edge, the wheel is drawn at the selected color's saturation (the base color's when none is selected), a marker drag sets hue and brightness, the slider
under the wheel sets saturation, and Add Color adds the hue and brightness clicked at the selected color's saturation.
`hueSaturation`, unset (each opening) or any other value shows hue and saturation; switching changes no color. A color bar's
right-click menu has Remove Color too. The base color can't be removed. A removed color's row is dropped, unless it
has current colors and art or a group is open: it then keeps them with `to: null`, that art keeps its colors, and the
group's swatch at that place is removed. A row with no current colors recolors no art; with a group, the new color of
group's swatch at that place is removed, unless the row is excluded: an excluded row with current colors leaves the group's swatch at its place as it is. A row with no current colors recolors no art; with a group, the new color of
one with `added: true` that is not excluded is added to the group after the group's other colors, and a row made with New Row adds none.
The base color is the row with `base: true`, or the first color the Edit tab shows when no row has it; the harmony rules
build from it, and selecting another color for the sliders leaves it the base. A right-click on a wheel marker or a
color bar opens a menu with Set As Base Color (moves `base: true` to that row), Select Shade (a grid of the color's hue
at 7 saturations, 0% to 100%, by 7 brightnesses, 100% down to 14%; a click moves the color there as a drag of its
marker would, so linked colors follow), Color Picker and Remove Color; the base color's menu has neither Set As Base
Color nor Remove Color. A right-click elsewhere on either wheel offers Add New Color, which adds a color as the Add
Color tool does. A color added on the line from the center to a marker moves with that marker while the colors are
unlinked: the marker's row gets `tie: n` and the added row `follows: n`, and dragging the marker, or Select Shade on
it, moves every row that follows its `tie` by the same change. Set Current Color As Base Color, before the color chips,
makes the selected color the base. The rows keep these marks when Randomize (`recolor.randomize`) or Prominent Colors
(`recolor.weigh`) changes them, and the rows the dialog sends `recolor.apply` leave `base`, `tie` and `follows` out.
`groupStorage` shows the Color Groups list (true when the dialog opens); setting `group` to a color group's name makes
it the group being edited, as opening on it does, and refuses a name no group has; `groupAction` (`save`, `new` or
`delete`) runs the list's Save Changes, New Color Group or Delete button on the next frame, or first on confirm (see
+6
View File
@@ -91,6 +91,12 @@ alignment). **Position** is **Away from the Line** (the label on the far side of
from the object) or **Between Line and Object**; **Alignment** is **Left**, **Center** or
**Right** along the line. **Save** keeps them for new dimensions; existing ones don't change.
**Arrow Style** lists **Filled**, **Open**, **Tick** and **None**, then every other built-in
arrowhead of the Stroke panel, each with a drawn preview before its name. Custom arrowheads are not
listed. A version that has the arrowhead in the Stroke panel but not in Arrow Style keeps the saved
arrows of such a dimension until it draws the dimension again, and then draws **Filled** arrows. A
version without the arrowhead does not open the file.
Scale means **drawing : real size**, independent of zoom. At **1:10** a 1 in line on the page is
labelled 10 in; at **10:1**, 0.1 in. It scales lengths, not angles or the size of text and arrows.
+3 -3
View File
@@ -715,8 +715,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
libraries ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html),
[import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html)):
Window › Brush Libraries and the Brushes panel's Brush Libraries Menu open each library in a library panel of
its own (thirteen original libraries generated in code: Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes (one
bristle brush for each tip shape), Pattern Borders, Scatter Shapes, Stipple (Fine, Dense, Soft and Bold dot textures), Game Trails, Energy Beams, Dry Media (grainy chalk, pencil, crayon and charcoal art brushes), Tech Circuit (Circuit Trace, Bus Lines and Terminal Nodes) and Arrows (Solid, Open, Double, Chevron and Dashed Arrow); User Defined; Other Library… reads the brushes of any document VectorCraft opens); a
its own (fourteen original libraries generated in code: Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes (one
bristle brush for each tip shape), Pattern Borders, Scatter Shapes, Stipple (Fine, Dense, Soft and Bold dot textures), Game Trails, Energy Beams, Dry Media (grainy chalk, pencil, crayon and charcoal art brushes), Tech Circuit (Circuit Trace, Bus Lines and Terminal Nodes), Engraving (Fine, Dense, Tapered and Broken Hatching) and Arrows (Solid, Open, Double, Chevron and Dashed Arrow); User Defined; Other Library… reads the brushes of any document VectorCraft opens); a
click adds a
brush to the document's Brushes with the patterns, symbols and other resources its art uses, as one undo
step (applied to the selected paths in the same step), dragging one onto a path adds and applies it and
@@ -739,7 +739,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
painted with the texture effects, and Paper Cutouts with six original layered-paper styles, two colored cut edges
and crisp cast shadows; User Defined; Other Library…; `graphicStyle.libraries`,
`graphicStyle.addFromLibrary`).
- **Missing:** more built-in brush libraries beyond the eleven shipped (and further graphic-style libraries beyond the twelve shipped, and further symbol libraries beyond Basic
- **Missing:** more built-in brush libraries beyond the fourteen shipped (and further graphic-style libraries beyond the twelve shipped, and further symbol libraries beyond Basic
Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons and Weather Icons; original, generated in code, never Adobe's); dynamic symbols' `.ai` read and write.
- **Estimate:** 3–13 h (estimated).
+63 -12
View File
@@ -724,7 +724,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions
| `press_key` | `{key, mods?}` | Remote: a real key event. Headless: runs the command or tool bound to that shortcut, or sends the key to the busy tool (digits too: `5` while dragging with the Perspective Selection tool; `e` while dragging a Selection or Group Selection marquee; `c` and `f` while dragging out an arc; `f`, `v`, `x` and `c` while dragging out a rectangular or polar grid). |
| `type_text` | `{text}` | Remote only. |
| `answer_dialog` | `{set?: [{field, value?}], action?}` | Remote only. Sets fields of the app's open dialog in the order given with one `ui.dialog.set {fields, action?}` (a missing `value` is `null`). The app stores all of them or none, then answers that same dialog with `action` in the same request: `confirm` (OK) or `cancel`. Another connection cannot open a dialog between the two steps. When the app refuses the `ui.dialog.set`, for example because no dialog is open, the call is an error and the dialog is not confirmed or canceled. `set` cannot change a `__` field other than the dialog's controls held under a `__` name (such as Save PDF's `__section` or the Preferences `__search`): the `__command` and `__params` of a `confirm` or `command` dialog, and every other `__` field that holds what OK acts on, are refused with "the `<kind>` dialog cannot set protected field `<field>`", so OK runs what the dialog was opened for. `action` alone is sent as `ui.dialog.confirm` or `ui.dialog.cancel`. Give `set`, `action` or both; `set` holds at most 256 fields. `inspect_ui` shows the open dialog and its fields as `ui.dialog`. Returns `{dialog, result}`: the dialog after the fields were set (or `null`) and the reply to `confirm` or `cancel` (or `null`). After `invoke_menu` `app.quit`, `file.close` or `file.closeAll` replies `{"pending": "saveChanges"}`, `{action: "confirm"}` saves, `{set: [{field: "discard", value: true}], action: "confirm"}` closes without saving and `{action: "cancel"}` cancels the close or quit. |
| `invoke_menu` | `{command, params?}` | Invokes a menu item by command id. UI commands such as `view.*` and `window.*` are in `command_list` with `ui: true`; running them needs the desktop app (`--connect`). |
| `invoke_menu` | `{command, params?}` | Invokes a menu item by command id. UI commands such as `view.*` and `window.*` are in `command_list` with `ui: true`; running them needs the desktop app (`--connect`). The app refuses `attributes.openUrl`, `file.export.svg.browser`, `file.saveForWeb.browser` and `file.showPackage` for every control and MCP request, since each opens another app, so the headless error for them does not suggest `--connect`. |
| `open_panel` | `{panel}` | Remote only. `panel` is a panel id (`layers`, `swatches`, `colorGuide`, …, as `window.panel` takes) or its display label (`"Color Guide"`), in any case. |
| `screenshot` | `{path?, scale?, artboard?, window?, max_side?, traceViews?}` | Returns MCP image content (`image/png`, base64) plus a text block. Renders the artboard with the pixels of a PNG `export` with `background: "white"` at the same scale; `traceViews:true` draws Image Trace objects in the view set with `imageTrace.setView`, as in the app's window; `window:true` captures the app window (remote only), as `ui_screenshot` does, and `max_side` (1–4096, window captures only) scales the returned image down as described for `ui_screenshot`. With `path` the backend (the headless session or the app) writes the PNG there too; a window capture written there keeps its full size with `max_side`. An app that does not send the image back writes a window capture without `path` to a file in a new folder inside the system's temporary folder (on Unix only the user can open it); the server reads the file and then removes the folder, also when the capture or the read fails. |
| `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PICT (`.pct`/`.pic`/`.pict`, and a version 2 picture of any extension), HP-GL (`.plt`/`.hpgl`/`.hgl`/`.hpg`, and a file of an extension no other format reads that starts with plotter instructions), PNG (`.png`/`.pns`), JPEG, GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a PSD or PSB file with its layers as layers, or as its merged image through `run_command document.open` with `layers: false`; a JPEG XL file as its first frame), CDR drawings of versions 1 to 27 (`.cdr`, `.cdt`), CMX files with 32-bit coordinates (`.cmx`). Templates (`.vctemplate`, `.ait`, `.cdt`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin.<id>"` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. |
@@ -5356,7 +5356,7 @@ without `groupColors`, its new color then joins `group` after the new colors of
`recolor.randomize` and `recolor.weigh` keep such a row, and `recolor.randomize` keeps its `added`. A row without `from`, or with
a current color that is not a color, is refused. With art selected, the Recolor Artwork dialog's New Row button (beside
Merge) adds such a row above the first selected row, or at the top, with that row's new color, and selects it; Shift-click a row below it and Merge to move that row's colors into it (Merge keeps the topmost selected row's new color). An
empty row does not count toward Colors. While it is empty, the dialog's Edit tab does not show it (its sliders edit
empty row does not count toward Colors. While it is empty and not `added`, the dialog's Edit tab does not show it (its sliders edit
the base color when the empty row is selected), the harmony rules,
linked moves and the Color Theme Picker leave its new color as it is, and Save All Colors and a new color group saved
from colors alone leave its new color out. With `limitTo`, a row's `tint` (a percentage, default 100) gives the art
@@ -5407,7 +5407,7 @@ objects are read. As VectorCraft's own rule, each object read weighs the same, s
among its pixels; the vector art a symbol instance places counts as one object, and each image it places counts on
its own), and similar colors merge (k-means in Lab) into at most `colors` (1 to 64, default 5), each shown by its
most used color in its own model. Picks that touch no art return no colors. In the Recolor Artwork dialog the picks are the `themePicks` field: the rows that aren't
excluded and hold current colors take the palette as their new colors in row order, the colors repeating when the rows outnumber them.
excluded and hold current colors or were added on the Edit tab take the palette as their new colors in row order, the colors repeating when the rows outnumber them.
```json
{"name":"run_command","arguments":{"command":"recolor.pickTheme","params":{"picks":[{"at":[120,80]},{"rect":[200,40,320,140]}],"colors":4}}}
@@ -5433,7 +5433,7 @@ bar sits under the Edit tab's wheel: each row with a share is a part as wide as
the largest first. Dragging the edge between two parts moves width between them, and when the drag ends the widths
become the `weights` field, which moves the rows' current colors and previews the result. The New Color Group menu
beside the link button runs `swatch.newGroup` right away, as its own undo step: Save All Colors saves the new colors
of the rows that are not excluded and hold current colors, in row order, and Save Prominent Colors saves the bar's colors in the bar's order.
of the rows that are not excluded, hold current colors or were added on the Edit tab, and still have one, in row order, and Save Prominent Colors saves the bar's colors in the bar's order.
The Recolor Artwork dialog lists the document's color groups on its right, or under the tabs in a window too narrow
for both ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)).
@@ -5705,9 +5705,9 @@ error.
## Brush libraries
Brush libraries are read-only sets of brushes: thirteen generated in code (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive with Flex Ribbon, Pulse Stroke, Round Flow and Chisel Flow, Bristle
Brush libraries are read-only sets of brushes: fourteen generated in code (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive with Flex Ribbon, Pulse Stroke, Round Flow and Chisel Flow, Bristle
Brushes with one bristle brush for each tip shape, Pattern Borders, Scatter Shapes, Stipple with Fine, Dense, Soft and Bold dot textures, Game Trails, Energy Beams, and Dry Media with the Chalk Grain, Graphite Pencil, Wax Crayon and
Charcoal Dust art brushes, id `dry-media`, Tech Circuit with Circuit Trace (art), Bus Lines and Terminal Nodes (pattern), id `tech-circuit`, and Arrows with Solid, Open, Double, Chevron and Dashed Arrow art brushes, id `arrows`), the `.vectorcraft` files in the user library folder of the desktop app (User
Charcoal Dust art brushes, id `dry-media`, Tech Circuit with Circuit Trace (art), Bus Lines and Terminal Nodes (pattern), id `tech-circuit`, Engraving with Fine Hatching, Dense Hatching, Tapered Hatching and Broken Hatching art brushes, id `engraving`, and Arrows with Solid, Open, Double, Chevron and Dashed Arrow art brushes, id `arrows`), the `.vectorcraft` files in the user library folder of the desktop app (User
Defined) and the brushes of any document loaded with `brush.loadLibrary` (a document without brushes of its own has
the default ones). `brush.libraries` lists them (`id`, `name`, `category`: `builtIn`, `user` or `loaded`, `count`) and
`brush.library {library}` returns one's brushes (`name`, `type`; `library` is an id or a name).
@@ -5975,6 +5975,20 @@ details are VectorCraft's own rules; the help page says only that the option mov
(<https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/edit-patterns.html>).
`pattern.list` reports it as `moveTileWithArt`. A `pattern.options` call that changes nothing records no undo step.
`object.pattern.replaceArt {name, ids?}` (Replace Pattern Art) makes copies of the selected art, or of `ids`, the tile
art of pattern `name`, as one undo step, and returns `{name}`. The pattern keeps its name, its swatch and the swatch's
place, its tile and its options; with `sizeTileToArt` on, the tile is sized to the new art plus `hSpacing` and
`vSpacing`. Fills and strokes name the pattern, so every object painted with it draws the new tile. The art stays on the
canvas, selected as it was. Art that matches the tile art already records no undo step. The command is off while a
pattern is edited ("finish editing the pattern first"), and returns an error, changing nothing, for a missing `name`, a
pattern that does not exist, no art, and art painted with the pattern itself, directly or through the symbols, other
patterns, graph designs and brushes it uses, or the series and label paints a graph stores. In the Swatches panel, art dragged off the canvas and released with Alt (Option on macOS) held over a
pattern swatch runs it with that swatch's pattern; the swatch is outlined while the art is held there. Released anywhere
else in the list, or without Alt, the art becomes a new pattern swatch as before. The help page describes replacing a
pattern by dragging its edited tile onto the old swatch with Alt or Option held, with the pattern updated in the file
(<https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=226>,
archived copy). Keeping the tile, the options and the source art are VectorCraft's own rules.
```json
{"name":"run_command","arguments":{"command":"pattern.options","params":{"showSwatchBounds":true}}}
{"name":"run_command","arguments":{"command":"prefs.set","params":{"key":"patternTileEdgeColor","value":"#ff4f4f"}}}
@@ -6369,6 +6383,13 @@ arrowheads in a separate arrowheads file.
{"name":"run_command","arguments":{"command":"stroke.set","params":{"ids":[9],"endArrow":{"custom":"Example Arrowhead"}}}}
```
A dimension's options (`dimension.create`, `dimension.update` and the Dimension tool's `style`) take `arrowStyle`
(`filled`, `open`, `tick` or `none`: `Triangle`, `TriangleOpen`, `Slash` or no head) and `arrowHead`, `null` or one of
the built-in head names `stroke.set` takes, drawn at both ends in place of the arrow style's head. The Arrow Style menu
sets `arrowStyle` to `filled` when it sets `arrowHead`. A custom arrowhead and an unknown name are refused. Versions
that have the stroke arrowhead but do not read `arrowHead` keep the saved arrows until they draw the dimension again,
and then draw `arrowStyle`. Versions without the stroke arrowhead do not open the file.
## Stroke bounds and clicks
Visual bounds (Fit to Selected Art, Rasterize, exporting all art) and clicks on the canvas take
@@ -7382,6 +7403,25 @@ midpoint; any finite value is brought into 0 to 360). With both, the length appl
and a line that would reach past the coordinate limit (±4,000,000 pt), are errors that change no line. Each call is
one undo step.
A live rectangle's Rectangle Angle and a live ellipse's Ellipse Angle are `rectangleAngle` and `ellipseAngle`
(degrees counterclockwise, 0 for a shape drawn level; any number is read modulo 360). The help page
(https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html) lists
both as the shape's rotation on the canvas from 0° to 360°. The rest are VectorCraft's own rules: each selected shape
of that kind turns about its own center, keeping its size, corners and pie (an ellipse's pie turns with it), and other
objects stay as they are. A pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move
its center or change its size. The Transform and Properties panels show the angle in each shape's Properties section,
blank when the selected shapes of that kind differ. It is the shape's own angle: after Reset Bounding Box
(`object.resetBoundingBox`) the Rotate field reads 0° while the shape angle keeps the turn. An angle that is not a
number is an error and changes nothing (`null` counts as an omitted key), a shape that the turn would take past the
coordinate limit (±4,000,000 pt) is an error that changes nothing, whether or not it is selected, and the angle the
shape already has records no undo step; the same holds for `polygonAngle`, and the Polygon Properties angle is blank,
too, when the selected polygons differ.
```json
{"name":"run_command","arguments":{"command":"object.setLiveShape","params":{"rectangleAngle":30}}}
{"name":"run_command","arguments":{"command":"object.setLiveShape","params":{"ellipseAngle":45}}}
```
`object.setLiveShape` returns a parameter error, and leaves the document and its undo history as they were, for a key
it does not take, at the top level (`` unknown parameter `path` ``) or in one of `items`
(`` unknown parameter `items[0].corner`; did you mean `items[0].corners`? ``), for a `sides` that is not a whole number
@@ -10461,8 +10501,8 @@ clipping mask into one layer and discards hidden layers that require merging; th
imports one image, and Import Hidden Layers brings hidden layers in. `document.open` does the same, with
`layers: false` for the single image and `hiddenLayers: true` for the hidden layers. The page also merges
adjustment layers, layers with a knockout option, and layers that hold transparent pixels in some blend modes with
the layers below them. `document.open` applies neither adjustments nor knockouts, and it merges a layer by its blend
mode alone, as the rules below say.
the layers below them. `document.open` does not apply adjustments, applies only shallow knockouts inside groups, and
otherwise merges a layer by its blend mode alone, as the rules below say.
The rest are VectorCraft's own rules:
@@ -10482,6 +10522,12 @@ The rest are VectorCraft's own rules:
mask.
- A Dissolve layer's partly transparent pixels are merged as opaque or transparent, opaque at the share of its
pixels their transparency gives, in a fixed pattern that differs from layer to layer.
- A layer or group inside a group with a Knockout value of 1 (shallow) is merged with the visible layers below it
in that group: where it has pixels, shaped by its layer mask, they are cleared to transparency, it is drawn there
at its fill opacity, and its opacity fades the result back toward them. In a Pass Through group this applies only
when it and the visible layers below it are in Normal mode. A knockout at 0 opacity, one that draws nothing, one
with nothing visible below it, and one at 0 fill that covers none of their painted pixels are not merged for the
knockout; one in a mode VectorCraft lacks is still merged by its mode.
- A merged layer is named after the layers it holds, joined with ` + `.
- A layer name the file stores only as a one-byte Pascal string, without its Unicode name, is read as Mac Roman.
- A layer's opacity is multiplied by its fill opacity, in every blend mode. A layer that others are clipped to keeps
@@ -10493,16 +10539,21 @@ The rest are VectorCraft's own rules:
(RGB, CMYK, Grayscale, Lab or HSB) over the canvas. One whose shape is a vector mask isn't drawn, and the layers
clipped to it are left out.
- Adjustment layers, fill layers that store no pixels and whose fill isn't read, layer effects that are switched on,
knockouts and vector masks are not applied; the `warnings` count them.
the other knockouts (top-level layers, clipped layers, layers that others are clipped to, Pass Through groups with
layers in other modes, other Knockout values, and merges that need more memory than allowed) and vector masks are
not applied; the `warnings` count them.
- Layer channels may be raw, PackBits or zipped (with or without prediction) at 8, 16 and 32 bits.
- A file without layers opens as its merged image. A file whose layers can't be read opens as its merged image
with a warning, and when the merged image can't be read either, the file is refused with an error.
Each layer's pixels must fit the memory allowed for one image, and the pixels of all the layers and masks, with the
canvases the merges make, must together fit eight times that; a file past either limit opens as its merged image,
with a warning. The canvases one step of a merge holds at once must also fit the memory allowed for one image; when
they don't, the layer that needed the merge comes in alone, with a warning: in the Normal mode, or as a layer of its
own instead of clipped.
with a warning. A merge being tried may use the whole of that limit beyond what was read before it. The pixels and
canvases of merges that aren't made, including knockouts that turn out to cut nothing, then count against a second
limit of the same size instead. The
canvases one step of a merge holds at once must also fit the memory allowed for one image; when they don't, the
layer that needed the merge comes in alone, with a warning: in the Normal mode, as a layer of its own instead of
clipped, or without its knockout.
```json
{"name":"run_command","arguments":{"command":"document.open","params":{"path":"/tmp/poster.psd","hiddenLayers":true}}}
+4 -3
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+5 -2
View File
File diff suppressed because one or more lines are too long