Merge main into #8336

# Conflicts:
#	crates/ui-egui/src/i18n/bg.tsv
#	crates/ui-egui/src/i18n/bs.tsv
#	crates/ui-egui/src/i18n/ca.tsv
#	crates/ui-egui/src/i18n/cs.tsv
#	crates/ui-egui/src/i18n/da.tsv
#	crates/ui-egui/src/i18n/de.tsv
#	crates/ui-egui/src/i18n/el.tsv
#	crates/ui-egui/src/i18n/es.tsv
#	crates/ui-egui/src/i18n/fi.tsv
#	crates/ui-egui/src/i18n/fr.tsv
#	crates/ui-egui/src/i18n/gu.tsv
#	crates/ui-egui/src/i18n/hi.tsv
#	crates/ui-egui/src/i18n/hu.tsv
#	crates/ui-egui/src/i18n/id.tsv
#	crates/ui-egui/src/i18n/it.tsv
#	crates/ui-egui/src/i18n/ja.tsv
#	crates/ui-egui/src/i18n/ka.tsv
#	crates/ui-egui/src/i18n/ko.tsv
#	crates/ui-egui/src/i18n/nl.tsv
#	crates/ui-egui/src/i18n/pl.tsv
#	crates/ui-egui/src/i18n/pt-br.tsv
#	crates/ui-egui/src/i18n/ru.tsv
#	crates/ui-egui/src/i18n/sv.tsv
#	crates/ui-egui/src/i18n/tr.tsv
#	crates/ui-egui/src/i18n/uk.tsv
#	crates/ui-egui/src/i18n/vi.tsv
#	crates/ui-egui/src/i18n/zh-hans.tsv
#	crates/ui-egui/src/i18n/zh-hant.tsv
This commit is contained in:
bflatastic committed 2026-11-20 06:59:22 +07:00
commit b95ff44c06
161 files changed
+10373 -772

No files matched your search

Generated
+39 -39
View File
@@ -1001,7 +1001,7 @@ dependencies = [
[[package]]
name = "craft-affinity"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"crc32fast",
"flate2",
@@ -1012,7 +1012,7 @@ dependencies = [
[[package]]
name = "craft-cms"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"md-5",
"rayon",
@@ -1021,12 +1021,12 @@ dependencies = [
[[package]]
name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
[[package]]
name = "craft-dds"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"rayon",
]
@@ -1034,12 +1034,12 @@ dependencies = [
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
[[package]]
name = "craft-dxf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"craft-codepage",
"encoding_rs",
@@ -1051,7 +1051,7 @@ dependencies = [
[[package]]
name = "craft-eps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
[[package]]
name = "craft-font-catalog"
@@ -1070,12 +1070,12 @@ dependencies = [
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
[[package]]
name = "craft-gif"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"gif",
]
@@ -1083,7 +1083,7 @@ dependencies = [
[[package]]
name = "craft-gzip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"flate2",
]
@@ -1091,7 +1091,7 @@ dependencies = [
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"fixed_decimal",
"icu_decimal",
@@ -1114,7 +1114,7 @@ dependencies = [
[[package]]
name = "craft-image-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"craft-dds",
"craft-jpeg",
@@ -1141,7 +1141,7 @@ dependencies = [
[[package]]
name = "craft-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"thiserror 2.0.21",
]
@@ -1149,7 +1149,7 @@ dependencies = [
[[package]]
name = "craft-jxl"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"brotli-decompressor 5.0.3",
"jixel",
@@ -1160,7 +1160,7 @@ dependencies = [
[[package]]
name = "craft-keymap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"egui",
"serde",
@@ -1170,7 +1170,7 @@ dependencies = [
[[package]]
name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"brotli-decompressor 6.3.2",
"chrono",
@@ -1182,7 +1182,7 @@ dependencies = [
[[package]]
name = "craft-metafile"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"encoding_rs",
"image",
@@ -1193,7 +1193,7 @@ dependencies = [
[[package]]
name = "craft-mime"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"chrono",
"craft-codepage",
@@ -1203,7 +1203,7 @@ dependencies = [
[[package]]
name = "craft-pdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"hayro-interpret",
"hayro-syntax",
@@ -1214,7 +1214,7 @@ dependencies = [
[[package]]
name = "craft-plotter"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"kurbo 0.13.1",
"thiserror 2.0.21",
@@ -1223,7 +1223,7 @@ dependencies = [
[[package]]
name = "craft-print"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"craft-winprint-gdi",
"log",
@@ -1237,7 +1237,7 @@ dependencies = [
[[package]]
name = "craft-proof"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"log",
"miniz_oxide 0.9.1",
@@ -1248,7 +1248,7 @@ dependencies = [
[[package]]
name = "craft-ps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"flate2",
"kurbo 0.13.1",
@@ -1257,7 +1257,7 @@ dependencies = [
[[package]]
name = "craft-psd"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"encoding_rs",
"flate2",
@@ -1268,7 +1268,7 @@ dependencies = [
[[package]]
name = "craft-stream-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"fax",
"hayro-ccitt",
@@ -1279,7 +1279,7 @@ dependencies = [
[[package]]
name = "craft-svg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"craft-image-codecs",
"craft-xml",
@@ -1300,7 +1300,7 @@ dependencies = [
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -1309,7 +1309,7 @@ dependencies = [
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"craft-fonts-build",
"craft-i18n",
@@ -1330,7 +1330,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"chrono",
"dunce",
@@ -1357,7 +1357,7 @@ dependencies = [
[[package]]
name = "craft-vectorcraft-format"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"flate2",
"serde",
@@ -1379,7 +1379,7 @@ dependencies = [
[[package]]
name = "craft-window"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"egui",
"objc2 0.6.5",
@@ -1398,7 +1398,7 @@ dependencies = [
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"quick-xml 0.41.0",
"serde",
@@ -2505,7 +2505,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
[[package]]
name = "hayro-cmap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"brotli",
"hayro-postscript",
@@ -2514,7 +2514,7 @@ dependencies = [
[[package]]
name = "hayro-interpret"
version = "0.7.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"bitflags 2.13.2",
"hayro-cmap",
@@ -2532,7 +2532,7 @@ dependencies = [
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"fearless_simd",
"hayro-ccitt",
@@ -2550,12 +2550,12 @@ dependencies = [
[[package]]
name = "hayro-postscript"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"flate2",
"hayro-ccitt",
@@ -3355,7 +3355,7 @@ dependencies = [
[[package]]
name = "krilla"
version = "0.8.2"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"base64 0.22.1",
"bumpalo",
@@ -3464,7 +3464,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
[[package]]
name = "linesweeper"
version = "0.5.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"arrayvec",
"kurbo 0.13.1",
+33 -33
View File
@@ -11,41 +11,41 @@ rust-version = "1.95"
repository = "https://github.com/storytold/vectorcraft"
[workspace.dependencies]
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
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" }
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", default-features = false, features = ["interpret", "write"] }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["serde"] }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
# 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 = "50b0ee7bf811e363b5f238382b5c77318cf33e46", features = ["egui"] }
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", 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 = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
# 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 = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
# DXF tags, reader and writer (craft-libs#778, #926, #927).
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
# WMF, EMF and EMF+ reader (craft-libs#778).
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "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"] }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", default-features = false, features = ["write"] }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["egui"] }
# internal
vectorcraft-geom = { path = "crates/geom" }
vectorcraft-color = { path = "crates/color" }
@@ -186,13 +186,13 @@ lto = "thin"
codegen-units = 1
[patch.crates-io]
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" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
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" }
+2
View File
@@ -146,7 +146,9 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-17: Curvature Circle tool (after the Circle tool in its group): a click on a path draws the circle that touches it there and bends as it bends, on the side it bends toward, or with Shift on the other side; a segment that is the usual cubic of a circular arc of 90° or less gives the arc's own radius, so a click on a circle draws that circle; the tool shows the circle, its center and its radius (with an asterisk for an arc's radius) until the click, or "Straight segment", "Cusp", "Corner" or "Circle too large" where it draws none (`shape.curvatureCircle`). One undo step per circle. A VectorCraft addition: headline numbers unchanged.
- 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged.
- 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged.
- 2026-11-17: Circle Tool Options (double-click the Circle tool): Show Center, Show Radii and Show Diameter switch what the tool shows while a circle is drawn, Color sets the color of the center cross and radius lines, Anchors at Standard Positions off puts the circle's anchors at the points it was drawn through (`shape.circleThroughPoints {anchors: "points"}`), and Third Point by Dragging off draws a three-point circle with three clicks and a two-point circle with a double-click on the second point. A VectorCraft addition: headline numbers unchanged.
- 2026-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). Headline numbers unchanged.
- 2026-11-19: Quick Pen toolbar on the canvas while the tool is active: Straight Line, Continuous Arc and Sharp Corner Arc, Flip Arc, and More Options with Hide Toolbar, Pin Toolbar Position and Reset Toolbar Position; it follows the drawing beside the path's last point and its handle drags it (`tool.quickPen.flipArc`, `window.quickPenToolbar`, Window › Quick Pen Toolbar; part of #2660). Headline numbers unchanged.
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
- 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
+3 -1
View File
@@ -46,6 +46,8 @@ winreg = "0.55"
# Which GPU drives which display (EnumDisplayDevices, src/gpu.rs), so the window is drawn on the
# GPU that shows it: drawing on a GPU without a monitor reset the display driver. Safe wrappers over
# Win32 (MIT); the `user` feature is User32.dll only. Only the wgpu renderer chooses an adapter.
# It also lists each monitor's work area for floating panels (src/window.rs), so a build without
# the `wgpu` feature keeps the panels to the monitors' whole rects.
winsafe = { version = "0.0.29", default-features = false, features = ["user"], optional = true }
# Waits for Direct3D 12's adapter list before the window starts (src/gpu.rs, #4150). MIT OR
# Apache-2.0, already in the build through eframe.
@@ -73,7 +75,7 @@ vectorcraft-render = { workspace = true }
# with default features off). Pinned exactly: review the diff before bumping.
muda = { version = "=0.21.2", default-features = false }
objc2 = "0.6"
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-quartz-core", "NSApplication", "NSCursor", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSButton", "NSColor", "NSColorSampler", "NSColorSpace", "NSControl", "NSMenu", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSTextField", "NSTextInputContext", "NSView", "NSWindow"] }
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-quartz-core", "NSApplication", "NSCursor", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSButton", "NSColor", "NSColorSampler", "NSColorSpace", "NSControl", "NSMenu", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSScreen", "NSTextField", "NSTextInputContext", "NSView", "NSWindow"] }
# Files opened from Finder and the Dock (src/open_documents.rs), pasted bitmaps (src/clipboard.rs) and the control channel's App Nap activity (src/control_server.rs); both already come with winit, muda and rfd.
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSArray", "NSData", "NSGeometry", "NSNotification", "NSOperation", "NSProcessInfo", "NSString", "NSURL"] }
block2 = "0.6"
+213 -13
View File
@@ -11,26 +11,51 @@ use winit::dpi::{LogicalSize, PhysicalPosition, PhysicalSize};
pub const DEFAULT_SIZE: [f32; 2] = [1440.0, 900.0];
/// The smallest window, in points.
pub const MIN_SIZE: [f32; 2] = [800.0, 500.0];
/// Room the first window leaves around itself for a taskbar, Dock or menu bar (the system doesn't
/// say how much of the screen they take): a monitor with less room opens it maximized.
/// Room the first window leaves around itself for a taskbar, Dock or menu bar when it decides
/// whether to open maximized: a monitor with less room opens it maximized. This check uses the
/// fixed allowance on every platform, including where the system reports a work area.
const SCREEN_ROOM: [f32; 2] = [64.0, 128.0];
/// Seconds between readings of the monitor list, which picks up a monitor connected while the app runs.
const MONITORS_EVERY: f64 = 1.0;
/// A monitor: its top-left corner and size in physical pixels, and its scale factor.
/// A monitor: its top-left corner and size in physical pixels, its scale factor, and the part
/// windows may use where the system reports one.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Monitor {
pos: [i64; 2],
size: [i64; 2],
scale: f32,
/// `[x, y, width, height]` in physical pixels, without the taskbar, Dock or menu bar.
work: Option<[i64; 4]>,
}
/// A monitor's rect and its work area as the system lists them, `[x, y, width, height]` in
/// physical pixels. Only Windows and macOS list them.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(not(any(all(windows, feature = "wgpu"), target_os = "macos")), allow(dead_code))]
pub struct WorkArea {
monitor: [i64; 4],
work: [i64; 4],
}
impl Monitor {
pub fn new(pos: PhysicalPosition<i32>, size: PhysicalSize<u32>, scale: f64) -> Self {
let scale = scale as f32;
let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };
Self { pos: [pos.x.into(), pos.y.into()], size: [size.width.into(), size.height.into()], scale }
Self { pos: [pos.x.into(), pos.y.into()], size: [size.width.into(), size.height.into()], scale, work: None }
}
/// This monitor with the work area of the entry in `areas` whose monitor rect matches its own,
/// to the pixel either way to allow for rounding. Without a match, or when the matching work
/// area has no width or height, it has none.
fn with_work_area(self, areas: &[WorkArea]) -> Self {
let [x, y] = self.pos;
let [w, h] = self.size;
let rect = [x, y, w, h];
let work =
areas.iter().find(|a| a.monitor.iter().zip(rect).all(|(a, b)| a.abs_diff(b) <= 1)).map(|a| a.work).filter(|&[_, _, w, h]| w > 0 && h > 0);
Self { work, ..self }
}
/// Its size in points.
@@ -38,6 +63,19 @@ impl Monitor {
self.size.map(|s| s as f32 / self.scale)
}
/// This monitor with its work area made smaller by a window frame of `frame` physical pixels
/// (outer size less inner size), so a window whose inner size fits the result fits the work area
/// with its frame.
fn less_frame(self, frame: [i64; 2]) -> Self {
let work = self.work.map(|[x, y, w, h]| [x, y, (w - frame[0].max(0)).max(1), (h - frame[1].max(0)).max(1)]);
Self { work, ..self }
}
/// The size of its work area in points, or of the whole monitor when it has none.
fn work_points(&self) -> [f32; 2] {
self.work.map_or_else(|| self.points(), |[_, _, w, h]| [w, h].map(|s| s as f32 / self.scale))
}
/// Its size in points less room for a taskbar, Dock or menu bar.
fn usable(&self) -> [f32; 2] {
let points = self.points();
@@ -61,24 +99,31 @@ impl Monitor {
}
/// The top-left corner nearest to `pos` (centred when none) that keeps a window of `size`
/// points on this monitor.
/// points on this monitor, inside its work area when it has one. A window bigger than the area
/// gets the area's top-left corner.
fn keep_on(&self, pos: Option<[i32; 2]>, size: [f32; 2]) -> [i32; 2] {
let px = self.pixels(size);
let [x, y] = self.pos;
let [w, h] = self.size;
let [ax, ay, aw, ah] = self.work.unwrap_or([x, y, w, h]);
let (start, extent) = ([ax, ay], [aw, ah]);
std::array::from_fn(|i| {
let lo = self.pos[i];
let hi = lo + self.size[i].saturating_sub(px[i]).max(0);
let lo = start[i];
let hi = lo + extent[i].saturating_sub(px[i]).max(0);
let want = pos.map_or(lo + (hi - lo) / 2, |p| i64::from(p[i]));
i32::try_from(want.max(lo).min(hi)).unwrap_or_default()
})
}
/// This monitor for floating panels, in the points egui reports for a window on it: physical
/// pixels divided by the monitor's scale factor and the UI zoom.
/// pixels divided by the monitor's scale factor and the UI zoom. The work area is converted the
/// same way.
fn docking(&self, name: Option<String>, zoom: f32) -> DockMonitor {
let scale = self.scale * zoom;
let [x, y] = self.pos;
let [w, h] = self.size;
DockMonitor { name, rect: [x, y, w, h].map(|v| v as f32 / scale), scale, work_area: None }
let points = |rect: [i64; 4]| rect.map(|v| v as f32 / scale);
DockMonitor { name, rect: points([x, y, w, h]), scale, work_area: self.work.map(points) }
}
}
@@ -108,7 +153,10 @@ pub fn place(saved: Option<WindowGeometry>, monitors: &[Monitor], home: Option<u
// Bigger than its monitor (a smaller screen than last time): maximized, like the first window.
let room = m.points();
let too_big = (0..2).any(|i| saved.size[i] > room[i]);
let size = fit(saved.size, if too_big { m.usable() } else { room });
// No bigger than the work area either, so the window fits below or beside the taskbar.
let work = m.work_points();
let room = if too_big { m.usable() } else { room };
let size = fit(saved.size, std::array::from_fn(|i| room[i].min(work[i])));
WindowGeometry {
// Moved fully onto its monitor, or centred on the home monitor.
pos: saved.pos.map(|p| m.keep_on(shown.map(|_| p), size)),
@@ -128,12 +176,94 @@ pub fn monitors_due(listed: Option<(f64, f32)>, now: f64, zoom: f32) -> bool {
listed.is_none_or(|(at, listed_zoom)| listed_zoom != zoom || now - at >= MONITORS_EVERY)
}
/// The connected monitors for floating panels (`Services::dock_monitors`).
/// The connected monitors for floating panels (`Services::dock_monitors`), with the work area the
/// system reports for each (Windows and macOS).
pub fn dock_monitors(window: &winit::window::Window, zoom: f32) -> Vec<DockMonitor> {
let monitors: Vec<_> = window.available_monitors().map(|m| (Monitor::new(m.position(), m.size(), m.scale_factor()), m.name())).collect();
let areas = work_areas::list();
let monitors: Vec<_> =
window.available_monitors().map(|m| (Monitor::new(m.position(), m.size(), m.scale_factor()).with_work_area(&areas), m.name())).collect();
docking_list(&monitors, zoom, cfg!(target_os = "macos"))
}
/// A rect in macOS screen coordinates (points, origin at the bottom-left of the primary screen,
/// y up) in the physical pixels winit gives a monitor's position and size: points from the top-left
/// of the primary screen, `primary_height` points tall, times `scale`.
#[cfg(any(target_os = "macos", test))]
fn from_bottom_left([x, y, w, h]: [f64; 4], primary_height: f64, scale: f64) -> Option<[i64; 4]> {
let rect = [x, primary_height - (y + h), w, h].map(|v| (v * scale).round());
// `as` saturates; a coordinate of 1e12 pixels or more is not a monitor's.
rect.iter().all(|v| v.is_finite() && v.abs() < 1e12).then(|| rect.map(|v| v as i64))
}
/// Each monitor's rect and work area as the system reports them.
mod work_areas {
pub use platform::list;
/// `GetMonitorInfo` for every monitor: `rcMonitor` and `rcWork`, in the physical pixels winit
/// reports for a per-monitor DPI aware process.
#[cfg(all(windows, feature = "wgpu"))]
mod platform {
use super::super::WorkArea;
use winsafe::prelude::Handle;
use winsafe::{HDC, RECT};
pub fn list() -> Vec<WorkArea> {
let rect = |r: RECT| {
let [left, top, right, bottom] = [r.left, r.top, r.right, r.bottom].map(i64::from);
[left, top, right - left, bottom - top]
};
let mut areas = Vec::new();
// Without a list the panels keep to the monitors' whole rects, as before.
let _ = HDC::NULL.EnumDisplayMonitors(None, |monitor, _, _| {
if let Ok(info) = monitor.GetMonitorInfo() {
areas.push(WorkArea { monitor: rect(info.rcMonitor), work: rect(info.rcWork) });
}
true
});
areas
}
}
/// `NSScreen`'s `frame` and `visibleFrame` for every screen, turned into the top-left origin
/// and physical pixels winit uses for its monitors.
#[cfg(target_os = "macos")]
mod platform {
use super::super::{WorkArea, from_bottom_left};
use objc2_app_kit::NSScreen;
use objc2_foundation::{MainThreadMarker, NSRect};
pub fn list() -> Vec<WorkArea> {
// `NSScreen::screens` needs the main thread, where the UI frame runs.
let Some(mtm) = MainThreadMarker::new() else {
return Vec::new();
};
let screens: Vec<_> = NSScreen::screens(mtm).iter().collect();
// The first screen holds the menu bar and is the origin of the screen coordinates.
let Some(primary) = screens.first().map(|s| s.frame().size.height) else {
return Vec::new();
};
let rect = |r: NSRect| [r.origin.x, r.origin.y, r.size.width, r.size.height];
screens
.iter()
.filter_map(|s| {
let scale = s.backingScaleFactor();
let monitor = from_bottom_left(rect(s.frame()), primary, scale)?;
let work = from_bottom_left(rect(s.visibleFrame()), primary, scale)?;
Some(WorkArea { monitor, work })
})
.collect()
}
}
/// No work areas: the panels keep to the monitors' whole rects.
#[cfg(not(any(all(windows, feature = "wgpu"), target_os = "macos")))]
mod platform {
pub fn list() -> Vec<super::super::WorkArea> {
Vec::new()
}
}
}
/// The list for floating panels, empty when `monitors` have different scales and `shared_points` is
/// false. macOS has one desktop of points. Elsewhere a new window multiplies its saved position by the
/// scale of the monitor it is created on, which can put a window saved on another scale off every
@@ -154,7 +284,19 @@ fn docking_list(monitors: &[(Monitor, Option<String>)], zoom: f32, shared_points
/// until the host reports maximized (fixes #3635).
pub fn restore(window: &winit::window::Window, saved: Option<WindowGeometry>) -> WindowGeometry {
let handles: Vec<_> = window.available_monitors().collect();
let monitors: Vec<Monitor> = handles.iter().map(|m| Monitor::new(m.position(), m.size(), m.scale_factor())).collect();
let areas = work_areas::list();
// The system title bar and border, which the inner size leaves out, in points: each monitor
// draws them at its own scale.
let (outer, inner, scale) = (window.outer_size(), window.inner_size(), window.scale_factor());
let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };
let frame = [outer.width.saturating_sub(inner.width), outer.height.saturating_sub(inner.height)].map(|px| f64::from(px) / scale);
let monitors: Vec<Monitor> = handles
.iter()
.map(|m| {
let px = frame.map(|f| (f * m.scale_factor()).ceil().min(1e6) as i64);
Monitor::new(m.position(), m.size(), m.scale_factor()).with_work_area(&areas).less_frame(px)
})
.collect();
let home = window.current_monitor().or_else(|| window.primary_monitor()).and_then(|c| handles.iter().position(|m| *m == c));
let g = place(saved, &monitors, home);
if let Some([x, y]) = g.pos {
@@ -257,6 +399,64 @@ mod tests {
assert_eq!(zoomed, DockMonitor { name: Some("m".into()), rect: [-2048.0, 0.0, 2048.0, 1152.0], scale: 1.25, work_area: None });
}
#[test]
fn floating_panels_get_each_monitors_work_area_in_the_same_points() {
// A 4K monitor at 200% with a 96-pixel taskbar along its bottom, and one at 100% to its
// right with a 48-pixel taskbar along its left edge.
let areas = [
WorkArea { monitor: [0, 0, 3840, 2160], work: [0, 0, 3840, 2064] },
WorkArea { monitor: [3840, 0, 1920, 1080], work: [3888, 0, 1872, 1080] },
];
let left = monitor(0, 0, 3840, 2160, 2.0).with_work_area(&areas);
assert_eq!(left.docking(None, 1.0).work_area, Some([0.0, 0.0, 1920.0, 1032.0]));
// The UI zoom divides the work area as it divides the rect.
assert_eq!(left.docking(None, 1.25).work_area, Some([0.0, 0.0, 1536.0, 825.6]));
// Rounding of a fractional scale can move a rect by a pixel.
let right = monitor(3841, 0, 1919, 1080, 1.0).with_work_area(&areas);
assert_eq!(right.docking(None, 1.0).work_area, Some([3888.0, 0.0, 1872.0, 1080.0]));
// A monitor the system did not list keeps to its whole rect.
let other = monitor(5760, 0, 1920, 1080, 1.0).with_work_area(&areas);
assert_eq!(other.docking(None, 1.0).work_area, None);
assert_eq!(monitor(0, 0, 3840, 2160, 2.0).with_work_area(&[]).docking(None, 1.0).work_area, None);
// A work area with no height is left out, so the monitor keeps to its whole rect.
let flat = [WorkArea { monitor: [0, 0, 1920, 1080], work: [0, 1080, 1920, 0] }];
assert_eq!(monitor(0, 0, 1920, 1080, 1.0).with_work_area(&flat).docking(None, 1.0).work_area, None);
}
#[test]
fn a_restored_window_keeps_its_title_bar_out_of_a_taskbar_along_the_top() {
// A 1920 × 1080 monitor with a 48-pixel taskbar along its top edge.
let areas = [WorkArea { monitor: [0, 0, 1920, 1080], work: [0, 48, 1920, 1032] }];
let m = [monitor(0, 0, 1920, 1080, 1.0).with_work_area(&areas)];
// A window saved at the top edge moves down below the taskbar.
let g = place(saved(Some([100, 0]), [1000.0, 700.0], false), &m, Some(0));
assert_eq!(g.pos, Some([100, 48]));
// A window that fits below the taskbar keeps its place.
assert_eq!(place(saved(Some([100, 200]), [1000.0, 700.0], false), &m, Some(0)).pos, Some([100, 200]));
// A window taller than the work area is made as tall as the work area and placed in it.
let tall = place(saved(Some([0, 0]), [1900.0, 1060.0], false), &m, Some(0));
assert_eq!((tall.pos, tall.size), (Some([0, 48]), [1900.0, 1032.0]));
// With a system frame of 16 × 39 pixels the inner size leaves room for it.
let framed = [m[0].less_frame([16, 39])];
let tall = place(saved(Some([0, 0]), [1900.0, 1060.0], false), &framed, Some(0));
assert_eq!((tall.pos, tall.size), (Some([0, 48]), [1900.0, 993.0]));
// Without a work area the frame leaves the monitor's rect as it was.
assert_eq!(monitor(0, 0, 1920, 1080, 1.0).less_frame([16, 39]).work, None);
}
#[test]
fn macos_screen_rects_turn_into_winits_top_left_pixels() {
// A 1512 × 982 point primary screen at 2× with a 37-point menu bar and an 80-point Dock,
// and a 1920 × 1080 screen at 1× above it, its bottom-left 200 points right of the
// primary's top-left.
let primary = 982.0;
assert_eq!(from_bottom_left([0.0, 0.0, 1512.0, 982.0], primary, 2.0), Some([0, 0, 3024, 1964]));
assert_eq!(from_bottom_left([0.0, 80.0, 1512.0, 865.0], primary, 2.0), Some([0, 74, 3024, 1730]));
assert_eq!(from_bottom_left([200.0, 982.0, 1920.0, 1080.0], primary, 1.0), Some([200, -1080, 1920, 1080]));
assert_eq!(from_bottom_left([f64::NAN, 0.0, 1.0, 1.0], primary, 1.0), None);
assert_eq!(from_bottom_left([0.0, 0.0, 1e300, 1.0], primary, 1.0), None);
}
#[test]
fn monitors_of_different_scales_are_listed_only_on_a_desktop_of_shared_points() {
let named = |m: Monitor, name: &str| (m, Some(name.to_string()));
+3 -53
View File
@@ -639,8 +639,7 @@ fn jpeg_icc(bytes: &[u8]) -> Option<Vec<u8>> {
craft_image_codecs::jpeg_inks::jpeg_icc_profile(bytes)
}
/// The bytes after an `ICC_PROFILE` APP2 segment's length: its name, then the segment's number and
/// the count of segments.
#[cfg(test)]
const ICC_SEGMENT: &[u8; 12] = b"ICC_PROFILE\0";
/// JPEG `bytes` carrying `icc` in place of the ICC profile they carry, if any: every
@@ -649,63 +648,14 @@ const ICC_SEGMENT: &[u8; 12] = b"ICC_PROFILE\0";
/// for bytes whose segments before the scan can't be read, an empty `icc`, and one longer than 255
/// segments hold.
pub fn jpeg_with_icc(bytes: &[u8], icc: &[u8]) -> Option<Vec<u8>> {
// A segment's length counts itself (2 bytes) and the name, number and count (14).
const CHUNK: usize = 0xFFFF - 2 - ICC_SEGMENT.len() - 2;
let chunks: Vec<&[u8]> = icc.chunks(CHUNK).collect();
let count = u8::try_from(chunks.len()).ok().filter(|n| *n > 0)?;
let mut segments = Vec::with_capacity(icc.len() + 18 * chunks.len());
for (i, chunk) in chunks.iter().enumerate() {
let len = u16::try_from(chunk.len() + 2 + ICC_SEGMENT.len() + 2).ok()?;
segments.extend_from_slice(&[0xFF, 0xE2]);
segments.extend_from_slice(&len.to_be_bytes());
segments.extend_from_slice(ICC_SEGMENT);
segments.extend_from_slice(&[u8::try_from(i + 1).ok()?, count]);
segments.extend_from_slice(chunk);
}
with_icc_segments(bytes, segments)
craft_image_codecs::jpeg_inks::jpeg_with_icc(bytes, icc)
}
/// JPEG `bytes` without the ICC profile they carry: every `ICC_PROFILE` APP2 segment before the
/// scan taken out, and the other segments and the scan as they are. `None` for bytes whose
/// segments before the scan can't be read.
pub fn jpeg_without_icc(bytes: &[u8]) -> Option<Vec<u8>> {
with_icc_segments(bytes, vec![])
}
/// JPEG `bytes` with every `ICC_PROFILE` APP2 segment before the scan taken out and `segments`
/// written after the leading application segments; `None` when the bytes don't start a JPEG or
/// their segments before the scan can't be read.
fn with_icc_segments(bytes: &[u8], segments: Vec<u8>) -> Option<Vec<u8>> {
if !bytes.starts_with(&[0xFF, 0xD8]) {
return None;
}
let mut out = Vec::with_capacity(bytes.len() + segments.len());
out.extend_from_slice(&[0xFF, 0xD8]);
let mut icc_segments = Some(segments);
let mut at = 2;
// The segments before the scan (SOS), each with its length; a marker without one ends them.
// Fill bytes (0xFF) before a marker are left out.
loop {
while bytes.get(at..at + 2) == Some(&[0xFF, 0xFF]) {
at += 1;
}
let (Some(&0xFF), Some(&marker)) = (bytes.get(at), bytes.get(at + 1)) else { return None };
let app = (0xE0..=0xEF).contains(&marker);
if !app && let Some(s) = icc_segments.take() {
out.extend_from_slice(&s);
}
if matches!(marker, 0xDA | 0xD8 | 0xD9 | 0x01 | 0xD0..=0xD7) {
break;
}
let len = usize::from(u16::from_be_bytes(bytes.get(at + 2..at + 4)?.try_into().ok()?));
let segment = bytes.get(at..(at + 2).checked_add(len)?).filter(|_| len >= 2)?;
if !(marker == 0xE2 && segment.get(4..16) == Some(ICC_SEGMENT.as_slice())) {
out.extend_from_slice(segment);
}
at += segment.len();
}
out.extend_from_slice(bytes.get(at..)?);
Some(out)
craft_image_codecs::jpeg_inks::jpeg_without_icc(bytes)
}
/// `icc` when it is a profile of CMYK colors, which the samples of a CMYK image are in.
+2 -2
View File
@@ -198,8 +198,8 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
INFLATE,
"Inflate…",
&["Effect", "3D and Materials"],
"{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Painted with the top fill (else the top stroke).",
json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"render":{"mode":"shaded"}}),
"{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the puffed front and back, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind and takes graphics with bothSides and cap on), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the art's plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); carried straight out from the art's plane onto the puffed face, twist and taper turning and shrinking the back's with it, shaded with the surface and drawn only where its outside faces the viewer), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Painted with the top fill (else the top stroke).",
json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}),
),
g(
ROTATE,
+11 -2
View File
@@ -229,11 +229,20 @@ pub(crate) fn seamed_fill(path: &vectorcraft_geom::PathData, seam: f64) -> Optio
/// footprints. Where two facets' antialiased edges meet, the underlay fills what they leave
/// uncovered with the neighbors' own colors, so the background does not show through. `None` unless
/// every face is a facet a surface draws: a path filled and stroked by its seam, or a facet composed
/// in a clip of its footprint, neither with an opacity mask.
/// in a clip of its footprint, neither with an opacity mask. A face drawn with the parts of Inflate's
/// graphics on it, a group of the facet and those parts, takes its facet's underlay and stays in the
/// order with its parts, which are cut to the facet's outline, so the clip keeps them.
pub(crate) fn sealed(id: vectorcraft_doc::NodeId, faces: &[std::sync::Arc<vectorcraft_doc::Node>]) -> Option<vectorcraft_doc::Node> {
use std::sync::Arc;
use vectorcraft_doc::{Node, NodeKind};
let (clip, mut underlay) = underlay(id, faces)?;
let facets: Vec<Arc<Node>> = faces
.iter()
.map(|face| match &face.kind {
NodeKind::Group { children, clip: false } if face.extras().mask.is_none() => children.first().cloned(),
_ => Some(face.clone()),
})
.collect::<Option<_>>()?;
let (clip, mut underlay) = underlay(id, &facets)?;
underlay.extend(faces.iter().cloned());
Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, underlay))], clip: true }))
}
+2 -1
View File
@@ -382,7 +382,8 @@ fn revolve_takes_graphics_on_its_side_only() {
let kept = three_d_params_as(crate::EXTRUDE, &both, REVOLVE);
assert_eq!(kept["graphics"].as_array().map(Vec::len), Some(1));
assert_eq!(kept["graphics"][0]["symbol"], "Red");
assert_eq!(three_d_params_as(REVOLVE, &front, crate::INFLATE).get("graphics"), None);
// Inflate keeps them, and its front takes them.
assert_eq!(three_d_params_as(REVOLVE, &front, crate::INFLATE)["graphics"], front["graphics"]);
}
#[test]
+136 -35
View File
@@ -98,13 +98,15 @@ pub fn three_d_params_as(from: &str, params: &Value, to: &str) -> Value {
}
}
// A plane has only a front, and Revolve's graphics go on its side, named the front, so graphics
// on the back cap and on Extrude & Bevel's side are dropped.
if (to == ROTATE || to == crate::REVOLVE)
// on the back cap and on Extrude & Bevel's side are dropped. Inflate takes graphics on its front
// and back, so it drops those on the side.
if (to == ROTATE || to == crate::REVOLVE || to == INFLATE)
&& let Some(Value::Array(list)) = out.get_mut(GRAPHICS)
{
let back = to != INFLATE;
list.retain(|g| {
let face = g.get("face").and_then(Value::as_str);
face != Some(PlanarFace::Back.id()) && face != Some(PlanarFace::Side.id())
!(back && face == Some(PlanarFace::Back.id())) && face != Some(PlanarFace::Side.id())
});
}
Value::Object(out)
@@ -259,6 +261,7 @@ pub fn inflate_options(p: &Value) -> Inflate {
twist: num(p, "twist", 0.0),
taper: num(p, "taper", 100.0) / 100.0,
cap: flag(p, "cap", true),
map_surface: false,
}
}
@@ -444,7 +447,8 @@ pub fn validate_solid_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value)
/// Inflate or Rotate, as drawn, or a new one after its other effects when it has none.
fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: (Option<usize>, Option<usize>)) -> Result<(), String> {
validate_solid_params(id, p)?;
if let Some(doc) = doc {
// In wireframe mode the edges are drawn with no graphics, and their art is not checked.
if let Some(doc) = doc.filter(|_| !wireframe::wireframe_params(id, p)) {
graphics::validate_symbols(doc, p)?;
}
let label = label_of(id);
@@ -461,7 +465,8 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at:
let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?;
check_profiles(id, p, &shapes, b)?;
check_solids(id, p, &shapes)?;
return check_side_graphics(doc, n, id, p, &shapes);
check_side_graphics(doc, n, id, p, &shapes)?;
return check_membrane_graphics(doc, n, id, p, &shapes);
}
let (path, rule) = object_profile(n, label)?;
let anchors = || format!("{label} requires a shape with at least two anchors");
@@ -479,7 +484,8 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at:
let shapes = [Profile { path, rule, items, opacity: 1.0, scopes: vec![] }];
check_profiles(id, p, &shapes, b)?;
check_solids(id, p, &shapes)?;
check_side_graphics(doc, n, id, p, &shapes)
check_side_graphics(doc, n, id, p, &shapes)?;
check_membrane_graphics(doc, n, id, p, &shapes)
}
/// Does 3D effect `id` with parameters `p` cast a shadow: is it Extrude & Bevel, Inflate or Rotate
@@ -493,6 +499,30 @@ fn visible(item: &AppearanceItem, member: f32) -> bool {
paint_of(item, member).1 > 0.0
}
/// An error when the graphics of Inflate `id` with parameters `p`, with the symbols of `doc`, are
/// past their limits on the front and puffed back of the solids of `shapes`: their art, or the
/// parts they draw on its pieces ([`graphics::surface_parts`]), or when the solids can't be built
/// with their pieces carrying the graphics. They are built as the art builds them
/// ([`surfaces_with`]). Without `doc` nothing is drawn, and nothing is checked. In wireframe mode no
/// graphics are drawn, and none are checked.
fn check_membrane_graphics(doc: Option<&Document>, n: &Node, id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> {
let Some(doc) = doc else { return Ok(()) };
if id != INFLATE || wireframe::wireframe_params(id, p) || mapped_graphics(p).is_empty() {
return Ok(());
}
for face in [PlanarFace::Front, PlanarFace::Back] {
graphics::validate_surface_symbols(doc, p, face)?;
}
let fx = Effect { id: id.into(), params: p.clone(), visible: true };
let mut dropped = false;
// Art that can't be built with the graphics draws without them.
let built = surfaces_with(Some(doc), n, &fx, shapes, false, true, &mut dropped);
if dropped || built.is_none() {
return Err("The graphics are too complex: simplify the symbols' art".into());
}
Ok(())
}
/// An error when the graphics on the side of Extrude & Bevel `id` with parameters `p`, with the
/// symbols of `doc`, are past their limits on the side of the solid of `shapes` that takes them
/// ([`side_carrier`]): their art, or the parts they draw on its pieces
@@ -521,7 +551,7 @@ fn check_side_graphics(doc: Option<&Document>, n: &Node, id: &str, p: &Value, sh
let fx = Effect { id: id.into(), params: p.clone(), visible: true };
let mut dropped = false;
// Art that can't be built draws the source path, without the side's graphics.
let built = surfaces_with(Some(doc), n, &fx, shapes, false, &mut dropped);
let built = surfaces_with(Some(doc), n, &fx, shapes, false, false, &mut dropped);
if dropped || built.is_none() {
return Err("The graphics are too complex: simplify the symbols' art".into());
}
@@ -572,7 +602,7 @@ fn check_solids(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> {
if !cast {
return built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ()));
}
let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true, None)
let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true, false, None)
.map(|r| r.map(|solid| solid.and_then(|(_, faces)| faces)))
.collect::<Result<Vec<_>, String>>()?;
cast_built(id, p, shapes, built).map(|_| ())
@@ -846,11 +876,37 @@ fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: Ble
group
}
/// The parts of `graphics` that fall on each of `facets`, the facets of one of Inflate's solids in
/// drawing order, built with their front and puffed back carrying the graphics
/// ([`vectorcraft_three_d::Inflate::map_surface`]): for each facet, the parts of the graphics on
/// its face to draw right after it ([`graphics::surface_parts`]), shaded as a solid color is on
/// that facet. `copies` counts the bytes of the paint copies of the object's graphics. `None` past
/// the graphics' limits.
fn membrane_parts(
doc: Option<&Document>,
id: NodeId,
graphics: &[MappedGraphic],
facets: &[Facet],
copies: &mut usize,
) -> Option<Vec<Vec<Arc<Node>>>> {
let shade = |f: &graphics::OnFace<'_>, c: vectorcraft_doc::color::Color| Paint::solid(crate::lighting::shade(c, f.facet.illumination));
let mut out: Vec<Vec<Arc<Node>>> = vec![vec![]; facets.len()];
for face in [PlanarFace::Front, PlanarFace::Back].into_iter().filter(|face| graphics.iter().any(|g| g.face == *face)) {
let on: Vec<graphics::OnFace<'_>> = facets.iter().map(|facet| graphics::OnFace { facet, face }).collect();
let parts = graphics::surface_parts(doc, id, (graphics, face), &on, &shade, copies)?;
for (slot, extra) in out.iter_mut().zip(parts) {
slot.extend(extra);
}
}
Some(out)
}
/// `surface`, a plain group of one face for each facet ([`surface`]), with each face followed by
/// the parts of the side's graphics that `parts` holds for its facet ([`graphics::surface_parts`]):
/// a face with parts becomes a group of the face and its parts, so nearer faces drawn after it
/// cover them too. `surface` is returned as it is when no facet has a part or it is not such a group.
fn with_side_parts(id: NodeId, mut surface: Node, parts: Vec<Vec<Arc<Node>>>) -> Node {
/// the parts of the graphics that `parts` holds for its facet (on Extrude & Bevel's side
/// [`graphics::surface_parts`], on Inflate's front and back [`membrane_parts`]): a face with parts
/// becomes a group of the face and its parts, so nearer faces drawn after it cover them too.
/// `surface` is returned as it is when no facet has a part or it is not such a group.
fn with_surface_parts(id: NodeId, mut surface: Node, parts: Vec<Vec<Arc<Node>>>) -> Node {
if parts.iter().all(Vec::is_empty) {
return surface;
}
@@ -984,7 +1040,7 @@ fn built_solids<'a>(
bounds: Rect,
limit: usize,
) -> impl Iterator<Item = Result<Option<Vec<Facet>>, String>> + 'a {
built_solids_cast(id, p, parts, bounds, limit, false, None).map(|r| r.map(|s| s.map(|(f, _)| f)))
built_solids_cast(id, p, parts, bounds, limit, false, false, None).map(|r| r.map(|s| s.map(|(f, _)| f)))
}
/// One solid's facets and, when its shadow is cast, the faces it is cast from.
@@ -995,9 +1051,12 @@ type CastingSolid = (Vec<Facet>, Option<SolidFaces>);
type SurfacesAndFaces = (Vec<Arc<Node>>, Vec<Option<SolidFaces>>);
/// [`built_solids`], and with `cast` for Extrude & Bevel or Inflate each solid's faces its shadow
/// is cast from, from the same build ([`SolidFaces`]). The solid of part `side`, when there is one,
/// is built with the pieces of its side carrying where they lie on it unrolled, for the graphics
/// on Extrude & Bevel's side ([`side_carrier`]).
/// is cast from, from the same build ([`SolidFaces`]). With `membrane`, Inflate's solids are built
/// with the pieces of their front and puffed back carrying where they lie in the art's plane, for
/// the graphics drawn on them ([`vectorcraft_three_d::Inflate::map_surface`]). The solid of part
/// `side`, when there is one, is built with the pieces of its side carrying where they lie on it
/// unrolled, for the graphics on Extrude & Bevel's side ([`side_carrier`]).
#[allow(clippy::too_many_arguments)] // the build's inputs and the two surfaces that carry graphics
fn built_solids_cast<'a>(
id: &'a str,
p: &'a Value,
@@ -1005,12 +1064,13 @@ fn built_solids_cast<'a>(
bounds: Rect,
limit: usize,
cast: bool,
membrane: bool,
side: Option<usize>,
) -> impl Iterator<Item = Result<Option<CastingSolid>, String>> + 'a {
// Inflate's eye is placed for every puff together, as far away as the highest needs.
let mut inflated = (id == INFLATE).then(|| -> Box<dyn Iterator<Item = Result<CastingSolid, String>>> {
let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect();
let (o, view) = (inflate_options(p), view_options(p));
let (o, view) = (Inflate { map_surface: membrane, ..inflate_options(p) }, view_options(p));
if cast {
Box::new(vectorcraft_three_d::inflate_shadowed(&shapes, bounds, o, view).map(|r| r.map(|(f, faces)| (f, Some(faces)))))
} else {
@@ -1962,14 +2022,33 @@ fn seen_ends(f: &[Facet]) -> impl Iterator<Item = &Facet> {
/// [`art_for`] without the shadow: the solids' surfaces, with the graphics mapped onto their planar
/// faces drawn right after the last of the solids' surfaces that holds that face. With `cast`, each
/// solid built also keeps the faces its shadow is cast from, from the same build, in the order the
/// solids are built ([`cast_built`]); `None` for a stroke's solid left out of the art.
/// solids are built ([`cast_built`]); `None` for a stroke's solid left out of the art. Inflate's
/// graphics are drawn on the pieces of its front and puffed back; when its solids can't be built
/// with those pieces, or the graphics are past their limits on them, the solids draw without them.
fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile], cast: bool) -> Option<SurfacesAndFaces> {
surfaces_with(doc, n, fx, shapes, cast, &mut false)
let p = crate::merged_params(&fx.id, &fx.params);
if fx.id == INFLATE && doc.is_some() && !mapped_graphics(&p).is_empty() {
let mut dropped = false;
if let Some(built) = surfaces_with(doc, n, fx, shapes, cast, true, &mut dropped).filter(|_| !dropped) {
return Some(built);
}
}
surfaces_with(doc, n, fx, shapes, cast, false, &mut false)
}
/// [`surfaces_for`], setting `side_dropped` when the graphics on Extrude & Bevel's side are past
/// their limits on the pieces drawn, and the solid that takes them draws without them.
fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile], cast: bool, side_dropped: &mut bool) -> Option<SurfacesAndFaces> {
/// [`surfaces_for`], with `membrane` building Inflate's solids with their front and puffed back
/// carrying the graphics ([`built_solids_cast`]), and setting `dropped` when those graphics, or the
/// graphics on Extrude & Bevel's side, are past their limits on the pieces drawn and the solid that
/// takes them draws without them.
fn surfaces_with(
doc: Option<&Document>,
n: &Node,
fx: &Effect,
shapes: &[Profile],
cast: bool,
membrane: bool,
dropped: &mut bool,
) -> Option<SurfacesAndFaces> {
let b = union_bounds(shapes)?;
let p = crate::merged_params(&fx.id, &fx.params);
let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE;
@@ -2025,7 +2104,7 @@ fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profil
let map_art = MapArt::of(doc, &fx.id, &p).filter(|_| fx.id == CLASSIC_EXTRUDE);
let mut layouts: Vec<SolidLayout> = vec![];
let mut surfaces_before = 0usize;
let made = built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast, carrier);
let made = built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast, membrane, carrier);
for (k, ((item, opacity, area, rule, scopes, member), f)) in parts.iter().zip(made).enumerate() {
let item: &AppearanceItem = item;
let layout = map_art.as_ref().map(|_| {
@@ -2044,11 +2123,12 @@ fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profil
layouts.extend(layout);
built.push(faces);
}
// A stroke's outline past the limits is left out; the fill's solid still draws, and
// A stroke's outline past the limits is left out; the fill's solid still draws. Built
// with the graphics' pieces, a stroke past the limits draws without the graphics, and
// the side's graphics on that outline are not drawn.
Ok(None) => {
built.push(None);
*side_dropped |= carrier == Some(k);
*dropped |= membrane || carrier == Some(k);
}
// A loaded file or a shape edited past the limits (its own, or those of the object's
// solids together) keeps drawing its source path instead of failing the frame;
@@ -2161,8 +2241,10 @@ fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profil
// ([`in_one_order`], [`underlaid_surface`]).
let seals: Vec<bool> = solids.iter().map(|(.., f, _)| underlaid(f, colored)).collect();
let seal = |range: std::ops::Range<usize>| seals.get(range).is_some_and(|s| s.iter().any(|s| *s));
let membrane_graphics = if membrane && graphics_on { mapped_graphics(&p) } else { vec![] };
let side_graphics = carrier.map(|_| mapped_graphics(&p)).unwrap_or_default();
// The paint copies of the side's graphics, apart from those of the surfaces, as on Revolve.
// The paint copies of Inflate's graphics and of the side's, apart from those of the surfaces,
// as on Revolve.
let mut graphic_copies = 0usize;
let surfaces: Vec<BuiltSurface> = solids
.into_iter()
@@ -2171,22 +2253,29 @@ fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profil
let depths: Vec<Placed> = f.iter().map(|f| Placed::of(f, shape, paints)).collect();
let ends = f.iter().map(|f| f.end.filter(|_| !f.away)).collect();
let (paint, opacity, blend) = paint_of(item, member);
// The carrier's pieces draw the parts of the side's graphics that fall on them; past
// the graphics' limits the solid draws without them.
let parts = if side_graphics.is_empty() || !f.iter().any(|f| f.surface.is_some()) {
// The pieces of Inflate's front and back, and the carrier's pieces of Extrude & Bevel's
// side, draw the parts of the graphics that fall on them; past the graphics' limits the
// solid draws without them.
let parts = if !f.iter().any(|f| f.surface.is_some()) {
vec![]
} else {
} else if !membrane_graphics.is_empty() {
let parts = membrane_parts(doc, n.id, &membrane_graphics, &f, &mut graphic_copies);
*dropped |= parts.is_none();
parts.unwrap_or_default()
} else if !side_graphics.is_empty() {
let shade = |f: &Facet, c: vectorcraft_doc::color::Color| Paint::solid(crate::lighting::shade(c, f.illumination));
let parts = graphics::surface_parts(doc, n.id, (&side_graphics, PlanarFace::Side), &f, &shade, &mut graphic_copies);
*side_dropped |= parts.is_none();
*dropped |= parts.is_none();
parts.unwrap_or_default()
} else {
vec![]
};
let drawn = parts.iter().any(|p| !p.is_empty());
let art = if classic {
classic_arts.next().unwrap_or_else(|| Node::group(n.id, vec![]))
} else {
let faces = drawn || (split && shared.get(shape).copied().unwrap_or(false));
with_side_parts(n.id, surface(n, f, &paint, opacity, blend, colored, faces), parts)
with_surface_parts(n.id, surface(n, f, &paint, opacity, blend, colored, faces), parts)
};
(depths, art, scopes, ends)
})
@@ -2476,14 +2565,15 @@ fn group_solid_art(doc: Option<&Document>, n: &Node) -> Option<Node> {
/// Where the graphics of the 3D effect of `n` (on the object itself with `item` `None`, else on its
/// fill or stroke `item`) are drawn: the bounds its solids are built with and the maps of their
/// planar faces ([`graphics::GraphicFrame`]). `None` when `n` has no visible Extrude & Bevel or
/// Rotate there, or its art can't be built.
/// planar faces, or Inflate's puffed faces ([`graphics::GraphicFrame`]). `None` when `n` has no
/// visible Extrude & Bevel, Inflate or Rotate there, or its art can't be built.
pub fn graphic_frame(doc: Option<&Document>, n: &Node, item: Option<usize>) -> Option<graphics::GraphicFrame> {
frame_of(doc, n, item, &solid)
}
/// [`graphic_frame`] of the 3D effect at `index` in that list, which must be a visible Extrude &
/// Bevel, Rotate or Revolve. Revolve's frame is its unrolled side seen from the front, centered on
/// Bevel, Rotate, Revolve or Inflate. Inflate's frame places handles on the pieces of its puffed
/// front and back the viewer sees. Revolve's frame is its unrolled side seen from the front, centered on
/// the origin, with no face maps: it sizes a new graphic and places no handles.
pub fn graphic_frame_at(doc: Option<&Document>, n: &Node, item: Option<usize>, index: usize) -> Option<graphics::GraphicFrame> {
frame_of(doc, n, item, &|fx: &[Effect]| fx.get(index).filter(|e| e.visible && is_three_d(&e.id)).map(|e| (index, e)))
@@ -2546,6 +2636,17 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option<usize>, pick: &Pick<'
return Some(graphics::GraphicFrame::new(b, plane, None));
}
let (parts, bounds) = solid_parts(&shapes, b);
if fx.id == INFLATE {
// Inflate's graphics lie on its puffed front and back: the pieces the viewer sees place
// their handles. A stroke left out places none of its own. When a fill's solid can't be
// built, or the solids together pass the limit, the art draws its source and no piece
// places a handle.
let built: Vec<Facet> = built_solids_cast(INFLATE, &p, &parts, bounds, MAX_OBJECT_FACES, false, true, None)
.collect::<Result<Vec<_>, String>>()
.map(|solids| solids.into_iter().flatten().flat_map(|(f, _)| f).collect())
.unwrap_or_default();
return Some(graphics::GraphicFrame::inflated(bounds, graphics::MembraneFrame::of(&built)));
}
let options = extrude_options(&p);
let map = |face| vectorcraft_three_d::extrude_face_map(bounds, options, view, face);
let frame = graphics::GraphicFrame::new(bounds, map(PlanarFace::Front), map(PlanarFace::Back));
+242 -56
View File
@@ -16,7 +16,14 @@
//! Bevel's side (face `side`) lie on its walls and bevels unrolled the same way, x along the
//! outline and y from the front toward the back, drawn on the pieces of the side of the solid with
//! the longest outline.
//!
//! On Inflate the graphics lie on the puffed front, and on the puffed back when Both Sides is on:
//! each is placed in the art's plane as on Extrude & Bevel's caps and carried straight out onto
//! the surface above it, so it follows the puff. Each piece of the surface draws the part of the
//! graphics that falls on it, as on Revolve's side, and the twist and taper carry the back's
//! graphics with the back.
use std::borrow::Cow;
use std::sync::Arc;
use serde_json::{Map, Value, json};
@@ -24,7 +31,7 @@ use vectorcraft_doc::color::{BlendMode, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, Symbol};
use vectorcraft_geom::kurbo::{CubicBez, ParamCurve, PathEl, Shape};
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2};
use vectorcraft_three_d::{FaceMap, Facet, PlanarFace};
use vectorcraft_three_d::{DepthPlane, FaceMap, Facet, PlanarFace};
/// The effect parameter that holds the graphics.
pub const GRAPHICS: &str = "graphics";
@@ -50,7 +57,7 @@ const MAX_NESTING: usize = 8;
const MAX_LEVELS: usize = 4 * vectorcraft_doc::MAX_DEPTH;
/// The error for graphics on a 3D effect that takes none.
pub const NOT_TAKEN: &str = "Graphics map onto the Plane, Extrude and Revolve object types";
pub const NOT_TAKEN: &str = "Graphics map onto the Plane, Extrude, Revolve and Inflate object types";
/// The buckets around the unrolled side surface that the pieces of Revolve's graphics are sorted
/// into, so each face looks only at the pieces near it.
@@ -151,10 +158,10 @@ impl MappedGraphic {
}
}
/// The 3D effects that take graphics: Extrude & Bevel (its caps and its side), Rotate (the plane)
/// and Revolve (its swept side).
/// The 3D effects that take graphics: Extrude & Bevel (its caps and its side), Rotate (the plane),
/// Revolve (its swept side) and Inflate (its puffed front and back).
pub fn takes_graphics(id: &str) -> bool {
id == super::EXTRUDE || id == super::ROTATE || id == crate::REVOLVE
id == super::EXTRUDE || id == super::ROTATE || id == crate::REVOLVE || id == super::INFLATE
}
/// The graphics in parameters `p`, leaving out entries that are not valid (a file may hold
@@ -166,9 +173,9 @@ pub fn mapped_graphics(p: &Value) -> Vec<MappedGraphic> {
}
}
/// Are the graphics in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel, Rotate and
/// Revolve take graphics; a plane has only a front, and Revolve's graphics go on its side, named
/// the front. Only Extrude & Bevel takes graphics on its side.
/// Are the graphics in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel, Rotate,
/// Revolve and Inflate take graphics; a plane has only a front, and Revolve's graphics go on its
/// side, named the front. Only Extrude & Bevel takes graphics on its side.
pub fn validate(id: &str, p: &Value) -> Result<(), String> {
// Map Art's maps are checked with the graphics: an effect that takes none refuses them.
map_art::validate(id, p)?;
@@ -194,6 +201,9 @@ pub fn validate(id: &str, p: &Value) -> Result<(), String> {
if id == crate::REVOLVE && g.face != PlanarFace::Front {
return Err("Revolve maps graphics onto its side: map them onto the front".into());
}
if id == super::INFLATE && g.face == PlanarFace::Side {
return Err("Inflate maps graphics onto its front and back, not onto a side".into());
}
}
Ok(())
}
@@ -629,10 +639,11 @@ struct Unrolled {
place: Affine,
}
/// The areas of `graphics` on `face` (the front, for Revolve's side, or Extrude & Bevel's side)
/// placed on the unrolled side surface, cut into straight pieces. A graphic whose symbol `doc` does
/// not have, or whose art is past the limits of [`pieces_of`], is left out. `None` when the pieces
/// take more than [`MAX_ELEMENTS`] points together.
/// The areas of `graphics` on `face` (the front, for Revolve's side; Extrude & Bevel's side;
/// Inflate's front or back) placed on the unrolled side surface, or in the art's plane about the
/// center of the object's bounds, cut into straight pieces. A graphic whose symbol `doc` does not
/// have, or whose art is past the limits of [`pieces_of`], is left out. `None` when the pieces take
/// more than [`MAX_ELEMENTS`] points together.
fn unrolled(doc: &Document, graphics: &[MappedGraphic], face: PlanarFace) -> Option<Vec<Unrolled>> {
let mut pieces = vec![];
let mut points = 0usize;
@@ -713,9 +724,9 @@ fn straight_pieces(path: &BezPath, points: &mut usize) -> Option<Vec<Vec<Point>>
(*points <= MAX_ELEMENTS).then_some(polygons)
}
/// Do the graphics on `face` in parameters `p` (the front of Revolve, Extrude & Bevel's side) fit
/// the limits with the symbols of `doc`? Their art, cut into straight pieces on the side surface,
/// may take up to [`MAX_ELEMENTS`] points together.
/// Do the graphics on `face` in parameters `p` (the front of Revolve; Extrude & Bevel's side;
/// Inflate's front or back) fit the limits with the symbols of `doc`? Their art, cut into straight
/// pieces on the surface, may take up to [`MAX_ELEMENTS`] points together.
pub(crate) fn validate_surface_symbols(doc: &Document, p: &Value, face: PlanarFace) -> Result<(), String> {
let list = mapped_graphics(p);
if !list.iter().any(|g| g.face == face) || unrolled(doc, &list, face).is_some() {
@@ -724,16 +735,16 @@ pub(crate) fn validate_surface_symbols(doc: &Document, p: &Value, face: PlanarFa
Err("The graphics are too complex: simplify the symbols' art".into())
}
/// A face of a side surface that graphics are drawn on ([`surface_parts`]): a face of Revolve's
/// swept side, or a piece of Extrude & Bevel's walls and bevels.
/// A face of a surface that graphics are drawn on ([`surface_parts`]): a face of Revolve's swept
/// side, a piece of Extrude & Bevel's walls and bevels, or a piece of Inflate's front or back.
pub(crate) trait SurfaceFace {
/// Where the face lies on the side unrolled, when it is a face of the side that shows its
/// outside to the viewer.
/// Where the face lies on the surface, when it carries graphics and shows the surface's outside
/// to the viewer.
fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell>;
/// The outline the face's parts are cut to, when it is not the polygon of its cell's corners:
/// its curved outline, when its edges along an end are curved, or the outline of a piece cut
/// from a larger face.
fn curved(&self) -> Option<std::borrow::Cow<'_, PathData>>;
fn curved(&self) -> Option<Cow<'_, PathData>>;
fn rgb_light(&self) -> Option<vectorcraft_three_d::RgbGradient>;
fn light(&self) -> [f64; 3];
fn outline_path(&self) -> PathData;
@@ -743,8 +754,8 @@ impl SurfaceFace for vectorcraft_three_d::Face {
fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell> {
self.surface.as_ref().filter(|c| c.outward && !self.cap)
}
fn curved(&self) -> Option<std::borrow::Cow<'_, PathData>> {
self.outline.as_ref().map(std::borrow::Cow::Borrowed)
fn curved(&self) -> Option<Cow<'_, PathData>> {
self.outline.as_ref().map(Cow::Borrowed)
}
fn rgb_light(&self) -> Option<vectorcraft_three_d::RgbGradient> {
self.rgb_gradient
@@ -757,17 +768,18 @@ impl SurfaceFace for vectorcraft_three_d::Face {
}
}
/// A piece of Extrude & Bevel's side ([`Facet::surface`]).
impl SurfaceFace for Facet {
fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell> {
self.surface.as_ref().filter(|c| c.outward)
}
fn curved(&self) -> Option<std::borrow::Cow<'_, PathData>> {
fn curved(&self) -> Option<Cow<'_, PathData>> {
if let Some(outline) = &self.outline {
return Some(std::borrow::Cow::Borrowed(outline));
return Some(Cow::Borrowed(outline));
}
// A piece of a stroke's face cut where it passes through a wall keeps its face's cell.
let cut = self.surface.as_ref().is_some_and(|c| self.contours.len() != 1 || self.contours.first() != Some(&c.page));
cut.then(|| std::borrow::Cow::Owned(self.path()))
cut.then(|| Cow::Owned(self.path()))
}
fn rgb_light(&self) -> Option<vectorcraft_three_d::RgbGradient> {
self.rgb_gradient
@@ -780,18 +792,48 @@ impl SurfaceFace for Facet {
}
}
/// The parts of the graphics on `face` of `graphics` (the front of Revolve, Extrude & Bevel's side)
/// that fall on each of `faces`, a side surface's faces in drawing order, for an object with id
/// `id`: for each face, the nodes to draw right after it. Only faces of the side that show their
/// outside to the viewer carry a part, so a graphic narrows toward the silhouette, is hidden past
/// it and is covered by the nearer faces drawn after it. `shade` gives the paint of a solid color
/// on a face, as the surface under it is shaded; the colors of gradients and patterns are
/// multiplied by the face's light. A graphic whose symbol `doc` does not have, or that is past the
/// limits of its art, draws nothing. `None` past [`MAX_ELEMENTS`] points together before they are
/// cut at the faces, [`MAX_SURFACE_POINTS`] after, [`MAX_SURFACE_CUTS`] points cut, or when the
/// copies of their paints in the parts take `copies`, the bytes of the copies of the object's
/// graphics so far, past Revolve's budget for them: commands refuse such graphics, and a loaded
/// file draws the surface without them.
/// A piece of Inflate's front or back ([`Facet::membrane`]) that carries graphics on `face` only.
pub(crate) struct OnFace<'a> {
pub(crate) facet: &'a Facet,
pub(crate) face: PlanarFace,
}
impl SurfaceFace for OnFace<'_> {
fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell> {
self.facet.surface.as_ref().filter(|c| c.outward && self.facet.membrane == Some(self.face))
}
fn curved(&self) -> Option<Cow<'_, PathData>> {
if let Some(outline) = &self.facet.outline {
return Some(Cow::Borrowed(outline));
}
// A piece of a stroke's face cut where it passes through another face keeps its face's
// cell, and its parts are cut to its own outline.
let cut = self.facet.surface.as_ref().is_some_and(|c| self.facet.contours.len() != 1 || self.facet.contours.first() != Some(&c.page));
cut.then(|| Cow::Owned(self.facet.path()))
}
fn rgb_light(&self) -> Option<vectorcraft_three_d::RgbGradient> {
self.facet.rgb_gradient
}
fn light(&self) -> [f64; 3] {
self.facet.illumination
}
fn outline_path(&self) -> PathData {
self.facet.path()
}
}
/// The parts of the graphics on `face` of `graphics` (the front of Revolve; Extrude & Bevel's side;
/// Inflate's front or back) that fall on each of `faces`, a surface's faces in drawing order, for
/// an object with id `id`: for each face, the nodes to draw right after it. Only faces of the
/// surface that show their outside to the viewer carry a part, so a graphic narrows toward the
/// silhouette, is hidden past it and is covered by the nearer faces drawn after it.
/// `shade` gives the paint of a solid color on a face, as the surface under it is shaded; the
/// colors of gradients and patterns are multiplied by the face's light. A graphic whose symbol
/// `doc` does not have, or that is past the limits of its art, draws nothing. `None` past
/// [`MAX_ELEMENTS`] points together before they are cut at the faces, [`MAX_SURFACE_POINTS`]
/// after, [`MAX_SURFACE_CUTS`] points cut, or when the copies of their paints in the parts take
/// `copies`, the bytes of the copies of the object's graphics so far, past Revolve's budget for
/// them: commands refuse such graphics, and a loaded file draws the surface without them.
pub(crate) fn surface_parts<F: SurfaceFace>(
doc: Option<&Document>,
id: NodeId,
@@ -1092,13 +1134,22 @@ pub(super) fn art_bounds(doc: &Document, name: &str) -> Option<Rect> {
/// Where a 3D object's graphics are drawn: the bounds its solids are built with (the graphics'
/// offsets are from their center), the maps of its front and back faces, when it has them, and
/// the visible part of its side unrolled, when it has graphics there.
/// the visible part of its side unrolled, when it has graphics there, and for Inflate the pieces of
/// its puffed faces the viewer sees.
#[derive(Clone, Debug, PartialEq)]
pub struct GraphicFrame {
pub bounds: Rect,
front: Option<FaceMap>,
back: Option<FaceMap>,
side: Option<SideFrame>,
membrane: Option<MembraneFrame>,
}
/// Does triangle `t` hold point `q`, its edges included?
fn in_triangle(t: &[Point; 3], q: Point) -> bool {
let side = |a: Point, b: Point| (b - a).cross(q - a);
let s = [side(t[0], t[1]), side(t[1], t[2]), side(t[2], t[0])];
s.iter().all(|v| *v >= -1e-9) || s.iter().all(|v| *v <= 1e-9)
}
/// The pieces of Extrude & Bevel's side that show their outside to the viewer, as the graphics are
@@ -1137,11 +1188,6 @@ impl SideFrame {
/// triangle of its corners on the same side of its diagonal from corner 0 to corner 2, grown and
/// cut to its outline as [`surface_parts`] cuts the parts. `None` when no piece holds it.
fn map(&self, p: Point, from_page: bool) -> Option<Point> {
let inside = |t: &[Point; 3], q: Point| {
let side = |a: Point, b: Point| (b - a).cross(q - a);
let s = [side(t[0], t[1]), side(t[1], t[2]), side(t[2], t[0])];
s.iter().all(|v| *v >= -1e-9) || s.iter().all(|v| *v <= 1e-9)
};
let mut best: Option<(Point, f64)> = None;
for piece in &self.pieces {
let (from, to) = if from_page { (&piece.page, &piece.uv) } else { (&piece.uv, &piece.page) };
@@ -1150,7 +1196,7 @@ impl SideFrame {
let pick = |of: &[Point]| Some([*of.get(corners[0])?, *of.get(corners[1])?, *of.get(corners[2])?]);
let (Some(a), Some(b)) = (pick(from), pick(to)) else { continue };
let window = if piece.outline.is_some() { grown(a, 3.0) } else { a };
if !inside(&window, p) {
if !in_triangle(&window, p) {
continue;
}
// A four-cornered piece's two triangles meet along its diagonal: each holds its side.
@@ -1176,9 +1222,136 @@ impl SideFrame {
}
}
/// The pieces of Inflate's front and puffed back that show their outside to the viewer, as the
/// graphics are drawn on them ([`surface_parts`]): each piece's face, its corners in the art's plane
/// (offsets from the center of the object's bounds) and on the page, its depth (larger is nearer)
/// and its plane, for its depth at a point of the page. The other facets the viewer sees (the
/// sides, and pieces that show the surface's inside) are kept as `covers`, for where they hide
/// a piece.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct MembraneFrame {
pieces: Vec<MembranePiece>,
covers: Vec<Cover>,
}
/// A facet that can hide a piece of Inflate's front or back: its contours on the page (nonzero
/// winding), its depth, its plane and its place among the solid's facets.
#[derive(Clone, Debug, PartialEq)]
struct Cover {
contours: Vec<Vec<Point>>,
depth: f64,
plane: Option<DepthPlane>,
index: usize,
}
impl Cover {
/// Does the facet hold page point `p`?
fn holds(&self, p: Point) -> bool {
let mut winding = 0i32;
for c in &self.contours {
for (a, b) in c.iter().zip(c.iter().cycle().skip(1)).take(c.len()) {
let side = (*b - *a).cross(p - *a);
if a.y <= p.y && b.y > p.y && side > 0.0 {
winding += 1;
} else if a.y > p.y && b.y <= p.y && side < 0.0 {
winding -= 1;
}
}
}
winding != 0
}
}
#[derive(Clone, Debug, PartialEq)]
struct MembranePiece {
face: PlanarFace,
uv: [Point; 3],
page: [Point; 3],
depth: f64,
plane: Option<DepthPlane>,
/// The piece's place among the solid's facets: of two facets drawn last, the later one is drawn
/// over the other.
index: usize,
}
impl MembranePiece {
/// The piece's depth at page point `p`: its plane's depth there, or its own depth when it has
/// no plane or the plane gives none.
fn depth_at(&self, p: Point) -> f64 {
self.plane.and_then(|plane| plane.depth_at(p)).unwrap_or(self.depth)
}
}
impl MembraneFrame {
/// The pieces of `facets` that carry where they lie in the art's plane and show the outside of
/// Inflate's front or back, and the other facets not turned away from the viewer as covers.
pub(super) fn of<'a>(facets: impl IntoIterator<Item = &'a Facet>) -> Self {
let (mut pieces, mut covers) = (Vec::new(), Vec::new());
for (index, f) in facets.into_iter().enumerate() {
let piece = f.membrane.zip(f.surface.as_ref().filter(|c| c.outward)).and_then(|(face, cell)| {
let uv = <[Point; 3]>::try_from(cell.uv.as_slice()).ok()?;
let page = <[Point; 3]>::try_from(cell.page.as_slice()).ok()?;
Some(MembranePiece { face, uv, page, depth: f.depth, plane: f.plane, index })
});
match piece {
Some(piece) => pieces.push(piece),
None if !f.away => covers.push(Cover { contours: f.contours.clone(), depth: f.depth, plane: f.plane, index }),
None => {}
}
}
Self { pieces, covers }
}
/// Point `p` of `face` in the art's plane mapped onto the page, or with `from_page` a page point
/// mapped into the art's plane, through the piece of that face that holds it and is nearest at
/// that point of the page. `None` when no piece the viewer sees holds it, or when another nearer
/// piece, of either face, or a nearer cover hides that point of the page.
fn map(&self, face: PlanarFace, p: Point, from_page: bool) -> Option<Point> {
let inside = in_triangle;
let mut best: Option<(Point, f64, &MembranePiece)> = None;
for piece in self.pieces.iter().filter(|piece| piece.face == face) {
let (from, to) = if from_page { (&piece.page, &piece.uv) } else { (&piece.uv, &piece.page) };
if !inside(from, p) {
continue;
}
let Some(q) = triangle_map(from, to).map(|m| m * p).filter(|q| q.is_finite()) else { continue };
let depth = piece.depth_at(if from_page { p } else { q });
// A piece drawn last is drawn over every other one, and the later of two drawn last is
// drawn over the other, whatever their planes' depths.
let over = |(_, nearest, other): (Point, f64, &MembranePiece)| match (piece.depth == f64::MAX, other.depth == f64::MAX) {
(true, true) => piece.index > other.index,
(true, false) => true,
(false, true) => false,
(false, false) => depth > nearest,
};
if best.is_none_or(over) {
best = Some((q, depth, piece));
}
}
let (q, depth, shown) = best?;
let at = if from_page { p } else { q };
// A facet drawn last (depth `f64::MAX`) is drawn over every other one, and over another
// drawn last before it. Otherwise, where the front, the back and the sides meet, they give
// the same depth there, and only a facet clearly nearer covers.
let hides = |raw: f64, there: f64, index: usize| match (raw == f64::MAX, shown.depth == f64::MAX) {
(true, true) => index > shown.index,
(true, false) => true,
(false, true) => false,
(false, false) => there > depth + 1e-6 * depth.abs().max(1.0),
};
let covered = self
.pieces
.iter()
.filter(|piece| !std::ptr::eq(*piece, shown))
.any(|piece| inside(&piece.page, at) && hides(piece.depth, piece.depth_at(at), piece.index))
|| self.covers.iter().any(|c| c.holds(at) && hides(c.depth, c.plane.and_then(|plane| plane.depth_at(at)).unwrap_or(c.depth), c.index));
(!covered).then_some(q)
}
}
impl GraphicFrame {
pub(super) fn new(bounds: Rect, front: Option<FaceMap>, back: Option<FaceMap>) -> Self {
Self { bounds, front, back, side: None }
Self { bounds, front, back, side: None, membrane: None }
}
/// The frame with the visible part of the side `side`, for its graphics' handles.
@@ -1186,6 +1359,12 @@ impl GraphicFrame {
Self { side: Some(side), ..self }
}
/// The frame of an Inflate object built about `bounds`, whose graphics are drawn on the pieces
/// of `membrane`.
pub(super) fn inflated(bounds: Rect, membrane: MembraneFrame) -> Self {
Self { bounds, front: None, back: None, side: None, membrane: Some(membrane) }
}
pub fn map(&self, face: PlanarFace) -> Option<&FaceMap> {
match face {
PlanarFace::Front => self.front.as_ref(),
@@ -1208,27 +1387,34 @@ impl GraphicFrame {
/// Where graphic `g`'s center lands on the page, and whether its face is turned toward the
/// viewer. `None` when the object has no such face or the point has no page point. A graphic on
/// the side lands where its center is on the part of the side the viewer sees, and is `None`
/// elsewhere.
/// elsewhere. On Inflate the center lands on the puffed face above it, and is `None` where the
/// viewer does not see that face.
pub fn handle(&self, g: &MappedGraphic) -> Option<(Point, bool)> {
if g.face == PlanarFace::Side {
return Some((self.side.as_ref()?.map(Point::new(g.x, g.y), false)?, true));
}
if let Some(membrane) = &self.membrane {
let uv = if g.face == PlanarFace::Back { Point::new(-g.x, g.y) } else { Point::new(g.x, g.y) };
return Some((membrane.map(g.face, uv, false)?, true));
}
let map = self.map(g.face)?;
Some((map.to_page(self.art_point(g.face, (g.x, g.y)))?, map.visible))
}
/// The offset of a graphic on `face` whose center lands on page point `page`. On the side, only
/// a point on the part of the side the viewer sees has one.
/// a point on the part of the side the viewer sees has one, and on Inflate only a point on the
/// part of the puffed face the viewer sees.
pub fn offset_at(&self, face: PlanarFace, page: Point) -> Option<(f64, f64)> {
let art = match face {
PlanarFace::Side => self.side.as_ref()?.map(page, true)?,
_ => self.map(face)?.to_art(page)?,
};
let c = self.bounds.center();
let (x, y) = match face {
PlanarFace::Front => (art.x - c.x, art.y - c.y),
PlanarFace::Back => (c.x - art.x, art.y - c.y),
PlanarFace::Side => (art.x, art.y),
let (x, y) = if face == PlanarFace::Side {
let art = self.side.as_ref()?.map(page, true)?;
(art.x, art.y)
} else if let Some(membrane) = &self.membrane {
let uv = membrane.map(face, page, true)?;
if face == PlanarFace::Back { (-uv.x, uv.y) } else { (uv.x, uv.y) }
} else {
let art = self.map(face)?.to_art(page)?;
let c = self.bounds.center();
if face == PlanarFace::Back { (c.x - art.x, art.y - c.y) } else { (art.x - c.x, art.y - c.y) }
};
(x.abs() <= MAX_OFFSET && y.abs() <= MAX_OFFSET).then_some((x, y))
}
+52
View File
@@ -587,6 +587,30 @@ fn drawn_face_bounds(f: &Node) -> Rect {
}
}
/// Under a colored light, an Inflate in a solid color with a graphic on its front lies over an
/// underlay of its faces, the faces that carry parts of the graphic included.
#[test]
fn a_colored_inflate_with_a_graphic_lies_over_an_underlay_of_its_faces() {
let mut d = Document::new(1000.0, 1000.0);
let mark = Node::path(
NodeId(0),
vectorcraft_geom::shapes::rectangle(Rect::new(500.0, 500.0, 510.0, 510.0)),
Appearance::basic(Paint::solid(BLUE), Paint::None, 0.0),
);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Mark".into(), art: Arc::new(mark) });
let square = vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0));
let mut n = Node::path(NodeId(7), square, Appearance::basic(Paint::solid(RED), Paint::None, 0.0));
let p = json!({"rotationX": -20, "rotationY": -30, "rotationZ": 0, "lights": [{"color": "#ff8080"}], "graphics": [{"symbol": "Mark", "scale": 300.0}]});
n.appearance.effects.push(fx(INFLATE, p));
let art = solid_art_in(Some(&d), &n).unwrap();
let order = art.children().unwrap()[0].children().unwrap();
let faces: Vec<Arc<Node>> = order.iter().flat_map(unsealed).collect();
assert!(faces.len() > order.len(), "the faces lie over an underlay");
let carrying = faces.iter().filter(|f| matches!(f.kind, NodeKind::Group { clip: false, .. })).count();
assert!(carrying > 0, "faces carry parts of the graphic");
assert!(order.iter().all(|run| !Arc::ptr_eq(&unsealed(run)[0], run)), "every face is in a sealed run");
}
/// Under a light that is not white, a solid-color fill and a solid-color stroke, plain, dashed or
/// with a width profile, draw their faces in one order, the faces of both solids in the order of
/// their depths where they overlap, in Inflate and in Extrude & Bevel, with and without perspective
@@ -775,6 +799,7 @@ fn a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet() {
away: false,
end: None,
surface: None,
membrane: None,
plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }),
cell: None,
};
@@ -1206,6 +1231,33 @@ fn a_groups_solids_together_past_the_limit_draw_the_source() {
assert_eq!(three_d_wireframe_in(None, &past), Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string()));
}
/// An Inflate group whose second member's fill is past the limits draws its source art, and its
/// frame places no graphic handle on the first member's puff.
#[test]
fn an_inflate_frame_places_no_handle_when_a_fill_is_past_the_limits() {
let mut b = BezPath::new();
b.move_to((0.0, 0.0));
b.line_to((40_000.0, 0.0));
b.line_to((40_000.0, 40_000.0));
b.line_to((0.0, 40_000.0));
b.close_path();
let square = Node::path(NodeId(1), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0));
let view = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0});
let group = |members: Vec<Node>| {
let mut g = Node::group(NodeId(9999), members.into_iter().map(Arc::new).collect());
g.appearance.effects.push(fx(INFLATE, view.clone()));
g
};
let center = MappedGraphic::from_value(&json!({"symbol": "Mark"})).unwrap();
// The square alone builds, and the graphic's handle sits on its puff.
let alone = group(vec![square.clone()]);
assert!(graphic_frame(None, &alone, None).unwrap().handle(&center).is_some());
// 70,000 corners: more points than a fill's solid takes.
let past = group(vec![square, polygon_node(2, 70_000)]);
assert!(solid_art(&past).is_none(), "the source art draws");
assert!(graphic_frame(None, &past, None).unwrap().handle(&center).is_none());
}
/// A fill and strokes whose solids each fit, but not all of them together, draw the source art,
/// and the strokes after the one past the limit are not left out to make room.
#[test]
+207 -1
View File
@@ -505,6 +505,31 @@ fn the_symbol_check_counts_what_the_view_draws() {
assert!(validate_three_d_in(Some(&dense_document(true)), &n, EXTRUDE, &flat).is_ok());
}
#[test]
fn a_wireframe_is_not_refused_for_graphics_it_does_not_draw() {
let check = |d: &Document, id: &str, mut p: Value, wire: bool| {
if wire {
p["render"] = json!({"mode": "wireframe"});
}
validate_three_d_in(Some(d), &object(id, p.clone()), id, &p)
};
// The straight 30,000-sided polygon at 1000% fits the symbol limit, but cut into pieces on
// Inflate's puffed front it is too complex.
let straight = dense_document(false);
let big = json!({"perspectiveAngle": 0.0, "graphics": [{"symbol": "Dense", "scale": 1000.0}]});
assert!(validate_symbols(&straight, &big).is_ok());
let e = check(&straight, INFLATE, big.clone(), false).unwrap_err();
assert!(e.contains("too complex"), "{e}");
// Two copies of the curved one under a perspective are past the symbol limit on Extrude & Bevel.
let curved = dense_document(true);
let two = json!({"perspectiveAngle": 60.0, "graphics": [{"symbol": "Dense"}, {"symbol": "Dense", "face": "back"}]});
let e = check(&curved, EXTRUDE, two.clone(), false).unwrap_err();
assert!(e.contains("too complex"), "{e}");
// A wireframe draws the faces' edges and no graphics, so neither is checked.
assert_eq!(check(&straight, INFLATE, big, true), Ok(()));
assert_eq!(check(&curved, EXTRUDE, two, true), Ok(()));
}
#[test]
fn a_plane_and_a_hollow_solid() {
let d = document();
@@ -548,7 +573,9 @@ fn graphics_are_checked() {
}
assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "back"}])).is_err());
assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "side"}])).is_err());
assert!(check(INFLATE, json!([{"symbol": "Mark"}])).is_err());
// Inflate takes graphics on its front and its puffed back, and none on a side.
assert!(check(INFLATE, json!([{"symbol": "Mark"}, {"symbol": "Mark", "face": "back"}])).is_ok());
assert!(check(INFLATE, json!([{"symbol": "Mark", "face": "side"}])).is_err());
// Revolve takes graphics on its side, named the front; Revolve (Classic) takes none.
assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_ok());
assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark", "face": "back"}]})).is_err());
@@ -579,6 +606,10 @@ fn a_change_to_a_plane_drops_the_back_caps_graphics() {
// Revolve drops the side's graphics too; Extrude & Bevel keeps every face's.
assert_eq!(three_d_params_as(EXTRUDE, &p, crate::REVOLVE)["graphics"], json!([{"symbol": "Mark", "face": "front"}]));
assert_eq!(three_d_params_as(EXTRUDE, &p, EXTRUDE)["graphics"], p["graphics"]);
// Inflate keeps the front's and the back's graphics and drops the side's.
let inflated = three_d_params_as(EXTRUDE, &p, INFLATE);
assert_eq!(inflated["graphics"], json!([{"symbol": "Mark", "face": "front"}, {"symbol": "Mark", "face": "back"}]));
assert!(validate_three_d_params(INFLATE, &inflated).is_ok());
// Back to Extrude & Bevel, the front's graphic stays.
assert_eq!(three_d_params_as(ROTATE, &plane, EXTRUDE)["graphics"], plane["graphics"]);
}
@@ -981,3 +1012,178 @@ fn only_an_opaque_part_on_revolve_takes_a_seam_stroke() {
// A pattern's tile may hold transparent art, which the overlap would show.
assert!(!takes_seam(&piece(Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }, 1.0, BlendMode::Normal)));
}
/// The paths in `art` filled in a shade of red: the parts of the "Mark" graphic.
fn red_parts(art: &Node) -> Vec<PathData> {
let mut out = vec![];
art.walk(&mut |n| {
let Some(path) = n.path_data() else { return };
let red = n.appearance.items.iter().any(|i| match i {
AppearanceItem::Fill(f) => f.paint.color().is_some_and(|c| c.to_rgb()[0] > 0.3 && c.to_rgb()[1] < 0.1 && c.to_rgb()[2] < 0.1),
AppearanceItem::Stroke(_) => false,
});
if red {
out.push(path.clone());
}
});
out
}
fn reach(parts: &[PathData]) -> Rect {
parts.iter().filter_map(PathData::bounds).reduce(|a, b| a.union(b)).unwrap()
}
#[test]
fn an_inflate_graphic_lies_on_its_puffed_front_where_the_art_is() {
let d = document();
let n = object(INFLATE, json!({"graphics": [{"symbol": "Mark", "x": 20.0, "y": -10.0, "scale": 200.0}]}));
let art = solid_art_in(Some(&d), &n).unwrap();
// Straight on, the puff rises toward the viewer and the graphic is carried straight out onto it:
// a 20 × 20 square centered 20 right of and 10 above (50, 50).
let parts = red_parts(&art);
assert!(!parts.is_empty());
assert!(close(reach(&parts), Rect::new(60.0, 30.0, 80.0, 50.0)), "{:?}", reach(&parts));
// Turned, the graphic moves and foreshortens with the puff under it.
let n = object(INFLATE, json!({"rotationY": 40.0, "graphics": [{"symbol": "Mark", "scale": 200.0}]}));
let turned = reach(&red_parts(&solid_art_in(Some(&d), &n).unwrap()));
assert!(turned.width() < 20.0 - 0.5 && (turned.height() - 20.0).abs() < 2.0, "{turned:?}");
// Without the document nothing is drawn.
assert!(red_parts(&solid_art_in(None, &n).unwrap()).is_empty());
}
#[test]
fn an_inflate_back_takes_its_graphic_with_both_sides_and_twist_carries_it() {
let d = document();
let back = |extra: Value| {
let mut p = json!({"rotationY": 180.0, "graphics": [{"symbol": "Mark", "face": "back", "x": 20.0, "scale": 200.0}]});
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
red_parts(&solid_art_in(Some(&d), &object(INFLATE, p)).unwrap())
};
// Without Both sides the back is flat and open, with no puffed face to carry the graphic.
assert!(back(json!({})).is_empty());
// Seen from behind, the back reads left to right: 20 to the right as seen from behind is 20 to
// the left of the art's center, which turned half a turn lies 20 right on the page.
let plain = back(json!({"bothSides": true}));
assert!(!plain.is_empty());
let r = reach(&plain);
assert!((r.center().x - 70.0).abs() < 0.5 && (r.center().y - 50.0).abs() < 0.5 && (r.width() - 20.0).abs() < 0.5, "{r:?}");
// Twist turns the back, and the graphic turns with it.
let twisted = reach(&back(json!({"bothSides": true, "twist": 45.0})));
assert!(twisted.width() > r.width() + 3.0, "{twisted:?} {r:?}");
}
#[test]
fn an_inflate_frame_puts_the_handle_on_the_puff_and_reads_it_back() {
let d = document();
let n = object(INFLATE, json!({"bothSides": true}));
let frame = graphic_frame(Some(&d), &n, None).unwrap();
let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "x": 20.0, "y": -10.0})).unwrap();
let (page, shown) = frame.handle(&g).unwrap();
assert!(shown && (page.x - 70.0).abs() < 1e-6 && (page.y - 40.0).abs() < 1e-6, "{page:?}");
let (x, y) = frame.offset_at(PlanarFace::Front, page).unwrap();
assert!((x - 20.0).abs() < 1e-6 && (y + 10.0).abs() < 1e-6, "{x} {y}");
// From the front the back is out of sight: it has no handle and no offset.
let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "back"})).unwrap();
assert!(frame.handle(&g).is_none());
assert!(frame.offset_at(PlanarFace::Back, Point::new(50.0, 50.0)).is_none());
// Turned half a turn, the back's handle reads back its offset, as seen from behind.
let n = object(INFLATE, json!({"bothSides": true, "rotationY": 180.0}));
let frame = graphic_frame(Some(&d), &n, None).unwrap();
let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "back", "x": 15.0, "y": 5.0})).unwrap();
let (page, _) = frame.handle(&g).unwrap();
let (x, y) = frame.offset_at(PlanarFace::Back, page).unwrap();
assert!((x - 15.0).abs() < 1e-6 && (y - 5.0).abs() < 1e-6, "{x} {y}");
}
/// Where two pieces of an Inflate face overlap on the page, a point maps through the piece nearer
/// at that point, though the other is nearer at its center.
#[test]
fn overlapping_inflate_pieces_map_a_point_through_the_one_nearer_there() {
let page = [Point::new(0.0, 0.0), Point::new(20.0, 0.0), Point::new(10.0, 20.0)];
let piece = |shift: f64, depth: f64, normal: [f64; 3], offset: f64| MembranePiece {
face: PlanarFace::Front,
uv: page.map(|p| p + Vec2::new(shift, 0.0)),
page,
depth,
plane: Some(DepthPlane { normal, offset, center: Point::ORIGIN, eye: None }),
index: 0,
};
// The tilted piece is nearer at its center (depth 10) but at depth 0 where x is 10; the flat
// one lies at depth 5 everywhere.
let tilted = piece(0.0, 10.0, [1.0, 0.0, 1.0], 10.0);
let flat = piece(100.0, 5.0, [0.0, 0.0, 1.0], 5.0);
let frame = GraphicFrame::inflated(Rect::new(0.0, 0.0, 20.0, 20.0), MembraneFrame { pieces: vec![tilted, flat], covers: vec![] });
let (x, y) = frame.offset_at(PlanarFace::Front, Point::new(10.0, 5.0)).unwrap();
assert!((x - 110.0).abs() < 1e-6 && (y - 5.0).abs() < 1e-6, "{x} {y}");
// Near the tilted piece's left corner it is the nearer one.
let (x, _) = frame.offset_at(PlanarFace::Front, Point::new(2.0, 0.5)).unwrap();
assert!((x - 2.0).abs() < 1e-6, "{x}");
// A graphic's center has a handle only where its own piece is the nearer one, and the handle
// maps back to the same offset.
let mark = |x: f64, y: f64| MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "front", "x": x, "y": y})).unwrap();
assert!(frame.handle(&mark(10.0, 5.0)).is_none());
for (x, y) in [(2.0, 0.5), (110.0, 5.0)] {
let (at, _) = frame.handle(&mark(x, y)).unwrap();
let (bx, by) = frame.offset_at(PlanarFace::Front, at).unwrap();
assert!((bx - x).abs() < 1e-6 && (by - y).abs() < 1e-6, "{x} {y}: {bx} {by}");
}
// Of two overlapping pieces drawn last, the later one is drawn over the other, though the
// earlier one's plane is nearer.
let last = |shift: f64, offset: f64, index: usize| MembranePiece { index, ..piece(shift, f64::MAX, [0.0, 0.0, 1.0], offset) };
let pieces = vec![last(0.0, 10.0, 0), last(100.0, 0.0, 1)];
let frame = GraphicFrame::inflated(Rect::new(0.0, 0.0, 20.0, 20.0), MembraneFrame { pieces, covers: vec![] });
let (x, _) = frame.offset_at(PlanarFace::Front, Point::new(10.0, 5.0)).unwrap();
assert!((x - 110.0).abs() < 1e-6, "{x}");
assert!(frame.handle(&mark(10.0, 5.0)).is_none());
assert!(frame.handle(&mark(110.0, 5.0)).is_some());
}
/// A graphic on Inflate's back has no handle where a nearer piece of the front covers its center
/// on the page, and the back has no offset there; where the back is nearer, it has both.
#[test]
fn an_inflate_back_graphic_covered_by_a_nearer_front_piece_has_no_handle() {
let page = [Point::new(0.0, 0.0), Point::new(20.0, 0.0), Point::new(10.0, 20.0)];
let piece = |face: PlanarFace, depth: f64| MembranePiece { face, uv: page, page, depth, plane: None, index: 0 };
let frame = |front: f64, back: f64| {
let pieces = vec![piece(PlanarFace::Front, front), piece(PlanarFace::Back, back)];
GraphicFrame::inflated(Rect::new(0.0, 0.0, 20.0, 20.0), MembraneFrame { pieces, covers: vec![] })
};
let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "back", "x": -10.0, "y": 5.0})).unwrap();
let covered = frame(10.0, 5.0);
assert!(covered.handle(&g).is_none());
assert!(covered.offset_at(PlanarFace::Back, Point::new(10.0, 5.0)).is_none());
assert!(covered.offset_at(PlanarFace::Front, Point::new(10.0, 5.0)).is_some());
let seen = frame(5.0, 10.0);
let (at, _) = seen.handle(&g).unwrap();
assert!((at.x - 10.0).abs() < 1e-6 && (at.y - 5.0).abs() < 1e-6, "{at:?}");
assert!(seen.offset_at(PlanarFace::Back, Point::new(10.0, 5.0)).is_some());
}
/// A nearer side facet that covers a graphic's center on Inflate's front hides its handle; one
/// behind the front, or beside the center, leaves it. A facet drawn last (a back cap) hides it
/// whatever its plane's depth, unless the front piece is drawn last too, after it.
#[test]
fn an_inflate_graphic_covered_by_a_nearer_side_has_no_handle() {
let page = [Point::new(0.0, 0.0), Point::new(20.0, 0.0), Point::new(10.0, 20.0)];
let front = |depth: f64, index: usize| MembranePiece { face: PlanarFace::Front, uv: page, page, depth, plane: None, index };
let side = |x0: f64, depth: f64, index: usize| Cover {
contours: vec![vec![Point::new(x0, 0.0), Point::new(x0 + 4.0, 0.0), Point::new(x0 + 4.0, 20.0), Point::new(x0, 20.0)]],
depth,
// A plane behind the front, as a back cap's is.
plane: Some(DepthPlane { normal: [0.0, 0.0, 1.0], offset: 1.0, center: Point::ORIGIN, eye: None }),
index,
};
let frame = |piece: MembranePiece, cover: Cover| {
GraphicFrame::inflated(Rect::new(0.0, 0.0, 20.0, 20.0), MembraneFrame { pieces: vec![piece], covers: vec![cover] })
};
let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "front", "x": 10.0, "y": 5.0})).unwrap();
let mut nearer = side(8.0, 10.0, 1);
nearer.plane = None;
assert!(frame(front(5.0, 0), nearer.clone()).handle(&g).is_none());
assert!(frame(front(5.0, 0), nearer).offset_at(PlanarFace::Front, Point::new(10.0, 5.0)).is_none());
assert!(frame(front(5.0, 0), side(8.0, 10.0, 1)).handle(&g).is_some());
assert!(frame(front(5.0, 0), side(14.0, 10.0, 1)).handle(&g).is_some());
assert!(frame(front(5.0, 0), side(8.0, f64::MAX, 1)).handle(&g).is_none());
assert!(frame(front(f64::MAX, 0), side(8.0, f64::MAX, 1)).handle(&g).is_none());
assert!(frame(front(f64::MAX, 2), side(8.0, f64::MAX, 1)).handle(&g).is_some());
}
@@ -185,6 +185,7 @@ fn a_piece_cut_from_a_face_draws_its_own_part() {
away: false,
end: None,
surface: Some(vectorcraft_three_d::SurfaceCell { page: square, uv, outward: true }),
membrane: None,
plane: Some(vectorcraft_three_d::DepthPlane { normal, offset, center: Point::ZERO, eye: None }),
cell: None,
}
@@ -207,6 +207,7 @@ fn art_on_a_facet_with_a_curved_edge_is_clipped_to_that_edge() {
end: None,
plane: None,
surface: None,
membrane: None,
cell: None,
};
let cell = MapCell { surface: 0, page: quad.clone(), uv: quad.clone() };
@@ -251,6 +252,7 @@ fn art_on_a_facet_whose_curved_edge_bows_out_covers_the_whole_facet() {
end: None,
plane: None,
surface: None,
membrane: None,
cell: None,
};
let cell = MapCell { surface: 0, page: quad.clone(), uv: quad };
@@ -290,6 +292,7 @@ fn the_bounds_tests_of_contours_away_from_a_cell_count_as_cuts() {
end: None,
plane: None,
surface: None,
membrane: None,
cell: None,
};
let cell = MapCell { surface: 0, page: quad.clone(), uv: quad };
+1 -1
View File
@@ -379,7 +379,7 @@ fn a_stroke_left_out_of_the_art_casts_no_shadow() {
let p = crate::merged_params(id, &json!({"shadow": true}));
let (parts, bounds) = solid_parts(&shapes, union_bounds(&shapes).unwrap());
let mut built: Vec<Option<SolidFaces>> =
built_solids_cast(id, &p, &parts, bounds, MAX_OBJECT_FACES, true, None).map(|r| r.unwrap().and_then(|(_, faces)| faces)).collect();
built_solids_cast(id, &p, &parts, bounds, MAX_OBJECT_FACES, true, false, None).map(|r| r.unwrap().and_then(|(_, faces)| faces)).collect();
let stroke = parts.iter().position(|(item, ..)| matches!(item, AppearanceItem::Stroke(_))).unwrap();
assert!(built.len() == 2 && built.iter().all(Option::is_some), "{id}");
let (both, _, cast) = cast_built(id, &p, &shapes, built.clone()).unwrap().unwrap();
+4
View File
@@ -911,6 +911,10 @@ pub use gradpresets::{GradientPreset, GradientPresetEntry};
/// A saved Image Trace preset ([`crate::Prefs::trace_presets`]), and a change to the saved presets.
pub use buildcmds::{TracePreset, TracePresetChange};
/// The `format`, extensions and largest size of the tracing presets files
/// `imageTrace.presets.export` writes and `imageTrace.presets.import` reads.
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, image_trace_target};
+175 -22
View File
@@ -29,6 +29,7 @@ use vectorcraft_color::{BlendMode, Paint};
use vectorcraft_doc::appearance::SharedStack;
use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, Document, FillLayer, Node, NodeKind, ParaStyle, StrokeLayer};
use vectorcraft_geom::Rect;
use vectorcraft_tools::builder::{edges, faces, is_live_paint};
use super::edit::{outermost, roots_of, selected_roots};
use super::opacitymask::percent;
@@ -48,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add New Fill",
["Window", "Appearance"],
Some("Cmd+/"),
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)",
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). In the contents of a Live Paint group the fill goes on its faces only, and its hidden source paths, like every contents edit, are left as they are. With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)",
has_doc,
|s, p| add_item(s, p, true)
),
@@ -57,7 +58,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add New Stroke",
["Window", "Appearance"],
Some("Cmd+Alt+/"),
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)",
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. In the contents of a Live Paint group the stroke goes on its edges only, and its hidden source paths are left as they are. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)",
has_doc,
|s, p| add_item(s, p, false)
),
@@ -129,7 +130,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Eyedropper",
[],
None,
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode when transparency is applied, and with `append` its topmost visible fill and stroke rows of the kinds it adds; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows, and when transparency is applied its object opacity and blend mode, for every line of its kind (a pick of some attributes without `append`: what it changes, and the paint, stroke weight and row transparency it applies to the topmost visible rows; with `append`: only the kinds of row it adds) → {ids}",
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; a whole Live Paint group (selected, in ids, or `source` with `reverse`) takes the fill attributes on its faces and the stroke attributes on its edges (a whole-appearance pick: every fill row on each face and every stroke row on each edge, which keep their rows of the other kind and their effects; `append` adds the source's rows but not its object effects to them), and its hidden source paths keep their paint; a whole Live Paint group picked up (`source`, or selected first with `reverse`) gives its first face's fills with its first edge's strokes above them and the group's own opacity, blend mode and effects; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode when transparency is applied, and with `append` its topmost visible fill and stroke rows of the kinds it adds; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows, and when transparency is applied its object opacity and blend mode, for every line of its kind (a pick of some attributes without `append`: what it changes, and the paint, stroke weight and row transparency it applies to the topmost visible rows; with `append`: only the kinds of row it adds) → {ids}",
has_doc,
copy_from
),
@@ -280,7 +281,8 @@ impl ItemTarget {
/// [`ItemTarget::targets`] of a fill (`fill`) or a stroke edit: on the topmost fill or stroke, a
/// Live Paint group stands for its faces in a fill edit and for its edges in a stroke edit
/// ([`super::paint::live_paint_parts_skipped`]).
/// ([`super::paint::live_paint_parts_skipped`]); an item edit with `target: "contents"` leaves out
/// the parts of the other kind the same way ([`contents_skipped`]).
pub(crate) fn targets_for(self, s: &Session, p: &Value, fill: bool) -> Result<Vec<NodeId>> {
Ok(self.targets_and_skipped(s, p, fill)?.0)
}
@@ -290,13 +292,16 @@ impl ItemTarget {
/// to new art.
pub(crate) fn targets_and_skipped(self, s: &Session, p: &Value, fill: bool) -> Result<(Vec<NodeId>, bool)> {
let mut ids = self.targets(s, p)?;
let mut skipped_any = false;
if self == ItemTarget::Top {
let skipped = super::paint::live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, fill);
let before = ids.len();
ids.retain(|id| !skipped.contains(id));
skipped_any = ids.len() != before;
}
// An item edit of the contents of a Live Paint group goes to its parts of the edited kind too.
let skipped = if self == ItemTarget::Top {
super::paint::live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, fill)
} else {
contents_skipped(s, p, fill)?
};
let before = ids.len();
ids.retain(|id| !skipped.contains(id));
// A contents edit already leaves hidden source paths out of `ids`, so `skipped` is checked on its own too.
let skipped_any = ids.len() != before || !skipped.is_empty();
Ok((ids, skipped_any))
}
@@ -491,15 +496,37 @@ pub(crate) fn subject_roots(s: &Session) -> Result<Vec<NodeId>> {
/// Objects whose own appearance stack a command edits: `ids`/`id` (layers too; an id inside
/// another given one is dropped), else the [`subject_roots`]; with `target: "contents"` the painted
/// objects inside the groups and layers among them ([`leaf_targets`]).
/// objects inside the groups and layers among them ([`leaf_targets`]), without the hidden source paths
/// of Live Paint groups.
pub(crate) fn appearance_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
let roots = if p.get("ids").is_none() && p.get("id").is_none() {
subject_roots(s)?
let roots = appearance_roots(s, p)?;
if !targets_contents(p)? {
return Ok(roots);
}
let (_, _, hidden) = super::paint::live_paint_split(&s.doc()?.doc, &roots);
let mut ids = leaf_targets(s, &roots)?;
ids.retain(|id| !hidden.contains(id));
Ok(ids)
}
/// The objects [`appearance_targets`] starts from: `ids`/`id`, else the [`subject_roots`].
fn appearance_roots(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
if p.get("ids").is_none() && p.get("id").is_none() {
subject_roots(s)
} else {
let d = &s.doc()?.doc;
outermost(d, targets(s, p)?.into_iter().filter(|id| d.node(*id).is_some()).collect())
};
if targets_contents(p)? { leaf_targets(s, &roots) } else { Ok(roots) }
Ok(outermost(d, targets(s, p)?.into_iter().filter(|id| d.node(*id).is_some()).collect()))
}
}
/// The parts of the Live Paint groups whose contents `p` targets (`target: "contents"`) that a fill
/// (`fill`) or stroke edit of those contents leaves as they are: their edges or faces. Empty without
/// `target: "contents"`.
pub(crate) fn contents_skipped(s: &Session, p: &Value, fill: bool) -> Result<HashSet<NodeId>> {
if !targets_contents(p)? {
return Ok(HashSet::new());
}
Ok(super::paint::live_paint_parts_skipped(&s.doc()?.doc, &appearance_roots(s, p)?, fill))
}
/// The refusal of an appearance edit whose targets are all the art of graph designs drawn in graph series.
@@ -897,7 +924,26 @@ fn set_active_item(s: &mut Session, p: &Value) -> Result<Value> {
}
fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
let ids = require_targets(s, p, if fill { "appearance.addFill" } else { "appearance.addStroke" })?;
let cmd = if fill { "appearance.addFill" } else { "appearance.addStroke" };
let mut ids = row_targets(s, p, cmd)?;
if ids.is_empty() {
// A selected Live Paint group left with only its hidden source paths has nothing to edit: it is
// still a selection, so the edit changes nothing.
let roots = appearance_roots(s, p)?;
if targets_contents(p)? && !roots.is_empty() && !super::paint::live_paint_split(&s.doc()?.doc, &roots).2.is_empty() {
return ok();
}
return Err(bad(cmd, "select objects or give ids"));
}
// In the contents of a Live Paint group, a new fill goes on its faces and a new stroke on its edges;
// with no part of that kind, nothing changes.
let skipped = contents_skipped(s, p, fill)?;
if !skipped.is_empty() {
ids.retain(|id| !skipped.contains(id));
if ids.is_empty() {
return ok();
}
}
let defaults = s.paint.clone();
// The panel's active Fill row, when the new fill goes on the selection: the new fill takes that
// row's paint, right above it in each target that has it (others take their top fill's paint).
@@ -1779,7 +1825,23 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
// Reversed, the first selected object's attributes go onto the clicked object; with nothing
// selected, what the Eyedropper picked up last does (#4382).
let (source, mut targets) = if reverse {
let source = match leaf_targets(s, &selected)?.into_iter().next() {
// The selected objects are tried in order: a Live Paint group with a look is picked up as a whole
// ([`live_paint_look`]), any other object gives its first painted leaf, and a group with nothing to pick
// up (its hidden source paths are not what it draws) passes to the next object.
let d = &s.doc()?.doc;
let mut first = None;
for root in &selected {
if d.node(*root).and_then(live_paint_look).is_some() {
first = Some(*root);
break;
}
let (_, _, hidden) = super::paint::live_paint_split(d, &[*root]);
if let Some(leaf) = leaf_targets(s, &[*root])?.into_iter().find(|id| !hidden.contains(id)) {
first = Some(leaf);
break;
}
}
let source = match first {
Some(first) => Some(first),
None if s.eyedropper_sample.is_some() => None,
None => return Err(bad(C, "select the object to copy from")),
@@ -1788,10 +1850,45 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
} else {
(Some(clicked), leaf_targets(s, &selected)?)
};
targets.retain(|id| Some(*id) != source);
// A whole Live Paint group takes the fill attributes on its faces and the stroke attributes on its edges, and its
// hidden source paths keep their paint.
let roots = if reverse { vec![clicked] } else { selected };
let (faces, edges, hidden) = super::paint::live_paint_split(&s.doc()?.doc, &roots);
// Some(true) for a face, Some(false) for an edge.
let part_of = |id: &NodeId| {
if faces.contains(id) {
Some(true)
} else if edges.contains(id) {
Some(false)
} else {
None
}
};
let attrs_for = |id: &NodeId| {
let mut a = attrs;
match part_of(id) {
Some(true) => a.appearance.stroke = StrokeAttrs::NONE,
Some(false) => a.appearance.fill = FillAttrs::NONE,
None => {}
}
a
};
// A pick of the whole appearance gives a face every fill row and an edge every stroke row.
let whole = attrs.appearance.fill == FillAttrs::ALL && attrs.appearance.stroke == StrokeAttrs::ALL;
// A source that is a Live Paint group is not one of its own targets: neither are its faces and edges.
let mut inside_source = HashSet::new();
if let Some(n) = source.and_then(|id| s.doc().ok()?.doc.node(id)).filter(|n| is_live_paint(n)) {
n.walk(&mut |c| {
inside_source.insert(c.id);
});
}
targets.retain(|id| Some(*id) != source && !hidden.contains(id) && !inside_source.contains(id));
let mut targets = without_design_art(&s.doc()?.doc, targets, C)?;
let node = match source {
Some(id) => Arc::new(s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.clone()),
Some(id) => {
let n = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?;
Arc::new(live_paint_look(n).unwrap_or_else(|| n.clone()))
}
None => s.eyedropper_sample.clone().ok_or_else(|| bad(C, "select the object to copy from"))?,
};
let picked = Picked::of(&node);
@@ -1919,7 +2016,17 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
super::overprint::edit_counted(s, "Eyedropper", |d| {
for id in &targets {
if let Some(n) = d.node_mut(*id) {
picked.apply(n, &attrs, append, characters.get(id));
match part_of(id) {
Some(fill) if whole && !append => picked.apply_rows(n, &attrs, fill),
// `append` does not add the picked object effects to a face or edge, as a whole pick keeps the part's
// own; a row's effects go with the row.
Some(_) => {
let effects = n.appearance.effects.len();
picked.apply(n, &attrs_for(id), append, characters.get(id));
n.appearance.effects.truncate(effects);
}
None => picked.apply(n, &attrs_for(id), append, characters.get(id)),
}
}
}
check_text_bounds(d)?;
@@ -2170,6 +2277,52 @@ impl Picked {
}
super::object::snap_if_aligned(n);
}
/// A whole pick ([`Self::apply`] with every fill and stroke attribute) onto a Live Paint face
/// (`fill`) or edge: the face's fills (the edge's strokes) become the picked ones, and its rows of
/// the other kind and its effects stay as they are.
fn apply_rows(&self, n: &mut Node, a: &EyedropperAttrs, fill: bool) {
if a.appearance.transparency {
n.opacity = self.opacity;
n.blend = self.blend;
}
let taken: Vec<AppearanceItem> = self.placed(n.geometric_bounds()).items.into_iter().filter(|it| it.is_fill() == fill).collect();
// The picked rows go where the part's first row of that kind was, the other rows keep their order; without
// such a row, fills go to the bottom and strokes to the top.
let items = &n.appearance.items;
let at = items.iter().position(|it| it.is_fill() == fill);
let at = at.map_or(if fill { 0 } else { items.iter().filter(|it| it.is_fill() != fill).count() }, |i| {
items.iter().take(i).filter(|it| it.is_fill() != fill).count()
});
let mut kept: Vec<AppearanceItem> = items.iter().filter(|it| it.is_fill() != fill).cloned().collect();
kept.splice(at..at, taken);
n.appearance.items = kept;
super::object::snap_if_aligned(n);
}
}
/// What the Eyedropper picks up from a whole Live Paint group `n`: its first face (else its first edge) with that
/// face's fills and the first edge's strokes above them, their gradients placed as on those parts, and the group's
/// own opacity, blend mode and effects. None for any other object, and for a group with no face and no edge.
fn live_paint_look(n: &Node) -> Option<Node> {
if !is_live_paint(n) {
return None;
}
let (face, edge) = (faces(n).first().copied(), edges(n).first().copied());
let mut look = (**face.or(edge)?).clone();
let rows = |part: Option<&Arc<Node>>, fill: bool| -> Vec<AppearanceItem> {
part.map(|p| p.appearance.items.iter().filter(|it| it.is_fill() == fill).cloned().collect()).unwrap_or_default()
};
// The edge's stroke gradients, placed relative to the look's bounds as they are to the edge's.
let mut strokes = Appearance { items: rows(edge, false), ..Default::default() };
if let (Some(from), Some(to)) = (edge.and_then(|e| e.geometric_bounds()), look.geometric_bounds()) {
strokes.rebase_gradients(from, to);
}
look.appearance.items = rows(face, true).into_iter().chain(strokes.items).collect();
look.appearance.effects = n.appearance.effects.clone();
look.opacity = n.opacity;
look.blend = n.blend;
Some(look)
}
/// The focal (topmost) fill and stroke attributes `a` of `from` onto `to`. Taking a colour creates
+48
View File
@@ -178,6 +178,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
BuiltinBrushLibrary { id: "paint", name: "Paint", make: paint },
BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders },
BuiltinBrushLibrary { id: "decorative", name: "Decorative", make: decorative },
BuiltinBrushLibrary { id: "ornamental", name: "Ornamental", make: ornamental },
BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes },
BuiltinBrushLibrary { id: "stipple", name: "Stipple", make: stipple },
BuiltinBrushLibrary { id: "game-trails", name: "Game Trails", make: game_trails },
@@ -733,6 +734,53 @@ fn decorative() -> BrushLibrary {
)
}
/// Ornamental: one-pass flourishes and arrow accents that stretch with the path rather than
/// repeating a pattern tile. Every shape is original filled vector art.
fn ornamental() -> BrushLibrary {
let scrollwork = group(vec![
black(band(100.0, 1.2, 64, |x| 2.6 * (x / 100.0 * std::f64::consts::TAU).sin())),
ring(Point::new(7.0, 0.0), 4.0, 2.0),
ring(Point::new(93.0, 0.0), 4.0, 2.0),
black(polygon(&[(28.0, 1.0), (34.0, -5.0), (40.0, -3.0), (33.0, 2.0)])),
black(polygon(&[(60.0, 3.0), (66.0, 5.0), (72.0, -1.0), (67.0, -2.0)])),
]);
let arrow = group(vec![
// The shaft runs into the head's notch at x = 85 so the two overlap.
black(shapes::rectangle(Rect::new(4.0, -0.7, 86.0, 0.7))),
black(polygon(&[(80.0, -6.5), (100.0, 0.0), (80.0, 6.5), (85.0, 0.0)])),
ring(Point::new(7.0, 0.0), 4.0, 1.7),
black(polygon(&[(25.0, -0.4), (31.0, -4.4), (37.0, -2.0), (31.0, 0.8)])),
black(polygon(&[(43.0, 0.4), (49.0, 4.4), (55.0, 2.0), (49.0, -0.8)])),
]);
let mut petals = vec![black(band(100.0, 1.0, 48, |x| 1.8 * (x / 100.0 * std::f64::consts::PI).sin()))];
for x in [19.0, 43.0, 67.0, 87.0] {
let y = 1.8 * (x / 100.0 * std::f64::consts::PI).sin();
petals.push(black(shapes::ellipse(Rect::new(x - 4.5, y - 7.5, x + 4.5, y - 0.3))));
petals.push(black(shapes::ellipse(Rect::new(x - 3.5, y + 0.3, x + 3.5, y + 5.5))));
}
let petal_sweep = group(petals);
let twin_curl = group(vec![
black(band(100.0, 0.9, 64, |x| -3.8 + 1.6 * (x / 100.0 * 2.0 * std::f64::consts::TAU).sin())),
black(band(100.0, 0.9, 64, |x| 3.8 - 1.6 * (x / 100.0 * 2.0 * std::f64::consts::TAU).sin())),
ring(Point::new(8.0, -3.8), 3.0, 1.5),
ring(Point::new(92.0, 3.8), 3.0, 1.5),
]);
let ornament = |name: &str, art: Node| Brush {
name: name.into(),
kind: BrushKind::Art(ArtBrush { art, width: 300.0, colorization: Colorization::Tints, ..Default::default() }),
};
built(
"Ornamental",
Document::new(100.0, 100.0),
vec![
ornament("Scrollwork", scrollwork),
ornament("Filigree Arrow", arrow),
ornament("Petal Sweep", petal_sweep),
ornament("Twin Curl", twin_curl),
],
)
}
fn scatter(name: &str, art: Node, s: Scatter) -> Brush {
Brush { name: name.into(), kind: BrushKind::Scatter(Scatter { art, ..s }) }
}
+24 -2
View File
@@ -42,8 +42,12 @@ 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::{TracePreset, TracePresetChange, TraceRun, Traced, image_trace_target};
use trace::{trace_expand, trace_make, trace_presets_delete, trace_presets_save, trace_release, trace_set_view};
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,
};
/// Name of an Image Trace group.
pub const TRACE_NAME: &str = "Image Trace";
@@ -208,6 +212,24 @@ pub fn specs() -> Vec<CommandSpec> {
always,
trace_presets_delete
),
cmd!(
query "imageTrace.presets.import",
"Import Image Trace Presets",
[],
None,
"{path? | data?: file text | dataBase64?, replace?: false (true: a preset whose name a saved preset has replaces that preset's settings; false: it is skipped)} add the presets of a .vctracepresets file (as imageTrace.presets.export writes, at most 4 MiB and 1,000 presets) to the saved ones → {imported: [names added], replaced: [names], skipped: [names]}; every preset is checked first, and a file with a built-in preset's or Custom's name, two presets of one name, a preset without a name or with settings imageTrace.presets.save refuses, or a newer version changes nothing",
always,
trace_presets_import
),
cmd!(
query "imageTrace.presets.export",
"Export Image Trace Presets",
[],
None,
"{names?: [saved preset names] (default: every saved preset; built-in ones are refused), path?} write the saved tracing presets as a .vctracepresets file (JSON: format, version 1, presets: [{name, params}]) → {path, count}; without path → {data: the file's text, count}; more than 1,000 presets, or a file over 4 MiB, is refused, as imageTrace.presets.import would refuse it",
always,
trace_presets_export
),
]
}
+159
View File
@@ -168,6 +168,9 @@ pub(super) fn trace_presets_save(s: &mut Session, p: &Value) -> Result<Value> {
if old.is_none() && new_name.is_some() {
return Err(bad(C, format!("no saved preset named `{name}` to rename")));
}
if old.is_none() && s.prefs.trace_presets.len() >= TRACE_PRESET_MAX_COUNT {
return Err(bad(C, format!("{TRACE_PRESET_MAX_COUNT} tracing presets are saved, the most there can be: delete one first")));
}
// A saved preset changes from its own settings unless `preset` says where to start.
let mut q = p.clone();
if let (Some(old), Some(o), None) = (&old, q.as_object_mut(), preset) {
@@ -203,6 +206,162 @@ pub(super) fn trace_presets_delete(s: &mut Session, p: &Value) -> Result<Value>
Ok(json!({ "deleted": deleted }))
}
/// The `format` of a tracing presets file, also its extension.
pub const TRACE_PRESET_FORMAT: &str = "vctracepresets";
/// The extensions of tracing presets files (opening one imports it).
pub const TRACE_PRESET_EXTS: &[&str] = &[TRACE_PRESET_FORMAT];
/// The `version` `imageTrace.presets.export` writes; `imageTrace.presets.import` reads files of
/// this version and earlier ones.
const TRACE_PRESET_VERSION: u64 = 1;
/// The largest tracing presets file `imageTrace.presets.import` reads.
pub const TRACE_PRESET_MAX_BYTES: usize = 4 << 20;
/// The most presets one tracing presets file may hold, and the most tracing presets that can be
/// saved (so every saved preset fits in one exported file).
const TRACE_PRESET_MAX_COUNT: usize = 1000;
pub(super) fn trace_presets_export(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "imageTrace.presets.export";
let presets: Vec<&TracePreset> = match p.get("names").filter(|v| !v.is_null()) {
Some(Value::Array(names)) => {
let mut out: Vec<&TracePreset> = vec![];
for n in names {
let n = n.as_str().ok_or_else(|| bad(C, "`names` must hold preset names"))?;
if tr::preset(n).is_some() {
return Err(bad(C, format!("`{n}` is a built-in preset: only saved presets are exported")));
}
let q = s.trace_preset(n).ok_or_else(|| bad(C, format!("no saved preset named `{n}`")))?;
if !out.iter().any(|o| o.name == q.name) {
out.push(q);
}
}
out
}
Some(_) => return Err(bad(C, "`names` must be an array of preset names")),
None => s.prefs.trace_presets.iter().collect(),
};
if presets.is_empty() {
return Err(bad(C, "no saved tracing presets to export"));
}
// A file is written only when `imageTrace.presets.import` can read it back.
let count = presets.len();
if count > TRACE_PRESET_MAX_COUNT {
return Err(bad(C, format!("{count} presets are more than one file holds ({TRACE_PRESET_MAX_COUNT}): export fewer with `names`")));
}
let rows: Vec<Value> = presets.iter().map(|q| json!({"name": q.name, "params": q.params})).collect();
let file = json!({"format": TRACE_PRESET_FORMAT, "version": TRACE_PRESET_VERSION, "presets": rows});
let text = serde_json::to_string_pretty(&file).map_err(|e| EngineError::Other(e.to_string()))?;
if text.len() > TRACE_PRESET_MAX_BYTES {
return Err(bad(C, format!("the file would be larger than {} MiB: export fewer with `names`", TRACE_PRESET_MAX_BYTES >> 20)));
}
match opt_str(C, p, "path")? {
Some(path) => {
crate::cmd::fileio::write_file(path, text.as_bytes())?;
Ok(json!({"path": path, "count": count}))
}
None => Ok(json!({"data": text, "count": count})),
}
}
/// The bytes of the tracing presets file `p` names (`path`, `data` or `dataBase64`), at most
/// [`TRACE_PRESET_MAX_BYTES`] of them.
fn trace_preset_file(c: &str, p: &Value) -> Result<Vec<u8>> {
let too_big = || bad(c, format!("the file is larger than {} MiB", TRACE_PRESET_MAX_BYTES >> 20));
let bytes = match (opt_str(c, p, "path")?, opt_str(c, p, "data")?, opt_str(c, p, "dataBase64")?) {
(Some(path), ..) => crate::cmd::fileio::read_file_head(path, TRACE_PRESET_MAX_BYTES + 1)?,
(None, Some(text), _) => {
if text.len() > TRACE_PRESET_MAX_BYTES {
return Err(too_big());
}
text.as_bytes().to_vec()
}
(None, None, Some(b64)) => {
if vectorcraft_format::base64_decoded_len(b64) > TRACE_PRESET_MAX_BYTES as u64 {
return Err(too_big());
}
vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))?
}
_ => return Err(bad(c, "give `path`, `data` or `dataBase64`")),
};
if bytes.len() > TRACE_PRESET_MAX_BYTES {
return Err(too_big());
}
Ok(bytes)
}
pub(super) fn trace_presets_import(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "imageTrace.presets.import";
let replace = switch_or(p, "replace", false, C)?;
let bytes = trace_preset_file(C, p)?;
let not_file = |why: String| bad(C, format!("not a tracing presets file: {why}"));
let file: Value = serde_json::from_slice(&bytes).map_err(|e| not_file(e.to_string()))?;
if file["format"] != TRACE_PRESET_FORMAT {
return Err(not_file(format!("format `{}`", file["format"].as_str().unwrap_or_default())));
}
match file["version"].as_u64() {
Some(v) if (1..=TRACE_PRESET_VERSION).contains(&v) => {}
Some(v) => return Err(bad(C, format!("the file's version {v} is newer than this version of VectorCraft reads ({TRACE_PRESET_VERSION})"))),
None => return Err(not_file("no `version`".into())),
}
let rows = file["presets"].as_array().ok_or_else(|| not_file("no `presets` list".into()))?;
if rows.len() > TRACE_PRESET_MAX_COUNT {
return Err(bad(C, format!("the file holds {} presets, more than {TRACE_PRESET_MAX_COUNT}", rows.len())));
}
// Every preset is checked before any is saved, so a file with a fault changes nothing.
let mut presets: Vec<TracePreset> = Vec::with_capacity(rows.len());
for (i, row) in rows.iter().enumerate() {
let name = row["name"].as_str().map(str::trim).unwrap_or_default();
if name.is_empty() {
return Err(bad(C, format!("preset {} has no name", i + 1)));
}
if tr::preset(name).is_some() || name.eq_ignore_ascii_case("Custom") {
return Err(bad(C, format!("`{name}` is the name of a built-in preset: rename it in the file")));
}
if presets.iter().any(|q| q.name.eq_ignore_ascii_case(name)) {
return Err(bad(C, format!("the file holds two presets named `{name}`")));
}
let params = match row.get("params").filter(|v| v.is_object()) {
Some(params) => trace_params(s, C, &json!({"preset": "Default", "params": params})).map_err(|e| match e {
EngineError::BadParams { msg, .. } => bad(C, format!("`{name}`: {msg}")),
e => e,
})?,
None => return Err(bad(C, format!("`{name}` has no `params`"))),
};
presets.push(TracePreset { name: name.to_string(), params });
}
let added = presets.iter().filter(|q| s.trace_preset_index(&q.name).is_none()).count();
if s.prefs.trace_presets.len() + added > TRACE_PRESET_MAX_COUNT {
return Err(bad(
C,
format!("the file's {added} new presets would make more than {TRACE_PRESET_MAX_COUNT} saved tracing presets: delete some first"),
));
}
let (mut imported, mut replaced, mut skipped) = (vec![], vec![], vec![]);
for preset in presets {
let name = preset.name.clone();
match s.trace_preset_index(&name) {
Some(i) if replace => {
let Some(slot) = s.prefs.trace_presets.get_mut(i) else { continue };
// The saved preset keeps its name as it was saved.
let kept = slot.name.clone();
*slot = TracePreset { name: kept.clone(), params: preset.params };
s.trace_preset_changes.note(TracePresetChange { revision: 0, name: kept.clone(), renamed_from: None, deleted: false });
replaced.push(kept);
}
Some(_) => skipped.push(name),
None => {
s.prefs.trace_presets.push(preset);
s.trace_preset_changes.note(TracePresetChange { revision: 0, name: name.clone(), renamed_from: None, deleted: false });
imported.push(name);
}
}
}
Ok(json!({"imported": imported, "replaced": replaced, "skipped": skipped}))
}
/// The string `key` of `p` (`None` when it is missing or null); any other type is an error of
/// command `c`.
fn opt_str<'a>(c: &str, p: &'a Value, key: &str) -> Result<Option<&'a str>> {
+7 -2
View File
@@ -19,7 +19,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_brush::Brush;
use vectorcraft_color::Swatch;
use vectorcraft_doc::{Document, GraphicStyle, ImageBlob, Node, NodeId, NodeKind, PatternDef, Selection, Symbol, TextStyleDef};
use vectorcraft_doc::{Document, GraphDesign, GraphicStyle, ImageBlob, Node, NodeId, NodeKind, PatternDef, Selection, Symbol, TextStyleDef};
use vectorcraft_geom::{PathData, Rect};
pub use flavours::{AI, BITMAP, EMF, EPS, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture};
@@ -94,6 +94,9 @@ pub struct Clipboard {
pub para_styles: Vec<TextStyleDef>,
/// Brushes the objects' strokes use.
pub brushes: Vec<Brush>,
/// Graph designs the copied graphs draw their columns, bars or markers with. Pasting adds the
/// ones the document lacks; a design the document has under the same name stays as it is.
pub graph_designs: Vec<GraphDesign>,
/// The artboard the objects were copied from (none when they lie on no artboard; the first of
/// [`Self::artboards`] when there are any): Paste on All Artboards keeps their offset to it.
pub source_artboard: Option<Rect>,
@@ -395,7 +398,7 @@ impl Clipboard {
if self.source_doc == Some(st.uid) && !self.colors_converted {
return vec![];
}
self.conflicts(&st.doc, &self.used())
self.conflicts(&st.doc, &self.used(&st.doc))
}
/// A standalone document holding the objects and their resources (SVG export).
@@ -408,6 +411,7 @@ impl Clipboard {
d.graphic_styles.extend(self.graphic_styles.iter().cloned());
d.char_styles = self.char_styles.clone().into();
d.para_styles = self.para_styles.clone().into();
d.graph_designs = self.graph_designs.clone();
if !self.brushes.is_empty() {
let mut lib = vectorcraft_brush::library(&d);
// Each brush's place in the library by name: finding it by scanning the growing list
@@ -469,6 +473,7 @@ impl Clipboard {
char_styles: d.char_styles.to_vec(),
para_styles: d.para_styles.to_vec(),
brushes: vectorcraft_brush::library(&d),
graph_designs: d.graph_designs.clone(),
images: self.images.clone(),
symbol_options: self.symbol_options.clone(),
source_artboard: self.source_artboard,
+212 -13
View File
@@ -1,8 +1,9 @@
//! The document resources copied objects use, and adding them to the document they're pasted into.
//!
//! Objects refer to resources by name (image blobs, symbols, patterns, swatches, character and
//! paragraph styles, brushes) and to graphic styles by id. Copy follows those references, also
//! through the symbols, patterns, styles and brush art it finds, and keeps what they lead to.
//! paragraph styles, brushes, graph designs) and to graphic styles by id. Copy follows those
//! references, also through the symbols, patterns, styles, brush art and graph design art it finds,
//! and keeps what they lead to.
//!
//! Pasting matches each resource by name: an identical one in the document is used, a missing one
//! is added, and a different one of the same name is added under a free name, which the pasted
@@ -22,8 +23,8 @@ use vectorcraft_brush::Brush;
use vectorcraft_color::{Color, Paint, Swatch};
use vectorcraft_doc::text::{KINSOKU_NAME_MAX, KINSOKU_SETS_MAX};
use vectorcraft_doc::{
Appearance, AppearanceItem, Document, Effect, GraphicStyle, Kinsoku, KinsokuSet, Node, NodeKind, PatternDef, Symbol, SymbolExportType,
SymbolNineSlice, SymbolRegistration, TextStyleDef,
Appearance, AppearanceItem, Document, Effect, GraphDesign, GraphicStyle, Kinsoku, KinsokuSet, Node, NodeKind, PatternDef, Symbol,
SymbolExportType, SymbolNineSlice, SymbolRegistration, TextStyleDef,
};
use super::super::brushsym::{set_natural_size, stored_natural_size};
@@ -44,6 +45,7 @@ enum Res {
ParaStyle,
Brush,
GraphicStyle,
GraphDesign,
}
impl Res {
@@ -57,6 +59,7 @@ impl Res {
Res::ParaStyle => "paraStyle",
Res::Brush => "brush",
Res::GraphicStyle => "graphicStyle",
Res::GraphDesign => "graphDesign",
}
}
}
@@ -139,6 +142,10 @@ fn node_refs(n: &Node, f: Visit) {
for s in [&l.values_para, &l.categories_para, &l.legend_para].into_iter().flatten().filter_map(|pa| pa.style_name.as_ref()) {
f(Ref::Name(Res::ParaStyle, s));
}
// The designs its series draw their markers, columns or bars with.
for d in g.series_markers.iter().flatten().chain(g.series_columns.iter().flatten().map(|c| &c.design)) {
f(Ref::Name(Res::GraphDesign, d));
}
}
match &m.kind {
NodeKind::Text(t) => {
@@ -217,6 +224,7 @@ struct Defs<'a> {
char_styles: &'a [TextStyleDef],
para_styles: &'a [TextStyleDef],
brushes: Brushes<'a>,
graph_designs: &'a [GraphDesign],
/// Where each name is defined, built the first time a kind is followed.
index: DefIndex,
}
@@ -236,6 +244,7 @@ struct DefIndex {
char_styles: OnceCell<NameIndex>,
para_styles: OnceCell<NameIndex>,
brushes: OnceCell<NameIndex>,
graph_designs: OnceCell<NameIndex>,
}
/// The items of `list` named `name`, in order, `index` holding their positions (built from
@@ -279,6 +288,7 @@ impl<'a> Defs<'a> {
char_styles: &d.char_styles,
para_styles: &d.para_styles,
brushes: Brushes::Lazy(d, brushes),
graph_designs: &d.graph_designs,
index: DefIndex::default(),
}
}
@@ -376,6 +386,7 @@ impl Used {
Res::ParaStyle => todo.extend(named(&ix.para_styles, defs.para_styles, |s| &s.name, name).map(|s| Source::Attrs(&s.attrs))),
// A scatter or art brush's art, a pattern brush's tiles.
Res::Brush => todo.extend(named(&ix.brushes, defs.brushes.get(), |b| &b.name, name).flat_map(|b| b.art().into_iter().map(Source::Node))),
Res::GraphDesign => todo.extend(named(&ix.graph_designs, defs.graph_designs, |g| &g.name, name).map(|g| Source::Node(&g.art))),
_ => {}
}
}
@@ -406,7 +417,7 @@ pub struct ArtResources {
/// The resources `art` uses in `doc`, through the definitions they lead to as Copy follows them
/// ([`Used`]): images, symbols, patterns (tile type, overlap and spacing too), swatches (linked
/// colours, tints, gradient swatches; colour groups' included), character and paragraph styles,
/// brushes and graphic styles, and the document's Spot Colors option. Art and image bytes count
/// brushes, graph designs and graphic styles, and the document's Spot Colors option. Art and image bytes count
/// by identity, the other definitions by their saved form: working the key out walks `art` and
/// the definitions it leads to, and never reads an image's bytes.
pub fn art_resources<'a>(doc: &'a Document, art: impl IntoIterator<Item = &'a Node>) -> ArtResources {
@@ -451,6 +462,7 @@ pub fn art_resources<'a>(doc: &'a Document, art: impl IntoIterator<Item = &'a No
Res::CharStyle => doc.char_styles.iter().filter(|s| s.name == *name).for_each(|s| saved(&mut h, s)),
Res::ParaStyle => doc.para_styles.iter().filter(|s| s.name == *name).for_each(|s| saved(&mut h, s)),
Res::Brush => defs.brushes.get().iter().filter(|b| b.name == *name).for_each(|b| saved(&mut h, b)),
Res::GraphDesign => doc.graph_designs.iter().filter(|g| g.name == *name).for_each(|g| node(&mut h, &mut kept.0, &g.art)),
// Swatches below (tints count too); graphic styles go by id.
Res::Swatch | Res::GraphicStyle => {}
}
@@ -824,6 +836,22 @@ fn same_art(r: &Relink, ours: &[Arc<Node>], theirs: &[Arc<Node>]) -> bool {
ours.len() == theirs.len() && ours.iter().zip(theirs).all(|(a, b)| relinked(&unlinked, a) == relinked(r, b))
}
/// `n` with the ids of its objects, those of opacity-mask art included, all 0: art drawn again
/// compares equal to art drawn the same way, whatever ids each drawing gave it.
fn without_ids(n: &Node) -> Node {
let mut n = n.clone();
n.id = vectorcraft_doc::NodeId(0);
if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) {
mask.art = Arc::new(without_ids(&mask.art));
}
if let Some(children) = n.children_mut() {
for c in children.iter_mut() {
*c = Arc::new(without_ids(c));
}
}
n
}
/// Is `ours` (a document brush) brush `theirs` (a pasted one) once the art of that is relinked by
/// `r`? Graphic style links don't count, as in [`same_art`].
fn same_brush(r: &Relink, ours: &Brush, theirs: &Brush) -> bool {
@@ -1106,6 +1134,17 @@ pub(crate) struct Imported {
/// `{kind, from, to}` for every resource the pasted objects now know under another name: added
/// renamed, or a copy added renamed by an earlier paste.
pub renamed: Vec<Value>,
/// The graph designs the pasted graphs draw with that the document has under the same name
/// and that would draw them otherwise than the art they were pasted with: the document keeps
/// its own, and the pasted graphs are drawn again with it.
pub kept_designs: BTreeSet<String>,
/// The names of the symbols added to the document, whose art may hold graphs that draw with
/// [`Self::kept_designs`].
pub added_symbols: BTreeSet<String>,
/// The names of the graph designs added to the document.
pub added_designs: BTreeSet<String>,
/// The global and spot colors that took the document's color (merged).
merged_swatches: BTreeSet<String>,
}
impl Imported {
@@ -1161,15 +1200,24 @@ impl Clipboard {
char_styles: pick(Res::CharStyle, &src.char_styles),
para_styles: pick(Res::ParaStyle, &src.para_styles),
brushes,
graph_designs: src.graph_designs.iter().filter(|g| used.has(Res::GraphDesign, &g.name)).cloned().collect(),
set_densities: src.set_densities_of(&nodes),
nodes,
..Default::default()
}
}
/// The resources the objects use now (Paste without Formatting leaves text styles behind).
pub(super) fn used(&self) -> Used {
let defs = Defs {
/// The resources the objects use now (Paste without Formatting leaves text styles behind),
/// pasted into `d`: the art of a graph design `d` has under the same name is not followed, as
/// `d` keeps its own design.
pub(super) fn used(&self, d: &Document) -> Used {
let designs: Vec<GraphDesign> = self.graph_designs.iter().filter(|g| !d.graph_designs.iter().any(|x| x.name == g.name)).cloned().collect();
Used::of(&self.defs(&designs), &self.nodes)
}
/// The clipboard's definitions, with graph designs `designs`.
fn defs<'a>(&'a self, designs: &'a [GraphDesign]) -> Defs<'a> {
Defs {
swatches: self.swatches.iter().collect(),
symbols: &self.symbols,
patterns: &self.patterns,
@@ -1177,9 +1225,9 @@ impl Clipboard {
char_styles: &self.char_styles,
para_styles: &self.para_styles,
brushes: Brushes::Ready(&self.brushes),
graph_designs: designs,
index: DefIndex::default(),
};
Used::of(&defs, &self.nodes)
}
}
/// The used global and spot colours whose name `d` gives another one: (pasted, document).
@@ -1200,7 +1248,8 @@ impl Clipboard {
/// paste ([`Self::colors_converted`]), its color-bearing resources are compared as another
/// document's are, while its image blobs are still the document's own under their keys.
pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Result<Imported> {
self.import_used_with_images(d, &self.used(), choices, same_doc && !self.colors_converted, same_doc)
let used = self.used(d);
self.import_used_with_images(d, &used, choices, same_doc && !self.colors_converted, same_doc)
}
/// Give the objects' colors linked to a global or spot swatch whose conflict with `d`
@@ -1211,7 +1260,7 @@ impl Clipboard {
if same_doc {
return;
}
let used = self.used();
let used = self.used(d);
let colors: BTreeMap<String, Color> = self
.conflicts(d, &used)
.into_iter()
@@ -1248,6 +1297,11 @@ impl Clipboard {
) -> Result<Imported> {
let mut out = Imported::default();
out.relink.filters = self.filter_links(d, same_doc)?;
let held = |name: &str| d.graph_designs.iter().any(|x| x.name == name);
let new_designs = self.graph_designs.iter().filter(|g| used.has(Res::GraphDesign, &g.name) && !held(&g.name)).count();
if new_designs > 0 && d.graph_designs.len().saturating_add(new_designs) > GraphDesign::MAX {
return Err(EngineError::Other(format!("a document keeps at most {} graph designs", GraphDesign::MAX)));
}
self.import_images(d, used, same_doc_images, &mut out);
self.import_swatches(d, used, choices, same_doc, &mut out);
self.import_kinsoku_sets(d, used, same_doc, &mut out);
@@ -1331,11 +1385,18 @@ impl Clipboard {
.collect(),
None => HashMap::new(),
};
// A symbol whose graphs the paste draws again with the document's designs is
// also the document's one that holds its art drawn that way (an earlier paste
// added it).
let redrawn = (!fresh && d.symbols.iter().any(|s| copy_of(&def.name, &s.name)))
.then(|| self.redrawn_art(d, &def.art, &out.relink))
.flatten();
let r = &out.relink;
let p = place(&mut d.symbols, def, same_doc, |a, b| {
!fresh
&& options.is_none_or(|o| theirs.get(&a.name) == Some(o))
&& same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art))
&& (same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art))
|| redrawn.as_ref().is_some_and(|art| without_ids(&a.art) == *art))
});
if let Some(name) = p.new_name(&def.name) {
if let Some(o) = options {
@@ -1371,6 +1432,7 @@ impl Clipboard {
}
}
self.import_graphic_styles(d, used, same_doc, &mut out);
self.import_graph_designs(d, used, same_doc, &mut out)?;
for (r, name, def) in added_styles {
let theirs = if r == Res::CharStyle { &mut d.char_styles } else { &mut d.para_styles };
if let Some(s) = theirs.iter_mut().find(|s| s.name == name) {
@@ -1381,6 +1443,7 @@ impl Clipboard {
for s in d.symbols.iter_mut().filter(|s| added_symbols.contains(&s.name)) {
out.relink.node(Arc::make_mut(&mut s.art));
}
out.added_symbols = added_symbols.into_iter().collect();
for p in d.patterns.iter_mut().filter(|p| added_patterns.contains(&p.name)) {
for a in &mut p.art {
out.relink.node(Arc::make_mut(a));
@@ -1497,6 +1560,10 @@ impl Clipboard {
for a in self.brushes.iter().flat_map(Brush::art) {
node_filters(a, &mut found);
}
// A design the document has under the same name stays its own, so its art here is not pasted.
for g in self.graph_designs.iter().filter(|g| !d.graph_designs.iter().any(|x| x.name == g.name)) {
node_filters(&g.art, &mut found);
}
for g in &self.graphic_styles {
appearance_filters(&g.appearance, &mut found);
}
@@ -1575,6 +1642,7 @@ impl Clipboard {
for w in &bases {
let p = if conflicts.contains(&w.name) && choices.of(&w.name) == SwatchChoice::Merge {
out.merged += 1;
out.merged_swatches.insert(w.name.clone());
Placed::Existing
} else {
add_swatch(d, w, same_doc)
@@ -1624,6 +1692,71 @@ impl Clipboard {
out.relink.styles.insert(g.id, d.graphic_style_id(i));
}
}
/// Symbol art `art` relinked by `relink` with its graphs drawn again with the designs `d` holds
/// under a name whose design the clipboard lacks or holds with other art, as a paste that adds
/// the symbol draws it, its ids left out ([`without_ids`]). `None` when no graph of it draws
/// with such a design.
fn redrawn_art(&self, d: &mut Document, art: &Arc<Node>, relink: &Relink) -> Option<Node> {
let theirs = |n: &str| self.graph_designs.iter().find(|g| g.name == n);
let differs: BTreeSet<String> = d
.graph_designs
.iter()
.filter(|x| theirs(&x.name).is_none_or(|g| !Arc::ptr_eq(&g.art, &x.art) && g.art != x.art))
.map(|x| x.name.clone())
.collect();
if differs.is_empty() || !crate::cmd::graph::holds_designs(art, &differs) {
return None;
}
let mut n = (**art).clone();
relink.node(&mut n);
crate::cmd::graph::redraw_detached(d, &mut n, &differs);
Some(without_ids(&n))
}
/// Graph designs: the document's design of a name stays as it is and the pasted graphs draw
/// with it ([`Imported::kept_designs`]); a design the document lacks is added under its name, its art following the
/// resources placed above, with fresh ids. Called once every other resource is placed.
fn import_graph_designs(&self, d: &mut Document, used: &Used, same_doc: bool, out: &mut Imported) -> Result<()> {
// Every name the pasted graphs draw with whose design in the document would draw them
// otherwise: another design of that name, one the clipboard holds no design for (deleted
// and made again), or, from another document, the same art when a resource came in renamed
// or a swatch took the document's color, that the design's art uses. (An SVG filter effect
// carries its definition, so a filter that draws otherwise makes the art differ.)
let defs = self.defs(&self.graph_designs);
let moved = |n: &str| {
if same_doc || (out.relink.renames.is_empty() && out.merged_swatches.is_empty()) {
return false;
}
let uses = designs_used(&defs, &[n.to_string()]);
out.relink.renames.iter().any(|(r, names)| names.keys().any(|from| uses.has(*r, from)))
|| out.merged_swatches.iter().any(|w| uses.has(Res::Swatch, w))
};
let differs = |n: &str| {
let ours = d.graph_designs.iter().find(|x| x.name == n);
let theirs = self.graph_designs.iter().find(|g| g.name == n);
ours.is_some_and(|x| theirs.is_none_or(|g| !Arc::ptr_eq(&g.art, &x.art) && g.art != x.art) || moved(n))
};
let named = used.names.get(&Res::GraphDesign).into_iter().flatten();
let kept: Vec<String> = named.filter(|n| differs(n)).cloned().collect();
out.kept_designs.extend(kept);
for g in self.graph_designs.iter().filter(|g| used.has(Res::GraphDesign, &g.name)) {
if d.graph_designs.iter().any(|x| x.name == g.name) {
out.placed(Res::GraphDesign, &g.name, &Placed::Existing);
continue;
}
if d.graph_designs.len() >= GraphDesign::MAX {
return Err(EngineError::Other(format!("a document keeps at most {} graph designs", GraphDesign::MAX)));
}
let mut art = (*g.art).clone();
out.relink.node(&mut art);
let art = d.reid(&art);
d.graph_designs.push(GraphDesign { name: g.name.clone(), art: Arc::new(art) });
out.placed(Res::GraphDesign, &g.name, &Placed::Added);
out.added_designs.insert(g.name.clone());
}
Ok(())
}
}
/// Where a loaded text style is in the document ([`import_text_styles`]).
@@ -1663,6 +1796,72 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool,
Ok(placed)
}
/// The resources graph designs `names` of `src` use, through the definitions they lead to.
fn designs_used(defs: &Defs<'_>, names: &[String]) -> Used {
let mut used = Used::default();
let mut todo = vec![];
for n in names {
used.note(defs, Ref::Name(Res::GraphDesign, n), &mut todo);
}
used.follow(defs, todo);
used
}
/// A document holding `src`'s graph designs and the swatches, patterns, symbols, styles, brushes
/// and images their art uses, and nothing else: what a document opened as a library keeps for the
/// Graph Column and Graph Marker dialogs. `None` when `src` has no graph designs.
pub(crate) fn graph_design_library(src: &Document) -> Option<Document> {
if src.graph_designs.is_empty() {
return None;
}
let names: Vec<String> = src.graph_designs.iter().map(|g| g.name.clone()).collect();
let library = OnceCell::new();
let used = designs_used(&Defs::of(src, &library), &names);
let clip = Clipboard::with_used(src, &used, &library, vec![]);
let mut d = clip.to_document();
// A new document's default swatches and graphic styles give way to the source's of the same
// name or id, so a design draws with the source's.
let defaults = d.swatches.len().saturating_sub(clip.swatches.len());
let mut i = 0;
d.swatches.retain(|s| {
i += 1;
i > defaults || !clip.swatches.iter().any(|c| c.name == s.name)
});
// The swatch groups are all a new document's.
for g in d.swatch_groups.iter_mut() {
g.swatches.retain(|s| !clip.swatches.iter().any(|c| c.name == s.name));
}
let defaults = d.graphic_styles.len().saturating_sub(clip.graphic_styles.len());
let mut i = 0;
d.graphic_styles.retain(|g| {
i += 1;
i > defaults || !clip.graphic_styles.iter().any(|c| (c.id != 0 && c.id == g.id) || c.name == g.name)
});
// The symbols keep their Symbol Options, which the document keeps by name.
for (name, options) in &clip.symbol_options {
options.give(&mut d, name);
}
d.title = src.title.clone();
Some(d)
}
/// Add graph designs `names` of `src` to `d`, with the swatches, patterns, symbols, styles,
/// brushes and images their art uses, placed as Paste places them ([`Clipboard::import_into`]; a
/// global or spot color whose name `d` gives another color is `d`'s). A design `d` has under the
/// same name stays as it is, and the art of `src`'s design of that name is not followed. → the
/// names of the designs added ([`Imported::added_designs`]): those of `names` `d` lacked, and those
/// their art uses; with the symbols added and the designs `d` kept that their art draws with
/// ([`Imported::added_symbols`], [`Imported::kept_designs`]). An error, with `d` unchanged, when `d`
/// would hold more than [`GraphDesign::MAX`] designs.
pub(crate) fn import_graph_designs(src: &Document, d: &mut Document, names: &[String]) -> Result<Imported> {
let library = OnceCell::new();
let held = |n: &str| d.graph_designs.iter().any(|x| x.name == n);
let followed: Vec<GraphDesign> = src.graph_designs.iter().filter(|g| names.contains(&g.name) || !held(&g.name)).cloned().collect();
let used = designs_used(&Defs { graph_designs: &followed, ..Defs::of(src, &library) }, names);
let clip = Clipboard::with_used(src, &used, &library, vec![]);
clip.import_used(d, &used, &SwatchChoices::default(), false)
}
/// Swatch `w` in `d` ([`existing`]), else added under a free name (swatches and colour groups
/// share one namespace).
fn add_swatch(d: &mut Document, w: &Swatch, same_doc: bool) -> Placed {
+18 -6
View File
@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Circle Through Points",
[],
None,
"{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn",
"{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count), anchors?: \"standard\"|\"points\" (default standard: four anchors at 0°, 90°, 180° and 270°; points: an anchor at each point and more between them so that no curve turns more than a quarter)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn",
has_doc,
circle_through_points
),
@@ -443,20 +443,32 @@ fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
}
/// A live ellipse whose edge passes through two or three points: `points`, or the two or three
/// selected anchor points ([`selected_anchor_points`]). Two points are the ends of a diameter. One
/// undo step, named as an Ellipse tool drag is.
/// selected anchor points ([`selected_anchor_points`]). Two points are the ends of a diameter. With
/// `anchors: "points"` the circle is a plain path with an anchor at each point
/// ([`shapes::circle_with_anchors_at`]); otherwise it is a live ellipse. One undo step, named as an
/// Ellipse tool drag is.
fn circle_through_points(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "shape.circleThroughPoints";
let points = match p.get("points").filter(|v| !v.is_null()) {
Some(v) => two_or_three_points(v).ok_or_else(|| bad(C, "`points` must be two or three [x, y] pairs of numbers"))?,
None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select two or three anchor points, or give `points`"))?,
};
let key = "anchors";
let at_points = match p.get(key).map(Value::as_str) {
None | Some(Some("standard")) => false,
Some(Some("points")) => true,
Some(_) => return Err(bad(C, format!("`{key}` must be one of {}", "standard, points"))),
};
let (center, radius) = shapes::circle_through_points(&points)
.ok_or_else(|| bad(C, "no circle passes through these points: two are the same or all three lie on one line"))?;
let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
// Not pixel-aligned: the circle stays through the points.
let mut out = add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?;
let mut out = if at_points {
add_art_unaligned(s, "Ellipse", path_kind(shapes::circle_with_anchors_at(center, radius, &points), None))?
} else {
let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?
};
out["cx"] = json!(center.x);
out["cy"] = json!(center.y);
out["radius"] = json!(radius);
+11
View File
@@ -1653,6 +1653,17 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
for id in &new_ids {
super::object::keep_compound_aligned(d, *id, vectorcraft_doc::Scaling::default());
}
// A pasted graph whose design the document has under the same name draws with the document's,
// in the pasted objects and in the art of the symbols the paste added.
if !imported.kept_designs.is_empty() {
super::graph::redraw_with_designs(d, &new_ids, &imported.kept_designs)?;
super::graph::redraw_symbols_with_designs(d, &imported.added_symbols, &imported.kept_designs);
}
// The graphs already in the document that draw with a design the paste added are drawn
// again with it; the pasted ones already draw with it.
if !imported.added_designs.is_empty() {
super::graph::refresh_graphs(d, &imported.added_designs, &new_ids, &imported.added_symbols)?;
}
sel.set(new_ids.iter().copied());
// Copied ruler guides (#3226): on the layer new art goes to, moved as the objects are (a
// paste of guides alone keeps them where they were, but onto another artboard or every
+10 -2
View File
@@ -1,5 +1,6 @@
//! Window › 3D and Materials › Materials › Graphics: art kept as a document symbol (Add as Single
//! Graphic) and mapped onto 3D objects (Extrude & Bevel's caps, a plane, Revolve's side). The
//! Graphic) and mapped onto 3D objects (Extrude & Bevel's caps, a plane, Revolve's side, Inflate's
//! puffed front and back). The
//! graphics an object shows are the `graphics` parameter of its 3D effect, which `effect.setParams`
//! also edits.
@@ -28,7 +29,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Map Graphic",
[],
None,
"{symbol: name of a document symbol, face?: front|back|side (front; Plane has only a front; the back reads left to right as seen from behind; side is Extrude & Bevel's walls and bevels; on Revolve the front is its swept side, which is the only face), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on a side from the middle of the side unrolled flat: on Extrude & Bevel x along the outline, clockwise from its top, and y from the front toward the back; on Revolve x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Extrude & Bevel's side inside the side unrolled about x = 0, short of its cut, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on a side wrapped around it, and drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap, or on the side, hollow or not), Rotate (the Plane type) or Revolve; one undo step → {ids, graphic}",
"{symbol: name of a document symbol, face?: front|back|side (front; Plane has only a front; the back reads left to right as seen from behind; side is Extrude & Bevel's walls and bevels; on Revolve the front is its swept side, which is the only face; on Inflate the back takes graphics only with Both sides and Cap on), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on Inflate in the art's plane, the graphic carried straight out onto the puffed face; on a side from the middle of the side unrolled flat: on Extrude & Bevel x along the outline, clockwise from its top, and y from the front toward the back; on Revolve x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Extrude & Bevel's side inside the side unrolled about x = 0, short of its cut, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on a side wrapped around it, and on Inflate following the puff, Twist and Taper carrying the back's, each drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap, or on the side, hollow or not), Rotate (the Plane type), Revolve or Inflate; one undo step → {ids, graphic}",
has_doc,
map_graphic
),
@@ -134,6 +135,13 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result<Value> {
if base.face != effects::PlanarFace::Front && extrude.is_some_and(|o| o.depth <= 0.0) {
return Err(bad(C, format!("object {}: with a depth of 0 the object has one face: map its graphics onto the front", id.0)));
}
// Inflate's back takes graphics where it puffs out: with Both sides and Cap on.
if base.face == effects::PlanarFace::Back && effect.id == effects::INFLATE {
let o = effects::inflate_options(&merged);
if !(o.both_sides && o.cap) {
return Err(bad(C, format!("object {}: Inflate's back takes graphics with Both sides and Cap on", id.0)));
}
}
let mut graphic = base.clone();
if p.get("scale").is_none()
&& let Some(art) = effects::graphic_bounds(d, &graphic.symbol)
@@ -95,10 +95,10 @@ fn map_graphic_puts_a_graphic_on_the_side_of_a_revolve() {
#[test]
fn map_graphic_refuses_what_cannot_take_it_and_changes_nothing() {
let (mut s, id) = setup("threeD.inflate");
let (mut s, id) = setup("threeD.classicExtrude");
let history = undo_len(&s);
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap_err().to_string();
assert!(e.contains("Plane, Extrude and Revolve"), "{e}");
assert!(e.contains("Plane, Extrude, Revolve and Inflate"), "{e}");
let (mut s, id) = setup("threeD.rotate");
for (p, says) in [
(json!({"symbol": "Gone"}), "no symbol named"),
@@ -188,11 +188,36 @@ fn set_params_edits_graphics_and_checks_them() {
let null = json!({"ids": [id.0], "index": 0, "item": null, "params": {"graphics": null}});
assert!(s.execute("effect.setParams", &null).is_err());
assert_eq!(graphics(&s, id), moved);
// Extrude to Plane keeps the graphics; to Inflate drops them.
// Extrude to Plane keeps the graphics, and so does Inflate.
s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "threeDType": "plane"})).unwrap();
assert_eq!(graphics(&s, id), moved);
s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "threeDType": "inflate"})).unwrap();
assert_eq!(graphics(&s, id), Value::Null);
assert_eq!(graphics(&s, id), moved);
}
#[test]
fn map_graphic_puts_a_graphic_on_an_inflate_and_its_back_only_with_both_sides() {
let (mut s, id) = setup("threeD.inflate");
let plain = {
let d = &s.doc().unwrap().doc;
vectorcraft_render::effects::solid_art_in(Some(d), d.node(id).unwrap())
};
let history = undo_len(&s);
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap();
assert_eq!(graphics(&s, id), json!([{"symbol": "Mark", "face": "front", "x": 0.0, "y": 0.0, "scale": 100.0, "rotation": 0.0}]));
assert_eq!(undo_len(&s), history + 1);
let d = &s.doc().unwrap().doc;
assert_ne!(vectorcraft_render::effects::solid_art_in(Some(d), d.node(id).unwrap()), plain, "the graphic is drawn");
// The back is flat until Both sides puffs it.
let history = undo_len(&s);
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back", "ids": [id.0]})).unwrap_err().to_string();
assert!(e.contains("Both sides and Cap"), "{e}");
assert_eq!(undo_len(&s), history);
s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": {"bothSides": true, "cap": false}})).unwrap();
assert!(s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back", "ids": [id.0]})).is_err());
s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": {"cap": true}})).unwrap();
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back", "ids": [id.0]})).unwrap();
assert_eq!(graphics(&s, id)[1]["face"], "back");
}
#[test]
+1 -1
View File
@@ -804,7 +804,7 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result<Value> {
let skipped = super::paint::live_paint_parts_skipped(&s.doc()?.doc, &roots, !stroke);
leaf_targets(s, &roots)?.into_iter().filter(|id| !skipped.contains(id)).collect()
}
_ => item.targets(s, p)?,
_ => item.targets_for(s, p, !stroke)?,
};
if targets.is_empty() {
return Err(EngineError::Other("nothing selected".into()));
+1
View File
@@ -41,6 +41,7 @@ pub use data::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph
pub(crate) use data::{apply_csv, graph_csv_from_file, parse_csv};
#[cfg(test)]
use data::{fmt_value, to_csv};
pub(crate) use designs::{holds_designs, redraw_detached, redraw_symbols_with_designs, redraw_with_designs, refresh_graphs};
pub use edit::{GraphTypeSubject, graph_type_subject};
pub(crate) use edit::{edit_graph_art, graphs_holding, keep_placed};
pub use generate::calculated_axes;
+17 -4
View File
@@ -1,5 +1,5 @@
use super::data::fmt_value;
use super::designs::design_names;
use super::designs::{bring_in_for, design_names, from_library, libraries_json};
use super::edit::{regenerate, spec_of, target};
use super::generate::generate_with;
use super::markers::{design_frame, fit_affine};
@@ -437,7 +437,7 @@ pub(super) fn set_column(s: &mut Session, p: &Value) -> Result<Value> {
let mut spec = spec_of(s, id)?;
let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).min(vectorcraft_doc::MAX_GRAPH_SERIES);
let picked = picked_series(s, p, id, count, C)?;
let names = design_names(&s.doc()?.doc);
let mut names = design_names(&s.doc()?.doc);
let all: Vec<usize> = if picked.is_empty() { (0..count).collect() } else { picked.clone() };
// The column design the picked series (all of them with none picked) share; a design deleted since doesn't count,
// as those series draw plain columns.
@@ -446,14 +446,21 @@ pub(super) fn set_column(s: &mut Session, p: &Value) -> Result<Value> {
let shared = used.first().copied().flatten().filter(|c| used.iter().all(|x| *x == Some(*c))).cloned();
let Some(v) = p.get("design") else {
let options = shared.clone().unwrap_or_default();
return Ok(json!({
let mut out = json!({
"designs": names,
"design": shared.map(|c| c.design),
"columnType": options.column_type.id(),
"each": options.each,
"fractions": options.fractions.id(),
}));
});
if let Some(libs) = libraries_json(s) {
out["libraries"] = libs;
}
return Ok(out);
};
// A design of a loaded library comes into the document in the same undo step.
let library = from_library(s, p, C)?;
names.extend(library.as_ref().map(|(_, n)| n.clone()));
let design = match v {
Value::Null => None,
Value::String(n) if names.contains(n) => Some(n.clone()),
@@ -485,11 +492,17 @@ pub(super) fn set_column(s: &mut Session, p: &Value) -> Result<Value> {
}
// Drawn once on a copy of the document, to refuse designs past the budget before the edit.
let mut probe = (*s.doc()?.doc).clone();
if let Some((lib, name)) = &library {
bring_in_for(&mut probe, lib, name, id, &mut spec)?;
}
let looks = column_designs(&probe, &spec);
if generate_with(&mut probe, &spec, &looks).is_none() {
return Err(bad(C, "the design is too big to draw in every column of this graph"));
}
s.edit("Graph Column", |d, sel| {
if let Some((lib, name)) = &library {
bring_in_for(d, lib, name, id, &mut spec)?;
}
regenerate(d, id, spec)?;
if !reselect.is_empty() {
reselect_series(d, sel, id, &reselect);
+3 -3
View File
@@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Design…",
["Object", "Graph"],
None,
"{new?: name|true (New Design: the selected art becomes a graph design, named \"New Design\" when true; put a rectangle at the back to set the size it draws at), rename?: name, to?: new name (the graphs drawing it follow), paste?: name (Paste Design: a copy of the design's art into the document, selected, to edit and save again), delete?: name|[names] (graphs drawing them go back to their default marks), ids?|id?: object ids (default: the selection), selectUnused?: bool (Select Unused: just the list)}; no params or selectUnused → {designs: [names], unused: [the names no graph draws with]}",
"{new?: name|true (New Design: the selected art becomes a graph design, named \"New Design\" when true; put a rectangle at the back to set the size it draws at), rename?: name, to?: new name (the graphs drawing it follow), paste?: name (Paste Design: a copy of the design's art into the document, selected, to edit and save again), delete?: name|[names] (graphs drawing them go back to their default marks), ids?|id?: object ids (default: the selection), selectUnused?: bool (Select Unused: just the list), library?: the id or name of a document loaded with swatch.library.load (Other Library…) that holds graph designs, add?: name|[names] of that library's designs (copy them into the document as one undo step, with the swatches, patterns, symbols, styles, brushes and images their art uses, as pasting brings them; a design the document already has under the same name stays as it is) → {added: [names], existing: [names the document already had]}}; library alone → {designs: [the library's names]}; no params or selectUnused → {designs: [names], unused: [the names no graph draws with], libraries?: [{library, name, designs}] (the loaded libraries that hold graph designs)}",
has_doc,
design
),
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Column…",
["Object", "Graph"],
None,
"{id?, seriesIndexes?: [index], design?: name|null, columnType?: vertical|uniform|repeating|sliding, each?: value (more than 0), fractions?: chop|scale} draw the columns or bars and the legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, its backmost object as its frame and its guides left out: vertical stretches it along the value axis to each column's length at the column's width, uniform scales it both ways to that length, centered on the column, repeating stacks copies out from the zero line that each stand for `each` and cuts off the last one where the value ends (chop) or scales it down to fit (scale) (vertical when one copy would be longer than the canvas), and sliding scales the part above its horizontal guide line (in bar graphs, right of a vertical one) in proportion to the column's width and stretches the part below to fill the rest (vertical without a guide, or in a column too short for the part above); type in the design that holds a `%` followed by two digits shows each column's value in place of the `%` and the digits, the first digit giving the least number of places before the decimal point (zeros added in front; 0 = as many as the value needs) and the second digit giving the places after it (rounded half away from zero), at the type's own size where the design's copy puts it (a repeating design shows it once, where a whole copy ending at the value end puts it; type inside a group that clips, is hidden or has its own opacity, blend mode, isolation, knockout, appearance or opacity mask, or inside a blend, compound shape, envelope, repeat or intertwine, stays there and is filled in each copy, drawn with the design; type inside a symbol stays as typed), and is left out of the legend swatch (a design of such type alone gets the default swatch); the design keeps its own orientation for negative values, and columns drawn with a design cast no drop shadow; null = plain columns; options left out keep the series' shared ones, else vertical, 10 and chop. Column, stacked column, bar and stacked bar series. No design → {designs: [names], design: the selected series' design or null, columnType, each, fractions}",
"{id?, seriesIndexes?: [index], design?: name|null, library?: id or name (a document loaded with swatch.library.load: a design of it that the document lacks is copied in first, in the same undo step, as graph.design's add copies it; the document's own design of a name is the one used), columnType?: vertical|uniform|repeating|sliding, each?: value (more than 0), fractions?: chop|scale} draw the columns or bars and the legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, its backmost object as its frame and its guides left out: vertical stretches it along the value axis to each column's length at the column's width, uniform scales it both ways to that length, centered on the column, repeating stacks copies out from the zero line that each stand for `each` and cuts off the last one where the value ends (chop) or scales it down to fit (scale) (vertical when one copy would be longer than the canvas), and sliding scales the part above its horizontal guide line (in bar graphs, right of a vertical one) in proportion to the column's width and stretches the part below to fill the rest (vertical without a guide, or in a column too short for the part above); type in the design that holds a `%` followed by two digits shows each column's value in place of the `%` and the digits, the first digit giving the least number of places before the decimal point (zeros added in front; 0 = as many as the value needs) and the second digit giving the places after it (rounded half away from zero), at the type's own size where the design's copy puts it (a repeating design shows it once, where a whole copy ending at the value end puts it; type inside a group that clips, is hidden or has its own opacity, blend mode, isolation, knockout, appearance or opacity mask, or inside a blend, compound shape, envelope, repeat or intertwine, stays there and is filled in each copy, drawn with the design; type inside a symbol stays as typed), and is left out of the legend swatch (a design of such type alone gets the default swatch); the design keeps its own orientation for negative values, and columns drawn with a design cast no drop shadow; null = plain columns; options left out keep the series' shared ones, else vertical, 10 and chop. Column, stacked column, bar and stacked bar series. No design → {designs: [names], design: the selected series' design or null, columnType, each, fractions, libraries?: [{library, name, designs}]}",
has_selection,
set_column
),
@@ -57,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Marker…",
["Object", "Graph"],
None,
"{id?, seriesIndexes?: [index], design?: name|null} draw the data points and legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, scaled so its backmost object fills the default marker's square; null = the default marker. Line, scatter and radar series. No design → {designs: [names], design: the selected series' design or null}",
"{id?, seriesIndexes?: [index], design?: name|null, library?: id or name (a document loaded with swatch.library.load: a design of it that the document lacks is copied in first, in the same undo step, as graph.design's add copies it; the document's own design of a name is the one used)} draw the data points and legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, scaled so its backmost object fills the default marker's square; null = the default marker. Line, scatter and radar series. No design → {designs: [names], design: the selected series' design or null, libraries?: [{library, name, designs}]}",
has_selection,
set_marker
),
+294 -18
View File
@@ -1,44 +1,291 @@
use super::edit::regenerate;
use super::{Arc, Document, GraphDesign, GraphSpec, Result, Session, Value, bad, json, ok, str_param};
use super::edit::{regenerate, regenerate_detached};
use std::collections::BTreeSet;
use super::{Arc, Document, GraphDesign, GraphKind, GraphSpec, Node, Result, Session, Value, bad, json, ok, str_param};
use crate::cmd::clipboard::resources::import_graph_designs;
use crate::cmd::swatchlib::{concealed_library_id, shown_library_id};
/// The document's graph design names, in order.
pub(super) fn design_names(d: &Document) -> Vec<String> {
d.graph_designs.iter().map(|x| x.name.clone()).collect()
}
/// Whether graph `g` draws a series with design `name`, as its marker or its columns.
/// The library param `library` names: a document Other Library… loaded (`swatch.library.load`)
/// that holds graph designs, by its id, the id a reply showed for it, or its name (in any case, as
/// swatch library names are matched). `None` without
/// `library`.
fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<Option<Arc<Document>>> {
let key = match p.get("library") {
None | Some(Value::Null) => return Ok(None),
Some(Value::String(k)) => k.as_str(),
Some(_) => {
let list = "graph.design";
return Err(bad(cmd, format!("`library` is a library id or name (see {list})")));
}
};
let libs = &s.graph_design_libraries;
let own = concealed_library_id(s, key);
libs.get(key)
.or_else(|| own.as_deref().and_then(|id| libs.get(id)))
.or_else(|| libs.iter().find(|l| l.name.eq_ignore_ascii_case(key)))
.map(|l| Some(l.doc.clone()))
.ok_or_else(|| bad(cmd, format!("no library `{key}`")))
}
/// The loaded libraries' designs, as lists show them: `[{library, name, designs}]`; `None` when no
/// loaded library holds graph designs.
pub(super) fn libraries_json(s: &Session) -> Option<Value> {
let libs: Vec<Value> = s
.graph_design_libraries
.iter()
.map(|l| json!({ "library": shown_library_id(s, &l.id), "name": l.name, "designs": design_names(&l.doc) }))
.collect();
(!libs.is_empty()).then(|| json!(libs))
}
/// The library design `p`'s `design` names, with the library to bring it in from, when `p` gives a
/// `library` and the document has no design of that name: the document's own design of a name is
/// the one a graph draws with.
pub(super) fn from_library(s: &Session, p: &Value, cmd: &str) -> Result<Option<(Arc<Document>, String)>> {
let Some(lib) = library_param(s, p, cmd)? else { return Ok(None) };
let Some(Value::String(n)) = p.get("design") else { return Ok(None) };
if s.doc()?.doc.graph_designs.iter().any(|x| x.name == *n) {
return Ok(None);
}
if !lib.graph_designs.iter().any(|x| x.name == *n) {
return Err(bad(cmd, format!("no design named `{n}`")));
}
Ok(Some((lib, n.clone())))
}
/// Add designs `names` of library `lib` to `d` with the resources their art uses, and redraw the
/// graphs that already name a design the document lacked: one of `names`, or one their art uses.
/// The graphs in the art of the symbols that came in are drawn with the designs the document kept.
pub(super) fn bring_in(d: &mut Document, lib: &Document, names: &[String]) -> Result<()> {
let imported = import_graph_designs(lib, d, names)?;
if !imported.kept_designs.is_empty() {
redraw_symbols_with_designs(d, &imported.added_symbols, &imported.kept_designs);
}
if !imported.added_designs.is_empty() {
refresh_graphs(d, &imported.added_designs, &[], &BTreeSet::new())?;
}
Ok(())
}
/// [`bring_in`] library design `name` for graph `id`, whose new spec is `spec`: when that redraws
/// the graph, `spec` takes the rectangle the redraw gave it, so a graph moved or resized since it
/// was last drawn stays where it is.
pub(super) fn bring_in_for(d: &mut Document, lib: &Document, name: &str, id: super::NodeId, spec: &mut GraphSpec) -> Result<()> {
bring_in(d, lib, &[name.to_string()])?;
if let Some(g) = d.node(id).and_then(|n| n.extras().graph.as_deref()) {
spec.rect = g.rect;
}
Ok(())
}
/// Whether graph `g` draws a series with design `name`: as the marker of a series drawn with
/// markers (every series of a scatter or radar graph, and line series) while Mark Data Points is
/// on or the legend has an entry for the series, or as the columns of a series drawn as columns or
/// bars.
fn draws_with(g: &GraphSpec, name: &str) -> bool {
let scatter = g.kind == GraphKind::Scatter;
let nser = g.rows.iter().map(Vec::len).max().unwrap_or(0).clamp(1, vectorcraft_doc::MAX_GRAPH_SERIES);
// The legend draws entry `s` with marker design `s`, and leaves out an entry whose label is blank
// (a scatter graph's entries are its pairs of series, labeled by the first of each pair).
let in_legend = |s: usize| {
let entries = if scatter { nser.div_ceil(2) } else { nser };
let label = g.series.get(if scatter { s * 2 } else { s }).map_or("", String::as_str);
g.legend && !g.series.is_empty() && s < entries && !super::labels::blank_label(label)
};
// Point markers use the same range of designs: a scatter graph plots a pair of series for each.
let plotted = if scatter { nser.div_ceil(2) } else { nser };
let shown = |s: usize| s < plotted && (g.mark_points || in_legend(s));
let marked = |s: usize| shown(s) && (matches!(g.kind, GraphKind::Scatter | GraphKind::Radar) || g.series_kind(s) == GraphKind::Line);
let columnar = |s: usize| matches!(g.series_kind(s), GraphKind::Column | GraphKind::StackedColumn | GraphKind::Bar | GraphKind::StackedBar);
g.series_markers.iter().enumerate().any(|(s, m)| m.as_deref() == Some(name) && marked(s))
|| g.series_columns.iter().enumerate().any(|(s, c)| c.as_ref().is_some_and(|c| c.design == name) && columnar(s))
}
/// Whether graph `g` names design `name` for a series, as its marker or its columns, whether or
/// not the series draws with it.
fn names_design(g: &GraphSpec, name: &str) -> bool {
g.series_markers.iter().flatten().any(|m| m == name) || g.series_columns.iter().flatten().any(|c| c.design == name)
}
/// Regenerate the graphs whose series use design `name` (it was added or removed).
/// Regenerate the graphs whose series use design `name` (it was added or removed), in the layers,
/// in opacity-mask art and in symbols' art.
fn refresh_graphs_using(d: &mut Document, name: &str) -> Result<()> {
let mut ids = vec![];
refresh_graphs(d, &BTreeSet::from([name.to_string()]), &[], &BTreeSet::new())
}
/// Regenerate the graphs that draw a series with one of the designs `names`, in the layers, in
/// opacity-mask art and in symbols' art, except those in the subtrees of `skip` and in the art of
/// symbols `skip_symbols`.
pub(crate) fn refresh_graphs(d: &mut Document, names: &BTreeSet<String>, skip: &[super::NodeId], skip_symbols: &BTreeSet<String>) -> Result<()> {
let mut skipped = std::collections::HashSet::new();
for n in skip.iter().filter_map(|id| d.node(*id)) {
n.walk(&mut |m| {
skipped.insert(m.id);
});
}
let (mut ids, mut masked) = (vec![], vec![]);
d.walk(|n| {
if n.extras().graph.as_deref().is_some_and(|g| draws_with(g, name)) {
if skipped.contains(&n.id) {
return;
}
if n.extras().graph.as_deref().is_some_and(|g| names.iter().any(|name| draws_with(g, name))) {
ids.push(n.id);
}
if n.extras().mask.as_deref().is_some_and(|m| holds(&m.art, names)) {
masked.push(n.id);
}
});
for id in ids {
if let Some(spec) = d.node(id).and_then(|n| n.extras().graph.as_deref().cloned()) {
regenerate(d, id, spec)?;
}
}
// The graphs in objects' opacity-mask art.
for id in masked {
let Some(mut art) = d.node(id).and_then(|n| n.extras().mask.as_deref()).map(|m| (*m.art).clone()) else { continue };
redraw_in(d, &mut art, names);
if let Some(mask) = d.node_mut(id).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_deref_mut()) {
mask.art = Arc::new(art);
}
}
// And the graphs in symbols' art, which instances draw.
let symbols: BTreeSet<String> = d.symbols.iter().map(|s| s.name.clone()).filter(|s| !skip_symbols.contains(s)).collect();
redraw_symbols_with_designs(d, &symbols, names);
Ok(())
}
/// The designs no graph's series draw with (Select Unused).
/// [`redraw_in`] for the clipboard: graph art `n`, outside the document, drawn again with `d`'s
/// designs `names`.
pub(crate) fn redraw_detached(d: &mut Document, n: &mut Node, names: &BTreeSet<String>) {
if holds(n, names) {
redraw_in(d, n, names);
}
}
/// Whether `n`'s subtree, the art of opacity masks included, holds a graph that draws a series
/// with one of the designs `names`.
pub(crate) fn holds_designs(n: &Node, names: &BTreeSet<String>) -> bool {
holds(n, names)
}
/// Draw the graphs in the subtrees of `ids` again that draw a series with one of the designs
/// `names`: pasted graphs, after the paste kept the document's own designs of those names.
pub(crate) fn redraw_with_designs(d: &mut Document, ids: &[super::NodeId], names: &std::collections::BTreeSet<String>) -> Result<()> {
for id in ids {
let Some(mut n) = d.node(*id).filter(|n| holds(n, names)).cloned() else { continue };
redraw_in(d, &mut n, names);
*d.node_mut(*id).ok_or(super::EngineError::NoNode(*id))? = n;
}
Ok(())
}
/// Draw the graphs in the art of symbols `symbols` again that draw a series with one of the
/// designs `names`: graphs of the symbols a paste added, after the paste kept the document's own
/// designs of those names.
pub(crate) fn redraw_symbols_with_designs(
d: &mut Document,
symbols: &std::collections::BTreeSet<String>,
names: &std::collections::BTreeSet<String>,
) {
for i in 0..d.symbols.len() {
let Some(s) = d.symbols.get(i).filter(|s| symbols.contains(&s.name) && holds(&s.art, names)) else { continue };
let old = s.art.clone();
let mut art = (*old).clone();
redraw_in(d, &mut art, names);
let Some(s) = d.symbols.get_mut(i) else { continue };
s.art = Arc::new(art);
// Instances' changes to parts the redraw replaced are dropped.
let name = s.name.clone();
crate::cmd::symboledit::follow_art_change(d, &name, &old);
}
}
/// Whether `n`'s subtree, the art of opacity masks included, holds a graph that draws a series
/// with one of the designs `names`.
fn holds(n: &Node, names: &std::collections::BTreeSet<String>) -> bool {
let mut found = false;
vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| {
found |= m.extras().graph.as_deref().is_some_and(|g| names.iter().any(|name| draws_with(g, name)));
});
found
}
/// Redraw the graphs of `n`'s subtree, the art of opacity masks included, that draw a series with
/// one of the designs `names`.
fn redraw_in(d: &mut Document, n: &mut Node, names: &std::collections::BTreeSet<String>) {
if let Some(mut art) = n.extras().mask.as_deref().filter(|m| holds(&m.art, names)).map(|m| (*m.art).clone()) {
redraw_in(d, &mut art, names);
if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) {
mask.art = Arc::new(art);
}
}
if n.extras().graph.as_deref().is_some_and(|g| names.iter().any(|name| draws_with(g, name))) {
regenerate_detached(d, n);
return;
}
if let Some(children) = n.children_mut() {
for c in children.iter_mut().filter(|c| holds(c, names)) {
redraw_in(d, Arc::make_mut(c), names);
}
}
}
/// The designs no graph's series draw with (Select Unused): graphs in the layers, in opacity-mask
/// art and in symbols' art count.
fn unused_designs(d: &Document) -> Vec<String> {
let mut used = std::collections::HashSet::new();
d.walk(|n| {
let mut note = |n: &Node| {
if let Some(g) = n.extras().graph.as_deref() {
used.extend(g.series_markers.iter().flatten().cloned());
used.extend(g.series_columns.iter().flatten().map(|c| c.design.clone()));
}
});
};
for art in d.layers.iter().chain(d.symbols.iter().map(|s| &s.art)) {
vectorcraft_doc::swatches::walk_with_masks(art, &mut note);
}
d.graph_designs.iter().map(|x| x.name.clone()).filter(|n| !used.contains(n)).collect()
}
/// Whether `n`'s subtree, the art of opacity masks included, holds a graph that names design
/// `name` for a series ([`names_design`]).
fn names_in(n: &Node, name: &str) -> bool {
let mut found = false;
vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| {
found |= m.extras().graph.as_deref().is_some_and(|g| names_design(g, name));
});
found
}
/// Graph `g`'s series that name design `old` name `new` instead.
fn rename_series(g: &mut GraphSpec, old: &str, new: &str) {
for m in g.series_markers.iter_mut().flatten().filter(|m| **m == old) {
*m = new.to_string();
}
for c in g.series_columns.iter_mut().flatten().filter(|c| c.design == old) {
c.design = new.to_string();
}
}
/// [`rename_series`] for the graphs of `n`'s subtree, the art of opacity masks included.
fn rename_in(n: &mut Node, old: &str, new: &str) {
if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()).filter(|m| names_in(&m.art, old)) {
rename_in(Arc::make_mut(&mut mask.art), old, new);
}
if let Some(g) = n.extras_if_any().and_then(|e| e.graph.as_deref_mut()) {
rename_series(g, old, new);
}
if let Some(children) = n.children_mut() {
for c in children.iter_mut().filter(|c| names_in(c, old)) {
rename_in(Arc::make_mut(c), old, new);
}
}
}
/// Design names from param `key`: one name or a list of names.
fn names_param(p: &Value, key: &str, cmd: &str) -> Result<Option<Vec<String>>> {
match p.get(key) {
@@ -105,22 +352,29 @@ pub(super) fn design(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(x) = d.graph_designs.iter_mut().find(|x| x.name == old) {
x.name = new.clone();
}
let mut graphs = vec![];
let (mut graphs, mut masked) = (vec![], vec![]);
d.walk(|n| {
if n.extras().graph.as_deref().is_some_and(|g| draws_with(g, &old)) {
if n.extras().graph.as_deref().is_some_and(|g| names_design(g, &old)) {
graphs.push(n.id);
}
if n.extras().mask.as_deref().is_some_and(|m| names_in(&m.art, &old)) {
masked.push(n.id);
}
});
for id in graphs {
if let Some(g) = d.node_mut(id).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) {
for m in g.series_markers.iter_mut().flatten().filter(|m| **m == old) {
*m = new.clone();
}
for c in g.series_columns.iter_mut().flatten().filter(|c| c.design == old) {
c.design = new.clone();
}
rename_series(g, &old, &new);
}
}
// The graphs in opacity-mask art and in symbols' art follow too, their art as it is.
for id in masked {
if let Some(mask) = d.node_mut(id).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_deref_mut()) {
rename_in(Arc::make_mut(&mut mask.art), &old, &new);
}
}
for s in d.symbols.iter_mut().filter(|s| names_in(&s.art, &old)) {
rename_in(Arc::make_mut(&mut s.art), &old, &new);
}
Ok(())
})?;
return Ok(json!({ "name": to }));
@@ -159,7 +413,29 @@ pub(super) fn design(s: &mut Session, p: &Value) -> Result<Value> {
})?;
return ok();
}
// Designs from a document loaded as a library: those the document has under the same name stay
// as they are.
if let Some(mut wanted) = names_param(p, "add", C)? {
let lib = library_param(s, p, C)?.ok_or_else(|| bad(C, "missing `library`"))?;
if let Some(n) = wanted.iter().find(|n| !lib.graph_designs.iter().any(|x| x.name == **n)) {
return Err(bad(C, format!("no design named `{n}`")));
}
let mut seen = std::collections::HashSet::new();
wanted.retain(|n| seen.insert(n.clone()));
let (existing, added): (Vec<String>, Vec<String>) = wanted.into_iter().partition(|n| taken(s, n));
if !added.is_empty() {
s.edit("New Design", |d, _| bring_in(d, &lib, &added))?;
}
return Ok(json!({ "added": added, "existing": existing }));
}
if let Some(lib) = library_param(s, p, C)? {
return Ok(json!({ "designs": design_names(&lib) }));
}
// The list, with the designs no graph draws with (Select Unused picks those).
let d = &s.doc()?.doc;
Ok(json!({ "designs": design_names(d), "unused": unused_designs(d) }))
let mut out = json!({ "designs": design_names(d), "unused": unused_designs(d) });
if let Some(libs) = libraries_json(s) {
out["libraries"] = libs;
}
Ok(out)
}
+27 -9
View File
@@ -109,6 +109,33 @@ pub(crate) fn edit_graph_art(n: &mut Node, edit: impl FnOnce(&mut Node)) {
/// generation, which is recorded in the spec's `placed_art` bounds, or `placed` in graphs saved without them).
pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> Result<()> {
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
carry_moves(n, &mut spec);
let children = generate(d, &spec);
spec.placed = children_bounds(&children);
spec.placed_art = art_bounds(&children);
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
if let Some(ch) = n.children_mut() {
*ch = children;
}
n.extras_mut().graph = Some(Box::new(spec));
Ok(())
}
/// [`regenerate`] graph `n` from its own spec, where `n` is outside `d`'s layers (in a symbol's art).
pub(super) fn regenerate_detached(d: &mut Document, n: &mut Node) {
let Some(mut spec) = n.extras().graph.as_deref().cloned() else { return };
carry_moves(n, &mut spec);
let children = generate(d, &spec);
spec.placed = children_bounds(&children);
spec.placed_art = art_bounds(&children);
if let Some(ch) = n.children_mut() {
*ch = children;
}
n.extras_mut().graph = Some(Box::new(spec));
}
/// Adjust `spec`'s plot rect for any move or scale of graph `n` since its last generation.
fn carry_moves(n: &Node, spec: &mut GraphSpec) {
if let Some((placed, now)) = measured(n)
&& placed.width() > 1e-9
&& placed.height() > 1e-9
@@ -119,15 +146,6 @@ pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> R
* Affine::translate(-placed.origin().to_vec2());
spec.rect = a.transform_rect_bbox(spec.rect);
}
let children = generate(d, &spec);
spec.placed = children_bounds(&children);
spec.placed_art = art_bounds(&children);
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
if let Some(ch) = n.children_mut() {
*ch = children;
}
n.extras_mut().graph = Some(Box::new(spec));
Ok(())
}
pub(super) fn create(s: &mut Session, p: &Value) -> Result<Value> {
+22 -4
View File
@@ -1,4 +1,4 @@
use super::designs::design_names;
use super::designs::{bring_in_for, design_names, from_library, libraries_json};
use super::edit::{regenerate, spec_of, target};
use super::series::{picked_series, reselect_series};
use super::{Affine, Arc, Document, GraphSpec, Node, NodeKind, Rect, Result, Session, Value, bad, json};
@@ -55,7 +55,7 @@ pub(super) fn set_marker(s: &mut Session, p: &Value) -> Result<Value> {
let mut spec = spec_of(s, id)?;
let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).min(vectorcraft_doc::MAX_GRAPH_SERIES);
let picked = picked_series(s, p, id, count, C)?;
let names = design_names(&s.doc()?.doc);
let mut names = design_names(&s.doc()?.doc);
let Some(v) = p.get("design") else {
// The design the picked series (all of them with none picked) share, or null.
let all: Vec<usize> = if picked.is_empty() { (0..count).collect() } else { picked };
@@ -63,8 +63,15 @@ pub(super) fn set_marker(s: &mut Session, p: &Value) -> Result<Value> {
let used: Vec<Option<&String>> =
all.iter().map(|i| spec.series_markers.get(*i).and_then(Option::as_ref).filter(|n| names.contains(n))).collect();
let shared = used.first().copied().flatten().filter(|d| used.iter().all(|x| *x == Some(*d)));
return Ok(json!({ "designs": names, "design": shared }));
let mut out = json!({ "designs": names, "design": shared });
if let Some(libs) = libraries_json(s) {
out["libraries"] = libs;
}
return Ok(out);
};
// A design of a loaded library comes into the document in the same undo step.
let library = from_library(s, p, C)?;
names.extend(library.as_ref().map(|(_, n)| n.clone()));
let design = match v {
Value::Null => None,
Value::String(n) if names.contains(n) => Some(n.clone()),
@@ -83,10 +90,21 @@ pub(super) fn set_marker(s: &mut Session, p: &Value) -> Result<Value> {
while spec.series_markers.last().is_some_and(Option::is_none) {
spec.series_markers.pop();
}
if marker_cost(&spec, &marker_designs(&s.doc()?.doc, &spec)) > MARKER_BUDGET {
let cost = match &library {
Some((lib, name)) => {
let mut probe = (*s.doc()?.doc).clone();
bring_in_for(&mut probe, lib, name, id, &mut spec)?;
marker_cost(&spec, &marker_designs(&probe, &spec))
}
None => marker_cost(&spec, &marker_designs(&s.doc()?.doc, &spec)),
};
if cost > MARKER_BUDGET {
return Err(bad(C, "the design is too big to draw at every data point of this graph"));
}
s.edit("Graph Marker", |d, sel| {
if let Some((lib, name)) = &library {
bring_in_for(d, lib, name, id, &mut spec)?;
}
regenerate(d, id, spec)?;
if !reselect.is_empty() {
reselect_series(d, sel, id, &reselect);
+958
View File
@@ -5469,6 +5469,964 @@ fn graph_designs_are_saved_pasted_and_deleted() {
assert!(series_parts(&s, id, 0).iter().all(|n| matches!(n.kind, NodeKind::Path { .. })));
}
/// Graph design "Coin" in the active document: a 10 × 10 rectangle filled with global swatch "Gold".
fn save_coin_design(s: &mut Session) {
s.execute("swatch.new", &json!({"name": "Gold", "color": "#d4a017", "global": true})).unwrap();
let r = s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"swatch": "Gold", "ids": [r]})).unwrap();
s.execute("select.set", &json!({"ids": [r]})).unwrap();
s.execute("graph.design", &json!({"new": "Coin"})).unwrap();
}
/// Load a saved document holding [`save_coin_design`]'s design as a swatch library (Other
/// Library…) → its id.
fn load_coin_library(s: &mut Session) -> String {
let mut src = Session::new();
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut src);
let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc);
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Coins.vectorcraft"});
let r = s.execute("swatch.library.load", &p).unwrap();
assert_eq!(r["graphDesigns"], 1);
r["library"].as_str().unwrap().to_string()
}
fn undo_len(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
/// Whether some object of `n` is filled with a colour linked to swatch `name`.
fn paints_with_swatch(n: &vectorcraft_doc::Node, name: &str) -> bool {
let mut found = false;
n.walk(&mut |m| found |= m.appearance.items.iter().any(|it| matches!(it.paint(), Paint::Solid { swatch: Some(w), .. } if w == name)));
found
}
#[test]
fn designs_of_a_document_loaded_as_a_swatch_library_come_in_when_applied() {
let mut s = Session::new();
let lib = load_coin_library(&mut s);
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
// The Column dialog's list: none of the document's, Coin from the library.
let q = s.execute("graph.column", &json!({})).unwrap();
assert_eq!((q["designs"].clone(), q["libraries"][0]["library"].clone()), (json!([]), json!(lib)));
assert_eq!(q["libraries"][0]["designs"], json!(["Coin"]));
assert!(s.execute("graph.column", &json!({"design": "Coin"})).is_err(), "not the document's");
let steps = undo_len(&s);
s.execute("graph.column", &json!({"design": "Coin", "library": lib})).unwrap();
assert_eq!(undo_len(&s), steps + 1, "one undo step");
let d = &s.doc().unwrap().doc;
assert_eq!(d.graph_designs.iter().map(|g| g.name.as_str()).collect::<Vec<_>>(), ["Coin"]);
assert!(d.swatch("Gold").is_some_and(|w| w.global), "the swatch the design's art uses comes along");
assert!(paints_with_swatch(&d.graph_designs[0].art, "Gold"));
assert!(paints_with_swatch(series(d.node(id).unwrap(), 0), "Gold"), "the columns draw the design");
// Undo takes the design, its swatch and the columns' design out together.
s.execute("edit.undo", &json!({})).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.graph_designs.is_empty() && d.swatch("Gold").is_none() && spec(&s, id).series_columns.is_empty());
// Marker takes them too.
let line = graph(&mut s, "line");
s.execute("select.set", &json!({"ids": [line.0]})).unwrap();
s.execute("graph.marker", &json!({"design": "Coin", "library": lib})).unwrap();
assert_eq!(spec(&s, line).series_markers, [Some("Coin".to_string()), Some("Coin".to_string())]);
assert!(s.doc().unwrap().doc.swatch("Gold").is_some());
// An unknown library or design, and a library that is not a string, are refused.
for p in [json!({"design": "Coin", "library": "Nope"}), json!({"design": "Nope", "library": lib}), json!({"design": "Coin", "library": 3})] {
assert!(s.execute("graph.column", &p).is_err(), "{p}");
}
}
#[test]
fn a_library_design_applied_to_a_moved_graph_that_names_it_keeps_the_graph_in_place() {
let mut s = Session::new();
let lib = load_coin_library(&mut s);
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
// A library's name works in any case, as swatch library names do.
assert_eq!(s.execute("graph.design", &json!({"library": "COINS"})).unwrap(), json!({"designs": ["Coin"]}));
for (kind, cmd) in [("line", "graph.marker"), ("column", "graph.column")] {
// The graph names design "Coin", which the document no longer has, and is moved after.
save_design(&mut s, "Coin");
let id = graph(&mut s, kind);
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute(cmd, &json!({"design": "Coin"})).unwrap();
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
let rect = spec(&s, id).rect;
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("object.move", &json!({"dx": 40, "dy": -10})).unwrap();
s.execute(cmd, &json!({"id": id.0, "design": "Coin", "library": lib})).unwrap();
let now = spec(&s, id).rect;
assert!((now.x0 - (rect.x0 + 40.0)).abs() < 1e-6 && (now.y0 - (rect.y0 - 10.0)).abs() < 1e-6, "{cmd}: {now:?}");
assert!((now.width() - rect.width()).abs() < 1e-6 && (now.height() - rect.height()).abs() < 1e-6, "{cmd}: {now:?}");
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
}
}
#[test]
fn a_design_the_document_has_under_the_same_name_stays_as_it_is() {
let mut s = Session::new();
let lib = load_coin_library(&mut s);
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
let own = s.doc().unwrap().doc.graph_designs[0].art.clone();
assert_eq!(s.execute("graph.design", &json!({"library": lib})).unwrap(), json!({"designs": ["Coin"]}));
let steps = undo_len(&s);
let r = s.execute("graph.design", &json!({"library": lib, "add": ["Coin", "Coin"]})).unwrap();
assert_eq!(r, json!({"added": [], "existing": ["Coin"]}));
assert_eq!(undo_len(&s), steps, "nothing changed: no undo step");
// Applying it with the library draws with the document's own design.
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin", "library": lib})).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.graph_designs.len() == 1 && std::sync::Arc::ptr_eq(&d.graph_designs[0].art, &own));
assert!(d.swatch("Gold").is_none());
assert!(s.execute("graph.design", &json!({"add": "Coin"})).is_err(), "no library");
assert!(s.execute("graph.design", &json!({"library": lib, "add": "Nope"})).is_err());
assert!(s.execute("graph.design", &json!({"library": lib, "add": 4})).is_err());
// The document without it takes it as one undo step.
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let r = s.execute("graph.design", &json!({"library": "Coins", "add": "Coin"})).unwrap();
assert_eq!(r, json!({"added": ["Coin"], "existing": []}));
assert!(s.doc().unwrap().doc.swatch("Gold").is_some());
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.graph_designs.is_empty());
}
#[test]
fn a_pasted_graph_brings_the_designs_its_series_draw_with() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut s);
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
s.execute("edit.paste", &json!({})).unwrap();
let d = &s.doc().unwrap().doc;
assert_eq!(d.graph_designs.iter().map(|g| g.name.as_str()).collect::<Vec<_>>(), ["Coin"]);
assert!(paints_with_swatch(&d.graph_designs[0].art, "Gold") && d.swatch("Gold").is_some());
// A data edit redraws the pasted graph with the design.
let pasted = s.doc().unwrap().selection.objects.to_vec()[0];
s.execute("graph.setData", &json!({"id": pasted.0, "csv": ",A\nQ1,4\nQ2,6"})).unwrap();
assert!(paints_with_swatch(series(s.doc().unwrap().doc.node(pasted).unwrap(), 0), "Gold"));
// A document with its own design of that name keeps it.
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
let own = s.doc().unwrap().doc.graph_designs[0].art.clone();
s.execute("edit.paste", &json!({})).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.graph_designs.len() == 1 && std::sync::Arc::ptr_eq(&d.graph_designs[0].art, &own));
// The pasted graph is drawn with that design straight away.
let pasted = s.doc().unwrap().selection.objects.to_vec()[0];
// The document's design is a rectangle and an ellipse, the pasted one a rectangle alone: each
// column and the legend swatch hold two paths.
let paths = |n: &vectorcraft_doc::Node| {
let mut count = 0;
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
count
};
let columns: Vec<usize> = series(d.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| paths(n)).collect();
assert_eq!(columns, [2, 2, 2, 2], "drawn with the document's design");
}
#[test]
fn a_design_the_document_keeps_brings_none_of_the_pasted_designs_resources() {
// A column graph whose spec names marker design "Coin", which only line series draw: the
// graph's own art does not use the design's swatch.
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut s);
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.marker", &json!({"design": "Coin"})).unwrap();
assert!(spec(&s, id).series_markers.iter().any(|m| m.as_deref() == Some("Coin")));
assert!(!paints_with_swatch(s.doc().unwrap().doc.node(id).unwrap(), "Gold"));
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
// A document with its own "Coin" keeps it and takes nothing the pasted design's art uses.
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
s.execute("edit.paste", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.swatch("Gold").is_none());
// A document without one takes the design and its swatch.
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
s.execute("edit.paste", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.swatch("Gold").is_some());
}
#[test]
fn a_pasted_graph_naming_a_deleted_design_draws_with_the_documents_design_of_that_name() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut s);
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
assert!(spec(&s, id).series_columns.iter().flatten().any(|c| c.design == "Coin"), "the graph still names it");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
s.execute("edit.paste", &json!({})).unwrap();
let pasted = s.doc().unwrap().selection.objects.to_vec()[0];
let paths = |n: &vectorcraft_doc::Node| {
let mut count = 0;
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
count
};
let d = &s.doc().unwrap().doc;
let columns: Vec<usize> = series(d.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| paths(n)).collect();
assert_eq!(columns, [2, 2, 2, 2], "drawn with the document's design");
}
#[test]
fn a_pasted_graph_keeps_its_art_when_only_a_resource_its_design_does_not_use_comes_in_renamed() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
s.execute("swatch.new", &json!({"name": "Ink", "color": "#ff0000", "global": true})).unwrap();
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"swatch": "Ink", "ids": [r]})).unwrap();
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
// An edit of the graph's art that drawing the graph again would not keep.
let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
s.edit("Name", |d, _| {
if let Some(n) = d.node_mut(mark) {
n.name = Some("Mine".into());
}
Ok(())
})
.unwrap();
// A copy of the document holds the same design; its "Ink" is another color, so the pasted
// rectangle's swatch takes the document's color, or with "add" comes in renamed.
let saved = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&s.doc().unwrap().doc));
s.execute("select.set", &json!({"ids": [id.0, r]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
s.execute("document.open", &json!({"name": "b.vectorcraft", "dataBase64": saved})).unwrap();
s.execute("swatch.edit", &json!({"name": "Ink", "color": "#0000ff"})).unwrap();
for conflict in ["merge", "add"] {
let r = s.execute("edit.paste", &json!({"swatchConflict": conflict})).unwrap();
let ink_renamed = r["renamed"].as_array().is_some_and(|a| a.iter().any(|x| x["from"] == "Ink"));
let expected = if conflict == "merge" { (json!(1), false) } else { (json!(0), true) };
assert_eq!((r["merged"].clone(), ink_renamed), expected, "{conflict}: {r}");
let st = s.doc().unwrap();
let d = &st.doc;
let pasted = st.selection.objects.iter().copied().find(|i| d.node(*i).is_some_and(|n| n.extras().graph.is_some())).unwrap();
let names: Vec<Option<String>> = series(d.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| n.name.clone()).collect();
assert_eq!(names[0].as_deref(), Some("Mine"), "{conflict}: not drawn again: {names:?}");
}
}
#[test]
fn a_pasted_graph_is_drawn_again_when_its_designs_svg_filter_comes_in_under_another_name() {
const SHIFT: &str = r#"<filter id="Shift"><feOffset dx="3" dy="3"/></filter>"#;
const SHIFT_MORE: &str = r#"<filter id="Shift"><feOffset dx="9" dy="9"/></filter>"#;
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
s.execute("svgFilter.define", &json!({"xml": SHIFT})).unwrap();
let r = s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("svgFilter.apply", &json!({"name": "Shift", "ids": [r]})).unwrap();
s.execute("select.set", &json!({"ids": [r]})).unwrap();
s.execute("graph.design", &json!({"new": "Coin"})).unwrap();
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
s.edit("Name", |d, _| {
if let Some(n) = d.node_mut(mark) {
n.name = Some("Mine".into());
}
Ok(())
})
.unwrap();
// A copy of the document holds the same design, but its "Shift" filter draws otherwise, so the
// pasted graph's filter keeps its own definition under another name.
let saved = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&s.doc().unwrap().doc));
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
s.execute("document.open", &json!({"name": "b.vectorcraft", "dataBase64": saved})).unwrap();
s.execute("svgFilter.define", &json!({"xml": SHIFT_MORE, "replace": "Shift"})).unwrap();
s.execute("edit.paste", &json!({})).unwrap();
let st = s.doc().unwrap();
let pasted = st.selection.objects.to_vec()[0];
let names: Vec<Option<String>> = series(st.doc.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| n.name.clone()).collect();
assert_ne!(names[0].as_deref(), Some("Mine"), "drawn again with the document's design: {names:?}");
}
#[test]
fn a_symbol_pasted_with_a_graph_inside_draws_it_with_the_documents_design_of_that_name() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut s);
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let instance = s.execute("symbol.new", &json!({"name": "Chart"})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [instance]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
// A document whose "Coin" is a rectangle and an ellipse: the symbol's graph draws with it.
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
s.execute("edit.paste", &json!({})).unwrap();
let d = &s.doc().unwrap().doc;
let art = &d.symbols.iter().find(|x| x.name == "Chart").expect("the symbol came in").art;
let mut graphs = vec![];
art.walk(&mut |m| {
if m.extras().graph.is_some() {
graphs.push(m.clone());
}
});
let paths = |n: &vectorcraft_doc::Node| {
let mut count = 0;
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
count
};
let columns: Vec<usize> = series(&graphs[0], 0).children().unwrap().iter().map(|n| paths(n)).collect();
assert_eq!(columns, [2, 2, 2, 2], "drawn with the document's design");
}
#[test]
fn a_design_brought_in_from_a_library_redraws_the_graphs_in_symbols_that_name_it() {
let mut s = Session::new();
let lib = load_coin_library(&mut s);
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
// A graph that names "Coin", which the document no longer has, kept as a symbol's art.
save_design(&mut s, "Coin");
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap();
s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap();
let d = &s.doc().unwrap().doc;
let art = &d.symbols.iter().find(|x| x.name == "Chart").unwrap().art;
let mut graphs = vec![];
art.walk(&mut |m| {
if m.extras().graph.is_some() {
graphs.push(m.clone());
}
});
assert!(paints_with_swatch(series(&graphs[0], 0), "Gold"), "drawn with the library's design");
}
#[test]
fn a_design_brought_in_from_a_library_leaves_a_scatter_graph_that_names_it_for_a_slot_it_does_not_plot() {
let mut s = Session::new();
let lib = load_coin_library(&mut s);
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
// Four data columns plot two series, so marker slot 2 is never drawn.
let id = make(&mut s, "scatter", ",y1,x1,y2,x2\nP,1,10,2,20\nQ,3,11,4,22");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
assert!(spec(&s, id).mark_points, "Mark Data Points is on");
s.execute("graph.marker", &json!({"design": "Coin", "library": lib, "seriesIndexes": [2]})).unwrap();
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
assert_eq!(spec(&s, id).series_markers.get(2).cloned().flatten().as_deref(), Some("Coin"));
// An edit of the graph's art that drawing the graph again would not keep.
let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
s.edit("Name", |d, _| {
if let Some(n) = d.node_mut(mark) {
n.name = Some("Mine".into());
}
Ok(())
})
.unwrap();
s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap();
let names: Vec<Option<String>> = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap().iter().map(|n| n.name.clone()).collect();
assert_eq!(names[0].as_deref(), Some("Mine"), "not drawn again: {names:?}");
}
#[test]
fn a_symbol_a_library_design_brings_draws_its_graph_with_the_documents_design_it_keeps() {
// The library's design "A" holds an instance of symbol "Chart", whose graph draws columns with
// the library's "B": a rectangle and an ellipse.
let mut src = Session::new();
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut src, "B");
let id = graph(&mut src, "column");
src.execute("select.set", &json!({"ids": [id.0]})).unwrap();
src.execute("graph.column", &json!({"design": "B"})).unwrap();
let instance = src.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap();
src.execute("select.set", &json!({"ids": [instance]})).unwrap();
src.execute("graph.design", &json!({"new": "A"})).unwrap();
let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc);
let mut s = Session::new();
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Lib.vectorcraft"});
let lib = s.execute("swatch.library.load", &p).unwrap()["library"].as_str().unwrap().to_string();
// The document's own "B" is a single rectangle, and stays.
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let r = s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [r]})).unwrap();
s.execute("graph.design", &json!({"new": "B"})).unwrap();
s.execute("graph.design", &json!({"library": lib, "add": "A"})).unwrap();
let d = &s.doc().unwrap().doc;
assert_eq!(d.graph_designs.len(), 2, "A came in and B stayed");
let art = &d.symbols.iter().find(|x| x.name == "Chart").expect("the symbol came in").art;
let mut graphs = vec![];
art.walk(&mut |m| {
if m.extras().graph.is_some() {
graphs.push(m.clone());
}
});
let paths = |n: &vectorcraft_doc::Node| {
let mut count = 0;
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
count
};
let columns: Vec<usize> = series(&graphs[0], 0).children().unwrap().iter().map(|n| paths(n)).collect();
assert_eq!(columns, [1, 1, 1, 1], "drawn with the document's B");
}
#[test]
fn a_design_brought_in_from_a_library_redraws_a_graph_in_an_opacity_mask() {
let mut s = Session::new();
let lib = load_coin_library(&mut s);
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap();
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
s.execute("select.set", &json!({"ids": [r, id.0]})).unwrap();
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap();
let mut graphs = vec![];
vectorcraft_doc::swatches::walk_with_masks(s.doc().unwrap().doc.node(NodeId(r)).unwrap(), &mut |m| {
if m.extras().graph.is_some() {
graphs.push(m.clone());
}
});
assert!(paints_with_swatch(series(&graphs[0], 0), "Gold"), "drawn with the library's design");
}
#[test]
fn an_instance_drops_its_changes_to_graph_parts_a_design_change_redraws() {
use vectorcraft_doc::symbol_overrides::SymbolOverride;
let mut s = Session::new();
let lib = load_coin_library(&mut s);
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
let instance = s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0], "type": "dynamic"})).unwrap()["id"].as_u64().unwrap();
let instance = NodeId(instance);
// A change to the graph itself, and one to a part of it that drawing it again replaces.
let changes = vec![
SymbolOverride { path: vec![], opacity: Some(0.5), ..Default::default() },
SymbolOverride { path: vec![0], opacity: Some(0.25), ..Default::default() },
];
s.edit("Change", |d, _| {
if let Some(n) = d.node_mut(instance) {
n.extras_mut().symbol_overrides = changes;
}
Ok(())
})
.unwrap();
s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap();
let kept = s.doc().unwrap().doc.node(instance).unwrap().extras().symbol_overrides.clone();
assert_eq!(kept.iter().map(|o| o.path.clone()).collect::<Vec<_>>(), [Vec::<u32>::new()], "{kept:?}");
}
#[test]
fn a_graph_in_an_opacity_mask_draws_with_the_documents_design_when_pasted() {
let paths = |n: &vectorcraft_doc::Node| {
let mut count = 0;
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
count
};
let mask_graph = |n: &vectorcraft_doc::Node| {
let mut graphs = vec![];
vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| {
if m.extras().graph.is_some() {
graphs.push(m.clone());
}
});
graphs.into_iter().next().expect("the masked graph")
};
// In a symbol's art and among the pasted objects.
for in_symbol in [true, false] {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut s);
let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap();
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("select.set", &json!({"ids": [r, id.0]})).unwrap();
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
let copied = if in_symbol { s.execute("symbol.new", &json!({"name": "Masked", "ids": [r]})).unwrap()["id"].as_u64().unwrap() } else { r };
s.execute("select.set", &json!({"ids": [copied]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
s.execute("edit.paste", &json!({})).unwrap();
let st = s.doc().unwrap();
let g = if in_symbol {
mask_graph(&st.doc.symbols.iter().find(|x| x.name == "Masked").expect("the symbol came in").art)
} else {
mask_graph(st.doc.node(st.selection.objects.to_vec()[0]).unwrap())
};
let columns: Vec<usize> = series(&g, 0).children().unwrap().iter().map(|n| paths(n)).collect();
assert_eq!(columns, [2, 2, 2, 2], "in a symbol: {in_symbol}");
}
}
#[test]
fn a_graph_pasted_back_after_its_design_was_made_again_draws_with_the_new_design() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut s);
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
// Made again under the same name as a rectangle and an ellipse.
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
save_design(&mut s, "Coin");
s.execute("edit.paste", &json!({})).unwrap();
let pasted = s.doc().unwrap().selection.objects.to_vec()[0];
let paths = |n: &vectorcraft_doc::Node| {
let mut count = 0;
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
count
};
let d = &s.doc().unwrap().doc;
let columns: Vec<usize> = series(d.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| paths(n)).collect();
assert_eq!(columns, [2, 2, 2, 2], "drawn with the design the document has now");
}
/// The graphs in `n`'s subtree, those in opacity-mask art included.
fn graphs_in(n: &vectorcraft_doc::Node) -> Vec<vectorcraft_doc::Node> {
let mut graphs = vec![];
vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| {
if m.extras().graph.is_some() {
graphs.push(m.clone());
}
});
graphs
}
/// Load a saved document holding [`save_coin_design`]'s "Coin" and design "Chart", an instance of
/// symbol "Plot" whose column graph names "Coin" as its columns (`columns`) or only as a marker
/// its columns do not draw, as a swatch library → its id.
fn load_chart_library(s: &mut Session, columns: bool) -> String {
let mut src = Session::new();
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut src);
let id = graph(&mut src, "column");
src.execute("select.set", &json!({"ids": [id.0]})).unwrap();
src.execute(if columns { "graph.column" } else { "graph.marker" }, &json!({"design": "Coin"})).unwrap();
let instance = src.execute("symbol.new", &json!({"name": "Plot", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap();
src.execute("select.set", &json!({"ids": [instance]})).unwrap();
src.execute("graph.design", &json!({"new": "Chart"})).unwrap();
let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc);
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Charts.vectorcraft"});
s.execute("swatch.library.load", &p).unwrap()["library"].as_str().unwrap().to_string()
}
#[test]
fn a_library_design_brings_none_of_the_resources_of_a_design_the_document_keeps() {
let mut s = Session::new();
let lib = load_chart_library(&mut s, false);
// The document keeps its own "Coin": nothing the library's "Coin" uses comes in.
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
s.execute("graph.design", &json!({"library": lib, "add": "Chart"})).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.symbols.iter().any(|x| x.name == "Plot"), "the design's symbol came in");
assert!(d.swatch("Gold").is_none());
// A document without one takes the design and its swatch.
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
s.execute("graph.design", &json!({"library": lib, "add": "Chart"})).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.graph_designs.iter().any(|x| x.name == "Coin") && d.swatch("Gold").is_some());
}
#[test]
fn a_design_a_library_design_brings_along_redraws_the_graphs_that_name_it() {
let mut s = Session::new();
let lib = load_chart_library(&mut s, true);
// A graph that names "Coin", which the document no longer has.
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
let r = s.execute("graph.design", &json!({"library": lib, "add": "Chart"})).unwrap();
assert_eq!(r, json!({"added": ["Chart"], "existing": []}));
let d = &s.doc().unwrap().doc;
assert!(paints_with_swatch(series(d.node(id).unwrap(), 0), "Gold"), "drawn with the library's Coin");
}
#[test]
fn a_paste_that_adds_a_design_redraws_the_documents_graphs_that_name_it_and_not_the_pasted_ones() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut s);
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
// An edit of the copied graph's art that drawing it again would not keep.
let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
s.edit("Name", |d, _| {
if let Some(n) = d.node_mut(mark) {
n.name = Some("Mine".into());
}
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
// A document whose graph names "Coin", which it no longer has.
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
let own = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [own.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
s.execute("edit.paste", &json!({})).unwrap();
let st = s.doc().unwrap();
assert!(paints_with_swatch(series(st.doc.node(own).unwrap(), 0), "Gold"), "drawn with the pasted Coin");
let pasted = st.selection.objects.to_vec()[0];
let first = series(st.doc.node(pasted).unwrap(), 0).children().unwrap()[0].name.clone();
assert_eq!(first.as_deref(), Some("Mine"), "the pasted graph is not drawn again");
}
#[test]
fn a_paste_that_adds_a_marker_design_a_graph_does_not_show_leaves_that_graph_as_it_is() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut s);
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
// A line graph whose series name "Coin", which the document no longer has, as a marker that
// Mark Data Points does not show, with no legend or with a legend that has no entry for them.
for (legend, csv) in [(false, ",2024,2025\nQ1,3,2\nQ2,5,4"), (true, ",,\nQ1,3,2\nQ2,5,4")] {
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
let p = json!({"type": "line", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv});
let own = NodeId(s.execute("graph.create", &p).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [own.0]})).unwrap();
s.execute("graph.marker", &json!({"design": "Coin"})).unwrap();
s.execute("graph.setType", &json!({"id": own.0, "markPoints": false, "legend": legend})).unwrap();
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
let mark = series(s.doc().unwrap().doc.node(own).unwrap(), 0).children().unwrap()[0].id;
s.edit("Name", |d, _| {
if let Some(n) = d.node_mut(mark) {
n.name = Some("Mine".into());
}
Ok(())
})
.unwrap();
s.execute("edit.paste", &json!({})).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.graph_designs.iter().any(|x| x.name == "Coin"), "legend {legend}: the paste added Coin");
let first = series(d.node(own).unwrap(), 0).children().unwrap()[0].name.clone();
assert_eq!(first.as_deref(), Some("Mine"), "legend {legend}: not drawn again");
}
}
#[test]
fn a_symbol_pasted_twice_with_a_graph_the_document_draws_again_is_added_once() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut s);
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
let instance = s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [instance]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
// A document whose "Coin" is other art: the first paste draws the symbol's graph with it.
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
// The paths of each column of the symbol's graph: 2 for the document's Coin, 1 for the copied one.
let columns = |s: &Session| {
let art = s.doc().unwrap().doc.symbols.iter().find(|x| x.name == "Chart").unwrap().art.clone();
let graph = graphs_in(&art).remove(0);
let paths = |n: &vectorcraft_doc::Node| {
let mut count = 0;
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
count
};
series(&graph, 0).children().unwrap().iter().map(|n| paths(n)).collect::<Vec<usize>>()
};
s.execute("edit.paste", &json!({})).unwrap();
assert_eq!(columns(&s), [2, 2, 2, 2], "the first paste draws with the document's Coin");
s.execute("edit.paste", &json!({})).unwrap();
let d = &s.doc().unwrap().doc;
let names: Vec<&str> = d.symbols.iter().map(|x| x.name.as_str()).filter(|n| n.starts_with("Chart")).collect();
assert_eq!(names, ["Chart"]);
assert_eq!(columns(&s), [2, 2, 2, 2], "drawn with the document's Coin");
}
#[test]
fn a_symbol_pasted_twice_whose_designs_swatch_takes_the_documents_color_is_added_once() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut s);
// A copy of the document holds the same "Coin"; its "Gold" is another color.
let saved = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&s.doc().unwrap().doc));
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
let instance = s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [instance]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
for conflict in ["merge", "add"] {
s.execute("document.open", &json!({"name": format!("{conflict}.vectorcraft"), "dataBase64": saved})).unwrap();
s.execute("swatch.edit", &json!({"name": "Gold", "color": "#0000ff"})).unwrap();
let r = s.execute("edit.paste", &json!({"swatchConflict": conflict})).unwrap();
let gold_renamed = r["renamed"].as_array().is_some_and(|a| a.iter().any(|x| x["from"] == "Gold"));
let expected = if conflict == "merge" { (json!(1), false) } else { (json!(0), true) };
assert_eq!((r["merged"].clone(), gold_renamed), expected, "{conflict}: {r}");
s.execute("edit.paste", &json!({"swatchConflict": conflict})).unwrap();
let d = &s.doc().unwrap().doc;
let names: Vec<&str> = d.symbols.iter().map(|x| x.name.as_str()).filter(|n| n.starts_with("Chart")).collect();
assert_eq!(names, ["Chart"], "{conflict}");
}
}
#[test]
fn a_pasted_graph_that_only_names_a_kept_design_as_an_undrawn_marker_keeps_its_art() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut s);
// A column graph whose series name "Coin" as a marker, which columns do not draw.
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.marker", &json!({"design": "Coin"})).unwrap();
let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
s.edit("Name", |d, _| {
if let Some(n) = d.node_mut(mark) {
n.name = Some("Mine".into());
}
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
s.execute("edit.paste", &json!({})).unwrap();
let st = s.doc().unwrap();
let pasted = st.selection.objects.to_vec()[0];
let first = series(st.doc.node(pasted).unwrap(), 0).children().unwrap()[0].name.clone();
assert_eq!(first.as_deref(), Some("Mine"), "not drawn again");
}
#[test]
fn renaming_a_design_renames_it_in_the_graphs_of_symbols_and_opacity_masks() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut s);
let in_symbol = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [in_symbol.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("symbol.new", &json!({"name": "Chart", "ids": [in_symbol.0]})).unwrap();
let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap();
let masked = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [masked.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("select.set", &json!({"ids": [r, masked.0]})).unwrap();
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
let before = graphs_in(&s.doc().unwrap().doc.symbols.iter().find(|x| x.name == "Chart").unwrap().art);
s.execute("graph.design", &json!({"rename": "Coin", "to": "Medal"})).unwrap();
let d = &s.doc().unwrap().doc;
let symbol = graphs_in(&d.symbols.iter().find(|x| x.name == "Chart").unwrap().art);
let mask = graphs_in(d.node(NodeId(r)).unwrap());
for (where_, g) in [("symbol", &symbol[0]), ("mask", &mask[0])] {
let designs: Vec<String> = g.extras().graph.as_deref().unwrap().series_columns.iter().flatten().map(|c| c.design.clone()).collect();
assert!(!designs.is_empty() && designs.iter().all(|n| n == "Medal"), "{where_}: {designs:?}");
}
assert_eq!(symbol[0].children(), before[0].children(), "the symbol's graph keeps its art");
}
#[test]
fn a_design_only_a_graph_in_a_symbol_or_a_mask_draws_with_is_not_unused() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
save_design(&mut s, "Pill");
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap();
let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap();
let masked = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [masked.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Pill"})).unwrap();
s.execute("select.set", &json!({"ids": [r, masked.0]})).unwrap();
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
assert_eq!(s.execute("graph.design", &json!({})).unwrap()["unused"], json!([]));
}
#[test]
fn a_library_copied_to_user_defined_keeps_its_graph_designs_under_the_loaded_id() {
let dir = vectorcraft_testkit::TempDir::new("graph-design-library-user");
let mut s = Session::new();
s.swatch_libraries.set_user_dir(Some(dir.to_string_lossy().to_string()));
let loaded = load_coin_library(&mut s);
// The User Defined copy is a swatch file: it holds the swatches alone.
let copy = s.execute("swatch.library.copyToUser", &json!({"library": loaded})).unwrap()["library"].as_str().unwrap().to_string();
assert_ne!(copy, loaded);
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let libraries = s.execute("graph.design", &json!({})).unwrap()["libraries"].clone();
assert_eq!(libraries, json!([{"library": loaded, "name": libraries[0]["name"], "designs": ["Coin"]}]));
assert_eq!(s.execute("graph.design", &json!({"library": loaded})).unwrap(), json!({"designs": ["Coin"]}));
assert!(s.execute("graph.design", &json!({"library": copy})).is_err());
}
#[test]
fn a_swatch_library_file_over_the_size_limit_is_refused_before_it_is_read() {
let dir = vectorcraft_testkit::TempDir::new("graph-design-library-size");
let path = dir.join("big.vectorcraft");
let f = std::fs::File::create(&path).unwrap();
f.set_len(((256 << 20) + 1) as u64).unwrap();
let mut s = Session::new();
let e = s.execute("swatch.library.load", &json!({"path": path})).unwrap_err().to_string();
assert!(e.contains("larger than 256 MB"), "{e}");
}
#[test]
fn a_document_with_graph_designs_and_no_swatches_loads_for_its_designs() {
let mut src = Session::new();
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut src, "Pill");
let mut d = (*src.doc().unwrap().doc).clone();
d.swatches.clear();
d.swatch_groups.clear();
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&d)), "name": "Pills.vectorcraft"});
let mut s = Session::new();
let r = s.execute("swatch.library.load", &p).unwrap();
assert_eq!((r["count"].clone(), r["graphDesigns"].clone()), (json!(0), json!(1)));
// Without graph designs it has nothing to offer.
d.graph_designs.clear();
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&d)), "name": "Bare.vectorcraft"});
let e = s.execute("swatch.library.load", &p).unwrap_err().to_string();
assert!(e.contains("has no swatches of its own"), "{e}");
}
#[test]
fn a_design_library_keeps_the_sources_color_for_a_default_swatch_name() {
let mut src = Session::new();
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
// A default swatch the source made global and gave another color, used by a design.
let name = src.doc().unwrap().doc.swatches.iter().find(|w| !w.name.starts_with('[')).unwrap().name.clone();
let mine = Paint::solid(vectorcraft_color::Color::rgb(0.1, 0.7, 0.3));
let (n, p) = (name.clone(), mine.clone());
src.edit("Change", move |d, _| {
if let Some(w) = d.swatches.iter_mut().find(|w| w.name == n) {
w.paint = p;
w.global = true;
}
Ok(())
})
.unwrap();
let r = src.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
src.execute("paint.setFill", &json!({"swatch": name, "ids": [r]})).unwrap();
src.execute("select.set", &json!({"ids": [r]})).unwrap();
src.execute("graph.design", &json!({"new": "Green"})).unwrap();
let lib = crate::cmd::clipboard::resources::graph_design_library(&src.doc().unwrap().doc).unwrap();
let named: Vec<_> = lib.swatches.iter().filter(|w| w.name == name).collect();
assert_eq!(named.len(), 1, "one swatch named {name}");
assert_eq!(named[0].paint, mine);
// And one named like a swatch in a default group.
let grouped = src.doc().unwrap().doc.swatch_groups.iter().flat_map(|g| g.swatches.iter()).next().unwrap().name.clone();
let (n, p) = (grouped.clone(), mine.clone());
src.edit("Change", move |d, _| {
if let Some(w) = d.swatch_groups.iter_mut().flat_map(|g| g.swatches.iter_mut()).find(|w| w.name == n) {
w.paint = p;
w.global = true;
}
Ok(())
})
.unwrap();
let r = src.execute("shape.rectangle", &json!({"x": 650, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
src.execute("paint.setFill", &json!({"swatch": grouped, "ids": [r]})).unwrap();
src.execute("select.set", &json!({"ids": [r]})).unwrap();
src.execute("graph.design", &json!({"new": "Grouped"})).unwrap();
let lib = crate::cmd::clipboard::resources::graph_design_library(&src.doc().unwrap().doc).unwrap();
let all: Vec<_> = lib.swatches.iter().chain(lib.swatch_groups.iter().flat_map(|g| g.swatches.iter())).filter(|w| w.name == grouped).collect();
assert_eq!(all.len(), 1, "one swatch named {grouped}");
}
#[test]
fn inline_swatch_library_data_over_the_size_limit_is_refused_before_it_is_read() {
// With a limit of 3 bytes: text and base64 of 3 bytes pass, and of 4 bytes are refused.
let too_big = |p: serde_json::Value| crate::cmd::swatchlib::library_too_big(&p, "swatch.library.load", 3).unwrap();
assert!(!too_big(json!({"data": "abc"})));
assert!(too_big(json!({"data": "abcd"})));
let b64 = |n: usize| vectorcraft_format::base64_encode(&vec![7u8; n]);
assert!(!too_big(json!({"dataBase64": b64(3)})));
assert!(too_big(json!({"dataBase64": b64(4)})));
}
#[test]
fn a_swatch_library_file_is_read_no_further_than_the_size_limit() {
let dir = vectorcraft_testkit::TempDir::new("graph-design-library-bound");
let path = dir.join("grown.gpl");
std::fs::write(&path, [b'a'; 9]).unwrap();
let mut s = Session::new();
let p = json!({"path": path});
let parsed = |_: &[u8], _: &str| Err(crate::EngineError::Other("parsed".into()));
// A file that grew past the limit after the size check is refused when it is read.
let e = s.swatch_libraries.load_within(&p, "swatch.library.load", Some(8), parsed).unwrap_err().to_string();
assert!(e.contains("larger than"), "{e}");
let e = s.swatch_libraries.load_within(&p, "swatch.library.load", Some(9), parsed).unwrap_err().to_string();
assert!(e.contains("parsed"), "{e}");
}
#[test]
fn reading_the_head_of_a_swatch_library_file_stops_at_the_limit() {
let dir = vectorcraft_testkit::TempDir::new("graph-design-library-head");
let path = dir.join("long.gpl");
std::fs::write(&path, vec![b'a'; 1 << 20]).unwrap();
// The read the limit check relies on returns the bytes up to one past the limit, not the file.
let head = crate::cmd::fileio::read_file_head(&path.to_string_lossy(), 9).unwrap();
assert_eq!(head.len(), 9);
}
#[test]
fn a_library_design_brings_its_symbols_with_their_symbol_options() {
// The source design is an instance of symbol "Corner" with 9-slice scaling, a top-left
// registration point and the Graphic export type.
let mut src = Session::new();
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
src.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap();
src.execute("select.all", &json!({})).unwrap();
let opts = json!({"name": "Corner", "nineSlice": true, "registration": 0, "exportType": "graphic"});
let inst = src.execute("symbol.new", &opts).unwrap()["id"].as_u64().unwrap();
src.execute("select.set", &json!({"ids": [inst]})).unwrap();
src.execute("graph.design", &json!({"new": "Corner Mark"})).unwrap();
let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc);
let mut s = Session::new();
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Corners.vectorcraft"});
let lib = s.execute("swatch.library.load", &p).unwrap()["library"].as_str().unwrap().to_string();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
s.execute("graph.design", &json!({"library": lib, "add": "Corner Mark"})).unwrap();
let (from, to) = (&src.doc().unwrap().doc, &s.doc().unwrap().doc);
assert!(from.symbol_nine_slice("Corner").is_some());
assert_eq!(to.symbol_nine_slice("Corner"), from.symbol_nine_slice("Corner"));
assert_eq!(to.symbol_registration("Corner"), from.symbol_registration("Corner"));
assert_eq!(to.symbol_export_type("Corner"), from.symbol_export_type("Corner"));
}
#[test]
fn designs_and_markers_survive_save_and_open() {
let mut s = Session::new();
+2 -2
View File
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Overprint",
[],
None,
"{fill?: bool, stroke?: bool, item?: appearance item index|null, ids?|id?, target?: \"object\"|\"contents\"} make fills and/or strokes overprint (Overprint Preview, Separations Preview) or knock out: item's, else every fill or stroke of the painted objects (groups: their contents; type: its characters too). Without item and ids, the Appearance panel's active item stands in when it is of that kind → {changed: objects}",
"{fill?: bool, stroke?: bool, item?: appearance item index|null, ids?|id?, target?: \"object\"|\"contents\"} make fills and/or strokes overprint (Overprint Preview, Separations Preview) or knock out: item's, else every fill or stroke of the painted objects (groups: their contents; type: its characters too). Without item and ids, the Appearance panel's active item stands in when it is of that kind. A whole Live Paint group (also its contents with `item`) takes the fill flags on its faces and the stroke flags on its edges, and its hidden source paths keep theirs → {changed: objects}",
has_doc,
set_overprint
),
@@ -135,7 +135,7 @@ fn aims(s: &Session, p: &Value, cmd: &str, kinds: impl IntoIterator<Item = bool>
.into_iter()
.map(|fill| {
let it = item.of_kind(s, fill);
let ids = it.targets(s, p)?;
let ids = it.targets_for(s, p, fill)?;
let ids = if edit { super::appearance::drop_design_art_rows(s, ids, it, fill, cmd)? } else { ids };
Ok((fill, it, ids))
})
+39 -14
View File
@@ -216,12 +216,15 @@ impl Session {
}
let first = st.doc.node(*st.selection.subjects().first()?)?;
let item = self.appearance_item();
// Only an active Appearance row is shown here: it is a row of the first selected object.
if first.appearance.item_of_kind(item, !stroke).is_some() {
return Some((Cow::Borrowed(first), item));
}
// A Live Paint group without faces (or edges) shows the next selected object's paint; any other
// object without a painted object shows the defaults for new art.
for id in st.selection.subjects() {
// object without a painted object shows the defaults for new art. A face or edge selected with
// its Live Paint group counts with the group, wherever it is in the selection.
let covered = live_paint_covered(&st.doc, st.selection.subjects());
for id in st.selection.subjects().iter().filter(|id| !covered.contains(*id)) {
let Some(n) = st.doc.node(*id) else { continue };
let mut nodes = vec![];
painted(n, true, stroke, &mut nodes);
@@ -273,14 +276,6 @@ fn same_in_proxy(a: &Paint, b: &Paint) -> bool {
}
}
/// The ids of the faces and edges of `n` when it is a Live Paint group, else none.
pub(crate) fn live_paint_parts(n: &Node) -> Vec<NodeId> {
if !is_live_paint(n) {
return vec![];
}
faces(n).into_iter().chain(edges(n)).map(|part| part.id).collect()
}
/// The objects whose paints the proxies show for a selected `n`, the ones the paint commands
/// change ([`leaf_targets`]): groups and layers stand for their contents (and so do blends and
/// other containers inside them), a compound path for its parts. A Live Paint group stands for its
@@ -331,8 +326,9 @@ impl DocState {
// Looking the first object up builds the id cache when there is none.
let first = self.selection.objects.first().and_then(|id| self.doc.node(*id));
let (mut selected, mut fills, mut strokes) = (vec![], vec![], vec![]);
// The faces and edges of the selected Live Paint groups: selected as well, they count with their group's.
let mut covered = std::collections::HashSet::new();
// The faces and edges of the selected Live Paint groups (or of those inside selected groups): selected as well,
// they count with their group's.
let covered = live_paint_covered(&self.doc, &self.selection.objects);
// Every node with a selected id, in tree order: a repeated id (a damaged file) counts at each
// place it appears.
for n in self.doc.nodes_in_order(self.selection.objects.iter().copied()) {
@@ -342,7 +338,6 @@ impl DocState {
if covered.contains(&n.id) {
continue;
}
covered.extend(live_paint_parts(n));
painted(n, true, false, &mut fills);
painted(n, true, true, &mut strokes);
}
@@ -839,6 +834,36 @@ pub(crate) fn live_paint_parts_skipped(d: &Document, roots: &[NodeId], fill: boo
out
}
/// Faces, edges and the other objects (the hidden source paths) of Live Paint groups.
pub(crate) type LivePaintParts = (std::collections::HashSet<NodeId>, std::collections::HashSet<NodeId>, std::collections::HashSet<NodeId>);
/// The faces, the edges and the hidden source paths of the Live Paint groups in `roots` (or inside them),
/// found as [`live_paint_parts_skipped`] finds them.
pub(crate) fn live_paint_split(d: &Document, roots: &[NodeId]) -> LivePaintParts {
let groups = live_paint_groups(d, roots);
let mut hidden = inside_live_paint(d, &groups);
let (mut faces, mut edges) = (std::collections::HashSet::new(), std::collections::HashSet::new());
for (_, f, e) in &groups {
faces.extend(f.iter().copied());
edges.extend(e.iter().copied());
}
hidden.retain(|id| !faces.contains(id) && !edges.contains(id));
(faces, edges, hidden)
}
/// The faces and edges in `selected` whose Live Paint group is selected too, itself or inside another selected
/// object: they count with their group, wherever they are in `selected`. The groups are looked for only when an
/// object in `selected` is inside a Live Paint group.
pub(crate) fn live_paint_covered(d: &Document, selected: &[NodeId]) -> std::collections::HashSet<NodeId> {
let inside = |id: &NodeId| d.ancestry(*id).is_some_and(|up| up.iter().rev().skip(1).filter_map(|a| d.node(*a)).any(is_live_paint));
if !selected.iter().any(inside) {
return std::collections::HashSet::new();
}
let (mut parts, edges, _) = live_paint_split(d, selected);
parts.extend(edges);
parts
}
/// The instance whose object is selected with Direct Selection, and that object's path
/// ([`super::brushsym::selected_part`]), when `p` names no `ids`, `id` or `item`: the paint commands
/// then change that object. A bad `target` or `aligned` is refused as it is for any other selection.
@@ -1356,7 +1381,7 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
let item = item_target(s, p, cmd)?.of_kind(s, !stroke);
// Read before the check below, so that a bad param (such as `target` or `aligned`, or an explicit `item` the art has
// no row for) is still an error.
let targets = super::appearance::drop_design_art_rows(s, item.targets(s, p)?, item, !stroke, cmd)?;
let targets = super::appearance::drop_design_art_rows(s, item.targets_for(s, p, !stroke)?, item, !stroke, cmd)?;
let of = match item {
ItemTarget::Item { .. } => super::appearance::reference_of(s, p, item, cmd)?,
ItemTarget::Top => None,
+2 -3
View File
@@ -11,7 +11,7 @@ use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, LayerColor, Node, NodeId, NodeKind};
use vectorcraft_geom::{Rect, shapes};
use super::{live_paint_parts, painted, picked_colors, proxy_paint, same_in_proxy};
use super::{live_paint_covered, painted, picked_colors, proxy_paint, same_in_proxy};
use crate::{DocState, Session};
thread_local! {
@@ -39,12 +39,11 @@ fn walked(st: &DocState, item: Option<usize>, points: &[(NodeId, Vec<usize>)]) -
}
let ids: HashSet<NodeId> = st.selection.objects.iter().copied().collect();
let (mut selected, mut fills, mut strokes) = (vec![], vec![], vec![]);
let mut covered = HashSet::new();
let covered = live_paint_covered(&st.doc, &st.selection.objects);
st.doc.walk(|n| {
if ids.contains(&n.id) {
selected.push(n);
if !covered.contains(&n.id) {
covered.extend(live_paint_parts(n));
painted(n, true, false, &mut fills);
painted(n, true, true, &mut strokes);
}
@@ -153,6 +153,7 @@ pub(super) const ALLOWED: &[&str] = &[
"color.gamutCheck",
"color.harmony",
"color.plates",
"color.used",
"dataset.capture",
"dataset.delete",
"dataset.list",
+96 -33
View File
@@ -29,6 +29,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
colors
),
cmd!(
query "color.used",
"Document Colors",
[],
None,
"{selection?: true (false: the objects select.all takes, also while something is selected), limit?: n (only the n most used; default all)} → {colors: [{key, hex, color: the color in its own model ({model, …}), count, swatch?: the global swatch it is linked to (from its first linked use in paint order, a plain use before a gradient stop that mixes the swatch's ink with process inks; left out when only such stops link it), tint?: 0..100 to three decimals (the percent of that swatch's color the same use stores)}] as recolor.colors lists them, selection: true when they are the selection's, uses: the uses of every color, those past limit included} the unique colors of the selection, or with nothing selected or selection false of the objects select.all takes without the hidden and locked objects inside them, most used first; the selection is left as it is",
has_doc,
used
),
cmd!(
"recolor.apply",
"Recolor Artwork",
@@ -952,16 +961,19 @@ fn pick_theme(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"colors": colors.iter().map(key_str).collect::<Vec<_>>(), "objects": theme.objects}))
}
/// A colour the art uses: how often, and the global swatch it is linked to.
/// A color the art uses: how often, and the global swatch of its first linked use in paint order.
struct Used {
color: Color,
count: usize,
swatch: Option<String>,
/// The global swatch of the first linked use that is not a gradient stop mixing the swatch's
/// ink with process inks, with the tint (0..1) its paint stores when the paint gives one.
plain: Option<(String, Option<f32>)>,
}
/// The unique colours of the objects `ids` and the objects inside them, most used first (ties by
/// key): fills, strokes, gradient stops, text, mesh points and the tiles of the patterns used as
/// fills or strokes. With `only`, an object not in it is left out with everything it holds.
/// key): fills, strokes, gradient stops, text, mesh points, the tiles of the patterns used as
/// fills or strokes, and the tiles of the patterns those tiles use. With `only`, an object not in it is left out with everything it holds.
fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet<NodeId>>) -> Vec<Used> {
fn read<'a>(n: &'a Node, only: Option<&BTreeSet<NodeId>>, out: &mut Vec<&'a Node>) {
if only.is_some_and(|o| !o.contains(&n.id)) {
@@ -974,44 +986,64 @@ fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet<NodeId>>) ->
}
let mut index: HashMap<ColorKey, usize> = HashMap::new();
let mut used: Vec<(ColorKey, Used)> = vec![];
let mut count = |c: &Color, link: Option<&str>| {
let mut count_tint = |c: &Color, link: Option<&str>, tint: Option<f32>, mixed: bool| {
let k = ColorKey::of(c);
let i = *index.entry(k).or_insert_with(|| {
used.push((k, Used { color: *c, count: 0, swatch: None }));
used.push((k, Used { color: *c, count: 0, swatch: None, plain: None }));
used.len() - 1
});
let u = &mut used[i].1;
u.count += 1;
if u.swatch.is_none() {
u.swatch = link.filter(|l| d.swatch(l).is_some_and(|w| w.global && w.paint.color().is_some())).map(str::to_string);
if u.swatch.is_some() && (u.plain.is_some() || mixed) {
return;
}
if let Some(l) = link.filter(|l| d.swatch(l).is_some_and(|w| w.global && w.paint.color().is_some())) {
if u.swatch.is_none() {
u.swatch = Some(l.to_string());
}
if u.plain.is_none() && !mixed {
u.plain = Some((l.to_string(), tint));
}
}
};
// The patterns used as fills or strokes: their tiles count once each.
// The patterns used as fills or strokes, and the patterns their tiles use: each tile counts
// once, and a pattern whose tile uses itself, directly or through other patterns, counts once.
let mut patterns: Vec<&str> = vec![];
let mut nodes = vec![];
for n in ids.iter().filter_map(|id| d.node(*id)) {
read(n, only, &mut nodes);
}
for m in nodes {
for p in node_paints(m).chain(override_paints(m)) {
match p {
Paint::Solid { color, swatch, .. } => count(color, swatch.as_deref()),
Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| count(&s.color, s.swatch.as_deref())),
Paint::Pattern { pattern, .. } if !patterns.contains(&pattern.as_str()) => patterns.push(pattern),
_ => {}
}
}
if let NodeKind::Mesh(mesh) = &m.kind {
mesh.points.iter().for_each(|p| count(&p.color, None));
}
paints(m, &mut count_tint, &mut patterns);
}
for def in patterns.iter().filter_map(|p| d.pattern(p)) {
def.art.iter().for_each(|n| node_colors(n, &mut count));
let mut next = 0;
while let Some(&name) = patterns.get(next) {
next += 1;
for a in d.pattern(name).map(|def| def.art.as_slice()).unwrap_or_default() {
a.walk(&mut |m| paints(m, &mut count_tint, &mut patterns));
}
}
used.sort_by(|a, b| b.1.count.cmp(&a.1.count).then(a.0.cmp(&b.0)));
used.into_iter().map(|(_, u)| u).collect()
}
/// Count the colors `m` holds itself with `count` (the color, its swatch, the tint the paint
/// stores, and whether it is a gradient stop that mixes the swatch's ink with process inks), and
/// add the patterns it is painted with to `patterns`.
fn paints<'a>(m: &'a Node, count: &mut impl FnMut(&Color, Option<&str>, Option<f32>, bool), patterns: &mut Vec<&'a str>) {
for p in node_paints(m).chain(override_paints(m)) {
match p {
Paint::Solid { color, swatch, tint } => count(color, swatch.as_deref(), Some(*tint), false),
Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| count(&s.color, s.swatch.as_deref(), Some(s.tint), s.plates.is_some())),
Paint::Pattern { pattern, .. } if !patterns.contains(&pattern.as_str()) => patterns.push(pattern),
_ => {}
}
}
if let NodeKind::Mesh(mesh) = &m.kind {
mesh.points.iter().for_each(|p| count(&p.color, None, None, false));
}
}
/// The colors `n` shows, in paint order ([`node_colors`]), then the colors of the tiles of the
/// patterns it uses as fills or strokes, and of the patterns those tiles use (each pattern once).
fn shown_colors<'a>(d: &'a Document, n: &'a Node) -> Vec<Color> {
@@ -1054,30 +1086,61 @@ fn scope_ids(s: &Session, p: &Value, cmd: &str) -> Result<(Vec<NodeId>, Option<B
let st = s.doc()?;
let ids = match p.get("ids") {
Some(_) => checked_ids_param(s, p, "ids", cmd)?,
None if st.selection.is_empty() => {
let only = super::select::selectable_ids(&st.doc, st.isolation);
return Ok((super::select::selectable(&st.doc, st.isolation), Some(only)));
}
None if st.selection.is_empty() => return Ok(all_art(st)),
None => st.selection.objects.clone(),
};
let mut seen = BTreeSet::new();
Ok((super::edit::outermost(&st.doc, ids).into_iter().filter(|id| seen.insert(*id)).collect(), None))
}
fn colors(s: &mut Session, p: &Value) -> Result<Value> {
let (ids, only) = scope_ids(s, p, "recolor.colors")?;
let st = s.doc()?;
let v: Vec<Value> = used_colors(&st.doc, &ids, only.as_ref())
.iter()
/// The objects Select All takes, and the objects whose colors count ([`scope_ids`] with nothing
/// selected).
fn all_art(st: &crate::DocState) -> (Vec<NodeId>, Option<BTreeSet<NodeId>>) {
let only = super::select::selectable_ids(&st.doc, st.isolation);
(super::select::selectable(&st.doc, st.isolation), Some(only))
}
/// The `colors` list of `recolor.colors` and `color.used` for the objects `ids` (see
/// [`used_colors`]). Each names the swatch of its first linked use. With `with_color`, each has its
/// color in its own model, and the swatch and tint come from its first linked use that is not a
/// gradient stop mixing the swatch's ink with process inks (none when every linked use is one).
fn colors_json(used: &[Used], with_color: bool) -> Vec<Value> {
used.iter()
.map(|u| {
let mut v = json!({"key": key_str(&u.color), "hex": u.color.to_hex(), "count": u.count});
if let Some(w) = &u.swatch {
if with_color {
v["color"] = json!(u.color);
if let Some((w, tint)) = &u.plain {
v["swatch"] = json!(w);
if let Some(t) = tint {
v["tint"] = json!((f64::from(*t) * 100_000.0).round() / 1000.0);
}
}
} else if let Some(w) = &u.swatch {
v["swatch"] = json!(w);
}
v
})
.collect();
Ok(json!({ "colors": v }))
.collect()
}
fn colors(s: &mut Session, p: &Value) -> Result<Value> {
let (ids, only) = scope_ids(s, p, "recolor.colors")?;
let st = s.doc()?;
Ok(json!({ "colors": colors_json(&used_colors(&st.doc, &ids, only.as_ref()), false) }))
}
/// `color.used {selection?, limit?}`: the colors of the selection, or of the art Select All takes.
fn used(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "color.used";
let limit = super::index_opt(p, "limit", C)?.unwrap_or(usize::MAX);
let selection = switch_or(p, "selection", true, C)? && !s.doc()?.selection.is_empty();
let (ids, only) = if selection { scope_ids(s, &json!({}), C)? } else { all_art(s.doc()?) };
let st = s.doc()?;
let used = used_colors(&st.doc, &ids, only.as_ref());
let uses: usize = used.iter().map(|u| u.count).sum();
let shown = used.get(..limit.min(used.len())).unwrap_or_default();
Ok(json!({ "colors": colors_json(shown, true), "selection": selection, "uses": uses }))
}
/// `recolor.weigh`'s rows as given, each with `from` as a list (a `{current: new}` map gives a
+14 -6
View File
@@ -11,7 +11,7 @@ use vectorcraft_geom::PathData;
use vectorcraft_tools::builder::is_live_paint;
use super::appearance::{ItemTarget, edit_items, item_target};
use super::paint::{live_paint_parts, live_paint_parts_skipped, painted};
use super::paint::{live_paint_covered, live_paint_parts_skipped, painted};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, ok, str_param};
use crate::DocState;
use crate::inspect::{ALIGNS, CAPS, JOINS, StrokeMixed, node_stroke, scale_layer};
@@ -250,10 +250,15 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> {
} else if item == ItemTarget::Top {
own_stroke_or_leaves(s, p)?
} else {
item.targets(s, p)?
item.targets_for(s, p, false)?
};
// A Live Paint group without edges was still selected or given: the options do not go to new art.
let live_paint = !bucket && item == ItemTarget::Top && !live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, false).is_empty();
let live_paint = !bucket
&& if item == ItemTarget::Top {
!live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, false).is_empty()
} else {
!super::appearance::contents_skipped(s, p, false)?.is_empty()
};
let new_art = bucket || (no_targets(&ids, p) && !live_paint);
let given = !ids.is_empty() || live_paint;
// The art of a graph design in a series keeps the design's stroke.
@@ -453,12 +458,15 @@ impl Session {
}
let Some(first) = st.selection.objects.first() else { return Some(self.new_art_stroke()) };
let first = st.doc.node(*first)?;
// Only an active Appearance row is shown here: it is a row of the first selected object.
if let Some(i) = first.appearance.item_of_kind(self.appearance_item(), false) {
return first.appearance.stroke_at(Some(i)).cloned();
}
// A Live Paint group without edges shows the next selected object's stroke; any other object
// without a painted object shows none.
for id in &st.selection.objects {
// without a painted object shows none. A face or edge selected with its Live Paint group counts
// with the group, wherever it is in the selection.
let covered = live_paint_covered(&st.doc, &st.selection.objects);
for id in st.selection.objects.iter().filter(|id| !covered.contains(*id)) {
let Some(n) = st.doc.node(*id) else { continue };
let mut nodes = vec![];
painted(n, true, true, &mut nodes);
@@ -532,7 +540,7 @@ impl DocState {
} else {
let selected: Vec<&Node> = self.selection.objects.iter().filter_map(|id| self.doc.node(*id)).collect();
// The faces and edges of the selected Live Paint groups: selected as well, they count with their group's.
let covered: std::collections::HashSet<vectorcraft_doc::NodeId> = selected.iter().flat_map(|n| live_paint_parts(n)).collect();
let covered = live_paint_covered(&self.doc, &self.selection.objects);
for n in selected.into_iter().filter(|n| !covered.contains(&n.id)) {
painted(n, true, true, &mut nodes);
}
+104 -8
View File
@@ -17,7 +17,7 @@ use vectorcraft_color::swatch::REGISTRATION;
use vectorcraft_color::{Paint, Swatch, SwatchGroup, SwatchLibrary, default_swatches};
use vectorcraft_doc::pattern::pattern_paint;
use super::fileio::{create_dir, extension, read_file, write_file, write_new_file};
use super::fileio::{create_dir, extension, read_file, read_file_head, write_file, write_new_file};
use super::menucmds::squash;
use super::package::free_name;
use super::patternlib;
@@ -76,7 +76,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Other Library…",
["Window", "Swatch Libraries"],
None,
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl, .ase (swatch exchange) or .acb (color book, read only) library, or the swatches of any document VectorCraft opens (see document.formats), such as a .ai or .eps swatch library, for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library). A document's colors, tints, gradients and pattern swatches come in, in its order and color groups; swatch.library.add brings a pattern swatch's pattern with it. A document with no swatches is an error, and so is a .ai, .eps or PostScript file whose swatches are only the default ones (it has no palette of its own) → {library: id, name, count}",
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl, .ase (swatch exchange) or .acb (color book, read only) library, or the swatches of any document VectorCraft opens (see document.formats), such as a .ai or .eps swatch library, for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library). A document's colors, tints, gradients and pattern swatches come in, in its order and color groups; swatch.library.add brings a pattern swatch's pattern with it. A document's graph designs are offered by Object › Graph › Column… and Marker… (graph.column, graph.marker and graph.design take the library's id) until the app quits. A document with no swatches is an error, and so is a .ai, .eps or PostScript file whose swatches are only the default ones (it has no palette of its own), unless it has graph designs, which then load with no swatches. A file larger than 256 MB is refused before it is read → {library: id, name, count, graphDesigns: the document's graph designs (0 for a library file)}",
always,
load
),
@@ -92,6 +92,45 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
/// The graph designs of the documents Other Library… loaded (`swatch.library.load`), which the
/// Graph Column and Graph Marker dialogs offer besides the document's own; not saved.
#[derive(Clone, Debug, Default)]
pub struct DesignLibraries {
libs: Vec<DesignLibrary>,
}
/// A document loaded as a swatch library that holds graph designs ([`DesignLibraries`]).
#[derive(Clone, Debug)]
pub struct DesignLibrary {
/// The id `swatch.library.load` gave the swatch library. A User Defined copy of it
/// (`swatch.library.copyToUser`) holds the swatches alone, so the designs stay under this id.
pub id: String,
pub name: String,
/// The designs and the resources their art uses.
pub doc: Arc<vectorcraft_doc::Document>,
}
impl DesignLibraries {
/// The libraries, in the order they were loaded.
pub fn iter(&self) -> impl Iterator<Item = &DesignLibrary> {
self.libs.iter()
}
/// The library loaded as swatch library `id`.
pub fn get(&self, id: &str) -> Option<&DesignLibrary> {
self.libs.iter().find(|l| l.id == id)
}
/// Keep `doc`'s graph designs as library `id` named `name`, in place of the ones loaded as `id`
/// before; with no designs, `id` no longer has any.
fn set(&mut self, id: &str, name: &str, doc: Option<vectorcraft_doc::Document>) {
self.libs.retain(|l| l.id != id);
if let Some(doc) = doc {
self.libs.push(DesignLibrary { id: id.to_string(), name: name.to_string(), doc: Arc::new(doc) });
}
}
}
/// The libraries beyond the built-in ones: User Defined (the library files in the user library
/// folder, as last scanned) and loaded ones (`swatch.library.load`). Graphic style libraries use
/// the same with [`vectorcraft_doc::StyleLibrary`] ([`super::stylelib`]).
@@ -354,12 +393,32 @@ impl<L: LibraryFile> Libraries<L> {
/// or a file with the same extension and bytes as one there, is that User Defined library;
/// others are listed as loaded until the app quits.
pub(crate) fn load(&mut self, p: &Value, cmd: &str, parse: impl FnOnce(&[u8], &str) -> Result<L>) -> Result<(LibraryInfo, Arc<L>)> {
self.load_within(p, cmd, None, parse)
}
/// [`Self::load`], with a file at `path` read up to `max` bytes and refused when it is longer.
pub(crate) fn load_within(
&mut self,
p: &Value,
cmd: &str,
max: Option<usize>,
parse: impl FnOnce(&[u8], &str) -> Result<L>,
) -> Result<(LibraryInfo, Arc<L>)> {
let path = text_param(p, "path", cmd)?;
let data = text_param(p, "data", cmd)?;
let data_base64 = text_param(p, "dataBase64", cmd)?;
let name = text_param(p, "name", cmd)?;
let bytes = match (path, data, data_base64) {
(Some(path), ..) => read_file(path)?,
(Some(path), ..) => match max {
Some(max) => {
let bytes = read_file_head(path, max.saturating_add(1))?;
if bytes.len() > max {
return Err(bad(cmd, too_big_message(max)));
}
bytes
}
None => read_file(path)?,
},
(None, Some(text), _) => text.as_bytes().to_vec(),
(None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(cmd, "bad dataBase64"))?,
_ => return Err(bad(cmd, "give `path`, `data` or `dataBase64`")),
@@ -777,12 +836,40 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
Ok(out)
}
/// The error for a library file larger than `max` bytes.
fn too_big_message(max: usize) -> String {
format!("the file is larger than {} MB", max >> 20)
}
/// Whether the library `p` gives (`path`, `data` or `dataBase64`) is larger than `max` bytes,
/// checked before the file is read, copied or decoded.
pub(crate) fn library_too_big(p: &Value, cmd: &str, max: usize) -> Result<bool> {
Ok(match text_param(p, "path", cmd)? {
Some(path) => super::fileio::file_stamp(path).is_some_and(|(len, _)| len > max as u64),
None => match text_param(p, "data", cmd)? {
Some(text) => text.len() > max,
// Base64 holds 3 bytes in every 4 characters (padding and white space hold none).
None => {
text_param(p, "dataBase64", cmd)?.is_some_and(|b| b.bytes().filter(|c| *c != b'=' && !c.is_ascii_whitespace()).count() * 3 / 4 > max)
}
},
})
}
fn load(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "swatch.library.load";
let max = super::place::document::MAX_FILE;
if library_too_big(p, C, max)? {
return Err(bad(C, too_big_message(max)));
}
let mut designs = None;
// The document a library with pattern swatches was read from, which holds their patterns.
let mut patterns = None;
let (info, lib) = s.swatch_libraries.load(p, C, |bytes, file| {
// A library file, or a document whose swatches become the library.
// The file is read no further than the limit, so a file that grew since it was checked is
// refused too.
let (info, lib) = s.swatch_libraries.load_within(p, C, Some(max), |bytes, file| {
// A library file, or a document whose swatches become the library and whose graph
// designs the Graph Column and Graph Marker dialogs offer.
if palette_io::sniff_bytes(bytes) {
return palette_io::read_bytes(bytes, stem(file)).map_err(|e| bad(C, e));
}
@@ -792,10 +879,17 @@ fn load(s: &mut Session, p: &Value) -> Result<Value> {
}
// A `.ai`, EPS or PostScript file without a palette of its own opens with the default swatches.
let defaults = matches!(loaded.format.id, "ai" | "ait" | "eps" | "ps") && has_only_default_swatches(&loaded.doc);
let lib = document_library(&loaded.doc, &[], stem(file).to_string(), true, C)?;
let mut lib = document_library(&loaded.doc, &[], stem(file).to_string(), true, C)?;
let doc_designs = super::clipboard::resources::graph_design_library(&loaded.doc);
if defaults || lib.is_empty() {
return Err(bad(C, format!("`{file}` has no swatches of its own")));
// A document with graph designs loads for them, with no swatches.
if doc_designs.is_none() {
return Err(bad(C, format!("`{file}` has no swatches of its own")));
}
lib.swatches.clear();
lib.groups.clear();
}
designs = doc_designs;
if lib.iter().any(|w| matches!(w.paint, Paint::Pattern { .. })) {
patterns = Some(Arc::new(loaded.doc));
}
@@ -804,7 +898,9 @@ fn load(s: &mut Session, p: &Value) -> Result<Value> {
if info.category == "loaded" {
s.swatch_libraries.set_pattern_doc(&info.id, patterns);
}
Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len()}))
let count = designs.as_ref().map_or(0, |d| d.graph_designs.len());
s.graph_design_libraries.set(&info.id, &info.name, designs);
Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len(), "graphDesigns": count}))
}
/// `d`'s swatches and color groups are exactly the default ones of a color mode, as a new
+13
View File
@@ -424,6 +424,19 @@ fn each_changed_instance(n: &mut Node, name: &str, f: &mut dyn FnMut(&mut Vec<Sy
}
}
/// Each instance's appearance changes to objects of symbol `name`'s art follow those objects after
/// its art changed from `old` outside symbol editing (a graph in it drawn again): a change to an
/// object that is no longer there is dropped ([`follow_objects`]).
pub(crate) fn follow_art_change(d: &mut Document, name: &str, old: &Arc<Node>) {
let Some(new) = d.symbols.iter().find(|s| s.name == name).map(|s| s.art.clone()) else { return };
let parts = |art: &Arc<Node>| match (&art.kind, art.children()) {
(NodeKind::Group { .. }, Some(ch)) => (ch.to_vec(), true),
_ => (vec![art.clone()], false),
};
let (old, new) = (parts(old), parts(&new));
follow_objects(d, name, (&old.0, old.1), (&new.0, new.1));
}
/// Each instance's appearance changes to objects of symbol `name`'s art follow those objects
/// through an edit of the editing layer (see [`follow_paths`]), and keep only the changes the art
/// still draws ([`fit_parts`]). That covers the instances on the layers and in the art of the
+3
View File
@@ -356,6 +356,7 @@ pub struct FillAttrs {
impl FillAttrs {
pub const ALL: Self = Self { color: true, transparency: true, overprint: true };
pub const NONE: Self = Self { color: false, transparency: false, overprint: false };
}
impl Default for FillAttrs {
@@ -383,6 +384,8 @@ pub struct StrokeAttrs {
impl StrokeAttrs {
pub const ALL: Self = Self { color: true, transparency: true, overprint: true, weight: true, cap: true, join: true, miter: true, dash: true };
pub const NONE: Self =
Self { color: false, transparency: false, overprint: false, weight: false, cap: false, join: false, miter: false, dash: false };
}
impl Default for StrokeAttrs {
+3
View File
@@ -153,6 +153,9 @@ pub struct Session {
pub(crate) pending_paint: Option<Paint>,
/// User Defined and loaded swatch libraries (Window → Swatch Libraries); not saved.
pub swatch_libraries: cmd::swatchlib::Libraries,
/// The graph designs of the documents loaded as swatch libraries (Window → Swatch Libraries →
/// Other Library…), for the Graph Column and Graph Marker dialogs; not saved.
pub graph_design_libraries: cmd::swatchlib::DesignLibraries,
/// The selected freeform gradient point (`paint.freeform.selectPoint`) and whose gradient it
/// was selected on: read it with [`Session::selected_freeform_point`].
pub(crate) freeform_point: Option<(usize, cmd::gradient::StopOwner)>,
+1
View File
@@ -85,6 +85,7 @@ impl Session {
recent_colors: vec![],
pending_paint: None,
swatch_libraries: Default::default(),
graph_design_libraries: Default::default(),
freeform_point: None,
style_libraries: Default::default(),
symbol_libraries: Default::default(),
+53
View File
@@ -115,6 +115,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
"paint",
"pattern-borders",
"decorative",
"ornamental",
"scatter-shapes",
"stipple",
"game-trails",
@@ -197,6 +198,7 @@ fn every_builtin_library_brush_has_its_kind_and_draws() {
("paint", "art"),
("pattern-borders", "pattern"),
("decorative", "pattern"),
("ornamental", "art"),
("scatter-shapes", "scatter"),
("stipple", "scatter"),
("game-trails", "art"),
@@ -661,6 +663,57 @@ fn decorative_brushes_repeat_distinct_art_and_survive_a_saved_library() {
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
}
#[test]
fn ornamental_brushes_draw_flourishes_and_survive_a_saved_library() {
let mut s = session();
let (_, lib) = cmd::brushlib::library(&s, "Ornamental").unwrap();
let names = ["Scrollwork", "Filigree Arrow", "Petal Sweep", "Twin Curl"];
assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), names);
let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 40, "x2": 190, "y2": 40}))["id"].as_u64().unwrap();
let mut curve = line_to(20.0);
curve.curve_to((60.0, -25.0), (140.0, 25.0), (180.0, 0.0));
for b in &lib.brushes {
let BrushKind::Art(art) = &b.kind else { panic!("{} is not an art brush", b.name) };
assert_eq!(art.colorization, vectorcraft_brush::Colorization::Tints);
assert_eq!(art.width, 300.0);
for line in [line_to(2.0), line_to(180.0), curve.clone()] {
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line, &black_stroke());
let points = anchors(&pieces.iter().collect::<Vec<_>>());
assert!(!points.is_empty() && points.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{}", b.name);
}
let before = undo_len(&s);
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "ornamental", "name": b.name, "apply": true, "ids": [path]}));
assert_eq!(strs(&added["added"]), [b.name.as_str()]);
assert_eq!(added["applied"], json!([path]));
assert_eq!(undo_len(&s), before + 1);
assert_eq!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some(b.name.as_str()));
}
let saved = run(&mut s, "brush.saveLibrary", json!({"names": names}));
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
let reopened = vectorcraft_format::load(&bytes).unwrap();
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
}
/// Filigree Arrow's shaft runs into its head with no gap, so a straight stroke draws one arrow.
#[test]
fn the_filigree_arrow_shaft_meets_its_head() {
let s = session();
let (_, lib) = cmd::brushlib::library(&s, "Ornamental").unwrap();
let BrushKind::Art(art) = &lib.brush("Filigree Arrow").unwrap().kind else { panic!("Filigree Arrow is not an art brush") };
let mut parts = vec![];
art.art.walk(&mut |c| {
if c.path_data().is_some() {
parts.push(c.contains_fn());
}
});
for y in [-0.6, 0.0, 0.6] {
for i in 0..=930 {
let p = vectorcraft_geom::Point::new(4.05 + 0.1 * f64::from(i), y);
assert!(parts.iter().any(|inside| inside(p)), "gap at {p:?}");
}
}
}
#[test]
fn pressure_sensitive_brushes_widen_with_pen_pressure_and_survive_a_saved_library() {
let mut s = session();
+454
View File
@@ -4283,6 +4283,353 @@ fn live_paint_group_stroke_panel_edits_change_its_edges() {
assert_eq!(node(&s, g).appearance.stroke().map(|st| st.width), Some(1.0));
}
/// A face or edge selected before its Live Paint group counts with the group: the Fill proxy shows
/// the faces' fill and the Stroke panel the edges' stroke, whatever the order of the selection.
#[test]
fn live_paint_group_proxies_do_not_depend_on_the_selection_order() {
let mut s = session();
let g = live(&mut s);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap();
s.execute("stroke.set", &json!({"weight": 6})).unwrap();
let magenta = serde_json::to_value(Paint::solid(Color::from_hex("#ff00ff").unwrap())).unwrap();
let edge = vectorcraft_tools::builder::edges(&node(&s, g))[0].id;
s.execute("select.set", &json!({"ids": [edge.0, g.0]})).unwrap();
assert_eq!(s.execute("paint.proxies", &json!({})).unwrap()["fill"], magenta, "an edge first shows the faces' fill");
// A face with a stroke of its own (from a file, say), selected first, shows the edges' stroke.
let face = vectorcraft_tools::builder::faces(&node(&s, g))[0].id;
s.edit("t", |d, _| {
let n = d.node_mut(face).unwrap();
n.appearance.set_stroke(Paint::solid(Color::BLACK));
n.appearance.stroke_at_mut(None).unwrap().width = 2.0;
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [face.0, g.0]})).unwrap();
assert_eq!(s.shown_stroke().map(|st| st.width), Some(6.0), "a face first shows the edges' stroke");
}
/// The Eyedropper onto a whole selected Live Paint group, or reversed onto a clicked one, gives the
/// picked fill attributes to its faces and the picked stroke attributes to its edges; its hidden
/// source paths keep their paint.
#[test]
fn live_paint_group_eyedropper_gives_the_fill_to_faces_and_the_stroke_to_edges() {
for reverse in [false, true] {
let mut s = session();
let g = live(&mut s);
let src = rect(&mut s, 400.0, 0.0, 50.0, 50.0);
s.execute("paint.setFill", &json!({"ids": [src.0], "color": "#ff00ff"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [src.0], "color": "#0000ff"})).unwrap();
s.execute("stroke.set", &json!({"ids": [src.0], "weight": 3})).unwrap();
let (faces0, edges0) = part_looks(&s, g);
let sources0 = sources_looks(&s, g);
if reverse {
s.execute("select.set", &json!({"ids": [src.0]})).unwrap();
s.execute("appearance.copyFrom", &json!({"source": g.0, "reverse": true})).unwrap();
} else {
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("appearance.copyFrom", &json!({"source": src.0})).unwrap();
}
let (faces1, edges1) = part_looks(&s, g);
let magenta = Paint::solid(Color::from_hex("#ff00ff").unwrap());
let blue = Paint::solid(Color::from_hex("#0000ff").unwrap());
for (f, f0) in faces1.iter().zip(&faces0) {
assert_eq!(f.fill_paint(), magenta, "reverse {reverse}: a face takes the fill");
assert_eq!((f.stroke_paint(), f.stroke_width()), (f0.stroke_paint(), f0.stroke_width()), "reverse {reverse}: a face takes no stroke");
}
for (e, e0) in edges1.iter().zip(&edges0) {
assert_eq!((e.stroke_paint(), e.stroke_width()), (blue.clone(), 3.0), "reverse {reverse}: an edge takes the stroke");
assert_eq!(e.fill_paint(), e0.fill_paint(), "reverse {reverse}: an edge takes no fill");
}
assert_eq!(sources_looks(&s, g), sources0, "reverse {reverse}: the hidden source paths keep their paint");
}
}
/// A whole-appearance Eyedropper pick of a source with several fills and strokes gives each face
/// of a selected Live Paint group every fill row and each edge every stroke row.
#[test]
fn live_paint_group_eyedropper_gives_every_fill_and_stroke_row() {
let mut s = session();
let g = live(&mut s);
let src = rect(&mut s, 400.0, 0.0, 50.0, 50.0);
s.execute("paint.setFill", &json!({"ids": [src.0], "color": "#ff00ff"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [src.0], "color": "#0000ff"})).unwrap();
s.execute("appearance.addFill", &json!({"ids": [src.0]})).unwrap();
s.execute("appearance.addStroke", &json!({"ids": [src.0]})).unwrap();
let kinds = |a: &vectorcraft_doc::Appearance, fill: bool| a.items.iter().filter(|it| it.is_fill() == fill).count();
let source = (*node(&s, src).appearance).clone();
assert_eq!((kinds(&source, true), kinds(&source, false)), (2, 2));
// A face with a stroke row below its fill keeps that row below the picked fills.
let face = vectorcraft_tools::builder::faces(&node(&s, g))[0].id;
s.edit("t", |d, _| {
let n = d.node_mut(face).unwrap();
n.appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::BLACK), 9.0)));
Ok(())
})
.unwrap();
let (faces0, edges0) = part_looks(&s, g);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("appearance.copyFrom", &json!({"source": src.0})).unwrap();
let (faces1, edges1) = part_looks(&s, g);
let order: Vec<bool> = faces1[0].items.iter().map(|it| it.is_fill()).collect();
assert_eq!(order.first(), Some(&false), "the face's lower stroke row stays below its fills: {order:?}");
for (f, f0) in faces1.iter().zip(&faces0) {
assert_eq!(kinds(f, true), 2, "a face takes every fill row");
assert_eq!(kinds(f, false), kinds(f0, false), "a face keeps its strokes");
}
for (e, e0) in edges1.iter().zip(&edges0) {
assert_eq!(kinds(e, false), 2, "an edge takes every stroke row");
assert_eq!(kinds(e, true), kinds(e0, true), "an edge keeps its fills");
}
}
/// The Appearance panel's edits of a Live Paint group's contents (`target: "contents"`) follow the
/// group's rule: a new fill goes on its faces, a new stroke on its edges, and its hidden source paths
/// keep their appearance under every contents edit.
#[test]
fn live_paint_group_contents_edits_follow_the_group_rule() {
let mut s = session();
let g = live(&mut s);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
let (faces0, edges0) = part_looks(&s, g);
let sources0 = sources_looks(&s, g);
s.execute("appearance.addFill", &json!({"target": "contents"})).unwrap();
let (faces1, edges1) = part_looks(&s, g);
assert!(faces1.iter().zip(&faces0).all(|(f, f0)| f.items.len() == f0.items.len() + 1), "every face takes a new fill");
assert_eq!(edges1, edges0, "edges take no new fill");
s.execute("appearance.addStroke", &json!({"target": "contents"})).unwrap();
let (faces2, edges2) = part_looks(&s, g);
assert_eq!(faces2, faces1, "faces take no new stroke");
assert!(edges2.iter().zip(&edges1).all(|(e, e0)| e.items.len() == e0.items.len() + 1), "every edge takes a new stroke");
// A stroke row edit of the contents reaches the edges, not the faces.
s.execute("stroke.set", &json!({"target": "contents", "item": 0, "weight": 7})).unwrap();
let (faces3, edges3) = part_looks(&s, g);
assert_eq!(faces3, faces2, "faces keep their rows");
assert!(edges3.iter().all(|e| e.stroke_at(Some(0)).map(|st| st.width) == Some(7.0)), "every edge's stroke row takes the weight");
s.execute("appearance.clear", &json!({"target": "contents"})).unwrap();
assert_eq!(sources_looks(&s, g), sources0, "the hidden source paths keep their appearance");
}
/// Fill edits of a Live Paint group's contents with an `item` (a gradient vector, Invert, Overprint
/// Fill) change its faces and leave an edge's fill row as it is, and Overprint on the whole group goes
/// to the faces' fills and the edges' strokes, leaving the hidden source paths as they are.
#[test]
fn live_paint_group_item_edits_and_overprint_follow_the_group_rule() {
let mut s = session();
let g = live(&mut s);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("paint.setFill", &json!({"gradient": {}})).unwrap();
// Each edge gets a copy of a face's gradient fill row, below its stroke.
let n = node(&s, g);
let face_row = vectorcraft_tools::builder::faces(&n)[0].appearance.items[0].clone();
let edge_ids: Vec<NodeId> = vectorcraft_tools::builder::edges(&n).iter().map(|e| e.id).collect();
let mut face_ids: Vec<u64> = vectorcraft_tools::builder::faces(&n).iter().map(|f| f.id.0).collect();
face_ids.sort_unstable();
s.edit("t", |d, _| {
for e in &edge_ids {
d.node_mut(*e).unwrap().appearance.items.insert(0, face_row.clone());
}
Ok(())
})
.unwrap();
let (faces0, edges0) = part_looks(&s, g);
let sources0 = sources_looks(&s, g);
let r = s.execute("paint.setGradientGeom", &json!({"stroke": false, "item": 0, "target": "contents", "start": [0, 0], "end": [100, 0]})).unwrap();
let mut changed: Vec<u64> = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
changed.sort_unstable();
assert_eq!(changed, face_ids, "only the faces take the vector");
assert_eq!(part_looks(&s, g).1, edges0, "an edge's fill row keeps its vector");
let stops = |a: &vectorcraft_doc::Appearance| match a.fill_paint() {
Paint::Gradient(gr) => gr.gradient.stops.iter().map(|st| st.color).collect::<Vec<_>>(),
_ => vec![],
};
let before: Vec<_> = part_looks(&s, g).0.iter().map(stops).collect();
s.execute("paint.invert", &json!({"stroke": false, "item": 0, "target": "contents"})).unwrap();
for (f, b) in part_looks(&s, g).0.iter().zip(&before) {
assert_eq!(stops(f), b.iter().rev().copied().collect::<Vec<_>>(), "the black-to-white stops of a face's fill are inverted");
}
assert_ne!(part_looks(&s, g).0, faces0);
assert_eq!(part_looks(&s, g).1, edges0, "an edge's fill row is not inverted");
s.execute("object.setOverprint", &json!({"fill": true, "item": 0, "target": "contents"})).unwrap();
let (faces1, edges1) = part_looks(&s, g);
assert!(faces1.iter().all(|f| f.items[0].overprint()), "the faces' fill overprints");
assert_eq!(edges1, edges0, "an edge's fill row does not overprint");
s.execute("object.setOverprint", &json!({"fill": true, "stroke": true})).unwrap();
let (_, edges2) = part_looks(&s, g);
assert!(edges2.iter().all(|e| e.items.iter().all(|it| it.overprint() != it.is_fill())), "only the edges' strokes overprint");
assert_eq!(sources_looks(&s, g), sources0, "the hidden source paths keep their flags");
}
/// A face selected before an ordinary group that holds its Live Paint group counts with that group:
/// the Stroke panel shows the edges' stroke.
#[test]
fn live_paint_group_inside_a_selected_group_keeps_the_proxies_independent_of_order() {
let mut s = session();
let g = live(&mut s);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("stroke.set", &json!({"weight": 6})).unwrap();
let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let face = vectorcraft_tools::builder::faces(&node(&s, g))[0].id;
s.edit("t", |d, _| {
let n = d.node_mut(face).unwrap();
n.appearance.set_stroke(Paint::solid(Color::BLACK));
n.appearance.stroke_at_mut(None).unwrap().width = 2.0;
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [face.0, outer.0]})).unwrap();
assert_eq!(s.shown_stroke().map(|st| st.width), Some(6.0), "a face first shows the edges' stroke");
assert!(!s.active().unwrap().stroke_mixed().weight, "the face's own stroke does not make the weight mixed");
// An unfilled edge selected with the outer group does not make the faces' fill mixed.
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
let edge = vectorcraft_tools::builder::edges(&node(&s, g))[0].id;
s.execute("select.set", &json!({"ids": [edge.0, outer.0]})).unwrap();
let r = s.execute("paint.proxies", &json!({})).unwrap();
assert_eq!(r["fill"], serde_json::to_value(Paint::solid(Color::from_hex("#ff0000").unwrap())).unwrap());
assert_eq!(r["fillMixed"], false, "the edge counts with its group");
}
/// The Eyedropper picks up a whole Live Paint group as its faces' fill under its edges' stroke, and
/// `append` onto a whole group adds the picked fills and strokes without the picked effects.
#[test]
fn live_paint_group_eyedropper_picks_up_the_group_and_appends_without_effects() {
let mut s = session();
let g = live(&mut s);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap();
s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap();
s.execute("stroke.set", &json!({"weight": 5})).unwrap();
s.edit("t", |d, _| {
d.node_mut(g).unwrap().opacity = 0.5;
Ok(())
})
.unwrap();
let target = rect(&mut s, 400.0, 0.0, 50.0, 50.0);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("appearance.copyFrom", &json!({"source": target.0, "reverse": true})).unwrap();
let a = (*node(&s, target).appearance).clone();
assert_eq!(a.fill_paint(), Paint::solid(Color::from_hex("#ff00ff").unwrap()), "the faces' fill");
assert_eq!((a.stroke_paint(), a.stroke_width()), (Paint::solid(Color::from_hex("#0000ff").unwrap()), 5.0), "the edges' stroke");
assert_eq!(node(&s, target).opacity, 0.5, "the group's own opacity");
// A Live Paint group with no face and no edge is not picked up: the next selected object is.
let empty = rect(&mut s, 600.0, 0.0, 50.0, 50.0);
s.execute("select.set", &json!({"ids": [empty.0]})).unwrap();
let e = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let en = node(&s, e);
let parts: Vec<NodeId> =
vectorcraft_tools::builder::faces(&en).iter().chain(vectorcraft_tools::builder::edges(&en).iter()).map(|p| p.id).collect();
assert!(!parts.is_empty());
s.edit("t", |d, _| {
d.node_mut(e).unwrap().children_mut().unwrap().retain(|c| !parts.contains(&c.id));
Ok(())
})
.unwrap();
assert!(vectorcraft_tools::builder::is_live_paint(&node(&s, e)));
let other = rect(&mut s, 700.0, 0.0, 50.0, 50.0);
s.execute("paint.setFill", &json!({"ids": [other.0], "color": "#00ff00"})).unwrap();
s.execute("select.set", &json!({"ids": [e.0, other.0]})).unwrap();
s.execute("appearance.copyFrom", &json!({"source": target.0, "reverse": true})).unwrap();
assert_eq!(node(&s, target).appearance.fill_paint(), Paint::solid(Color::from_hex("#00ff00").unwrap()), "the next selected object's fill");
// Append a source with a drop shadow onto the whole group.
let src = rect(&mut s, 500.0, 0.0, 50.0, 50.0);
s.execute("select.set", &json!({"ids": [src.0]})).unwrap();
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "item": null})).unwrap();
assert!(!node(&s, src).appearance.effects.is_empty());
let (faces0, edges0) = part_looks(&s, g);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("appearance.copyFrom", &json!({"source": src.0, "append": true})).unwrap();
let (faces1, edges1) = part_looks(&s, g);
for (p, p0) in faces1.iter().chain(&edges1).zip(faces0.iter().chain(&edges0)) {
assert_eq!(p.effects, p0.effects, "a face or edge takes no effect");
}
assert!(faces1.iter().zip(&faces0).all(|(f, f0)| f.items.len() > f0.items.len()), "every face takes the fill");
}
/// Reversed onto a clicked object, an empty Live Paint group first in the selection passes to the next
/// selected Live Paint group, whose faces' fill and edges' stroke are both picked up.
#[test]
fn live_paint_group_eyedropper_reversed_skips_an_empty_group_for_the_next_whole_group() {
let mut s = session();
let g = live(&mut s);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap();
s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap();
s.execute("stroke.set", &json!({"weight": 5})).unwrap();
let empty = rect(&mut s, 600.0, 0.0, 50.0, 50.0);
s.execute("select.set", &json!({"ids": [empty.0]})).unwrap();
let e = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let en = node(&s, e);
let parts: Vec<NodeId> =
vectorcraft_tools::builder::faces(&en).iter().chain(vectorcraft_tools::builder::edges(&en).iter()).map(|p| p.id).collect();
s.edit("t", |d, _| {
d.node_mut(e).unwrap().children_mut().unwrap().retain(|c| !parts.contains(&c.id));
Ok(())
})
.unwrap();
let target = rect(&mut s, 400.0, 0.0, 50.0, 50.0);
s.execute("appearance.copyFrom", &json!({"source": target.0, "reverse": true, "ids": [e.0, g.0]})).unwrap();
let a = (*node(&s, target).appearance).clone();
assert_eq!(a.fill_paint(), Paint::solid(Color::from_hex("#ff00ff").unwrap()), "the faces' fill");
assert_eq!((a.stroke_paint(), a.stroke_width()), (Paint::solid(Color::from_hex("#0000ff").unwrap()), 5.0), "the edges' stroke");
}
/// An Eyedropper pick whose source is the selected Live Paint group leaves the group's own faces and
/// edges as they are.
#[test]
fn live_paint_group_eyedropper_does_not_target_its_own_source_group() {
let mut s = session();
let g = live(&mut s);
s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 50], "color": "#ff0000"})).unwrap();
s.execute("livePaint.fill", &json!({"group": g.0, "point": [75, 50], "color": "#00ff00"})).unwrap();
let before = part_looks(&s, g);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("appearance.copyFrom", &json!({"source": g.0})).unwrap();
assert_eq!(part_looks(&s, g), before);
}
/// A Live Paint group left with only its hidden source paths is still a selection: a stroke edit of its
/// contents changes nothing and leaves the settings for new art as they are.
#[test]
fn live_paint_group_with_only_source_paths_leaves_new_art_alone_for_a_contents_edit() {
let mut s = session();
let g = live(&mut s);
let n = node(&s, g);
let parts: Vec<NodeId> = vectorcraft_tools::builder::faces(&n).iter().chain(vectorcraft_tools::builder::edges(&n).iter()).map(|p| p.id).collect();
s.edit("t", |d, _| {
d.children_mut(Some(g)).unwrap().retain(|c| !parts.contains(&c.id));
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
let (paint0, stroke0) = (s.paint.clone(), s.new_art_stroke());
s.execute("stroke.setAdvanced", &json!({"target": "contents", "item": 0, "arrowScale": [200, 150]})).unwrap();
assert_eq!((s.paint.clone(), s.new_art_stroke()), (paint0, stroke0), "new art keeps its stroke");
}
/// Adding a fill or a stroke to the contents of a Live Paint group left with only its hidden source paths
/// succeeds and changes nothing, while an empty selection is still refused.
#[test]
fn live_paint_group_with_only_source_paths_ignores_add_fill_and_add_stroke_of_its_contents() {
let mut s = session();
let g = live(&mut s);
let n = node(&s, g);
let parts: Vec<NodeId> = vectorcraft_tools::builder::faces(&n).iter().chain(vectorcraft_tools::builder::edges(&n).iter()).map(|p| p.id).collect();
s.edit("t", |d, _| {
d.children_mut(Some(g)).unwrap().retain(|c| !parts.contains(&c.id));
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
let before = node(&s, g);
for cmd in ["appearance.addFill", "appearance.addStroke"] {
s.execute(cmd, &json!({"target": "contents"})).unwrap();
assert_eq!(node(&s, g), before, "{cmd} changes nothing");
}
s.execute("select.none", &json!({})).unwrap();
assert!(s.execute("appearance.addFill", &json!({"target": "contents"})).is_err(), "no selection is still refused");
}
/// A selected Live Paint group with no part of the edited kind is still a selection: a stroke edit
/// of a group without edges, or a fill gradient edit of a group without faces, changes nothing and
/// leaves the settings for new art as they are.
@@ -4304,6 +4651,8 @@ fn live_paint_group_without_parts_of_the_edited_kind_leaves_new_art_alone() {
s.execute("stroke.set", &json!({"weight": 4})).unwrap();
s.execute("stroke.weightUp", &json!({})).unwrap();
s.execute("stroke.setAdvanced", &json!({"arrowScale": [200, 150]})).unwrap();
// A stroke row edit of the group's contents finds no edge either.
s.execute("stroke.set", &json!({"target": "contents", "item": 0, "weight": 9})).unwrap();
assert_eq!((s.paint.clone(), s.new_art_stroke()), (paint0, stroke0), "new art keeps its stroke");
assert_eq!(part_looks(&s, g), looks);
@@ -9280,6 +9629,111 @@ fn image_trace_built_in_presets_cannot_be_saved_over_or_deleted() {
assert_eq!(six["params"], serde_json::to_value(vectorcraft_trace::preset("6 Colors").unwrap()).unwrap());
}
/// Saved tracing presets go out to a .vctracepresets file and come back with their names and
/// settings; a hand-written file in the documented layout imports too.
#[test]
fn image_trace_presets_export_and_import_round_trip() {
let mut s = session();
assert!(s.execute("imageTrace.presets.export", &json!({})).unwrap_err().to_string().contains("no saved tracing presets"));
s.execute("imageTrace.presets.save", &json!({"name": "Poster", "preset": "6 Colors", "params": {"noise": 40, "ignoreWhite": true}})).unwrap();
s.execute("imageTrace.presets.save", &json!({"name": "Ink", "params": {"threshold": 90, "fills": false, "strokes": true}})).unwrap();
let e = s.execute("imageTrace.presets.export", &json!({"names": ["Default"]})).unwrap_err().to_string();
assert!(e.contains("only saved presets are exported"), "{e}");
assert!(s.execute("imageTrace.presets.export", &json!({"names": ["Nope"]})).is_err());
let all = s.execute("imageTrace.presets.export", &json!({})).unwrap();
assert_eq!(all["count"], 2);
let one = s.execute("imageTrace.presets.export", &json!({"names": ["poster", "Poster"]})).unwrap();
assert_eq!(one["count"], 1);
let file: Value = serde_json::from_str(all["data"].as_str().unwrap()).unwrap();
assert_eq!((file["format"].as_str(), file["version"].as_u64()), (Some("vctracepresets"), Some(1)));
let saved = s.prefs.trace_presets.clone();
// Into a session without them: the same names and settings, and a new revision the panel follows.
let mut t = session();
let before = t.trace_presets_revision();
let r = t.execute("imageTrace.presets.import", &json!({"data": all["data"]})).unwrap();
assert_eq!(r, json!({"imported": ["Poster", "Ink"], "replaced": [], "skipped": []}));
assert_eq!(t.prefs.trace_presets, saved);
assert_eq!(t.trace_presets_revision(), before + 2);
// A file written by hand in the documented layout: missing settings are Default's.
let hand = r#"{"format": "vctracepresets", "version": 1, "presets": [{"name": "Hand", "params": {"mode": "grayscale", "colors": 12}}]}"#;
t.execute("imageTrace.presets.import", &json!({ "dataBase64": vectorcraft_format::base64_encode(hand.as_bytes()) })).unwrap();
let hand = t.trace_preset("hand").unwrap().params.clone();
assert_eq!((hand.mode, hand.colors, hand.threshold), (vectorcraft_trace::Mode::Grayscale, 12, 128));
}
/// Export writes no file that import would refuse (more than 1,000 presets, or more than 4 MiB),
/// and no more than 1,000 tracing presets can be saved.
#[test]
fn image_trace_presets_export_keeps_to_what_import_reads() {
let mut s = session();
let params = vectorcraft_trace::preset("Default").unwrap();
let preset = |name: String| crate::cmd::TracePreset { name, params: params.clone() };
s.prefs.trace_presets = (1..=1001).map(|i| preset(format!("P{i}"))).collect();
let e = s.execute("imageTrace.presets.export", &json!({})).unwrap_err().to_string();
assert!(e.contains("more than one file holds (1000)"), "{e}");
s.prefs.trace_presets.pop();
let all = s.execute("imageTrace.presets.export", &json!({})).unwrap();
assert_eq!(all["count"], 1000);
let mut t = session();
assert_eq!(t.execute("imageTrace.presets.import", &json!({"data": all["data"]})).unwrap()["imported"].as_array().map(Vec::len), Some(1000));
// No more can be saved or imported then, so every saved preset still fits in one file; a
// saved preset can still change, and a file of saved names still replaces them.
let e = t.execute("imageTrace.presets.save", &json!({"name": "One More"})).unwrap_err().to_string();
assert!(e.contains("delete one first"), "{e}");
t.execute("imageTrace.presets.save", &json!({"name": "P1", "params": {"noise": 9}})).unwrap();
let one = json!({"format": "vctracepresets", "version": 1, "presets": [{"name": "Fresh", "params": {}}]}).to_string();
let e = t.execute("imageTrace.presets.import", &json!({ "data": one })).unwrap_err().to_string();
assert!(e.contains("more than 1000 saved"), "{e}");
let again = json!({"format": "vctracepresets", "version": 1, "presets": [{"name": "P2", "params": {}}]}).to_string();
assert_eq!(t.execute("imageTrace.presets.import", &json!({"data": again, "replace": true})).unwrap()["replaced"], json!(["P2"]));
assert_eq!(t.prefs.trace_presets.len(), 1000);
s.prefs.trace_presets = vec![preset("x".repeat(4 << 20))];
let e = s.execute("imageTrace.presets.export", &json!({})).unwrap_err().to_string();
assert!(e.contains("larger than 4 MiB"), "{e}");
}
/// A saved preset of the same name is skipped unless `replace` is on; a file with a fault, or one
/// too large, changes nothing.
#[test]
fn image_trace_presets_import_checks_the_whole_file_first() {
let mut s = session();
s.execute("imageTrace.presets.save", &json!({"name": "Poster", "params": {"noise": 40}})).unwrap();
let file = |rows: Value| json!({"format": "vctracepresets", "version": 1, "presets": rows}).to_string();
let data = file(json!([{"name": "poster", "params": {"noise": 7}}, {"name": "Fresh", "params": {}}]));
let r = s.execute("imageTrace.presets.import", &json!({ "data": data })).unwrap();
assert_eq!(r, json!({"imported": ["Fresh"], "replaced": [], "skipped": ["poster"]}));
assert_eq!(s.trace_preset("Poster").unwrap().params.noise, 40);
let r = s.execute("imageTrace.presets.import", &json!({"data": data, "replace": true})).unwrap();
assert_eq!(r, json!({"imported": [], "replaced": ["Poster", "Fresh"], "skipped": []}));
assert_eq!(s.trace_preset("Poster").unwrap().params.noise, 7);
assert!(s.execute("imageTrace.presets.import", &json!({"data": data, "replace": "yes"})).is_err());
let saved = s.prefs.trace_presets.clone();
let revision = s.trace_presets_revision();
let bad_files = [
(file(json!([{"name": "New One", "params": {}}, {"name": "[Default]", "params": {}}])), "built-in preset"),
(file(json!([{"name": "custom", "params": {}}])), "built-in preset"),
(file(json!([{"name": "Twice", "params": {}}, {"name": "twice", "params": {}}])), "two presets named"),
(file(json!([{"name": " ", "params": {}}])), "has no name"),
(file(json!([{"name": "No Params"}])), "has no `params`"),
(file(json!([{"name": "Neither", "params": {"fills": false, "strokes": false}}])), "Create needs fills"),
(file(json!([{"name": "Typo", "params": {"nosie": 3}}])), "nosie"),
(json!({"format": "vctracepresets", "version": 2, "presets": []}).to_string(), "newer"),
(json!({"format": "vcflattener", "version": 1, "presets": []}).to_string(), "not a tracing presets file"),
("{".to_string(), "not a tracing presets file"),
(file(Value::Array(vec![json!({"name": "x", "params": {}}); 1001])), "more than 1000"),
(" ".repeat((4 << 20) + 1), "larger than 4 MiB"),
];
for (data, why) in bad_files {
let e = s.execute("imageTrace.presets.import", &json!({ "data": data })).unwrap_err().to_string();
assert!(e.contains(why), "{why}: {e}");
}
let big = vectorcraft_format::base64_encode(&vec![b' '; (4 << 20) + 1]);
assert!(s.execute("imageTrace.presets.import", &json!({ "dataBase64": big })).unwrap_err().to_string().contains("larger than 4 MiB"));
assert!(s.execute("imageTrace.presets.import", &json!({})).is_err());
assert_eq!(s.prefs.trace_presets, saved, "nothing changed");
assert_eq!(s.trace_presets_revision(), revision);
}
/// Saved tracing presets are kept with the preferences, are not a preference key, and survive
/// resetting the preferences.
#[test]
+29
View File
@@ -204,6 +204,35 @@ fn the_circle_is_not_moved_onto_the_pixel_grid() {
assert!(!node(&s, id).extras().pixel_aligned);
}
/// `anchors: "points"` puts an anchor exactly at each point, with one more on each half of a
/// diameter's circle; the circle is a plain path, not pixel-aligned, and one undo step. Any other
/// `anchors` value is an error and draws nothing.
#[test]
fn anchors_at_the_points_puts_an_anchor_at_each_point() {
let mut s = session();
s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap();
let undo = undo_len(&s);
let points = [Point::new(0.3, 0.2), Point::new(80.6, 0.1), Point::new(0.4, 60.7)];
let pairs: Vec<Value> = points.iter().map(|p| json!([p.x, p.y])).collect();
let id = id_of(&s.execute(C, &json!({ "points": pairs, "anchors": "points" })).unwrap());
let n = node(&s, id);
let anchors: Vec<Point> = n.path_data().unwrap().subpaths[0].anchors.iter().map(|a| a.p).collect();
assert!(points.iter().all(|p| anchors.contains(p)), "{anchors:?}");
assert!(matches!(n.kind, NodeKind::Path { live: None, .. }), "{:?}", n.kind);
assert!(!n.extras().pixel_aligned);
assert_eq!(undo_len(&s), undo + 1);
let id = id_of(&s.execute(C, &json!({ "points": [[0, 0], [100, 0]], "anchors": "points" })).unwrap());
let anchors: Vec<Point> = node(&s, id).path_data().unwrap().subpaths[0].anchors.iter().map(|a| a.p).collect();
assert_eq!(anchors.len(), 4, "{anchors:?}");
assert_eq!((anchors[0], anchors[2]), (Point::new(0.0, 0.0), Point::new(100.0, 0.0)));
let (count, undo) = (object_count(&s), undo_len(&s));
for bad in [json!("corners"), json!(true), json!(4), Value::Null] {
let e = s.execute(C, &json!({ "points": [[0, 0], [100, 0]], "anchors": bad })).unwrap_err().to_string();
assert!(e.contains("`anchors` must be one of standard, points"), "{e}");
}
assert_eq!((object_count(&s), undo_len(&s)), (count, undo));
}
fn view() -> ViewInfo {
ViewInfo { smart_guides: false, ..ViewInfo::default() }
}
+264
View File
@@ -127,6 +127,25 @@ fn c_flips_and_brackets_size_the_last_sharp_arc() {
assert!(!s.tool_claims_key(ToolKey::Letter('c'), view()));
}
/// The drawing end (where the Quick Pen toolbar sits beside) is the path's last point with the
/// direction it arrives in: none before the first click, no direction for one point, and none
/// once Escape ends the path.
#[test]
fn the_drawing_end_is_the_last_point_and_its_direction() {
let mut s = session();
quick_pen(&mut s);
assert_eq!(s.tool_drawing_end(view()), None);
click(&mut s, 100.0, 100.0);
assert_eq!(s.tool_drawing_end(view()), Some((pt(100.0, 100.0), None)));
click(&mut s, 100.0, 200.0);
let (p, dir) = s.tool_drawing_end(view()).unwrap();
assert_eq!(p, pt(100.0, 200.0));
let dir = dir.unwrap();
assert!(dir.x.abs() < 1e-9 && dir.y > 0.99, "arrives heading down: {dir:?}");
key(&mut s, ToolKey::Escape);
assert_eq!(s.tool_drawing_end(view()), None);
}
/// Alt tapped during a drag draws the piece with the next action: a continuous arc becomes a
/// sharp-corner arc with a corner where it starts, and the path goes on drawing after it.
#[test]
@@ -183,6 +202,251 @@ fn escape_ends_the_path_and_a_drag_places_the_piece() {
assert_eq!(paths(&s).len(), 2);
}
/// The piece a press draws ends where the press is let go, past the last drag too, and a press let
/// go a drag's distance away with no drag in between places it there as well.
#[test]
fn the_piece_ends_where_the_press_is_let_go() {
let mut s = session();
quick_pen(&mut s);
click(&mut s, 100.0, 100.0);
let v = view();
s.pointer(&PointerEvent::new(PointerKind::Down, 150.0, 100.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 180.0, 120.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 250.0, 150.0), v).unwrap();
assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(250.0, 150.0));
let undo = undo_steps(&s);
s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 100.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 340.0, 100.0), v).unwrap();
assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(340.0, 100.0));
assert_eq!(undo_steps(&s), undo + 1);
}
/// C and `[` `]` during a drag change the sharp-corner arc being dragged, within the press's one
/// undo step.
#[test]
fn c_and_brackets_during_a_drag_change_the_arc_being_dragged() {
let mut s = session();
quick_pen(&mut s);
s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap();
click(&mut s, 100.0, 300.0);
let undo = undo_steps(&s);
let v = view();
s.pointer(&PointerEvent::new(PointerKind::Down, 280.0, 300.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 300.0, 300.0), v).unwrap();
assert!(s.tool_claims_key(ToolKey::Letter('c'), view()));
key(&mut s, ToolKey::Letter('c'));
assert!(only_path(&s).anchors.get(1).unwrap().p.distance(pt(200.0, 400.0)) < 1e-9, "flipped while dragging");
key(&mut s, ToolKey::BracketLeft);
assert_eq!(s.tool_options()["turn"], 165.0);
// A 165° arc is two segments, and its middle point lies the arc's sagitta below the chord
// (a 180° arc's lies 100 below).
let half = 82.5f64.to_radians();
let mid_165 = pt(200.0, 300.0 + 100.0 / half.sin() * (1.0 - half.cos()));
assert_eq!(only_path(&s).anchors.len(), 3);
assert!(only_path(&s).anchors.get(1).unwrap().p.distance(mid_165) < 1e-6, "the dragged arc is 165°");
s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 300.0), v).unwrap();
let sp = only_path(&s);
assert_eq!(sp.anchors.len(), 3);
assert!(sp.anchors.get(1).unwrap().p.distance(mid_165) < 1e-6, "the flip and the size stay after the release");
assert_eq!(undo_steps(&s), undo + 1);
}
/// An edit made by another command during a drag ends the path: the next drag does not draw over
/// the edit, the piece stays as last shown, and the next click starts a new path.
#[test]
fn an_edit_during_a_drag_ends_the_path() {
let mut s = session();
quick_pen(&mut s);
click(&mut s, 100.0, 100.0);
click(&mut s, 200.0, 100.0);
let id = paths(&s)[0].0;
let v = view();
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 180.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap();
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 90, "y": 90})).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 250.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 260.0, 260.0), v).unwrap();
let ends: Vec<Point> = only_path(&s).anchors.iter().map(|a| a.p).collect();
assert_eq!(ends, [pt(90.0, 90.0), pt(200.0, 100.0), pt(200.0, 200.0)], "the edit and the piece as last shown");
click(&mut s, 400.0, 400.0);
assert_eq!(paths(&s).len(), 2, "a new path");
}
/// With Real-time Drawing off, a sharp-corner arc let go past the last drag is placed where it was
/// let go, and C then flips that arc.
#[test]
fn a_deferred_arc_let_go_past_the_last_drag_flips() {
let mut s = session();
s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap();
quick_pen(&mut s);
s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap();
click(&mut s, 100.0, 300.0);
let v = view();
s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 300.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 270.0, 300.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 300.0), v).unwrap();
let sp = only_path(&s);
assert_eq!(sp.anchors.len(), 3);
assert_eq!(sp.anchors.last().unwrap().p, pt(300.0, 300.0));
let mid = sp.anchors.get(1).unwrap().p;
key(&mut s, ToolKey::Letter('c'));
let flipped = only_path(&s);
assert_eq!(flipped.anchors.len(), 3);
assert!(flipped.anchors.get(1).unwrap().p.distance(pt(200.0, 600.0 - mid.y)) < 1e-9, "flipped across the chord");
}
/// An edit made by another command to the path's look during a drag ends the path too.
#[test]
fn a_look_edit_during_a_drag_ends_the_path() {
let mut s = session();
quick_pen(&mut s);
click(&mut s, 100.0, 100.0);
click(&mut s, 200.0, 100.0);
let id = paths(&s)[0].0;
let v = view();
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 180.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap();
s.execute("paint.setStroke", &json!({"ids": [id.0], "color": "#00ff00"})).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 260.0, 260.0), v).unwrap();
let ends: Vec<Point> = only_path(&s).anchors.iter().map(|a| a.p).collect();
assert_eq!(ends, [pt(100.0, 100.0), pt(200.0, 100.0), pt(200.0, 200.0)], "the piece as last shown");
click(&mut s, 400.0, 400.0);
assert_eq!(paths(&s).len(), 2, "a new path");
}
/// An edit made by another command to another object during a drag stays and ends the path: the
/// press previews no more, its piece stays as last shown, and the next click starts a new path.
#[test]
fn an_edit_to_another_object_during_a_drag_stays() {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 500, "y": 400, "width": 50, "height": 50})).unwrap();
let rect = s.doc().unwrap().selection.objects[0];
quick_pen(&mut s);
click(&mut s, 100.0, 100.0);
click(&mut s, 200.0, 100.0);
let v = view();
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 180.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap();
s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#00ff00"})).unwrap();
let edited = s.doc().unwrap().doc.node(rect).unwrap().clone();
s.pointer(&PointerEvent::new(PointerKind::Up, 260.0, 260.0), v).unwrap();
assert_eq!(*s.doc().unwrap().doc.node(rect).unwrap(), edited, "the other object's edit stays");
let pen = paths(&s).into_iter().find(|(id, _)| *id != rect).unwrap().1;
let ends: Vec<Point> = pen.subpaths[0].anchors.iter().map(|a| a.p).collect();
assert_eq!(ends, [pt(100.0, 100.0), pt(200.0, 100.0), pt(200.0, 200.0)], "the piece as last shown");
click(&mut s, 400.0, 400.0);
assert_eq!(paths(&s).len(), 3, "a new path");
}
/// With Real-time Drawing off, a drag during which another command edits the path adds no piece,
/// and the edit stays.
#[test]
fn an_edit_during_a_deferred_drag_stays() {
let mut s = session();
s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap();
quick_pen(&mut s);
click(&mut s, 100.0, 100.0);
click(&mut s, 200.0, 100.0);
let id = paths(&s)[0].0;
let v = view();
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 180.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap();
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 90, "y": 90})).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 250.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 260.0, 260.0), v).unwrap();
let ends: Vec<Point> = only_path(&s).anchors.iter().map(|a| a.p).collect();
assert_eq!(ends, [pt(90.0, 90.0), pt(200.0, 100.0)], "the edit, and no piece");
}
/// An edit made by another command to another object during a click stays, and the path goes on:
/// a click previews its piece only when the press begins.
#[test]
fn an_edit_to_another_object_during_a_click_stays() {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 500, "y": 400, "width": 50, "height": 50})).unwrap();
let rect = s.doc().unwrap().selection.objects[0];
quick_pen(&mut s);
click(&mut s, 100.0, 100.0);
click(&mut s, 200.0, 100.0);
let v = view();
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0), v).unwrap();
s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#00ff00"})).unwrap();
let edited = s.doc().unwrap().doc.node(rect).unwrap().clone();
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0), v).unwrap();
assert_eq!(*s.doc().unwrap().doc.node(rect).unwrap(), edited, "the other object's edit stays");
click(&mut s, 300.0, 200.0);
let all = paths(&s);
assert_eq!(all.len(), 2, "no new path");
let pen = all.into_iter().find(|(id, _)| *id != rect).unwrap().1;
let ends: Vec<Point> = pen.subpaths[0].anchors.iter().map(|a| a.p).collect();
assert_eq!(ends, [pt(100.0, 100.0), pt(200.0, 100.0), pt(200.0, 200.0), pt(300.0, 200.0)]);
}
/// An edit made by another command during a click (a press let go where it went down) ends the
/// path too: the next click starts a new path instead of drawing over the edit.
#[test]
fn an_edit_during_a_click_ends_the_path() {
let mut s = session();
quick_pen(&mut s);
click(&mut s, 100.0, 100.0);
click(&mut s, 200.0, 100.0);
let id = paths(&s)[0].0;
let v = view();
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 180.0), v).unwrap();
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 90, "y": 90})).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 180.0), v).unwrap();
click(&mut s, 400.0, 400.0);
assert_eq!(paths(&s).len(), 2, "a new path");
let ends: Vec<Point> = paths(&s)[0].1.subpaths[0].anchors.iter().map(|a| a.p).collect();
assert_eq!(ends, [pt(90.0, 90.0), pt(200.0, 100.0), pt(200.0, 180.0)], "the edit stays");
}
/// With Align New Objects to Pixel Grid on, the path the tool draws is pixel-aligned: its points
/// move onto the grid, and the next click and drag still go on drawing the same path.
#[test]
fn a_pixel_aligned_path_goes_on_drawing() {
let mut s = session();
s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap();
quick_pen(&mut s);
click(&mut s, 100.0, 100.0);
click(&mut s, 200.0, 100.0);
let ends = |s: &Session| only_path(s).anchors.iter().map(|a| a.p).collect::<Vec<Point>>();
let two = ends(&s);
assert_eq!(two.len(), 2);
assert_eq!(two[0].y, two[1].y, "a level line");
press(&mut s, &[(300.0, 150.0), (310.0, 170.0), (320.0, 200.0)]);
let three = ends(&s);
assert_eq!(three.len(), 3, "one path of three points");
assert_eq!(three[..2], two[..], "the points before the piece stay as they were");
assert!(three[2].distance(pt(320.0, 200.0)) <= 1.0, "the drag's piece ends near where it was let go: {:?}", three[2]);
click(&mut s, 400.0, 100.0);
let four = ends(&s);
assert_eq!(four.len(), 4);
assert_eq!(four[..3], three[..]);
}
/// A dropped press takes back only its own piece, and with Real-time Drawing off a drag places its
/// piece on the release: in both cases the next click goes on drawing the same path.
#[test]
fn a_dropped_press_and_a_deferred_drag_keep_the_path() {
let mut s = session();
quick_pen(&mut s);
click(&mut s, 100.0, 100.0);
click(&mut s, 200.0, 100.0);
let v = view();
s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 100.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 320.0, 150.0), v).unwrap();
s.drop_tool_press(v).unwrap();
assert_eq!(only_path(&s).anchors.len(), 2, "the dropped piece is gone");
click(&mut s, 300.0, 200.0);
assert_eq!(only_path(&s).anchors.len(), 3, "the path goes on");
s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap();
press(&mut s, &[(400.0, 200.0), (420.0, 250.0), (450.0, 300.0)]);
assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(450.0, 300.0));
click(&mut s, 500.0, 100.0);
assert_eq!(only_path(&s).anchors.len(), 5, "the path goes on after the deferred piece");
}
/// An anchor moved by another command ends the path being drawn: C does not flip the old arc back
/// over the edit, and the next click starts a new path instead of rebuilding the old one.
#[test]
+168
View File
@@ -133,6 +133,174 @@ fn colors_with_nothing_selected_leave_out_what_select_all_leaves_out() {
assert_eq!(hexes(&run(&mut s, "recolor.colors", json!({"ids": [hidden.0]}))), ["#0000ff"]);
}
#[test]
fn used_colors_list_the_most_used_first_with_their_colors() {
let mut s = session();
let reds: Vec<NodeId> = (0..3).map(|_| rect(&mut s, json!("#ff0000"))).collect();
let blue = rect(&mut s, json!({"c": 100, "m": 100, "y": 0, "k": 0}));
run(&mut s, "select.set", json!({"ids": []}));
let r = run(&mut s, "color.used", json!({}));
assert_eq!(r["selection"], false, "{r}");
let colors = r["colors"].as_array().unwrap();
assert_eq!(colors.len(), 2, "{r}");
assert_eq!((colors[0]["key"].as_str(), colors[0]["hex"].as_str(), colors[0]["count"].as_u64()), (Some("rgb 255 0 0"), Some("#ff0000"), Some(3)));
assert_eq!(colors[1]["count"], 1);
let first = run(&mut s, "color.used", json!({"limit": 1}));
assert_eq!(first["colors"], json!([colors[0]]), "`limit` keeps the most used");
assert_eq!((r["uses"].clone(), first["uses"].clone()), (json!(4), json!(4)), "`uses` counts every color");
// `color` is the color in its own model, which the paint commands take back.
assert_eq!(colors[1]["color"]["model"], "cmyk", "{r}");
assert!(close(color_value(&colors[1]["color"]).unwrap(), fill(&s, blue)));
// The selection's colors while something is selected; `selection: false` reads all the art.
run(&mut s, "select.set", json!({"ids": [blue.0]}));
let r = run(&mut s, "color.used", json!({}));
assert_eq!((r["selection"].clone(), r["colors"].as_array().unwrap().len()), (json!(true), 1), "{r}");
let all = run(&mut s, "color.used", json!({"selection": false}));
assert_eq!((all["selection"].clone(), all["colors"][0]["count"].clone()), (json!(false), json!(3)), "{all}");
assert_eq!(s.doc().unwrap().selection.objects, [blue], "the selection is left as it was");
// A hidden object's color is left out with nothing selected, as Select All leaves it out.
run(&mut s, "object.hide", json!({"ids": [reds[0].0]}));
assert_eq!(run(&mut s, "color.used", json!({"selection": false}))["colors"][0]["count"], 2);
let e = s.execute("color.used", &json!({"selection": "no"})).unwrap_err().to_string();
assert!(e.contains("`selection` must be true or false"), "{e}");
assert!(s.execute("color.used", &json!({"ids": [blue.0]})).is_err(), "an unknown key is refused");
}
#[test]
fn used_colors_name_the_swatch_and_tint_a_color_is_linked_to() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true}));
let tinted = rect(&mut s, json!("#000000"));
run(&mut s, "paint.setFill", json!({"ids": [tinted.0], "swatch": "Ink", "tint": 40}));
run(&mut s, "select.set", json!({"ids": []}));
let r = run(&mut s, "color.used", json!({}));
let c = &r["colors"][0];
assert_eq!(c["swatch"].as_str(), Some("Ink"), "{r}");
assert!((c["tint"].as_f64().unwrap() - 40.0).abs() < 1e-4, "{r}");
// recolor.colors keeps its own fields.
assert_eq!(run(&mut s, "recolor.colors", json!({}))["colors"][0].get("tint"), None);
// A swatch of paper white looks the same at every tint; the tint comes from the paint.
run(&mut s, "swatch.new", json!({"name": "Paper", "color": {"c": 0, "m": 0, "y": 0, "k": 0}, "spot": true}));
let paper = rect(&mut s, json!("#000000"));
run(&mut s, "paint.setFill", json!({"ids": [paper.0], "swatch": "Paper", "tint": 33.333}));
run(&mut s, "select.set", json!({"ids": [paper.0]}));
let c = run(&mut s, "color.used", json!({}))["colors"][0].clone();
assert_eq!(c["swatch"].as_str(), Some("Paper"), "{c}");
// The tint is the paint's own, unrounded.
let vectorcraft_color::Paint::Solid { tint, .. } = s.doc().unwrap().doc.node(paper).unwrap().appearance.fill_paint() else {
panic!("a solid fill")
};
assert_eq!((c["tint"].as_f64().unwrap() / 100.0) as f32, tint, "{c}");
assert!((tint - 0.33333).abs() < 1e-5);
// A pattern's tile keeps its tint as well.
run(&mut s, "select.set", json!({"ids": [paper.0]}));
run(&mut s, "object.pattern.make", json!({"name": "Sheet", "width": 20, "height": 20}));
run(&mut s, "object.pattern.done", json!({}));
let filled = rect(&mut s, json!("#000000"));
run(&mut s, "paint.setFill", json!({"ids": [filled.0], "swatch": "Sheet"}));
run(&mut s, "select.set", json!({"ids": [filled.0]}));
let c = run(&mut s, "color.used", json!({}))["colors"][0].clone();
assert_eq!(c["swatch"].as_str(), Some("Paper"), "{c}");
assert_eq!((c["tint"].as_f64().unwrap() / 100.0) as f32, tint, "{c}");
}
#[test]
fn used_colors_read_the_tiles_of_patterns_used_inside_pattern_tiles() {
let mut s = session();
let red = rect(&mut s, json!("#ff0000"));
run(&mut s, "select.set", json!({"ids": [red.0]}));
run(&mut s, "object.pattern.make", json!({"name": "Inner", "width": 20, "height": 20}));
run(&mut s, "object.pattern.done", json!({}));
let middle = rect(&mut s, json!("#000000"));
run(&mut s, "paint.setFill", json!({"ids": [middle.0], "swatch": "Inner"}));
run(&mut s, "select.set", json!({"ids": [middle.0]}));
run(&mut s, "object.pattern.make", json!({"name": "Outer", "width": 20, "height": 20}));
run(&mut s, "object.pattern.done", json!({}));
let square = rect(&mut s, json!("#000000"));
run(&mut s, "paint.setFill", json!({"ids": [square.0], "swatch": "Outer"}));
// The inner tile's square is stroked with the outer pattern, so the two patterns use each other.
let outer = s.doc().unwrap().doc.node(square).unwrap().appearance.fill_paint().clone();
let st = s.doc_mut().unwrap();
let doc = std::sync::Arc::make_mut(&mut st.doc);
let tile = doc.pattern_mut("Inner").unwrap().art.first_mut().unwrap();
std::sync::Arc::make_mut(tile).appearance.set_stroke(outer);
run(&mut s, "select.set", json!({"ids": [square.0]}));
let r = run(&mut s, "color.used", json!({}));
let colors = r["colors"].as_array().unwrap();
assert_eq!(colors.iter().map(|c| (c["hex"].as_str(), c["count"].as_u64())).collect::<Vec<_>>(), [(Some("#ff0000"), Some(1))], "{r}");
}
#[test]
fn used_colors_give_no_swatch_for_a_stop_that_mixes_its_ink_with_process_inks() {
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop, Paint};
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true}));
let shape = rect(&mut s, json!("#000000"));
let mixed = Color::Cmyk { c: 0.3, m: 0.5, y: 0.3, k: 0.0 };
let stop = |color, plates| GradientStop { swatch: Some("Ink".into()), tint: 0.5, plates, ..GradientStop::new(0.0, color) };
let mut end = stop(Color::Cmyk { c: 0.0, m: 0.5, y: 0.3, k: 0.0 }, None);
end.offset = 1.0;
let g = Gradient::new(GradientKind::Linear, vec![stop(mixed, Some([0.3, 0.0, 0.0, 0.0])), end]);
let st = s.doc_mut().unwrap();
std::sync::Arc::make_mut(&mut st.doc).node_mut(shape).unwrap().appearance.set_fill(Paint::Gradient(Box::new(GradientPaint::new(g))));
let r = run(&mut s, "color.used", json!({}));
let entry = |key: &str| r["colors"].as_array().unwrap().iter().find(|c| c["key"] == key).cloned().unwrap();
let mix = entry("cmyk 30 50 30 0");
assert_eq!((mix.get("swatch"), mix.get("tint")), (None, None), "{r}");
assert_eq!(entry("cmyk 0 50 30 0")["swatch"], "Ink", "{r}");
// recolor.colors keeps the swatch it lists.
let listed = run(&mut s, "recolor.colors", json!({}));
assert!(listed["colors"].as_array().unwrap().iter().all(|c| c["swatch"] == "Ink"), "{listed}");
}
#[test]
fn used_colors_take_the_swatch_of_a_plain_use_painted_after_a_mixed_stop_of_the_same_color() {
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop, Paint};
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true}));
let shape = rect(&mut s, json!("#000000"));
let plain = rect(&mut s, json!("#000000"));
run(&mut s, "paint.setFill", json!({"ids": [plain.0], "swatch": "Ink", "tint": 50}));
let ink = fill(&s, plain);
// The stop below the plain fill has the same color, and process plates that add nothing.
let stop = GradientStop { swatch: Some("Ink".into()), tint: 0.5, plates: Some([0.0; 4]), ..GradientStop::new(0.0, ink) };
let mut end = stop.clone();
end.offset = 1.0;
let g = Gradient::new(GradientKind::Linear, vec![stop, end]);
let st = s.doc_mut().unwrap();
std::sync::Arc::make_mut(&mut st.doc).node_mut(shape).unwrap().appearance.set_fill(Paint::Gradient(Box::new(GradientPaint::new(g))));
run(&mut s, "select.set", json!({"ids": []}));
let r = run(&mut s, "color.used", json!({}));
let c = r["colors"].as_array().unwrap().iter().find(|c| c["count"] == 3).cloned().unwrap();
assert_eq!((c["swatch"].as_str(), c["tint"].as_f64()), (Some("Ink"), Some(50.0)), "{r}");
}
#[test]
fn recolor_colors_keeps_the_swatch_of_the_first_linked_use_when_a_mixed_stop_comes_first() {
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop, Paint};
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true}));
run(&mut s, "swatch.new", json!({"name": "Other", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true}));
let shape = rect(&mut s, json!("#000000"));
let plain = rect(&mut s, json!("#000000"));
run(&mut s, "paint.setFill", json!({"ids": [plain.0], "swatch": "Other", "tint": 50}));
let ink = fill(&s, plain);
// The stop below the plain fill has the same color, linked to another swatch, with process
// plates that add nothing.
let stop = GradientStop { swatch: Some("Ink".into()), tint: 0.5, plates: Some([0.0; 4]), ..GradientStop::new(0.0, ink) };
let mut end = stop.clone();
end.offset = 1.0;
let g = Gradient::new(GradientKind::Linear, vec![stop, end]);
let st = s.doc_mut().unwrap();
std::sync::Arc::make_mut(&mut st.doc).node_mut(shape).unwrap().appearance.set_fill(Paint::Gradient(Box::new(GradientPaint::new(g))));
run(&mut s, "select.set", json!({"ids": []}));
let three = |r: &Value| r["colors"].as_array().unwrap().iter().find(|c| c["count"] == 3).cloned().unwrap();
let used = run(&mut s, "color.used", json!({}));
assert_eq!(three(&used)["swatch"], "Other", "{used}");
let listed = run(&mut s, "recolor.colors", json!({}));
assert_eq!(three(&listed)["swatch"], "Ink", "recolor.colors names the first linked use: {listed}");
}
#[test]
fn colors_with_nothing_selected_leave_out_hidden_and_locked_objects_in_groups() {
let mut s = session();
+15
View File
@@ -856,6 +856,12 @@ impl Session {
self.ruler_origin = None;
}
/// A guide is being dragged out of a ruler ([`Session::ruler_guide`]): its first event came
/// and its release has not.
pub fn ruler_guide_dragging(&self) -> bool {
self.ruler_guide.is_some()
}
/// Time passed while the pointer button is held (`dt` seconds; see [`Tool::tick`]): the
/// desktop app ticks every frame of a press, agents with `holdMs` on a pointer event.
pub fn tool_tick(&mut self, dt: f64, view: ViewInfo) -> Result<Vec<UiRequest>> {
@@ -1256,6 +1262,12 @@ impl Session {
self.with_tool_cx(view, |t, cx| t.ends_on_escape(cx))
}
/// The point a path the active tool is drawing goes on from, and the direction the path
/// arrives there in (see `Tool::drawing_end`).
pub fn tool_drawing_end(&mut self, view: ViewInfo) -> Option<(Point, Option<vectorcraft_geom::Vec2>)> {
self.with_tool_cx(view, |t, cx| t.drawing_end(cx))
}
pub fn overlays(&mut self, view: ViewInfo) -> Vec<Overlay> {
// The Blend tool's first pick is not marked after an edit that dropped it.
self.tell_tool_history_moved();
@@ -1478,6 +1490,9 @@ impl Session {
}
// Every value is checked before any is set, so an invalid one changes nothing.
vectorcraft_tools::builder::check_builder_options(id, &values)?;
if id == vectorcraft_tools::circle::ID {
vectorcraft_tools::circle::check_options(&values)?;
}
vectorcraft_tools::symbolism::check_options(id, &values)?;
if id == vectorcraft_tools::cropimage::ID {
use vectorcraft_tools::cropimage as crop;
+102
View File
@@ -367,6 +367,61 @@ pub fn circle_through_points(points: &[Point]) -> Option<(Point, f64)> {
circle.filter(|(c, r)| c.is_finite() && r.is_finite() && *r > 0.0)
}
/// The circle at `center` with `radius` as a closed path whose anchors are `points` (points on the
/// circle, as [`circle_through_points`] gives it) plus as many more as split each arc between two
/// of them into equal parts of at most a quarter turn. The path starts at the first point and runs
/// as [`ellipse`] does (left, top, right on the page); each curve's handles are 4/3·tan(θ/4) of
/// the radius along the tangents at its ends (θ, its turn). Two points with `center` at their
/// midpoint give four anchors. A point given twice is one anchor; with no points it starts at the
/// left, as [`ellipse`] does.
pub fn circle_with_anchors_at(center: Point, radius: f64, points: &[Point]) -> PathData {
let quarter = PI / 2.0;
let angle = |p: Point| (p.y - center.y).atan2(p.x - center.x);
let start = points.first().map_or(PI, |p| angle(*p));
// (turn from the first point, the point itself).
let mut placed: Vec<(f64, Point)> = points.iter().map(|p| ((angle(*p) - start).rem_euclid(TAU), *p)).collect();
placed.sort_by(|a, b| a.0.total_cmp(&b.0));
placed.dedup_by(|a, b| a.1 == b.1);
// Two points with the center at their midpoint are the ends of a diameter: the second is half a
// turn from the first, also where rounding moves the angle from the center off it.
if let [(_, a), (turn, b)] = placed.as_mut_slice()
&& a.midpoint(*b) == center
{
*turn = PI;
}
if placed.is_empty() {
placed.push((0.0, Point::new(center.x - radius, center.y)));
}
let on_circle = |t: f64| Point::new(center.x + radius * (start + t).cos(), center.y + radius * (start + t).sin());
// Every anchor: (turn, position), the given points where they are and the others on the circle.
let mut turns: Vec<(f64, Point)> = Vec::new();
for (i, &(t, p)) in placed.iter().enumerate() {
turns.push((t, p));
let next = placed.get(i + 1).map_or(TAU, |n| n.0);
let gap = next - t;
// At most 4 parts for the whole turn: a gap is never more than a full turn.
let parts = (gap / quarter - 1e-9).ceil().clamp(1.0, 4.0);
for k in 1..parts as u32 {
let tk = t + gap * f64::from(k) / parts;
turns.push((tk, on_circle(tk)));
}
}
let n = turns.len();
let anchors = (0..n)
.filter_map(|i| {
let &(t, p) = turns.get(i)?;
let prev = if i == 0 { turns.last()?.0 - TAU } else { turns.get(i - 1)?.0 };
let next = turns.get(i + 1).map_or(TAU, |n| n.0);
// The unit tangent along the run (y down: increasing angle).
let a = start + t;
let tangent = Vec2::new(-a.sin(), a.cos());
let handle = |turn: f64| radius * 4.0 / 3.0 * (turn / 4.0).tan();
Some(Anchor { p, h_in: p - tangent * handle(t - prev), h_out: p + tangent * handle(next - t), kind: AnchorKind::Smooth })
})
.collect();
PathData::single(SubPath::new(anchors, true))
}
/// Regular polygon with `sides` (≥ 3), first vertex straight up from the centre.
pub fn polygon(center: Point, radius: f64, sides: u32, rotation_deg: f64) -> PathData {
let n = sides.max(3);
@@ -1146,6 +1201,53 @@ mod tests {
}
}
/// The anchors are the given points exactly, plus enough more that no curve turns more than a
/// quarter; every anchor and every curve's middle lies on the circle, and the path starts at
/// the first point.
#[test]
fn a_circle_with_its_anchors_at_given_points() {
use kurbo::ParamCurve;
let (a, b, c) = (Point::new(8.0, 0.0), Point::new(0.0, 6.0), Point::ORIGIN);
let center = Point::new(4.0, 3.0);
for (points, count) in [(&[a, b][..], 4), (&[a, b, c][..], 5), (&[b, a, c, b][..], 5), (&[][..], 4)] {
let path = circle_with_anchors_at(center, 5.0, points);
let sub = &path.subpaths[0];
assert!(sub.closed, "{points:?}");
assert_eq!(sub.anchors.len(), count, "{points:?}: {sub:?}");
for p in points {
assert!(sub.anchors.iter().any(|q| q.p == *p), "{p:?} is an anchor: {sub:?}");
}
if let Some(first) = points.first() {
assert_eq!(sub.anchors[0].p, *first);
}
for q in &sub.anchors {
assert!((q.p.distance(center) - 5.0).abs() < 1e-9, "{q:?}");
}
for seg in path.to_bezpath().segments() {
let turn = {
let (p0, p1) = (seg.start() - center, seg.end() - center);
p0.cross(p1).atan2(p0.dot(p1))
};
assert!(turn > 0.0 && turn <= PI / 2.0 + 1e-9, "{turn} for {seg:?}");
assert!((seg.eval(0.5).distance(center) - 5.0).abs() < 5.0 * 1e-3, "{seg:?}");
}
}
}
/// The two ends of a diameter give four anchors, also where the midpoint rounds off it: at
/// x = 10⁶, steps of 2⁻³³ put the second point more than half a turn from the first, seen from
/// the rounded center.
#[test]
fn a_diameter_gives_four_anchors_where_its_midpoint_rounds() {
let u = 2f64.powi(-33);
let (a, b) = (Point::new(1_000_000.0, 0.0), Point::new(1_000_000.0 + 9.0 * u, 8.0 * u));
let (center, radius) = circle_through_points(&[a, b]).expect("a circle");
let path = circle_with_anchors_at(center, radius, &[a, b]);
let sub = &path.subpaths[0];
assert_eq!(sub.anchors.len(), 4, "{sub:?}");
assert_eq!((sub.anchors[0].p, sub.anchors[2].p), (a, b));
}
/// Nearly on one line: a point 10⁻⁴ off a chord 2000 long still gives the circle (its sagitta
/// formula `r = (h² + (L/2)²) / 2h`), and its center sits on the chord's perpendicular
/// bisector; a point 10⁻¹² off it does not.
+28 -3
View File
@@ -699,6 +699,25 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"",
"{} show every Contextual Task Bar action and chip that Bar Actions turned off, as the bar's More Options › Reset Bar Actions does; returns the ids shown again",
),
(
"window.quickPenToolbar",
"Quick Pen Toolbar",
"",
"{} show or hide the toolbar the Quick Pen tool shows on the canvas (toggles; returns whether it shows), as Window › Quick Pen Toolbar and the toolbar's More Options › Hide Toolbar do; selecting the Quick Pen tool shows it again",
),
(
"window.quickPenToolbar.pin",
"Pin Toolbar Position",
"",
"{pinned?: bool} keep the Quick Pen toolbar where it is in the canvas window instead of following the drawing (true), let it follow the drawing again from where it is (false) or toggle (omitted), as the toolbar's More Options menu does; returns the new state",
),
("window.quickPenToolbar.reset", "Reset Toolbar Position", "", "{} unpin the Quick Pen toolbar and put it back beside the drawing"),
(
"tool.quickPen.flipArc",
"Flip Arc",
"",
"{} flip the last sharp-corner arc of the path the Quick Pen tool is drawing to the other side of its chord, as C and the toolbar's Flip Arc button do, as one undo step; first finishes any pending tool edit (which can change the document), then returns false, changing nothing more, when the Quick Pen tool is not active, no path is being drawn or the last piece is not a sharp-corner arc",
),
(
"window.dock",
"Panels",
@@ -1156,7 +1175,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"tool.options",
"Tool Options…",
"",
"{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOpti Line truncated
"{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's To Line truncated
),
(
"ui.colorGuideOptions",
@@ -1330,6 +1349,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"",
"{params?: tracing settings (default: the Default preset's), rename?: a saved preset's name} the Image Trace panel's Manage Presets: open Save as New Preset… for those settings, or with `rename`, Rename… for that saved preset (dialog `imageTracePreset`, field `name`: a new \"Tracing Preset N\" or the preset's name); OK runs imageTrace.presets.save with the name (as `newName` when renaming), and the panel shows the preset it made from its settings",
),
(
"ui.tracingPresetsDialog",
"Tracing Presets…",
"",
"{selected?: preset name (default Default)} open Edit → Tracing Presets (dialog `tracingPresets`, field `selected`): the built-in presets (in brackets, read-only) and the saved ones, with the selected one's settings. New… (from the selected preset) and Edit… (a saved one) open the preset editor (dialog `tracingPreset`, fields `name` and `params`, the tracing settings): OK runs imageTrace.presets.save and returns to Tracing Presets, and a name of a built-in preset, Custom or another saved preset keeps the editor open; Cancel returns with nothing saved. Delete runs imageTrace.presets.delete; Import… runs imageTrace.presets.import, and when saved presets have names in the file, asks (dialog `tracingPresetsReplace`) whether to replace them (OK) or keep them (Cancel); Export… runs imageTrace.presets.export on every saved preset",
),
(
"ui.flattenerPreview",
"Flattener Preview",
@@ -1579,7 +1604,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.colorWheel",
"Color Wheel Options",
"",
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, vision}",
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, vision, documentColors}",
),
(
"ui.savePdfDialog",
@@ -1907,7 +1932,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.hpglOptionsDialog",
"HP-GL Options Dialog",
"",
"{path?, useArtboards?, range?, hpglVersion?, curveTolerance?, origin?, pens?, sortPaths?, insideFirst?} open HP-GL Options (dialog `hpglOptions`: fields = these document.export options over the ones used last; pens null is One Pen per Color); OK checks them, remembers them and writes path (else asks). Export As… → HP-GL opens it too",
"{path?, useArtboards?, range?, hpglVersion?, curveTolerance?, origin?, pens?, sortPaths?, insideFirst?} open HP-GL Options (dialog `hpglOptions`: fields = these document.export options over the ones used last; pens null is One Pen per Color); OK checks them, remembers them and writes path (else asks); OK after another document has become active closes the dialog and writes nothing. Export As… → HP-GL opens it too",
),
(
"file.saveForWeb",
+39 -6
View File
@@ -262,6 +262,12 @@ fn spend(work: &mut usize, steps: usize) -> Result<(), String> {
/// The triangles covering one face: `contours` (outlines one way round, holes the other) on the
/// plane across `normal` (its Newell normal).
pub(crate) fn triangulate(contours: &[Vec<V3>], normal: V3, work: &mut usize) -> Result<Vec<[V3; 3]>, String> {
triangulate_keeping(contours, normal, work, false)
}
/// [`triangulate`], keeping the corners that lie straight between their neighbors as triangle
/// corners when `keep_straight` is set.
fn triangulate_keeping(contours: &[Vec<V3>], normal: V3, work: &mut usize, keep_straight: bool) -> Result<Vec<[V3; 3]>, String> {
// Cut the face on the coordinate plane it is least slanted to, turned so outlines run
// counterclockwise.
let (ax, ay, az) = (normal.0.abs(), normal.1.abs(), normal.2.abs());
@@ -332,11 +338,30 @@ pub(crate) fn triangulate(contours: &[Vec<V3>], normal: V3, work: &mut usize) ->
let (hole, rest) = holes[k..].split_first().ok_or_else(too_complex)?;
ring = bridge(ring, hole, rest, work)?;
}
clip(&ring, &mut out, work)?;
clip(&ring, &mut out, work, keep_straight)?;
}
Ok(out)
}
/// The triangles covering `rings`, a flat face in the art's plane (outlines with a positive signed
/// area, holes negative), cut as a mesh's faces are: each hole bridged to the outline around it,
/// then ear clipped. Every corner of the rings that lies straight between its neighbors (a corner
/// a neighboring cell shares) stays a triangle corner. Each triangle runs the way its outline does,
/// and a triangle with no area that way round is left out. The steps add to `work`, and the cut
/// stops as soon as `work` passes `budget`. `None` when a hole crosses an outline or another hole,
/// or when `work` passes `budget`.
pub(crate) fn flat_triangles(rings: &[Vec<Point>], work: &mut usize, budget: usize) -> Option<Vec<[Point; 3]>> {
let contours: Vec<Vec<V3>> = rings.iter().map(|r| r.iter().map(|q| V3(q.x, q.y, 0.0)).collect()).collect();
// Counted up from MAX_WORK less the budget, the cut's own checks stop it at the budget.
let start = MAX_WORK - budget.min(MAX_WORK);
let mut spent = start.saturating_add(*work);
let triangles = triangulate_keeping(&contours, V3(0.0, 0.0, 1.0), &mut spent, true);
*work = spent.saturating_sub(start);
let triangles = triangles.ok()?;
let triangles = triangles.into_iter().map(|t| t.map(|v| Point::new(v.0, v.1)));
Some(triangles.filter(|[a, b, c]| (*b - *a).cross(*c - *a) > 0.0).collect())
}
/// Do segments `a`–`b` and `c`–`d` cross (touching at a shared end does not count)?
fn crosses(a: (f64, f64), b: (f64, f64), c: (f64, f64), d: (f64, f64)) -> bool {
let same = |p: (f64, f64), q: (f64, f64)| (p.0 - q.0).hypot(p.1 - q.1) < 1e-9;
@@ -401,9 +426,10 @@ fn bridge(ring: Vec<Corner>, hole: &[Corner], others: &[Vec<Corner>], work: &mut
}
/// Cut `ring` (counterclockwise, possibly joined to its holes by bridges) into triangles by ear
/// clipping. A corner in line with its neighbors goes without a triangle. If no ear is left (a
/// ring that crosses itself), the rest is cut as a fan.
fn clip(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize) -> Result<(), String> {
/// clipping. A corner in line with its neighbors goes without a triangle, unless `keep_straight`
/// is set and it lies straight between them: it then stays a corner of the triangles beside it. If
/// no ear is left (a ring that crosses itself), the rest is cut as a fan.
fn clip(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize, keep_straight: bool) -> Result<(), String> {
let n = ring.len();
if n < 3 {
return Ok(());
@@ -419,8 +445,10 @@ fn clip(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize) -> Result<(),
let turn = cross(pa, pb, pc);
let scale = (pb.x - pa.x).hypot(pb.y - pa.y) * (pc.x - pb.x).hypot(pc.y - pb.y);
let mut ear = false;
let drop = turn.abs() <= 1e-12 * scale.max(1e-300);
if !drop && turn > 0.0 {
let flat = turn.abs() <= 1e-12 * scale.max(1e-300);
let straight = keep_straight && flat && (pb.x - pa.x) * (pc.x - pb.x) + (pb.y - pa.y) * (pc.y - pb.y) > 0.0;
let drop = flat && !straight;
if !flat && turn > 0.0 {
spend(work, left)?;
ear = true;
let mut k = next[c];
@@ -430,6 +458,11 @@ fn clip(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize) -> Result<(),
ear = false;
break;
}
// A kept corner on the ear's new edge would be left off every triangle.
if keep_straight && touches((p.x, p.y), (pc.x, pc.y), (pa.x, pa.y)) {
ear = false;
break;
}
k = next[k];
}
}
+62
View File
@@ -173,6 +173,68 @@ fn a_bridge_through_another_corner_touches_it() {
assert!(!super::touches((5.0, 1.0), (0.0, 0.0), (10.0, 0.0)));
}
#[test]
fn flat_triangles_keep_corners_that_lie_along_an_edge() {
// A square with a hole, its edges carrying corners midway, as a cell shares with its finer
// neighbors: every corner is a corner of some triangle, and the triangles cover the face.
let p = |x: f64, y: f64| Point::new(x, y);
let outline = vec![p(5.0, 0.0), p(10.0, 0.0), p(10.0, 5.0), p(10.0, 10.0), p(5.0, 10.0), p(0.0, 10.0), p(0.0, 5.0), p(0.0, 0.0)];
let hole = vec![p(1.0, 4.0), p(1.0, 6.0), p(2.0, 6.0), p(2.0, 4.0)];
let mut work = 0;
let triangles = flat_triangles(&[outline.clone(), hole], &mut work, usize::MAX).unwrap();
let area = |t: &[Point; 3]| ((t[1].x - t[0].x) * (t[2].y - t[0].y) - (t[1].y - t[0].y) * (t[2].x - t[0].x)) / 2.0;
assert!(triangles.iter().all(|t| area(t) > 0.0));
assert!((triangles.iter().map(area).sum::<f64>() - 98.0).abs() < 1e-9);
for q in &outline {
assert!(triangles.iter().any(|t| t.contains(q)), "{q:?} is no triangle's corner");
}
assert!(work > 0);
}
#[test]
fn flat_triangles_keep_corners_on_the_edge_an_ear_would_cut() {
// The first ear's new edge runs along the bottom, through its two middle corners.
let p = |x: f64, y: f64| Point::new(x, y);
let outline = vec![p(0.0, 3.0), p(0.0, 0.0), p(1.0, 0.0), p(2.0, 0.0), p(3.0, 0.0)];
let mut work = 0;
let triangles = flat_triangles(std::slice::from_ref(&outline), &mut work, usize::MAX).unwrap();
let area = |t: &[Point; 3]| ((t[1].x - t[0].x) * (t[2].y - t[0].y) - (t[1].y - t[0].y) * (t[2].x - t[0].x)) / 2.0;
assert!((triangles.iter().map(area).sum::<f64>() - 4.5).abs() < 1e-9);
for q in &outline {
assert!(triangles.iter().any(|t| t.contains(q)), "{q:?} is no triangle's corner");
}
}
#[test]
fn flat_triangles_pass_over_an_ear_whose_new_edge_runs_through_a_dent() {
// The first ear's new edge, from (0, 4) to (4, 0), runs through the dent's corner at (2, 2).
let p = |x: f64, y: f64| Point::new(x, y);
let outline = vec![p(0.0, 0.0), p(4.0, 0.0), p(4.0, 4.0), p(2.0, 2.0), p(0.0, 4.0)];
let mut work = 0;
let triangles = flat_triangles(std::slice::from_ref(&outline), &mut work, usize::MAX).unwrap();
let area = |t: &[Point; 3]| ((t[1].x - t[0].x) * (t[2].y - t[0].y) - (t[1].y - t[0].y) * (t[2].x - t[0].x)) / 2.0;
assert!((triangles.iter().map(area).sum::<f64>() - 12.0).abs() < 1e-9);
for t in &triangles {
for (a, b) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] {
for q in &outline {
assert!(!super::touches((q.x, q.y), (a.x, a.y), (b.x, b.y)), "{q:?} lies inside the edge {a:?} to {b:?}");
}
}
}
}
#[test]
fn flat_triangles_stop_at_their_budget() {
let p = |x: f64, y: f64| Point::new(x, y);
let outline = vec![p(0.0, 0.0), p(10.0, 0.0), p(10.0, 10.0), p(0.0, 10.0)];
let hole = vec![p(1.0, 4.0), p(1.0, 6.0), p(2.0, 6.0), p(2.0, 4.0)];
let mut all = 0;
assert!(flat_triangles(&[outline.clone(), hole.clone()], &mut all, usize::MAX).is_some());
let mut work = 0;
assert!(flat_triangles(&[outline, hole], &mut work, all - 1).is_none());
assert!(work >= all, "{work} of {all}");
}
#[test]
fn a_beveled_extrusion_stays_closed() {
let mut b = BezPath::new();
+16 -4
View File
@@ -30,10 +30,10 @@ use build::{Camera, cuts, edge_distance, newell, section};
pub(crate) use build::{Face3, Keep, extrude_faces, plane_faces};
pub use build::{extrude, extrude_side_size, extrude_surfaces, plane};
pub use face_map::{FaceMap, MeshFace, extrude_face_map, extrude_mesh_face, plane_face_map, plane_mesh_face};
#[cfg(test)]
use inflate::GRID_WORK;
pub(crate) use inflate::inflate_faces;
#[cfg(test)]
use inflate::{FLAT_BUDGET, FLAT_WORK, GRID_WORK, MAX_FLAT_CORNERS, MAX_FLAT_WORK};
#[cfg(test)]
pub(crate) use inflate::{INFLATED, PUFFED, SOLVE_FIRST};
pub use inflate::{inflate, inflate_each, inflate_together};
#[cfg(test)]
@@ -354,11 +354,15 @@ pub struct Inflate {
pub taper: f64,
/// A closed back (a solid) or none, so the inflated front is a shell open behind.
pub cap: bool,
/// Graphics are mapped onto the front or the puffed back: the pieces of those faces are drawn
/// as triangles, each carrying where its corners lie in the art's plane ([`Facet::surface`]).
/// Off by default, which leaves the facets without one.
pub map_surface: bool,
}
impl Default for Inflate {
fn default() -> Self {
Self { depth: 0.0, volume: 50.0, both_sides: false, twist: 0.0, taper: 1.0, cap: true }
Self { depth: 0.0, volume: 50.0, both_sides: false, twist: 0.0, taper: 1.0, cap: true, map_surface: false }
}
}
@@ -414,8 +418,15 @@ pub struct Facet {
pub end: Option<PlanarFace>,
/// For a piece of Extrude & Bevel's side built for graphics ([`Extrude::map_surface`]): where
/// its corners lie on the side unrolled flat, for a graphic mapped onto it. x runs along the
/// outline and y from the front toward the back ([`crate::SurfaceCell`]).
/// outline and y from the front toward the back ([`crate::SurfaceCell`]). For a piece of
/// Inflate's front or puffed back built for graphics ([`Inflate::map_surface`]): where its
/// corners lie in the art's plane, as offsets from the center of the bounds the solid was built
/// with. The back's corners are where they were in the art before the twist and taper turned
/// and scaled it.
pub surface: Option<crate::SurfaceCell>,
/// The face of Inflate's solid that a facet with a [`Facet::surface`] is a piece of: its front
/// or its puffed back. `None` for every other facet, Extrude & Bevel's side included.
pub membrane: Option<PlanarFace>,
/// The face's plane in view space and the projection it was drawn with, for its depth at a
/// point of the drawing ([`Facet::depth_at`]). `None` for a face whose corners lie more than
/// 0.001 pt off one plane (a piece of a twisted wall) or reach the eye.
@@ -514,6 +525,7 @@ impl Facet {
away: false,
// Revolve's graphics are drawn from its faces, before they become facets.
surface: None,
membrane: None,
plane: face.plane,
#[cfg(test)]
view: vec![],
+1
View File
@@ -232,6 +232,7 @@ impl<'a> Builder<'a> {
away: behind,
end: None,
surface: None,
membrane: None,
plane,
cell: None,
#[cfg(test)]
+98 -13
View File
@@ -1,7 +1,7 @@
use super::build::{Builder, Built, Camera, Keep, Order, Turn, check_bounds, cuts, fit, newell, outward};
use super::membrane::{Edges, MAX_MATERIAL_SEGMENTS, Membrane, cell_triangles, clip, crossings, filled, material};
use super::rings::{MAX_SOLID_POINTS, TOO_COMPLEX_SURFACE, curve_pieces, signed_area, solid_rings};
use super::{Facet, FillRule, Inflate, MAX_FACES, MAX_SOLID_FACES, PathData, Point, Rect, V3, Vec2, View};
use super::{Facet, FillRule, Inflate, MAX_FACES, MAX_SOLID_FACES, PathData, PlanarFace, Point, Rect, V3, Vec2, View};
/// The slices the sides are cut into: more to follow a twist or taper.
fn slices(o: &Inflate) -> usize {
@@ -196,6 +196,44 @@ thread_local! {
pub(crate) static INFLATED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// The grid work of the last solid this thread inflated in full, for the tests.
pub(super) static GRID_WORK: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// The work of cutting cells with holes for graphics in the last solid this thread inflated
/// in full, for the tests.
pub(super) static FLAT_WORK: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// The work the next solids of this thread may take cutting cells with holes for graphics,
/// for the tests.
pub(super) static FLAT_BUDGET: std::cell::Cell<usize> = const { std::cell::Cell::new(MAX_FLAT_WORK) };
}
/// Most work one inflated surface may take cutting the cells graphics are mapped onto that
/// [`cell_triangles`] can't take (a hole inside the cell, or a ring of more corners), all its
/// cells together ([`crate::mesh::flat_triangles`]).
pub(super) const MAX_FLAT_WORK: usize = 1 << 26;
/// Most corners the pieces of one such cell may have.
pub(super) const MAX_FLAT_CORNERS: usize = 4096;
/// The work cutting cells with holes for graphics may take.
fn flat_budget() -> usize {
#[cfg(test)]
return FLAT_BUDGET.with(std::cell::Cell::get);
#[cfg(not(test))]
MAX_FLAT_WORK
}
/// Marks the facet the builder `b` added after it held `before` facets, if it added one, as a piece
/// of `face` (Inflate's front or puffed back) whose corners lie at the art points `points`, as
/// offsets from `center` ([`Facet::surface`]). `outward` is the triangle's normal pointing out of
/// the solid: the piece shows the outside of the surface when it was neither turned around to show
/// its inside (on a shell open behind) nor kept turned away.
fn mark_surface(b: &mut Builder<'_>, before: usize, points: [Point; 3], center: Point, outward: V3, face: PlanarFace) {
if b.facets.len() <= before {
return;
}
let Some(f) = b.facets.last_mut() else { return };
let Some(page) = f.contours.first().filter(|c| c.len() == 3).cloned() else { return };
let shows = !f.away && f.normal[0] * outward.0 + f.normal[1] * outward.1 + f.normal[2] * outward.2 > 0.0;
f.surface = Some(crate::SurfaceCell { page, uv: points.iter().map(|q| Point::new(q.x - center.x, q.y - center.y)).collect(), outward: shows });
f.membrane = Some(face);
}
/// The facets of one inflated shape, for a camera that allows for a puff `reach` high (or the
@@ -241,6 +279,8 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee
};
let smooth = view.shade && view.has_colored_lights();
let camera = Camera::new(view, bounds, o.depth + 2.0 * height.max(reach));
// A graphic's offsets are from the center of the bounds the solid is built with.
let center = bounds.center();
// Without its back cap the object is a shell open behind, its inside showing.
let mut b = Builder::new(&camera, o.cap, false, keep);
let half = o.depth / 2.0;
@@ -260,6 +300,8 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee
// builds the topology of every outline ring near its cell, so a self-crossing outline cost its
// crossings again in every cell it spans. Past it, cells take their clipped pieces.
let material_left = std::cell::Cell::new(MAX_MATERIAL_SEGMENTS);
// The work of cutting cells with holes for graphics, all the cells together ([`MAX_FLAT_WORK`]).
let mut flat_work = 0usize;
// Every ring's bounds, and the crossings of the last few rows the cells' centres lie on (a
// row of cells has at most seven, at its three levels).
let ring_bounds: Vec<Option<Rect>> =
@@ -410,22 +452,63 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee
out
})
.collect();
if height > 0.0
&& smooth
&& let Some(triangles) = cell_triangles(&pieces)
{
// Smooth shading draws the pieces as triangles, and so do graphics mapped onto
// the front or back: each triangle then carries where its corners lie in the
// art's plane.
let smoothed = height > 0.0 && smooth;
let triangles = match (smoothed || o.map_surface).then(|| cell_triangles(&pieces)) {
// A cell graphics are mapped onto that the quick cut can't take (a hole
// inside it, or a ring of more corners) is cut with its holes, against one
// budget for the whole surface. Drawn whole instead, its piece would show
// no graphics.
Some(None) if o.map_surface => {
if pieces.iter().map(Vec::len).fold(0usize, usize::saturating_add) > MAX_FLAT_CORNERS {
return Err(TOO_COMPLEX_SURFACE.into());
}
let budget = flat_budget();
let holed = crate::mesh::flat_triangles(&pieces, &mut flat_work, budget);
if flat_work > budget {
return Err(TOO_COMPLEX_SURFACE.into());
}
Some(holed.ok_or_else(|| TOO_COMPLEX_SURFACE.to_string())?)
}
quick => quick.flatten(),
};
if let Some(triangles) = triangles {
let order = if flat { Order::Last } else { Order::Depth };
for points in triangles {
let front = points.map(|q| camera.place(q, half + lift(q)));
b.smooth_triangle(front, points.map(|q| camera.rotate(normal(q))), false)?;
let before = b.facets.len();
let outward = newell(&[front.to_vec()]);
if smoothed {
b.smooth_triangle(front, points.map(|q| camera.rotate(normal(q))), false)?;
} else {
b.face(vec![front.to_vec()], outward, order)?;
}
if o.map_surface {
mark_surface(&mut b, before, points, center, outward, PlanarFace::Front);
}
if o.both_sides && o.cap {
let back = points.map(|q| camera.place(back_turn.apply(q), -half - lift(q) * back_turn.scale));
let normals = points.map(|q| {
let n = normal(q);
// A uniform taper scales all three coordinates equally;
// twist turns the back normal about the shape's z-axis.
camera.rotate(V3(back_turn.cos * n.0 - back_turn.sin * n.1, back_turn.sin * n.0 + back_turn.cos * n.1, -n.2))
});
b.smooth_triangle(back, normals, true)?;
let before = b.facets.len();
let n = newell(&[back.to_vec()]);
// The back winds the same way round as the front, so its outward
// normal is reversed.
let outward = V3(-n.0, -n.1, -n.2);
if smoothed {
let normals = points.map(|q| {
let n = normal(q);
// A uniform taper scales all three coordinates equally;
// twist turns the back normal about the shape's z-axis.
camera.rotate(V3(back_turn.cos * n.0 - back_turn.sin * n.1, back_turn.sin * n.0 + back_turn.cos * n.1, -n.2))
});
b.smooth_triangle(back, normals, true)?;
} else {
b.face(vec![back.to_vec()], outward, order)?;
}
if o.map_surface {
mark_surface(&mut b, before, points, center, outward, PlanarFace::Back);
}
}
}
continue;
@@ -507,6 +590,8 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee
}
#[cfg(test)]
GRID_WORK.with(|w| w.set(edges.work()));
#[cfg(test)]
FLAT_WORK.with(|w| w.set(flat_work));
if edges.spent() {
return Err(TOO_COMPLEX_SURFACE.into());
}
+117 -1
View File
@@ -457,6 +457,122 @@ fn inflate_leaves_holes_open() {
assert!(close(area(&f), 100.0 * 100.0 - 40.0 * 40.0, 1e-3), "{}", area(&f));
}
#[test]
fn inflate_marks_where_each_piece_lies_in_the_art_for_graphics() {
let (p, r) = shape(&square(0.0, 0.0, 100.0));
let on = |o: Inflate, view: View| inflate(&p, FillRule::EvenOdd, r, Inflate { map_surface: true, ..o }, view).unwrap();
// Without the request no piece carries a surface point.
assert!(inflate(&p, FillRule::EvenOdd, r, Inflate::default(), front()).unwrap().iter().all(|f| f.surface.is_none() && f.membrane.is_none()));
// Straight on, every piece is a front triangle whose corners lie where the art does, as
// offsets from the center of the bounds, and together they cover the shape.
let f = on(Inflate::default(), front());
let marked: Vec<&Facet> = f.iter().filter(|f| f.surface.is_some()).collect();
assert!(marked.len() > 20, "{}", marked.len());
assert!(close(marked.iter().map(|f| signed_area(&f.contours[0]).abs()).sum::<f64>(), 100.0 * 100.0, 1e-3));
for f in &marked {
let s = f.surface.as_ref().unwrap();
assert_eq!(f.membrane, Some(PlanarFace::Front));
assert!(s.outward);
for (page, uv) in s.page.iter().zip(&s.uv) {
assert!(close(page.x, uv.x + 50.0, 1e-6) && close(page.y, uv.y + 50.0, 1e-6), "{page:?} {uv:?}");
}
}
// Both sides puffs a back: seen from behind its pieces show their outside, and under Twist
// they keep the untwisted art points while the pieces turn on the page.
let behind = View { rotation_y: 180.0, ..front() };
let back = |o: Inflate| {
on(o, behind)
.into_iter()
.filter(|f| f.membrane == Some(PlanarFace::Back) && f.surface.as_ref().is_some_and(|s| s.outward))
.collect::<Vec<_>>()
};
let plain = back(Inflate { both_sides: true, ..Inflate::default() });
assert!(!plain.is_empty());
let twisted = back(Inflate { both_sides: true, twist: 30.0, ..Inflate::default() });
assert!(!twisted.is_empty());
let uv_extent =
|f: &[Facet]| f.iter().flat_map(|f| f.surface.as_ref().unwrap().uv.clone()).fold(Rect::new(0.0, 0.0, 0.0, 0.0), |r, q| r.union_pt(q));
assert!(close(uv_extent(&twisted).width(), 100.0, 1e-6) && close(uv_extent(&twisted).height(), 100.0, 1e-6));
assert!(extent(&twisted).width() > extent(&plain).width() + 10.0, "{:?} {:?}", extent(&twisted), extent(&plain));
// Without Both sides there is no back to mark.
assert!(on(Inflate::default(), behind).iter().all(|f| f.membrane != Some(PlanarFace::Back)));
}
/// A square 0.3 pt across with its corner at the lattice point `(qx, qy)` of the grid of a
/// 100 pt shape, offset 0.1 pt: it lies inside one quarter cell of that grid.
fn speck(qx: f64, qy: f64) -> BezPath {
let unit = 100.0 / 48.0 / 4.0;
square(qx * unit + 0.1, qy * unit + 0.1, 0.3)
}
/// The area of the pieces marked for graphics on `face`.
fn mapped_area(f: &[Facet], face: PlanarFace) -> f64 {
f.iter().filter(|f| f.membrane == Some(face)).map(|f| signed_area(&f.contours[0]).abs()).sum()
}
/// A hole inside one cell of the surface's grid leaves that cell's piece with a hole in it:
/// graphics still map onto the rest of the cell, front and back, and the hole stays open.
#[test]
fn inflate_maps_graphics_around_a_hole_inside_one_cell() {
let mut b = square(0.0, 0.0, 100.0);
b.extend(speck(96.0, 96.0));
let (p, r) = shape(&b);
let o = Inflate { map_surface: true, both_sides: true, ..Inflate::default() };
let f = inflate(&p, FillRule::EvenOdd, r, o, front()).unwrap();
let mapped = mapped_area(&f, PlanarFace::Front);
assert!(close(mapped, 100.0 * 100.0 - 0.3 * 0.3, 1e-3), "{mapped}");
let f = inflate(&p, FillRule::EvenOdd, r, o, View { rotation_y: 180.0, ..front() }).unwrap();
let mapped = mapped_area(&f, PlanarFace::Back);
assert!(close(mapped, 100.0 * 100.0 - 0.3 * 0.3, 1e-3), "{mapped}");
}
/// The cells graphics are mapped onto that need their holes cut out share one budget for the
/// whole surface: past it the surface is refused, however little each cell takes.
#[test]
fn inflate_cuts_holed_cells_for_graphics_within_one_budget() {
let mut b = square(0.0, 0.0, 100.0);
for i in 0..8 {
for j in 0..8 {
b.extend(speck(20.0 + 20.0 * i as f64, 20.0 + 20.0 * j as f64));
}
}
let (p, r) = shape(&b);
let o = Inflate { map_surface: true, ..Inflate::default() };
let f = inflate(&p, FillRule::EvenOdd, r, o, front()).unwrap();
assert!(close(mapped_area(&f, PlanarFace::Front), 100.0 * 100.0 - 64.0 * 0.3 * 0.3, 1e-3));
let all = FLAT_WORK.with(std::cell::Cell::get);
assert!(all > 0);
// Half the work all 64 cells took is far more than any one of them takes.
FLAT_BUDGET.with(|w| w.set(all / 2));
let half = inflate(&p, FillRule::EvenOdd, r, o, front());
FLAT_BUDGET.with(|w| w.set(MAX_FLAT_WORK));
assert_eq!(half.err().as_deref(), Some(TOO_COMPLEX_SOLID));
// The art draws without graphics as before.
assert!(inflate(&p, FillRule::EvenOdd, r, Inflate::default(), front()).is_ok());
}
/// A cell graphics are mapped onto whose pieces have more corners than one cut may take refuses
/// the surface rather than drawing that cell without its graphics.
#[test]
fn inflate_refuses_graphics_on_a_cell_with_too_many_corners() {
let mut b = square(0.0, 0.0, 100.0);
let unit = 100.0 / 48.0 / 4.0;
let c = Point::new(96.5 * unit, 96.5 * unit);
let n = MAX_FLAT_CORNERS + 10;
let mut ring = BezPath::new();
for k in 0..n {
let a = -std::f64::consts::TAU * k as f64 / n as f64;
let q = (c.x + 0.2 * a.cos(), c.y + 0.2 * a.sin());
if k == 0 { ring.move_to(q) } else { ring.line_to(q) }
}
ring.close_path();
b.extend(ring);
let (p, r) = shape(&b);
let mapped = inflate(&p, FillRule::EvenOdd, r, Inflate { map_surface: true, ..Inflate::default() }, front());
assert_eq!(mapped.err().as_deref(), Some(TOO_COMPLEX_SOLID));
assert!(inflate(&p, FillRule::EvenOdd, r, Inflate::default(), front()).is_ok());
}
#[test]
fn malformed_and_degenerate_input_is_bounded() {
let (p, b) = shape(&square(0.0, 0.0, 100.0));
@@ -483,7 +599,7 @@ fn malformed_and_degenerate_input_is_bounded() {
&p,
FillRule::EvenOdd,
b,
Inflate { depth: -5.0, volume: f64::NAN, both_sides: true, twist: f64::INFINITY, taper: f64::NAN, cap: true },
Inflate { depth: -5.0, volume: f64::NAN, both_sides: true, twist: f64::INFINITY, taper: f64::NAN, cap: true, map_surface: false },
front()
)
.is_ok()
+260 -21
View File
@@ -16,8 +16,17 @@
//! circle passes through the points (two are the same, three lie on one line) or the circle would
//! reach past the canvas, the tool shows none and the release draws nothing; for three different
//! points on one line, or a circle past the canvas, the pointer shows "Circle too large".
//!
//! The tool's options (Circle Tool Options, `tool.setOption`; kept with the preferences):
//! `center`, `radii` and `diameter` show or hide the center cross, the radius lines and the
//! diameter label; `color` is the color of the cross and the lines (one of [`COLORS`]);
//! `standardAnchors` off puts the circle's anchors at the points it was drawn through instead of
//! at 0°, 90°, 180° and 270° (`anchors: "points"`); `dragThird` off places the second point with
//! a click and draws the circle through three points with a third click, and a click on the second
//! point again (as a double-click there does) draws the circle on the two points. Every option is
//! on by default, and `color` is blue.
use serde_json::{Value, json};
use serde_json::{Map, Value, json};
use vectorcraft_doc::MAX_COORD;
use vectorcraft_geom::{Point, Rect, Vec2, shapes};
@@ -35,6 +44,71 @@ const REACH_PX: f64 = 3.0;
/// The longest outline (screen points) the preview draws dashed, about 7,000 dashes.
const DASHED_PX: f64 = 50_000.0;
/// The colors the center cross and the radius lines can be drawn in, by option value. Blue is the
/// feedback color the other drawing tools use.
pub const COLORS: &[(&str, [u8; 3])] = &[
("red", [0xe5, 0x2d, 0x27]),
("blue", crate::draw2::FEEDBACK),
("magenta", [0xd6, 0x2c, 0xd6]),
("green", [0x1f, 0xb4, 0x4b]),
("black", [0x00, 0x00, 0x00]),
("gray", [0x80, 0x80, 0x80]),
];
/// The option keys that are true or false.
const SWITCHES: &[&str] = &["center", "radii", "diameter", "standardAnchors", "dragThird"];
/// The tool's options (see the module comment).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Options {
center: bool,
radii: bool,
diameter: bool,
/// An entry of [`COLORS`].
color: usize,
standard_anchors: bool,
drag_third: bool,
}
impl Default for Options {
fn default() -> Self {
Options { center: true, radii: true, diameter: true, color: 1, standard_anchors: true, drag_third: true }
}
}
impl Options {
fn switch(&mut self, key: &str) -> Option<&mut bool> {
Some(match key {
"center" => &mut self.center,
"radii" => &mut self.radii,
"diameter" => &mut self.diameter,
"standardAnchors" => &mut self.standard_anchors,
"dragThird" => &mut self.drag_third,
_ => return None,
})
}
}
/// Is every value in `values` one the tool takes? `tool.setOption` checks them all before setting
/// any; [`Tool::set_option`] skips a value it cannot read.
pub fn check_options(values: &Map<String, Value>) -> Result<(), String> {
for (key, v) in values {
if SWITCHES.contains(&key.as_str()) {
if !v.is_boolean() {
return Err(format!("`{key}` must be true or false"));
}
} else if key == "color" {
if !v.as_str().is_some_and(|s| COLORS.iter().any(|(name, _)| *name == s)) {
let names: Vec<&str> = COLORS.iter().map(|(name, _)| *name).collect();
return Err(format!("`{key}` must be one of {}", names.join(", ")));
}
} else {
return Err(format!("unknown Circle tool option `{key}`"));
}
}
Ok(())
}
/// The press in progress.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Press {
@@ -47,23 +121,36 @@ enum Press {
/// places the third point and the circle passes through `snapped`. A press within
/// [`REACH_PX`] of the first point, or one that snaps to it (`on_first`), is a press on it: let
/// go there it places nothing, and dragged out it draws the circle on the diameter it drags out.
/// With `dragThird` off, a drag moves the second point and the release places it.
Second { at: Point, snapped: Point, from: Point, on_first: bool, dragged: bool },
/// With `dragThird` off, the press after the second point was placed, at `at` (snapped). Let go
/// on the second point (`on_second`), it draws the circle on the two points; let go on the
/// first point it places nothing; otherwise it draws the circle through the three points.
Third { at: Point, from: Point, on_first: bool, on_second: bool, dragged: bool },
}
#[derive(Default)]
pub struct CircleTool {
snap: DrawSnap,
options: Options,
/// The first point, placed by a click (or by the press of a drag in progress).
first: Option<Point>,
/// With `dragThird` off, the second point, placed by a click where it is shown (snapped, with
/// Alt's rounding of the diameter when Alt was held), and where the click let go: a press near
/// either is a press on the second point, so the second click of a double-click finds it even
/// where Alt's rounding moved it away from the pointer.
second: Option<(Point, Point)>,
press: Option<Press>,
/// Where the pointer is, snapped: the point the next press or release places.
pointer: Option<Point>,
}
/// The command the tool runs for `points`.
fn command(points: &[Point]) -> (String, Value) {
/// The command the tool runs for `points`; with `standard_anchors` off, the circle's anchors are
/// at the points.
fn command(points: &[Point], standard_anchors: bool) -> (String, Value) {
let pairs: Vec<Value> = points.iter().map(|p| json!([p.x, p.y])).collect();
("shape.circleThroughPoints".into(), json!({ "points": pairs }))
let params = if standard_anchors { json!({ "points": pairs }) } else { json!({ "points": pairs, "anchors": "points" }) };
("shape.circleThroughPoints".into(), params)
}
/// The circle through two points (the ends of a diameter) or three, as `shape.circleThroughPoints`
@@ -73,6 +160,17 @@ pub fn circle_of(points: &[Point]) -> Option<(Point, f64)> {
shapes::circle_through_points(points).filter(on_canvas)
}
/// [`circle_of`], as the tool draws it: with `standard_anchors` off, also none where the path with
/// an anchor at each point ([`shapes::circle_with_anchors_at`]) reaches past the canvas, since its
/// curves can reach slightly outside the circle.
fn drawn_circle(points: &[Point], standard_anchors: bool) -> Option<(Point, f64)> {
let fits = |(c, r): &(Point, f64)| {
let b = vectorcraft_geom::Shape::bounding_box(&shapes::circle_with_anchors_at(*c, *r, points).to_bezpath());
[b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD)
};
circle_of(points).filter(|c| standard_anchors || fits(c))
}
/// With Alt, `p` moved along the line from `first` so that their distance (the diameter) is on
/// the nearest ruler tick at the current zoom, in the General unit; `p` itself without Alt, and
/// when that rounding leaves no distance.
@@ -84,43 +182,65 @@ fn round_diameter(cx: &ToolContext, first: Point, p: Point, mods: Mods) -> Point
/// Are the points two or more different points through which no circle is drawn: three on one
/// line, or a circle that would reach past the canvas?
fn too_large(points: &[Point]) -> bool {
fn too_large(points: &[Point], standard_anchors: bool) -> bool {
let distinct = points.iter().enumerate().all(|(i, p)| !points.iter().take(i).any(|q| q == p));
points.len() >= 2 && distinct && circle_of(points).is_none()
points.len() >= 2 && distinct && drawn_circle(points, standard_anchors).is_none()
}
impl CircleTool {
fn clear(&mut self) {
self.first = None;
self.second = None;
self.press = None;
self.pointer = None;
self.snap.clear();
}
/// How the second point keeps to the first: Shift's 45° steps and the construction guides.
/// How the second point keeps to the first: Shift's 45° steps and the construction guides. A
/// third point keeps to neither.
fn leave(&self, cx: &ToolContext, mods: Mods) -> Option<Leave> {
self.first.map(|a| Leave::segment(cx, a, mods.shift))
self.first.filter(|_| self.second.is_none()).map(|a| Leave::segment(cx, a, mods.shift))
}
/// The points the circle passes through as the tool shows it now.
fn points(&self) -> Vec<Point> {
let mut out: Vec<Point> = self.first.into_iter().collect();
if let Some((b, _)) = self.second {
match self.press {
// Let go where it was pressed, a press on the first point draws nothing and one on
// the second point draws the circle on the two.
Some(Press::Third { on_first: true, dragged: false, .. }) => {}
Some(Press::Third { on_second: true, dragged: false, .. }) => out.push(b),
_ => {
out.push(b);
out.extend(self.pointer);
}
}
return out;
}
match self.press {
Some(Press::First { .. }) | None => out.extend(self.pointer.filter(|_| self.first.is_some())),
// A press on the first point adds no point: a drag from it drags out a diameter.
Some(Press::Second { on_first: true, dragged, .. }) => out.extend(self.pointer.filter(|_| dragged)),
Some(Press::Second { at, dragged: false, .. }) => out.push(at),
// With `dragThird` off, a drag moves the second point.
Some(Press::Second { at, .. }) if !self.options.drag_third => out.push(at),
Some(Press::Second { snapped, dragged: true, .. }) => {
out.push(snapped);
out.extend(self.pointer);
}
Some(Press::Third { .. }) => {}
}
out
}
/// The second point as the tool shows it: none for a press on the first point.
fn second(&self) -> Option<Point> {
if let Some((b, _)) = self.second {
return Some(b);
}
match self.press {
Some(Press::Second { on_first: false, at, .. }) if !self.options.drag_third => Some(at),
Some(Press::Second { on_first: false, dragged: false, at, .. }) => Some(at),
Some(Press::Second { on_first: false, dragged: true, snapped, .. }) => Some(snapped),
_ => None,
@@ -131,18 +251,34 @@ impl CircleTool {
/// (the tool showed none), it only starts afresh.
fn draw(&mut self, points: &[Point]) -> Vec<Action> {
self.clear();
if circle_of(points).is_none() {
if drawn_circle(points, self.options.standard_anchors).is_none() {
return vec![];
}
let (c, v) = command(points);
let (c, v) = command(points, self.options.standard_anchors);
vec![Action::Exec(c, v)]
}
/// With `dragThird` off, the release of a press after the second point was placed: on the
/// second point it draws the circle on the two points, on the first it places nothing, and
/// elsewhere it draws the circle through the three, or keeps the points where none passes
/// through them.
fn third_up(&mut self, at: Point, on_first: bool, on_second: bool, dragged: bool) -> Vec<Action> {
let (Some(a), Some((b, _))) = (self.first, self.second) else { return vec![] };
if on_second && !dragged {
return self.draw(&[a, b]);
}
if (on_first && !dragged) || drawn_circle(&[a, b, at], self.options.standard_anchors).is_none() {
self.snap.clear();
return vec![];
}
self.draw(&[a, b, at])
}
/// Is the press let go at `ev` a drag: is `ev` [`DRAG_PX`] or more from the press? A release
/// nearer the press is a click, also after a drag that came back to it.
fn drags(&self, cx: &ToolContext, ev: &PointerEvent) -> bool {
match self.press {
Some(Press::First { from, .. } | Press::Second { from, .. }) => ev.pos.distance(from) >= cx.tol(DRAG_PX),
Some(Press::First { from, .. } | Press::Second { from, .. } | Press::Third { from, .. }) => ev.pos.distance(from) >= cx.tol(DRAG_PX),
None => false,
}
}
@@ -173,6 +309,13 @@ impl Tool for CircleTool {
*dragged = false;
(*at, *on_first)
}
// With `dragThird` off, a click on the third point's press: the point goes back
// to where it was pressed.
Press::Third { at, from, dragged, .. } => {
*dragged = false;
*at = self.snap.press(cx, *from, &[], None);
(*at, false)
}
};
// A click on the first point places nothing: the pointer goes back to that point, so
// the tool shows no circle.
@@ -184,10 +327,27 @@ impl Tool for CircleTool {
PointerKind::Move => {
let leave = self.leave(cx, ev.mods);
let p = self.snap.hover(cx, ev.pos, &[], leave.as_ref());
self.pointer = Some(self.first.map_or(p, |a| round_diameter(cx, a, p, ev.mods)));
// Alt's rounding of the diameter is for the second point only.
let rounds = self.first.filter(|_| self.second.is_none());
self.pointer = Some(rounds.map_or(p, |a| round_diameter(cx, a, p, ev.mods)));
vec![]
}
PointerKind::Down => {
if let (Some(a), Some((b, clicked))) = (self.first, self.second) {
let at = self.snap.press(cx, ev.pos, &[], None);
let reach = cx.tol(REACH_PX);
let to_second = ev.pos.distance(b).min(ev.pos.distance(clicked));
let (mut on_first, mut on_second) = (at == a || ev.pos.distance(a) <= reach, at == b || to_second <= reach);
// A press in reach of both points is on the one it snapped to, otherwise on the
// nearer one.
if on_first && on_second {
let first = if (at == a) != (at == b) { at == a } else { ev.pos.distance(a) < to_second };
(on_first, on_second) = (first, !first);
}
self.press = Some(Press::Third { at, from: ev.pos, on_first, on_second, dragged: false });
self.pointer = Some(at);
return vec![];
}
match self.first {
None => {
let at = self.snap.press(cx, ev.pos, &[], None);
@@ -207,7 +367,28 @@ impl Tool for CircleTool {
vec![]
}
PointerKind::Drag => {
let drag_third = self.options.drag_third;
let first = self.first;
match &mut self.press {
// With `dragThird` off, the second point follows the pointer as it does before
// the press.
// The point stays where it was pressed until the press is a drag.
Some(Press::Second { at, snapped, from, on_first: false, dragged }) if !drag_third => {
*dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX);
if *dragged {
let leave = first.map(|a| Leave::segment(cx, a, ev.mods.shift));
*snapped = self.snap.drag(cx, ev.pos, leave.as_ref());
*at = first.map_or(*snapped, |a| round_diameter(cx, a, *snapped, ev.mods));
self.pointer = Some(*at);
}
}
Some(Press::Third { at, from, dragged, .. }) => {
*dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX);
if *dragged {
*at = self.snap.drag(cx, ev.pos, None);
self.pointer = Some(*at);
}
}
Some(Press::First { at, from, dragged }) => {
*dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX);
let leave = Leave::segment(cx, *at, ev.mods.shift);
@@ -230,6 +411,16 @@ impl Tool for CircleTool {
vec![]
}
PointerKind::Up => match (self.press.take(), self.first, self.pointer) {
(Some(Press::Third { at, on_first, on_second, dragged, .. }), ..) => self.third_up(at, on_first, on_second, dragged),
// With `dragThird` off, the release places the second point; let go on the first
// point, as a press there is, it places nothing.
(Some(Press::Second { at, snapped, on_first: false, .. }), Some(a), _) if !self.options.drag_third => {
if !(at == a || snapped == a || ev.pos.distance(a) <= cx.tol(REACH_PX)) {
self.second = Some((at, ev.pos));
}
self.snap.clear();
vec![]
}
(Some(Press::First { at, dragged: true, .. }), _, Some(b)) if b.distance(at) >= cx.tol(DRAG_PX) => self.draw(&[at, b]),
// A click places the first point; the guides of the press go.
(Some(Press::First { .. }), ..) => {
@@ -296,22 +487,33 @@ impl Tool for CircleTool {
let mut o = self.snap.guides().to_vec();
let points = self.points();
let color = crate::draw2::FEEDBACK;
if let Some((c, r)) = circle_of(&points) {
let path = shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath();
if let Some((c, r)) = drawn_circle(&points, self.options.standard_anchors) {
// The path the release draws: with `standardAnchors` off, the one with an anchor at each point.
let path = if self.options.standard_anchors {
shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath()
} else {
shapes::circle_with_anchors_at(c, r, &points).to_bezpath()
};
// The canvas draws a dashed outline dash by dash along its whole length: a circle longer
// than DASHED_PX on screen is drawn solid instead.
let dashed = std::f64::consts::TAU * r <= cx.tol(DASHED_PX);
o.push(Overlay::Path { path, color, width: 1.0, dashed });
for p in &points {
o.push(Overlay::Line { a: c, b: *p, color, dashed: false });
let opts = self.options;
let lines = COLORS.get(opts.color).map_or(color, |(_, rgb)| *rgb);
if opts.radii {
for p in &points {
o.push(Overlay::Line { a: c, b: *p, color: lines, dashed: false });
}
}
let arm = cx.tol(CROSS_PX);
o.push(Overlay::Line { a: c - Vec2::new(arm, 0.0), b: c + Vec2::new(arm, 0.0), color, dashed: false });
o.push(Overlay::Line { a: c - Vec2::new(0.0, arm), b: c + Vec2::new(0.0, arm), color, dashed: false });
if let Some(p) = self.pointer.filter(|_| cx.measurement_labels) {
if opts.center {
let arm = cx.tol(CROSS_PX);
o.push(Overlay::Line { a: c - Vec2::new(arm, 0.0), b: c + Vec2::new(arm, 0.0), color: lines, dashed: false });
o.push(Overlay::Line { a: c - Vec2::new(0.0, arm), b: c + Vec2::new(0.0, arm), color: lines, dashed: false });
}
if let Some(p) = self.pointer.filter(|_| cx.measurement_labels && opts.diameter) {
o.push(Overlay::Measure { p: p + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("D: {}", cx.len(2.0 * r)) });
}
} else if let Some(p) = self.pointer.filter(|_| too_large(&points)) {
} else if let Some(p) = self.pointer.filter(|_| too_large(&points, self.options.standard_anchors)) {
o.push(Overlay::Label { p, text: "Circle too large".into(), color });
}
for p in self.first.into_iter().chain(self.second()) {
@@ -323,6 +525,43 @@ impl Tool for CircleTool {
fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor {
Cursor::Crosshair
}
fn options(&self) -> Value {
let o = self.options;
let color = COLORS.get(o.color).map_or("blue", |(name, _)| *name);
json!({
"center": o.center,
"radii": o.radii,
"diameter": o.diameter,
"color": color,
"standardAnchors": o.standard_anchors,
"dragThird": o.drag_third,
})
}
/// Takes the values [`check_options`] takes.
fn check_option(&self, key: &str, value: &Value) -> Result<(), String> {
check_options(&Map::from_iter([(key.to_string(), value.clone())]))
}
/// Sets one option; a value the option does not take leaves it as it was. Switching
/// `dragThird` drops the points placed so far.
fn set_option(&mut self, key: &str, value: &Value) {
if key == "color" {
if let Some(i) = value.as_str().and_then(|s| COLORS.iter().position(|(name, _)| *name == s)) {
self.options.color = i;
}
return;
}
let Some(on) = value.as_bool() else { return };
let was = self.options.drag_third;
if let Some(switch) = self.options.switch(key) {
*switch = on;
}
if self.options.drag_third != was {
self.clear();
}
}
}
#[cfg(test)]
+298 -2
View File
@@ -94,6 +94,302 @@ fn a_click_and_a_drag_draw_the_circle_through_three_points() {
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (300.0, 360.0), Mods::default())), circle(&[(300.0, 300.0), (380.0, 300.0), (300.0, 360.0)]));
}
/// The lines the tool shows from the center `c`: (radius lines, arms of the center cross), each
/// with its color.
fn annotations(o: &[Overlay], c: Point) -> (Vec<[u8; 3]>, Vec<[u8; 3]>) {
let (mut radii, mut cross) = (vec![], vec![]);
for o in o {
if let Overlay::Line { a, b, color, .. } = o {
if *a == c {
radii.push(*color);
} else if a.midpoint(*b).distance(c) < 1e-9 {
cross.push(*color);
}
}
}
(radii, cross)
}
/// `center`, `radii` and `diameter` show or hide the center cross, the radius lines and the
/// diameter label, each on its own, and `color` is the color of the cross and the lines; the
/// outline stays in the feedback color. Each option lasts in [`Tool::options`].
#[test]
fn the_options_show_or_hide_the_center_radii_and_diameter_in_their_color() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = CircleTool::default();
click(&mut t, &cx, (300.0, 300.0));
t.pointer(&cx, &ev(PointerKind::Move, (380.0, 360.0), Mods::default()));
let c = Point::new(340.0, 330.0);
let blue = crate::draw2::FEEDBACK;
assert_eq!(annotations(&t.overlays(&cx), c), (vec![blue; 2], vec![blue; 2]));
let diameter = |t: &CircleTool| t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Measure { .. }));
assert!(diameter(&t));
t.set_option("center", &json!(false));
assert_eq!(annotations(&t.overlays(&cx), c), (vec![blue; 2], vec![]));
t.set_option("radii", &json!(false));
assert_eq!(annotations(&t.overlays(&cx), c), (vec![], vec![]));
assert!(diameter(&t));
t.set_option("diameter", &json!(false));
assert!(!diameter(&t));
t.set_option("center", &json!(true));
t.set_option("radii", &json!(true));
t.set_option("color", &json!("red"));
let red = [0xe5, 0x2d, 0x27];
let o = t.overlays(&cx);
assert_eq!(annotations(&o, c), (vec![red; 2], vec![red; 2]));
assert!(o.iter().any(|o| matches!(o, Overlay::Path { color, .. } if *color == blue)), "{o:?}");
assert_eq!(t.options(), json!({"center": true, "radii": true, "diameter": false, "color": "red", "standardAnchors": true, "dragThird": true}));
// A value an option does not take leaves it as it was.
for (key, value) in [("color", json!("orange")), ("center", json!("no")), ("radii", json!(0))] {
t.set_option(key, &value);
}
assert_eq!(t.options()["color"], json!("red"));
assert_eq!((&t.options()["center"], &t.options()["radii"]), (&json!(true), &json!(true)));
}
/// With `standardAnchors` off, the circle's anchors go at the points it was drawn through.
#[test]
fn anchors_at_the_points_asks_for_them() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = CircleTool::default();
t.set_option("standardAnchors", &json!(false));
let acts = drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 360.0)], Mods::default());
let points = json!([[300.0, 300.0], [380.0, 360.0]]);
assert_eq!(acts, vec![Action::Exec("shape.circleThroughPoints".into(), json!({"points": points, "anchors": "points"}))]);
}
/// With `standardAnchors` off, the tool shows the path with an anchor at each point, the one its
/// release draws.
#[test]
fn anchors_at_the_points_show_the_path_they_draw() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = CircleTool::default();
t.set_option("standardAnchors", &json!(false));
click(&mut t, &cx, (300.0, 300.0));
t.pointer(&cx, &ev(PointerKind::Down, (380.0, 300.0), Mods::default()));
t.pointer(&cx, &ev(PointerKind::Drag, (310.0, 340.0), Mods::default()));
let points = [Point::new(300.0, 300.0), Point::new(380.0, 300.0), Point::new(310.0, 340.0)];
let (c, r) = circle_of(&points).expect("a circle");
let want = shapes::circle_with_anchors_at(c, r, &points).to_bezpath();
let o = t.overlays(&cx);
assert!(o.iter().any(|o| matches!(o, Overlay::Path { path, .. } if *path == want)), "{o:?}");
}
/// With `standardAnchors` off, a circle within 1 pt of the canvas edge whose path with anchors at
/// the points curves past that edge is not shown and not drawn; with standard anchors it is.
#[test]
fn anchors_at_the_points_keep_the_path_on_the_canvas() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let r = MAX_COORD - 1.0;
let at = |deg: f64| (r * deg.to_radians().cos(), r * deg.to_radians().sin());
let points = [at(0.0), at(70.0), at(180.0)];
let geom: Vec<Point> = points.iter().map(|(x, y)| Point::new(*x, *y)).collect();
assert!(drawn_circle(&geom, true).is_some());
assert_eq!(drawn_circle(&geom, false), None);
let mut t = CircleTool::default();
t.set_option("standardAnchors", &json!(false));
click(&mut t, &cx, points[0]);
t.pointer(&cx, &ev(PointerKind::Down, points[1], Mods::default()));
t.pointer(&cx, &ev(PointerKind::Drag, points[2], Mods::default()));
// No outline at all: at this size the tool would draw it solid, not dashed.
let o = t.overlays(&cx);
assert!(!o.iter().any(|o| matches!(o, Overlay::Path { .. })), "{o:?}");
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, points[2], Mods::default())), vec![]);
}
/// With `dragThird` off, a click in reach of both placed points is on the nearer one: nearer the
/// first point it places nothing, nearer the second it draws the circle on the two.
#[test]
fn with_third_point_by_dragging_off_a_click_near_both_points_takes_the_nearer() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = CircleTool::default();
t.set_option("dragThird", &json!(false));
click(&mut t, &cx, (100.0, 100.0));
assert_eq!(click(&mut t, &cx, (104.0, 100.0)), vec![]);
assert_eq!(click(&mut t, &cx, (101.0, 100.0)), vec![]);
assert_eq!(click(&mut t, &cx, (103.0, 100.0)), circle(&[(100.0, 100.0), (104.0, 100.0)]));
}
/// With `dragThird` off, a press on the second point shows the circle on the two points, which its
/// release draws, and a press on the first point shows none.
#[test]
fn with_third_point_by_dragging_off_a_press_shows_the_circle_its_release_draws() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = CircleTool::default();
t.set_option("dragThird", &json!(false));
click(&mut t, &cx, (100.0, 100.0));
click(&mut t, &cx, (200.0, 100.0));
t.pointer(&cx, &ev(PointerKind::Down, (101.0, 101.0), Mods::default()));
assert_eq!(preview(&t.overlays(&cx)), None);
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (101.0, 101.0), Mods::default())), vec![]);
t.pointer(&cx, &ev(PointerKind::Down, (202.0, 101.0), Mods::default()));
let o = t.overlays(&cx);
assert!(near(preview(&o).expect("the circle is shown"), Rect::new(100.0, 50.0, 200.0, 150.0)), "{o:?}");
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (202.0, 101.0), Mods::default())), circle(&[(100.0, 100.0), (200.0, 100.0)]));
}
/// With `dragThird` off, a press that moves less than 2 screen points keeps the point where it was
/// pressed, for the second point and for the third.
#[test]
fn with_third_point_by_dragging_off_a_short_move_keeps_the_pressed_point() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let (down, drag, up) = (PointerKind::Down, PointerKind::Drag, PointerKind::Up);
let mut t = CircleTool::default();
t.set_option("dragThird", &json!(false));
click(&mut t, &cx, (100.0, 100.0));
t.pointer(&cx, &ev(down, (200.0, 100.0), Mods::default()));
t.pointer(&cx, &ev(drag, (201.0, 100.0), Mods::default()));
assert_eq!(t.pointer(&cx, &ev(up, (200.0, 100.0), Mods::default())), vec![]);
t.pointer(&cx, &ev(down, (150.0, 200.0), Mods::default()));
t.pointer(&cx, &ev(drag, (151.0, 200.0), Mods::default()));
let three = circle(&[(100.0, 100.0), (200.0, 100.0), (150.0, 200.0)]);
assert_eq!(t.pointer(&cx, &ev(up, (150.0, 200.0), Mods::default())), three);
}
/// With `dragThird` off, a second click places the second point and a third click draws the circle
/// through the three; a click on the second point again (as a double-click there does) draws the
/// circle on the two; a second point let go on the first places nothing; a drag from the first
/// point still draws the circle on its diameter.
#[test]
fn with_third_point_by_dragging_off_three_clicks_draw_the_circle() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = CircleTool::default();
t.set_option("dragThird", &json!(false));
click(&mut t, &cx, (300.0, 300.0));
assert_eq!(click(&mut t, &cx, (380.0, 300.0)), vec![]);
t.pointer(&cx, &ev(PointerKind::Move, (300.0, 360.0), Mods::default()));
let o = t.overlays(&cx);
assert!(near(preview(&o).expect("the circle through the three is shown"), Rect::new(290.0, 280.0, 390.0, 380.0)), "{o:?}");
assert_eq!(o.iter().filter(|o| matches!(o, Overlay::Anchor { .. })).count(), 2, "{o:?}");
// A click on the first point places nothing and keeps both points.
assert_eq!(click(&mut t, &cx, (300.0, 300.0)), vec![]);
assert!(t.busy());
assert_eq!(click(&mut t, &cx, (300.0, 360.0)), circle(&[(300.0, 300.0), (380.0, 300.0), (300.0, 360.0)]));
assert!(!t.busy());
// The events of a double-click on the second point: its first click places it, the second
// draws the circle on the two points, and the double-click event that follows adds nothing.
click(&mut t, &cx, (100.0, 100.0));
assert_eq!(click(&mut t, &cx, (200.0, 100.0)), vec![]);
assert_eq!(click(&mut t, &cx, (200.0, 100.0)), circle(&[(100.0, 100.0), (200.0, 100.0)]));
assert_eq!(t.pointer(&cx, &ev(PointerKind::DoubleClick, (200.0, 100.0), Mods::default())), vec![]);
assert!(!t.busy());
// A drag that moves the second point places it where it is let go.
click(&mut t, &cx, (100.0, 100.0));
assert_eq!(drag(&mut t, &cx, (150.0, 100.0), &[(180.0, 100.0), (200.0, 100.0)], Mods::default()), vec![]);
assert_eq!(click(&mut t, &cx, (100.0, 200.0)), circle(&[(100.0, 100.0), (200.0, 100.0), (100.0, 200.0)]));
// Three points on one line keep the two placed: the next click elsewhere draws.
click(&mut t, &cx, (100.0, 100.0));
click(&mut t, &cx, (200.0, 100.0));
assert_eq!(click(&mut t, &cx, (300.0, 100.0)), vec![]);
assert_eq!(click(&mut t, &cx, (100.0, 200.0)), circle(&[(100.0, 100.0), (200.0, 100.0), (100.0, 200.0)]));
// A second press elsewhere, dragged back and let go on the first point, places nothing: the
// next click places the second point.
click(&mut t, &cx, (100.0, 100.0));
assert_eq!(drag(&mut t, &cx, (200.0, 100.0), &[(150.0, 100.0), (100.0, 100.0)], Mods::default()), vec![]);
assert!(t.busy());
assert_eq!(click(&mut t, &cx, (200.0, 100.0)), vec![]);
assert_eq!(click(&mut t, &cx, (100.0, 200.0)), circle(&[(100.0, 100.0), (200.0, 100.0), (100.0, 200.0)]));
// A drag from the first point.
assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 360.0)], Mods::default()), circle(&[(300.0, 300.0), (380.0, 360.0)]));
// Switching the option drops the points placed so far.
click(&mut t, &cx, (100.0, 100.0));
t.set_option("dragThird", &json!(true));
assert!(!t.busy());
}
/// With `dragThird` off, a drag of the second or third point ends where it is let go, also when the
/// release is away from the last drag.
#[test]
fn with_third_point_by_dragging_off_a_drag_ends_where_it_is_let_go() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let (down, drag, up) = (PointerKind::Down, PointerKind::Drag, PointerKind::Up);
let mut t = CircleTool::default();
t.set_option("dragThird", &json!(false));
click(&mut t, &cx, (300.0, 300.0));
t.pointer(&cx, &ev(down, (350.0, 300.0), Mods::default()));
t.pointer(&cx, &ev(drag, (380.0, 300.0), Mods::default()));
assert_eq!(t.pointer(&cx, &ev(up, (400.0, 300.0), Mods::default())), vec![]);
t.pointer(&cx, &ev(down, (350.0, 350.0), Mods::default()));
t.pointer(&cx, &ev(drag, (320.0, 380.0), Mods::default()));
assert_eq!(t.pointer(&cx, &ev(up, (300.0, 400.0), Mods::default())), circle(&[(300.0, 300.0), (400.0, 300.0), (300.0, 400.0)]));
}
/// With `dragThird` off, an Alt-click places the second point where Alt's rounding of the diameter
/// puts it (88 pt rounds to 90 pt at 100%), and the tool shows it there: the marker, the preview,
/// the circle on the two points and the circle through three all use it.
#[test]
fn an_alt_click_places_the_second_point_where_it_is_shown() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let alt = Mods { alt: true, ..Mods::default() };
let mut t = CircleTool::default();
t.set_option("dragThird", &json!(false));
click(&mut t, &cx, (300.0, 300.0));
t.pointer(&cx, &ev(PointerKind::Down, (388.0, 300.0), alt));
t.pointer(&cx, &ev(PointerKind::Up, (388.0, 300.0), alt));
t.pointer(&cx, &ev(PointerKind::Move, (300.0, 390.0), Mods::default()));
let o = t.overlays(&cx);
let second = Point::new(390.0, 300.0);
assert!(o.iter().any(|o| matches!(o, Overlay::Anchor { p, .. } if p.distance(second) < 1e-9)), "{o:?}");
// (300, 300), (390, 300) and (300, 390): center (345, 345), radius 45·√2.
let r = 45.0 * 2f64.sqrt();
assert!(near(preview(&o).unwrap(), Rect::new(345.0 - r, 345.0 - r, 345.0 + r, 345.0 + r)), "{o:?}");
assert_eq!(click(&mut t, &cx, (300.0, 390.0)), circle(&[(300.0, 300.0), (390.0, 300.0), (300.0, 390.0)]));
click(&mut t, &cx, (300.0, 300.0));
t.pointer(&cx, &ev(PointerKind::Down, (388.0, 300.0), alt));
t.pointer(&cx, &ev(PointerKind::Up, (388.0, 300.0), alt));
assert_eq!(click(&mut t, &cx, (390.0, 300.0)), circle(&[(300.0, 300.0), (390.0, 300.0)]));
// In inches the ticks are farther apart, and the rounding can move the point more than the
// 3 screen points a click reaches: the second click of a double-click, where the first let go,
// still draws the circle on the two points, at the rounded point.
let inches = ToolContext { unit: vectorcraft_doc::Unit::Inches, ..cx };
let d = 94.4;
let rounded = vectorcraft_doc::Unit::Inches.snap_to_ruler_tick(d, 1.0);
assert!((rounded - d).abs() > 3.0, "{rounded}");
click(&mut t, &inches, (300.0, 300.0));
t.pointer(&inches, &ev(PointerKind::Down, (300.0 + d, 300.0), alt));
t.pointer(&inches, &ev(PointerKind::Up, (300.0 + d, 300.0), alt));
assert_eq!(click(&mut t, &inches, (300.0 + d, 300.0)), circle(&[(300.0, 300.0), (300.0 + rounded, 300.0)]));
}
/// `tool.setOption`'s check takes the values the options take and nothing else.
#[test]
fn check_options_takes_only_the_values_the_options_take() {
let ok = json!({"center": false, "radii": true, "diameter": false, "color": "gray", "standardAnchors": false, "dragThird": false});
assert_eq!(check_options(ok.as_object().unwrap()), Ok(()));
// The tool's own check, which `tool.setOption` also runs, takes the same values.
let tool = CircleTool::default();
assert_eq!(tool.check_options(ok.as_object().unwrap()), Ok(()));
for (bad, error) in [
(json!({"center": 1}), "`center` must be true or false"),
(json!({"dragThird": null}), "`dragThird` must be true or false"),
(json!({"color": "orange"}), "`color` must be one of red, blue, magenta, green, black, gray"),
(json!({"colour": "red"}), "unknown Circle tool option `colour`"),
] {
assert_eq!(check_options(bad.as_object().unwrap()), Err(error.to_string()), "{bad}");
assert_eq!(tool.check_options(bad.as_object().unwrap()), Err(error.to_string()), "{bad}");
}
}
/// A drag ends where it is let go, also when the release is away from the last drag: from a first
/// press, from a second press, and from a press on the first point. A release within 2 screen
/// points of a second press is still a click and keeps the point of the press.
@@ -288,8 +584,8 @@ fn points_on_one_line_say_the_circle_is_too_large() {
assert_eq!(label(&t), None, "a circle is shown");
t.pointer(&cx, &ev(PointerKind::Drag, (200.0, 200.0), Mods::default()));
assert_eq!(label(&t), None, "the third point is on the second");
assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)]));
assert!(!too_large(&[Point::new(0.0, 0.0)]) && !too_large(&[Point::new(1.0, 0.0), Point::new(1.0, 0.0)]));
assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)], true));
assert!(!too_large(&[Point::new(0.0, 0.0)], true) && !too_large(&[Point::new(1.0, 0.0), Point::new(1.0, 0.0)], true));
}
/// Escape drops the first point; so do a dropped press and an edit made outside the tool. A
+3 -3
View File
@@ -1657,7 +1657,7 @@ impl DirectSelectionTool {
// The grabbed anchor snaps and the others follow it. Shift keeps the move at its
// angle, and the anchor slides along it onto what Smart Guides find there (#886).
self.guides.clear();
if segment && let Some(grid) = &self.partial_grid {
if segment && let Some(grid) = &mut self.partial_grid {
(d, self.guides) = if ev.mods.shift { grid.snap_along(cx, grab, d, false) } else { grid.snap(cx, grab, d, false) };
} else if let Some(snap) = &self.anchor_snap {
let shift = ev.mods.shift.then(|| Leave::segment(cx, grab, true));
@@ -1710,7 +1710,7 @@ impl DirectSelectionTool {
&& let Some(snap) = &self.partial_snap
{
let held = grab.unwrap_or(hold);
if let Some(grid) = &self.partial_grid {
if let Some(grid) = &mut self.partial_grid {
(d, self.guides) = if ev.mods.shift { grid.snap_along(cx, held, d, false) } else { grid.snap(cx, held, d, false) };
} else {
let shift = ev.mods.shift.then(|| Leave::segment(cx, held, true));
@@ -1730,7 +1730,7 @@ impl DirectSelectionTool {
let shift = ev.mods.shift.then(|| Leave::segment(cx, grab, true));
let (q, guides) = snap.snap_from(cx, grab + (p - start), shift.as_ref());
(d, self.guides) = (q - grab, guides);
} else if let Some(snap) = &self.move_snap {
} else if let Some(snap) = &mut self.move_snap {
(d, self.guides) = if ev.mods.shift { snap.snap_along(cx, hold, d, ev.mods.alt) } else { snap.snap(cx, hold, d, ev.mods.alt) };
}
self.snapped = snapped(d, unsnapped, ev.mods.shift, &self.guides);
+6
View File
@@ -707,6 +707,12 @@ impl Targets {
self
}
/// These targets without the ruler guides, once they stop showing during the drag they were
/// gathered for (#8363).
pub(crate) fn forget_rulers(&mut self) {
self.rulers.clear();
}
/// The ruler guides alone ([`Self::with_rulers`]): what a dragged selection's grabbed point
/// still snaps to with View → Snap to Point when Smart Guides line the selection up.
pub(crate) fn rulers(cx: &ToolContext) -> Self {
+6
View File
@@ -226,6 +226,12 @@ pub trait Tool: Send {
fn ends_on_escape(&self, _cx: &ToolContext) -> bool {
false
}
/// The point a path the tool is drawing goes on from, and the direction the path arrives there
/// in (none for a path of one point), while the tool draws one: the Quick Pen toolbar sits
/// beside it.
fn drawing_end(&self, _cx: &ToolContext) -> Option<(Point, Option<Vec2>)> {
None
}
/// Does the tool want typed text (Type tool editing)? Single-key shortcuts are suppressed.
fn wants_text(&self) -> bool {
false
+180 -57
View File
@@ -7,15 +7,17 @@
//! sharp-corner arc (it turns through the arc size, 180° by default, and meets the path before it
//! at a corner). Alt (Option) pressed and let go on its own switches to the next action. C flips
//! the last sharp-corner arc to the other side of its chord, and [ and ] make the arc size 15°
//! smaller or larger, for the last sharp-corner arc and the ones after it. A click on the first
//! smaller or larger, for the last sharp-corner arc and the ones after it; during a drag they
//! change the arc being dragged. A dragged piece ends where the press is let go. A click on the first
//! point closes the path, a click on an end of an open path goes on drawing from it, and Escape
//! or Enter ends the path. The path's points show as circles, without handles, and a preview
//! shows the piece the next click adds. Points snap to Smart Guides. Each piece is one undo step.
use std::f64::consts::{FRAC_PI_2, PI};
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_geom::{Anchor, AnchorKind, BezPath, Point, SubPath, Vec2};
use crate::draw2::FEEDBACK;
@@ -39,6 +41,11 @@ const DRAG_PX: f64 = 3.0;
/// A continuous arc whose end lies within this angle (radians) of straight ahead, or of straight
/// behind, is drawn as a line: no circle runs there in the path's direction.
const STRAIGHT: f64 = 1e-6;
/// The notice the tool asks for after each of its own edits, to see the path as the document then
/// has it.
const DRAWN: &str = "drawn";
/// The notice after a press's piece is committed.
const PLACED: &str = "placed";
/// What the next click adds.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@@ -214,21 +221,50 @@ pub fn build(base: &SubPath, pieces: &[Piece], closed: bool) -> SubPath {
sp
}
/// The path being drawn: subpath `si` of `id`, whose points were `base` before the tool drew on
/// (both none until the engine made a new path), then `pieces`. A new path starts at `start`.
#[derive(Clone, Debug, PartialEq)]
/// The path being drawn: subpath `si` of `id` (none until the engine made a new path, which starts
/// at `start`), and the `pieces` the tool added to it, each after the number of points in `kept`
/// the subpath had before it. `seen` is the path object as the document had it after the tool's
/// last edit, pixel alignment and other changes the engine makes after each edit included, and
/// `before_press` as it was when the press under way began. A piece is drawn again on the points
/// the document holds before it, so the points before it stay as they are.
#[derive(Clone, Debug, Default, PartialEq)]
struct Drawing {
id: Option<NodeId>,
si: usize,
base: Option<SubPath>,
start: Option<Point>,
pieces: Vec<Piece>,
kept: Vec<usize>,
seen: Option<Arc<Node>>,
before_press: Option<Arc<Node>>,
/// The document's revision ([`ToolContext::revision`]) after the tool's last edit.
revision: (u64, u64),
}
/// The node `id` as the document shares it, found through the document's index.
fn shared_node(doc: &Document, id: NodeId) -> Option<&Arc<Node>> {
let path = doc.index_path(id)?;
let (first, rest) = path.split_first()?;
let mut cur = doc.layers.get(*first)?;
for &i in rest {
cur = cur.children()?.get(i)?;
}
Some(cur)
}
/// Is `now` the node `then` was: the same shared node, or one equal to it?
fn same_node(now: &Node, then: &Arc<Node>) -> bool {
std::ptr::eq(now, Arc::as_ptr(then)) || *now == **then
}
impl Drawing {
/// The subpath as the tool drew it.
fn drawn(&self) -> Option<SubPath> {
Some(build(self.base.as_ref()?, &self.pieces, false))
fn push(&mut self, piece: Piece, kept: usize) {
self.pieces.push(piece);
self.kept.push(kept);
}
fn pop(&mut self) {
self.pieces.pop();
self.kept.pop();
}
}
@@ -266,30 +302,41 @@ fn point_tol(cx: &ToolContext) -> f64 {
cx.tol(5.0).max(cx.point_tol())
}
/// Asks to see the path once the actions before it are applied.
fn drawn() -> Action {
Action::Notify(DRAWN.into())
}
impl QuickPenTool {
/// The subpath being drawn, while it is selected, editable, open and still exactly what the tool
/// drew: an edit made outside the tool (a point moved, the path it went on from changed) ends
/// the drawing, so the next piece does not undo it.
/// The subpath being drawn, while it is selected, editable, open and its path still exactly as
/// the tool's last edit left it: an edit made to the path outside the tool (a point moved, its
/// look changed, the path it went on from changed), also during a press, ends the drawing, so
/// the next piece does not undo it.
fn active<'a>(&self, cx: &'a ToolContext) -> Option<(NodeId, &'a SubPath)> {
let dr = self.drawing.as_ref()?;
let id = dr.id?;
if !selected_alone(cx, id) || !cx.doc.is_editable(id) {
return None;
}
let sp = cx.doc.node(id)?.path_data()?.subpaths.get(dr.si)?;
(!sp.closed && dr.drawn()?.anchors == sp.anchors).then_some((id, sp))
let node = cx.doc.node(id)?;
if !same_node(node, dr.seen.as_ref()?) {
return None;
}
let sp = node.path_data()?.subpaths.get(dr.si)?;
(!sp.closed).then_some((id, sp))
}
/// `path.quickPen`'s params for the path being drawn, closed when `closed`.
/// `path.quickPen`'s params for the path being drawn: its last piece on the points before it,
/// closed when `closed`.
fn params(&self, closed: bool) -> Value {
let Some(dr) = &self.drawing else { return json!({}) };
let pieces: Vec<Value> = dr.pieces.iter().map(Piece::to_json).collect();
let pieces: Vec<Value> = dr.pieces.last().map(Piece::to_json).into_iter().collect();
let mut v = json!({"pieces": pieces});
match (dr.id, dr.start) {
(Some(id), _) => {
v["id"] = json!(id.0);
v["subpath"] = json!(dr.si);
v["keep"] = json!(dr.base.as_ref().map_or(1, |b| b.anchors.len().max(1)));
v["keep"] = json!(dr.kept.last().copied().unwrap_or(1).max(1));
}
(None, Some(s)) => v["start"] = json!([s.x, s.y]),
(None, None) => {}
@@ -300,15 +347,57 @@ impl QuickPenTool {
v
}
/// The last piece, while it is a sharp-corner arc and no press is under way.
/// The last piece, while it is a sharp-corner arc: the one drawn last while no press is under
/// way, or the one a press is drawing.
fn last_sharp_arc(&self, cx: &ToolContext) -> Option<Piece> {
if self.press.is_some() {
return None;
match self.press {
Some(pr) if !pr.begun => return None,
Some(_) => self.held(cx).then_some(())?,
None => self.active(cx).map(|_| ())?,
}
self.active(cx)?;
self.drawing.as_ref()?.pieces.last().copied().filter(|p| p.stroke == Stroke::SharpArc)
}
/// During a press: is the path being drawn still active, and the document as the tool's last
/// preview left it? A preview starts again from the document as the press found it, so after
/// an edit made outside the tool the press previews no more.
fn held(&self, cx: &ToolContext) -> bool {
self.active(cx).is_some() && self.drawing.as_ref().is_some_and(|dr| dr.revision == cx.revision)
}
/// Moves the end of the piece a press draws to `p` (snapped) and previews it. An edit made
/// outside the tool since the last preview ends the drawing instead: the press then commits
/// the document as it is.
fn drag_to(&mut self, cx: &ToolContext, p: Point) -> Vec<Action> {
if !self.held(cx) {
self.drawing = None;
self.snap.clear();
return vec![];
}
// The snapping leaves from the point before the piece being dragged, as the press found it.
let from = self.drawing.as_ref().and_then(|dr| {
let sp = dr.before_press.as_ref()?.path_data()?.subpaths.get(dr.si)?;
sp.anchors.get(dr.kept.last()?.checked_sub(1)?).map(|a| Leave::segment(cx, a.p, false).without_contact())
});
let q = self.snap.drag(cx, p, from.as_ref());
let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) else { return vec![] };
if last.to == q {
return vec![];
}
last.to = q;
vec![Action::Preview(COMMAND.into(), self.params(false)), drawn()]
}
/// Draws the path again after its last piece changed: a preview while a press draws that
/// piece, else a step of its own.
fn redraw(&self) -> Vec<Action> {
if self.press.is_some_and(|pr| pr.begun) {
vec![Action::Preview(COMMAND.into(), self.params(false)), drawn()]
} else {
vec![Action::Exec(COMMAND.into(), self.params(false)), drawn()]
}
}
fn piece_to(&self, to: Point) -> Piece {
Piece { to, stroke: self.action, turn: self.turn, flip: false }
}
@@ -332,9 +421,9 @@ impl QuickPenTool {
_ => return vec![],
};
if sp.anchors.len() >= 2 && p.distance(first) <= tol && p.distance(first) <= p.distance(last) {
let piece = self.piece_to(first);
let (piece, kept) = (self.piece_to(first), sp.anchors.len());
if let Some(dr) = self.drawing.as_mut() {
dr.pieces.push(piece);
dr.push(piece, kept);
}
let out = vec![Action::Exec(COMMAND.into(), self.params(true))];
self.drawing = None;
@@ -345,27 +434,25 @@ impl QuickPenTool {
}
let from = self.leave(cx).map(|l| l.1);
let q = self.snap.press(cx, p, &[id], from.as_ref());
let piece = self.piece_to(q);
let (piece, kept) = (self.piece_to(q), sp.anchors.len());
if let Some(dr) = self.drawing.as_mut() {
dr.pieces.push(piece);
dr.push(piece, kept);
dr.before_press = shared_node(cx.doc, id).cloned();
}
self.press = Some(Press { at: p, dragged: false, begun: true });
return vec![Action::Begin("Quick Pen".into()), Action::Preview(COMMAND.into(), self.params(false))];
return vec![Action::Begin("Quick Pen".into()), Action::Preview(COMMAND.into(), self.params(false)), drawn()];
}
if let Some((id, si, at_first)) = open_end_at(cx, p, tol, None)
&& cx.doc.is_editable(id)
&& let Some(sp) = cx.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si))
{
// From its start, `continue_from` reverses the path first.
let mut base = sp.clone();
if at_first {
base.reverse();
}
self.drawing = Some(Drawing { id: Some(id), si, base: Some(base), start: None, pieces: vec![] });
return continue_from(cx, id, si, at_first);
// From its start, `continue_from` reverses the path first; the tool then sees it.
self.drawing = Some(Drawing { id: Some(id), si, ..Drawing::default() });
let mut out = continue_from(cx, id, si, at_first);
out.push(drawn());
return out;
}
let q = self.snap.press(cx, p, &[], None);
self.drawing = Some(Drawing { id: None, si: 0, base: None, start: Some(q), pieces: vec![] });
self.drawing = Some(Drawing { start: Some(q), ..Drawing::default() });
vec![Action::Exec(COMMAND.into(), self.params(false)), Action::Notify("created".into())]
}
@@ -427,36 +514,61 @@ impl Tool for QuickPenTool {
}
pr.dragged = true;
self.press = Some(pr);
// The snapping leaves from the point before the piece being dragged.
let from = self.drawing.as_ref().and_then(|dr| {
let sp = build(dr.base.as_ref()?, dr.pieces.split_last().map_or(&[][..], |(_, rest)| rest), false);
sp.anchors.last().map(|a| Leave::segment(cx, a.p, false).without_contact())
});
let q = self.snap.drag(cx, p, from.as_ref());
if let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) {
last.to = q;
if !pr.begun {
return vec![];
}
vec![Action::Preview(COMMAND.into(), self.params(false))]
self.drag_to(cx, p)
}
PointerKind::Up => {
self.snap.clear();
match self.press.take() {
Some(pr) if pr.begun => vec![Action::Commit],
let out = match self.press {
// The piece ends where the press is let go, also past the last drag.
Some(pr) if pr.begun => {
let mut out = vec![];
if pr.dragged || p.distance(pr.at) >= cx.tol(DRAG_PX) {
out = self.drag_to(cx, p);
} else if self.active(cx).is_none() {
// An edit made outside the tool during the press ends the path.
self.drawing = None;
}
// With Real-time Drawing off, the commit applies the piece.
out.extend([Action::Commit, Action::Notify(PLACED.into())]);
out
}
_ => vec![],
};
if let Some(dr) = self.drawing.as_mut() {
dr.before_press = None;
}
self.press = None;
self.snap.clear();
out
}
PointerKind::DoubleClick | PointerKind::TripleClick => vec![],
}
}
fn notify(&mut self, cx: &ToolContext, what: &str) {
let Some(dr) = self.drawing.as_mut() else { return };
if what == "created"
&& let [id] = cx.selection.objects.as_slice()
&& let Some(base) = cx.doc.node(*id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.first())
&& let Some(dr) = self.drawing.as_mut()
&& let Some(node) = shared_node(cx.doc, *id).filter(|n| n.path_data().is_some_and(|pd| !pd.subpaths.is_empty()))
&& dr.id.is_none()
{
(dr.id, dr.si, dr.base, dr.start) = (Some(*id), 0, Some(base.clone()), None);
(dr.id, dr.si, dr.start, dr.seen) = (Some(*id), 0, None, Some(node.clone()));
} else if (what == DRAWN || what == PLACED)
&& let Some(id) = dr.id
{
dr.seen = shared_node(cx.doc, id).cloned();
dr.revision = cx.revision;
// Once committed, a piece that added no point to the path (the command refused it) is
// not kept for C and [ ] to change.
let points = dr.seen.as_ref().and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(dr.si)).map(|sp| sp.anchors.len());
if what == PLACED
&& let (Some(points), Some(&kept)) = (points, dr.kept.last())
&& points <= kept
{
dr.pop();
}
}
}
@@ -465,6 +577,11 @@ impl Tool for QuickPenTool {
self.active(cx).is_some()
}
fn drawing_end(&self, cx: &ToolContext) -> Option<(Point, Option<Vec2>)> {
let (_, sp) = self.active(cx)?;
Some((sp.anchors.last()?.p, arrival(sp)))
}
fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool {
match key {
ToolKey::Letter('c') => self.last_sharp_arc(cx).is_some(),
@@ -475,13 +592,19 @@ impl Tool for QuickPenTool {
}
/// A dropped press does not end the path being drawn: the piece it added goes.
fn drop_press(&mut self, _cx: &ToolContext) -> Vec<Action> {
/// The drawing goes on only when the path is back as it was before the press.
fn drop_press(&mut self, cx: &ToolContext) -> Vec<Action> {
self.snap.clear();
if self.press.take().is_some_and(|pr| pr.begun)
&& let Some(dr) = self.drawing.as_mut()
{
dr.pieces.pop();
dr.pop();
let now = dr.id.and_then(|id| cx.doc.node(id));
match (now, dr.before_press.take()) {
(Some(now), Some(before)) if same_node(now, &before) => dr.seen = Some(before),
_ => self.drawing = None,
}
}
self.snap.clear();
vec![]
}
@@ -495,7 +618,7 @@ impl Tool for QuickPenTool {
if let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) {
last.flip = !last.flip;
}
vec![Action::Exec(COMMAND.into(), self.params(false))]
self.redraw()
}
ToolKey::BracketLeft | ToolKey::BracketRight => {
let by = if key == ToolKey::BracketLeft { -TURN_STEP } else { TURN_STEP };
@@ -511,17 +634,17 @@ impl Tool for QuickPenTool {
if let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) {
last.turn = turn;
}
vec![Action::Exec(COMMAND.into(), self.params(false))]
self.redraw()
}
ToolKey::AltTap => {
self.action = self.action.next();
// A drag under way draws its piece with the new action.
if self.press.is_some_and(|pr| pr.begun) {
if self.press.is_some_and(|pr| pr.begun) && self.held(cx) {
let (action, turn) = (self.action, self.turn);
if let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) {
(last.stroke, last.turn, last.flip) = (action, turn, false);
}
return vec![Action::Preview(COMMAND.into(), self.params(false))];
return vec![Action::Preview(COMMAND.into(), self.params(false)), drawn()];
}
vec![]
}
+18 -3
View File
@@ -309,10 +309,24 @@ impl MoveSnap {
Self { bounds, targets: None, points: None, copy_targets: None, copy_points: None, rulers: None, by_edge: false }
}
/// The ruler guides stopped showing since the move began (View › Hide Guides, or Trim View,
/// #8363): the move no longer snaps to them, for the rest of it, while its other targets stay.
/// They were gathered when it began, and nothing pulls toward a guide the canvas does not draw.
fn forget_hidden_rulers(&mut self, cx: &ToolContext) {
if cx.guides {
return;
}
self.rulers = None;
for t in [&mut self.points, &mut self.copy_points].into_iter().flatten() {
t.forget_rulers();
}
}
/// The move (`copy`: the copy) by `d` of the selection grabbed at `start`, snapped, and its
/// guides. With Smart Guides › Snap to Last Location, a move within Snapping Tolerance of where
/// it began goes back there before anything else snaps ([`Targets::snap_back`]).
pub(crate) fn snap(&self, cx: &ToolContext, start: Point, mut d: Vec2, copy: bool) -> (Vec2, Vec<Overlay>) {
pub(crate) fn snap(&mut self, cx: &ToolContext, start: Point, mut d: Vec2, copy: bool) -> (Vec2, Vec<Overlay>) {
self.forget_hidden_rulers(cx);
let (targets, points) = if copy { (&self.copy_targets, &self.copy_points) } else { (&self.targets, &self.points) };
if let Some(ov) = targets.as_ref().and_then(|t| t.snap_back(self.bounds, d, cx.snap_tol())) {
return (Vec2::ZERO, ov);
@@ -391,7 +405,8 @@ impl MoveSnap {
/// passes an anchor or crosses a ruler guide ([`Targets::snap_point_along`]). A move of zero
/// length does not snap, and Snap to Last Location goes back to where the move began first, as
/// in [`Self::snap`].
pub(crate) fn snap_along(&self, cx: &ToolContext, start: Point, mut d: Vec2, copy: bool) -> (Vec2, Vec<Overlay>) {
pub(crate) fn snap_along(&mut self, cx: &ToolContext, start: Point, mut d: Vec2, copy: bool) -> (Vec2, Vec<Overlay>) {
self.forget_hidden_rulers(cx);
let len = d.hypot();
if !len.is_finite() || len <= 1e-9 {
return (d, vec![]);
@@ -1957,7 +1972,7 @@ impl SelectionTool {
}
let mut d = move_delta(start, p, m.shift, cx.constrain_angle);
let unsnapped = d;
if let Some(snap) = &self.moving {
if let Some(snap) = &mut self.moving {
(d, self.guides) = if m.shift { snap.snap_along(cx, hold, d, m.alt) } else { snap.snap(cx, hold, d, m.alt) };
}
// Shift has already constrained `d`: any change is a snap.
+1 -1
View File
@@ -2198,7 +2198,7 @@ fn move_follows_the_while_moving_option() {
let p = paint();
let pixel_snap = PixelSnap { moving: false, ..PixelSnap::default() };
let c = ToolContext { snap_to_pixel: true, pixel_snap, smart_guides: false, snap_to_point: false, ..cx(&d, &s, &p) };
let snap = MoveSnap::new(&c);
let mut snap = MoveSnap::new(&c);
let (dv, _) = snap.snap(&c, Point::new(150.0, 150.0), Vec2::new(3.3, 4.6), false);
assert!((dv - Vec2::new(3.3, 4.6)).hypot() < 1e-9, "{dv:?}");
let on = ToolContext { pixel_snap: PixelSnap::default(), ..c };
+2
View File
@@ -78,6 +78,8 @@ const ROWS: &[Row] = &[
(&["star"], None, &["points"]),
// The Ellipse dialog's Anchors.
(&["ellipse"], None, &["anchors"]),
// Circle Tool Options (`circle::CircleTool`).
(&[crate::circle::ID], None, &["center", "radii", "diameter", "color", "standardAnchors", "dragThird"]),
(&["freeTransform"], None, &["constrain"]),
// Shape Builder Tool Options (`builder::ShapeBuilderOptions`).
(
+4
View File
@@ -479,6 +479,10 @@ impl VectorcraftApp {
if crate::touch::is_drawing_tool(now) {
self.ui.touch_drawing_tool = Some(now.to_string());
}
// Selecting the Quick Pen tool shows its toolbar, even after Hide Toolbar.
if now == vectorcraft_tools::quickpen::ID {
self.ui.quick_pen_bar = true;
}
Ok(())
}
+1 -1
View File
@@ -122,7 +122,7 @@ impl VectorcraftApp {
zoom: self.view().map_or(1.0, |v| v.screen_zoom(self.canvas_ui_zoom)),
outline: self.outline_view(),
smart_guides: self.ui.view.smart_guides,
guides: self.ui.view.guides,
guides: self.ui.view.guides_shown(),
snap_to_grid: self.ui.view.snap_to_grid,
pixel_preview: self.ui.view.pixel_preview,
snap_to_pixel: self.ui.view.snap_to_pixel,
+8 -4
View File
@@ -28,6 +28,7 @@ mod input;
mod outline;
mod overlays;
mod panes;
mod quick_pen_bar;
mod raster;
mod selection_marks;
mod task_bar;
@@ -68,6 +69,7 @@ use overlays::{
};
pub use panes::{Layout as TileLayout, Panes};
pub(crate) use panes::{consolidate, note_drop, noted_cursor, pane, release_on_noted, tile, tiled_area};
pub(crate) use quick_pen_bar::quick_pen_bar_rect;
pub(crate) use raster::{KeptFrame, color_image, color_image_owned, render_job};
use raster::{changed_pixels, frame_ppp, pixel_region, upload};
pub use selection_marks::SelectionMarks;
@@ -326,7 +328,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
paint_paper(app, st, ui, &painter, &xf, rect, (&t, app.outline_view()));
// The grid behind the art (Guides & Grid › Grids In Back), else over it below.
let grid_look = (app.ui.view.grid && !presenting).then(|| LineLook::grid(&app.session.prefs));
let grid_look = (app.ui.view.grid_shown() && !presenting).then(|| LineLook::grid(&app.session.prefs));
let grids_in_back = app.session.prefs.grids_in_back;
if let Some(look) = grid_look.filter(|_| grids_in_back) {
grid(&painter, &xf, doc.grid.spacing, doc.grid.subdivisions, look);
@@ -416,7 +418,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
grid(&painter, &xf, 1.0, 1, LineLook { color: PIXEL_GRID, dots: false });
}
artboard_outlines(app, ui, &painter, &xf, &t);
if app.ui.view.guides {
if app.ui.view.guides_shown() {
guide_lines(app, &painter, &xf, rect, &t);
}
nine_slice_overlay(app, &painter, &xf);
@@ -463,6 +465,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
task_bar(app, ui, &xf);
}
if app.ui.screen_mode < 3 {
// The Quick Pen toolbar gives way to a drag as the task bar does.
quick_pen_bar::quick_pen_bar(app, ui, &xf);
contour_bar::contour_bar(app, ui, &xf);
// After the task bar, which the row of character alternates keeps clear of.
alternates_bar::alternates_bar(app, ui, &xf);
@@ -899,7 +903,7 @@ fn cache_key(
outline: app.outline_view(),
trim: app.ui.view.trim_view,
templates: app.ui.view.templates,
guides: app.ui.view.guides,
guides: app.ui.view.guides_shown(),
ppp,
hidden: vec![],
rot: v.rotation,
@@ -1098,7 +1102,7 @@ fn frame_options(
overprint_preview: vectorcraft_render::proof::overprint_preview_on(),
trim: app.ui.view.trim_view,
hide_templates: !app.ui.view.templates,
hide_guides: !app.ui.view.guides,
hide_guides: !app.ui.view.guides_shown(),
tile_edge: vectorcraft_color::Color::from_hex(&app.session.prefs.pattern_tile_edge_color).map_or(opts.tile_edge, |c| {
let [r, g, b, _] = c.to_rgba8(1.0);
[r, g, b]
+58 -12
View File
@@ -222,7 +222,14 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c
if resp.clicked_by(egui::PointerButton::Primary) {
ui.data_mut(|d| d.insert_temp(last_click, now));
}
if resp.double_clicked_by(egui::PointerButton::Primary)
// Trim View hides the guides (#8363): a guide made now could not be seen, so none is.
let trim_view = app.ui.view.trim_view;
let refuse = |app: &mut VectorcraftApp| app.status(crate::menus::TRIM_VIEW_HIDES.to_string());
if trim_view && first_here && resp.double_clicked_by(egui::PointerButton::Primary) {
refuse(app);
}
if !trim_view
&& resp.double_clicked_by(egui::PointerButton::Primary)
&& first_here
&& let Some(p) = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos()))
{
@@ -253,12 +260,22 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c
} else {
continue;
};
let p = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos()));
let on_canvas = p.is_some_and(|p| canvas.contains(p));
if on_canvas {
// The new guide shows even if guides were hidden.
app.ui.view.guides = true;
// A drag Trim View is on for at any point makes no guide, so none previews, even when
// Trim View is turned off again before the release: the whole gesture is cancelled and
// stays so until the button is released.
let cancel = egui::Id::unique(if vertical { "ruler-left-trim-cancel" } else { "ruler-top-trim-cancel" });
if resp.drag_started() {
ui.data_mut(|d| d.remove::<bool>(cancel));
}
if trim_view && ui.data(|d| d.get_temp::<bool>(cancel).is_none()) {
refuse(app);
ui.data_mut(|d| d.insert_temp(cancel, true));
}
let cancelled = ui.data(|d| d.get_temp::<bool>(cancel).is_some());
if cancelled && kind == PointerKind::Up {
ui.data_mut(|d| d.remove::<bool>(cancel));
}
let p = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos()));
let ev = PointerEvent {
kind,
pos: p.map_or(Point::ZERO, |p| xf.to_doc(p)),
@@ -267,6 +284,21 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c
pressure: 1.0,
pen: None,
};
if cancelled {
// A guide already dragged when Trim View turned on ends as a release off the canvas
// does: no guide, no undo step.
if app.session.ruler_guide_dragging()
&& let Err(e) = app.session.ruler_guide(vertical, &PointerEvent { kind: PointerKind::Up, ..ev }, false, app.view_info())
{
app.status(e.to_string());
}
continue;
}
let on_canvas = p.is_some_and(|p| canvas.contains(p));
if on_canvas {
// The new guide shows even if guides were hidden.
app.ui.view.guides = true;
}
if let Err(e) = app.session.ruler_guide(vertical, &ev, on_canvas, app.view_info()) {
app.status(e.to_string());
}
@@ -288,11 +320,14 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c
let drag_id = ruler_origin_drag_id();
let uid = app.session.active().map(|d| d.uid);
if corner.drag_started_by(egui::PointerButton::Primary) {
ui.data_mut(|d| d.insert_temp(drag_id, (uid, false)));
ui.data_mut(|d| d.insert_temp(drag_id, OriginDrag { doc: uid, cancelled: false, trim_view: app.ui.view.trim_view }));
}
let mut preview = None;
if let Some((started_in, mut cancelled)) = ui.data(|d| d.get_temp::<(Option<u64>, bool)>(drag_id)) {
cancelled |= started_in != uid || ui.input(|i| !i.focused || i.key_pressed(egui::Key::Escape));
if let Some(OriginDrag { doc: started_in, mut cancelled, trim_view }) = ui.data(|d| d.get_temp::<OriginDrag>(drag_id)) {
// Trim View turned on or off during the drag: the snap targets gathered at its start
// hold the ruler guides, or leave them out, as they no longer show (#8363), so the origin
// could snap to a guide nobody sees. The drag is cancelled as for hidden rulers.
cancelled |= started_in != uid || trim_view != app.ui.view.trim_view || ui.input(|i| !i.focused || i.key_pressed(egui::Key::Escape));
let pointer =
corner.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos())).filter(|p| canvas.contains(*p)).map(|p| xf.to_doc(p));
// The origin snaps as a drawn point does (Smart Guides, Snap to Point, pixels, the grid).
@@ -313,7 +348,7 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c
} else if !ui.input(|i| i.pointer.primary_down()) {
end_ruler_origin_drag(app, ui);
} else {
ui.data_mut(|d| d.insert_temp(drag_id, (started_in, cancelled)));
ui.data_mut(|d| d.insert_temp(drag_id, OriginDrag { doc: started_in, cancelled, trim_view }));
if !cancelled {
preview = at;
}
@@ -333,10 +368,21 @@ pub(super) fn rulers_hidden(app: &mut VectorcraftApp, ui: &Ui) -> Option<Point>
/// Ends a drag from the rulers' corner, released or cancelled: its state and its snapping guides go.
fn end_ruler_origin_drag(app: &mut VectorcraftApp, ui: &Ui) {
ui.data_mut(|d| d.remove::<(Option<u64>, bool)>(ruler_origin_drag_id()));
ui.data_mut(|d| d.remove::<OriginDrag>(ruler_origin_drag_id()));
app.session.end_ruler_origin_drag();
}
/// A drag of the rulers' origin out of their corner, kept between frames.
#[derive(Clone, Copy)]
struct OriginDrag {
/// The document it started in (`Document::uid`): another one active cancels it.
doc: Option<u64>,
/// Cancelled (Escape, focus lost, another document, Trim View toggled): it sets nothing.
cancelled: bool,
/// View › Trim View was on when it started.
trim_view: bool,
}
/// The key of the ruler origin drag's state in egui's temporary data.
fn ruler_origin_drag_id() -> egui::Id {
egui::Id::unique("ruler-origin-drag")
@@ -345,7 +391,7 @@ fn ruler_origin_drag_id() -> egui::Id {
/// Is a drag from the rulers' corner in progress? It stays true after Escape cancels the move, until
/// the button is released.
pub(crate) fn ruler_origin_dragging(ctx: &egui::Context) -> bool {
ctx.data(|d| d.get_temp::<(Option<u64>, bool)>(ruler_origin_drag_id()).is_some())
ctx.data(|d| d.get_temp::<OriginDrag>(ruler_origin_drag_id()).is_some())
}
/// What the rulers count, and from where: `unit`, from `origin` (document points), with each
+1 -1
View File
@@ -188,7 +188,7 @@ pub(super) fn hit_with<T>(
path_only: prefs.object_selection_by_path_only,
type_path_only: prefs.type_selection_by_path_only,
scope: app.session.active().and_then(|st| st.isolation),
skip_guides: !app.ui.view.guides,
skip_guides: !app.ui.view.guides_shown(),
..Default::default()
};
test(&app.session.active()?.doc, p, opt)
+2 -2
View File
@@ -554,7 +554,7 @@ fn draw_pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> boo
let xf = Xf::at(rect, &v, ui_zoom);
let painter = ui.painter_at(rect);
paint_paper(app, st, ui, &painter, &xf, rect, (&t, v.outline));
let grid_look = app.ui.view.grid.then(|| LineLook::grid(&app.session.prefs));
let grid_look = app.ui.view.grid_shown().then(|| LineLook::grid(&app.session.prefs));
let grids_in_back = app.session.prefs.grids_in_back;
if let Some(look) = grid_look.filter(|_| grids_in_back) {
grid(&painter, &xf, st.doc.grid.spacing, st.doc.grid.subdivisions, look);
@@ -587,7 +587,7 @@ fn draw_pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> boo
if shows_artboards(app) {
artboard_edges(app, &st.doc, (&painter, &xf, &t), (v.artboard, dim_on_canvas(&t, v.outline)), |_| false);
}
if app.ui.view.guides {
if app.ui.view.guides_shown() {
guides_of(app, st, (&painter, &xf, &t), rect);
}
if app.ui.view.edges {
+278
View File
@@ -0,0 +1,278 @@
//! The Quick Pen toolbar: a floating bar on the canvas while the Quick Pen tool is active. It holds
//! the tool's actions (Straight Line, Continuous Arc, Sharp Corner Arc), Flip Arc for the last
//! sharp-corner arc, and a More Options menu with Hide Toolbar, Pin Toolbar Position and Reset
//! Toolbar Position. Its handle, at its left end, drags it.
//!
//! Public behavior: selecting the tool shows the toolbar, its actions decide what a click or drag
//! draws, Flip Arc flips the sharp-corner arc just drawn, the More menu hides the toolbar and resets
//! its position, and the toolbar moves by dragging its left side
//! ([Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html)).
//! The toolbar follows the drawing, beside the point the path goes on from and away from what was
//! drawn ([Behind the design: the Quick Pen tool](https://adobe.design/ideas/behind-the-design-adobe-illustrator-s-quick-pen-tool)).
//! VectorCraft's own rules: the exact place beside the point, moving to the drawn side where the
//! other side runs off the canvas, the place with no path being drawn, how a drag's offset is kept,
//! Pin Toolbar Position (which holds the toolbar at its place in the canvas window, not on the
//! artboard), and Window › Quick Pen Toolbar to show it again.
use vectorcraft_tools::quickpen::{self, Stroke as Action};
use super::{Color32, CornerRadius, Pos2, Sense, Stroke, Tokens, Ui, Vec2, VectorcraftApp, Xf, json, pos2, vec2, widgets};
/// The space between the point the path goes on from and the toolbar's nearest corner.
const GAP: f32 = 24.0;
/// The width of the toolbar's handle.
const HANDLE: f32 = 4.0;
/// The side of the toolbar's buttons.
const BUTTON: f32 = 28.0;
/// The space between the toolbar's controls.
const SPACING: f32 = 4.0;
fn bar_id() -> egui::Id {
egui::Id::unique("quick-pen-bar")
}
/// Where the Quick Pen toolbar was last drawn (none while it isn't shown).
pub(crate) fn quick_pen_bar_rect(ctx: &egui::Context) -> Option<egui::Rect> {
let id = bar_id();
ctx.memory(|m| m.areas().is_visible(&egui::LayerId::new(egui::Order::Middle, id)).then(|| m.area_rect(id)).flatten())
}
/// The toolbar's top-left corner, of `size`, beside `end` (the point the path goes on from, on
/// screen), on the side the path arrives there from `dir` (on screen): to its right and below it
/// for a path drawn to the right and down, so the toolbar stays off what was drawn. A path of one
/// point puts it to the right and below. Where that side runs out of `room` (the canvas) and the
/// other side fits, it goes on the other side; where neither fits, on the side with more room.
/// Kept in `room` ([`keep_in`]), it covers `end` only when neither side fits across or down.
fn beside(end: Pos2, dir: Option<Vec2>, size: Vec2, room: egui::Rect) -> Pos2 {
// `first` unless it runs out of room and `other` fits or runs out by less.
let pick = |first: f32, other: f32, lo: f32, hi: f32, len: f32| {
let over = |p: f32| (lo - p).max(0.0) + (p + len - hi).max(0.0);
if over(other) < over(first) { other } else { first }
};
let (right, left) = (end.x + GAP, end.x - GAP - size.x);
let (below, above) = (end.y + GAP, end.y - GAP - size.y);
let x = if dir.is_none_or(|d| d.x >= 0.0) { (right, left) } else { (left, right) };
let y = if dir.is_none_or(|d| d.y >= 0.0) { (below, above) } else { (above, below) };
pos2(pick(x.0, x.1, room.left(), room.right(), size.x), pick(y.0, y.1, room.top(), room.bottom(), size.y))
}
/// The toolbar's place with no path being drawn: centered at the bottom of the canvas area `room`.
fn resting(room: egui::Rect, size: Vec2) -> Pos2 {
pos2(room.center().x - size.x / 2.0, room.bottom() - size.y)
}
/// `p` moved, as little as it takes, for a toolbar of `size` to lie inside `room`.
fn keep_in(p: Pos2, size: Vec2, room: egui::Rect) -> Pos2 {
p.clamp(room.min, (room.max - size).max(room.min))
}
/// Where an unpinned toolbar of `size` sits: `home` moved by the drag `offset`, kept in `room`,
/// unless that would cover `end` (the point the path goes on from, on screen), where it sits at
/// `home` as if never dragged.
fn unpinned(home: Pos2, offset: Vec2, end: Option<Pos2>, size: Vec2, room: egui::Rect) -> Pos2 {
let moved = keep_in(home + offset, size, room);
if end.is_some_and(|e| egui::Rect::from_min_size(moved, size).contains(e)) { keep_in(home, size, room) } else { moved }
}
/// What a click on the toolbar does.
enum Click {
Action(Action),
Run(&'static str, serde_json::Value),
}
/// Is a drag under way (past the drag threshold) that began on the canvas `canvas` outside the
/// toolbar's last place `bar`? A stroke, a Space or middle-button pan and a drag from a path's first
/// point all are; a drag of the toolbar's handle is not.
fn canvas_drag(dragging: bool, press: Option<Pos2>, canvas: egui::Rect, bar: Option<egui::Rect>) -> bool {
dragging && press.is_some_and(|p| canvas.contains(p) && !bar.is_some_and(|b| b.contains(p)))
}
/// The Quick Pen toolbar, while the Quick Pen tool is active, Window › Quick Pen Toolbar is on and
/// no press is dragging on the canvas. Selecting the tool turns Window › Quick Pen Toolbar on
/// ([`VectorcraftApp::try_select_tool`]).
pub(super) fn quick_pen_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) {
if !app.ui.quick_pen_bar || app.session.tool_id() != quickpen::ID {
return;
}
let (dragging, press, down) = ui.input(|i| (i.pointer.is_decidedly_dragging(), i.pointer.press_origin(), i.pointer.any_down()));
// The handle's drag moves the toolbar away from where the press began.
let handle_id = bar_id().with("handle");
if !down {
ui.ctx().data_mut(|d| d.insert_temp(handle_id, false));
}
let on_handle = ui.ctx().data(|d| d.get_temp::<bool>(handle_id)).unwrap_or(false);
let shown = app.ui.quick_pen_bar_place.shown_at.zip(egui::AreaState::load(ui.ctx(), bar_id()).and_then(|s| s.size));
if canvas_drag(dragging && !on_handle, press, xf.rect, shown.map(|(at, size)| egui::Rect::from_min_size(xf.rect.min + at, size))) {
return;
}
let Some(doc) = app.session.active().map(|st| st.uid) else { return };
let view = app.view_info();
let end = app.session.tool_drawing_end(view);
let flip = app.session.tool_claims_key(vectorcraft_tools::ToolKey::Letter('c'), view);
let current = app.session.tool_options().get("action").and_then(serde_json::Value::as_str).and_then(Action::parse).unwrap_or_default();
let t = Tokens::get(ui.ctx());
let id = bar_id();
let bounds = xf.rect.shrink(8.0);
let est = vec2(HANDLE + 5.0 * BUTTON + 6.0 * SPACING + 16.0, BUTTON + 12.0);
let size = egui::AreaState::load(ui.ctx(), id).and_then(|s| s.size).unwrap_or(est);
let end = end.map(|(p, dir)| {
let at = xf.to_screen(p);
(at, dir.map(|d| xf.to_screen(p + d) - at))
});
let drawing = end.is_some();
let home = match end {
Some((at, dir)) => beside(at, dir, size, bounds),
None => resting(bounds, size),
};
let place = &mut app.ui.quick_pen_bar_place;
// Just unpinned: follow the drawing from the pinned spot.
if !place.pinned
&& let Some(at) = place.pin_at.take()
{
place.offset = Some((doc, drawing, xf.rect.min + at - home));
}
// A drag's offset holds in the document and the kind of place (beside the drawing, or resting)
// it was made in.
let offset = place.offset.filter(|(d, beside, _)| *d == doc && *beside == drawing).map_or(Vec2::ZERO, |(_, _, o)| o);
let pos = match place.pin_at {
Some(at) => keep_in(xf.rect.min + at, size, bounds),
None => unpinned(home, offset, end.map(|(at, _)| at), size, bounds),
};
place.shown_at = Some(pos - xf.rect.min);
// Pinned before it ever showed: hold it here.
if place.pinned && place.pin_at.is_none() {
place.pin_at = place.shown_at;
}
let pinned = place.pinned;
let mut moved = Vec2::ZERO;
let mut click: Option<Click> = None;
egui::Area::new(id).order(egui::Order::Middle).fixed_pos(pos).show(ui.ctx(), |ui| {
egui::Frame::NONE
.fill(t.panel)
.stroke(Stroke::new(1.0, t.tool_active))
.corner_radius(CornerRadius::same(5))
.inner_margin(egui::Margin::symmetric(8, 6))
.shadow(egui::epaint::Shadow { offset: [0, 3], blur: 10, spread: 0, color: Color32::from_black_alpha(70) })
.show(ui, |ui| {
// In a canvas pane narrower than the toolbar, its controls wrap onto more rows.
ui.set_max_width((bounds.width() - 18.0).max(HANDLE + SPACING + BUTTON));
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing = vec2(SPACING, SPACING);
let (g, grip) = ui.allocate_exact_size(vec2(HANDLE, BUTTON), Sense::drag());
let active = grip.hovered() || grip.dragged();
ui.painter().rect_filled(g.shrink2(vec2(0.5, 4.0)), CornerRadius::same(2), if active { t.text_dim } else { t.button_border });
if grip.dragged() {
ui.ctx().data_mut(|d| d.insert_temp(handle_id, true));
ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);
moved = grip.drag_delta();
} else if grip.hovered() {
ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);
}
let actions = [
(Action::Line, "dc-line", tl!("Straight Line")),
(Action::ContinuousArc, "spline", tl!("Continuous Arc")),
(Action::SharpArc, "dc-arc", tl!("Sharp Corner Arc")),
];
for (action, icon, tip) in actions {
if widgets::icon_button(ui, icon, tip, current == action, BUTTON).clicked() {
click = Some(Click::Action(action));
}
}
if widgets::icon_button_enabled(ui, "flip-horizontal-2", tl!("Flip Arc"), false, flip, BUTTON).clicked() {
click = Some(Click::Run("tool.quickPen.flipArc", json!({})));
}
let more = widgets::icon_button(ui, "ellipsis", tl!("More Options"), false, BUTTON);
egui::Popup::menu(&more).show(|ui| {
ui.set_min_width(170.0);
let items = [
(tl!("Hide Toolbar"), "window.quickPenToolbar", false),
(tl!("Pin Toolbar Position"), "window.quickPenToolbar.pin", pinned),
(tl!("Reset Toolbar Position"), "window.quickPenToolbar.reset", false),
];
for (label, cmd, checked) in items {
if widgets::menu_item(ui, label, true, checked) {
click = Some(Click::Run(cmd, json!({})));
}
}
});
});
});
});
if moved != Vec2::ZERO {
let to = keep_in(pos + moved, size, bounds);
let place = &mut app.ui.quick_pen_bar_place;
if place.pinned {
place.pin_at = Some(to - xf.rect.min);
} else {
place.offset = Some((doc, drawing, to - home));
}
ui.ctx().request_repaint();
}
let r = match click {
Some(Click::Action(a)) => app.run("tool.setOption", json!({"key": "action", "value": a.name()})).map(|_| ()),
Some(Click::Run(cmd, p)) => app.run(cmd, p).map(|_| ()),
None => Ok(()),
};
if let Err(e) = r {
app.ui.status = e;
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The toolbar sits off what was drawn: ahead of a path drawn right and down, behind-left and
/// above for one drawn left and up, and to the right and below a single point.
#[test]
fn the_toolbar_sits_beside_the_end_away_from_the_drawing() {
let (end, size) = (pos2(500.0, 300.0), vec2(180.0, 40.0));
let room = egui::Rect::from_min_max(pos2(8.0, 8.0), pos2(808.0, 608.0));
assert_eq!(beside(end, Some(vec2(1.0, 0.0)), size, room), pos2(524.0, 324.0));
assert_eq!(beside(end, Some(vec2(-1.0, -1.0)), size, room), pos2(500.0 - 24.0 - 180.0, 300.0 - 24.0 - 40.0));
assert_eq!(beside(end, Some(vec2(0.0, 1.0)), size, room), pos2(524.0, 324.0));
assert_eq!(beside(end, Some(vec2(-1.0, 0.5)), size, room), pos2(296.0, 324.0));
assert_eq!(beside(end, None, size, room), pos2(524.0, 324.0));
assert_eq!(resting(room, size), pos2(318.0, 568.0));
// Near the canvas's bottom right corner, the side that runs off it gives way to the other.
let corner = pos2(700.0, 580.0);
assert_eq!(beside(corner, Some(vec2(1.0, 1.0)), size, room), pos2(700.0 - 24.0 - 180.0, 580.0 - 24.0 - 40.0));
// Near the top left corner, a path heading up and left still gets a toolbar off its end.
let corner = pos2(30.0, 30.0);
assert_eq!(beside(corner, Some(vec2(-1.0, -1.0)), size, room), pos2(54.0, 54.0));
// On a canvas too narrow for either side across, the toolbar goes on the side with more
// room and stays off the end by going below it.
let narrow = egui::Rect::from_min_max(pos2(8.0, 8.0), pos2(208.0, 608.0));
let end = pos2(60.0, 300.0);
let at = keep_in(beside(end, Some(vec2(-1.0, 1.0)), size, narrow), size, narrow);
assert_eq!(at, pos2(28.0, 324.0));
assert!(!egui::Rect::from_min_size(at, size).contains(end));
}
/// Any drag that began on the canvas hides the toolbar, whether or not the tool has a press
/// (a pan does not); a drag that began on the toolbar, and no drag, do not.
#[test]
fn a_drag_that_began_on_the_canvas_hides_the_toolbar() {
let canvas = egui::Rect::from_min_max(pos2(0.0, 0.0), pos2(800.0, 600.0));
let bar = Some(egui::Rect::from_min_size(pos2(300.0, 500.0), vec2(180.0, 40.0)));
assert!(canvas_drag(true, Some(pos2(100.0, 100.0)), canvas, bar), "a pan or stroke on the canvas");
assert!(canvas_drag(true, Some(pos2(100.0, 100.0)), canvas, None), "no toolbar shown yet");
assert!(!canvas_drag(false, Some(pos2(100.0, 100.0)), canvas, bar), "a click, not a drag");
assert!(!canvas_drag(true, Some(pos2(310.0, 510.0)), canvas, bar), "the toolbar's own drag");
assert!(!canvas_drag(true, Some(pos2(900.0, 100.0)), canvas, bar), "a drag in another panel");
assert!(!canvas_drag(true, None, canvas, bar));
}
/// A drag's offset moves the toolbar from its place, unless that would put it over the point
/// the path goes on from.
#[test]
fn a_dragged_toolbar_never_covers_the_end() {
let size = vec2(180.0, 40.0);
let room = egui::Rect::from_min_max(pos2(8.0, 8.0), pos2(808.0, 608.0));
let (end, home) = (pos2(500.0, 300.0), pos2(524.0, 324.0));
assert_eq!(unpinned(home, vec2(30.0, 40.0), Some(end), size, room), pos2(554.0, 364.0));
assert_eq!(unpinned(home, vec2(-60.0, -40.0), Some(end), size, room), home, "over the end");
assert_eq!(unpinned(home, vec2(-60.0, -40.0), None, size, room), pos2(464.0, 284.0));
assert_eq!(unpinned(home, vec2(900.0, 0.0), Some(end), size, room), pos2(628.0, 324.0), "kept on the canvas");
}
}
+247
View File
@@ -15357,3 +15357,250 @@ fn auto_spell_check_is_a_toggle_of_the_canvas_lines() {
assert_eq!(count(&mut app), 0, "off");
assert!(app.canvas.spelling.lines.is_empty(), "no node is kept");
}
/// #8363: Trim View hides the ruler guides, the guide paths and the grid while it is on, and they
/// are neither snapped to nor picked, as hidden guides are; turned off, they come back as they
/// were. The rulers stay.
#[test]
fn trim_view_hides_the_guides_and_the_grid() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.canvas.worker_started = true; // render on this thread
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
app.session.execute("guide.add", &json!({"vertical": true, "pos": 100})).unwrap();
app.run("shape.rectangle", json!({"x": 150, "y": 100, "width": 100, "height": 100})).unwrap();
app.run("view.guides.make", json!({})).unwrap();
app.run("select.none", json!({})).unwrap();
(app.ui.view.grid, app.ui.view.guides, app.ui.view.rulers) = (true, true, true);
let (red, green) = (Color32::from_rgb(255, 0, 0), Color32::from_rgb(0, 255, 0));
app.session.execute("prefs.set", &json!({"values": {"gridColor": "#ff0000", "guideColor": "#00ff00"}})).unwrap();
let ctx = egui::Context::default();
// → (a gridline, a ruler guide, guide paths in the art, guides snapped to and picked).
let drawn = |app: &mut VectorcraftApp| {
let s = shapes(app, &ctx);
let line = |c: Color32| s.iter().any(|s| matches!(s, Shape::LineSegment { stroke, .. } if stroke.color == c));
let guide_paths = !app.canvas.shown.as_ref().unwrap().1.hide_guides;
(line(red), line(green), guide_paths, app.view_info().guides)
};
assert_eq!(drawn(&mut app), (true, true, true, true), "Trim View off: all of them");
app.run("view.trimView", json!({})).unwrap();
assert_eq!(drawn(&mut app), (false, false, false, false), "Trim View on: none of them");
assert!(app.ui.view.grid && app.ui.view.guides && app.ui.view.rulers, "the choices stay, and so do the rulers");
app.run("view.trimView", json!({})).unwrap();
assert_eq!(drawn(&mut app), (true, true, true, true), "Trim View off: back as they were");
// Hidden before, they stay hidden after.
app.run("view.guides", json!({})).unwrap();
app.run("view.trimView", json!({})).unwrap();
app.run("view.trimView", json!({})).unwrap();
assert_eq!(drawn(&mut app), (true, false, false, false), "guides hidden before Trim View stay hidden");
}
/// #8363: a selected guide path is deselected when Trim View hides it, as Hide Guides does (#3219).
#[test]
fn trim_view_deselects_selected_guide_paths() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap();
app.run("view.guides.make", json!({})).unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
assert_eq!(app.session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(id)]);
app.run("view.trimView", json!({})).unwrap();
assert!(app.session.active().unwrap().selection.objects.is_empty());
}
/// #8363: Trim View hides the guides, so a guide dragged or double-clicked out of a ruler while it
/// is on would be made but never seen. None is: no preview line, no guide, no undo step, the
/// stored Show/Hide Guides choice is left alone, and the status line says why. A drag already
/// going when Trim View turns on ends as a release off the canvas does.
#[test]
fn trim_view_makes_no_guide_from_the_rulers() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
app.ui.view.rulers = true;
app.ui.view.guides = false;
app.ui.view.smart_guides = false;
app.ui.view.snap_to_point = false;
app.ui.view.trim_view = true;
let ctx = egui::Context::default();
frame(&mut app, &ctx, vec![]);
let rect = app.canvas_rect.unwrap();
let from = pos2(rect.center().x, rect.top() - RULER / 2.0);
let at = pos2(rect.center().x, rect.top() + 120.0);
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
let across = |s: &Shape| {
matches!(s, Shape::LineSegment { points, .. }
if (points[0].y - at.y).abs() <= 2.0 && points[0].y == points[1].y && (points[1].x - points[0].x).abs() >= rect.width() - 0.5)
};
let count = |app: &VectorcraftApp| app.session.active().unwrap().doc.ruler_guides().len();
let steps = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len();
let before = steps(&app);
// A drag: nothing previews and nothing is made.
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]);
frame(&mut app, &ctx, vec![button(from, true)]);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
assert!(!shapes(&mut app, &ctx).iter().any(across), "no guide previews");
assert!(!app.session.ruler_guide_dragging());
frame(&mut app, &ctx, vec![button(at, false)]);
assert_eq!(count(&app), 0, "no guide from a drag");
assert!(!app.ui.view.guides, "the stored choice is left alone");
assert_eq!(app.ui.status, crate::menus::TRIM_VIEW_HIDES);
// A double-click: nothing either.
app.ui.status.clear();
let click = |app: &mut VectorcraftApp| {
frame(app, &ctx, vec![egui::Event::PointerMoved(from)]);
frame(app, &ctx, vec![button(from, true)]);
frame(app, &ctx, vec![button(from, false)]);
};
click(&mut app);
click(&mut app);
assert_eq!(count(&app), 0, "no guide from a double-click");
assert!(!app.ui.view.guides);
assert_eq!(app.ui.status, crate::menus::TRIM_VIEW_HIDES);
assert_eq!(steps(&app), before, "no undo step");
// Trim View turned on during a drag: the drag ends without a guide.
app.ui.view.trim_view = false;
let from2 = pos2(rect.center().x + 30.0, rect.top() - RULER / 2.0);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from2)]);
frame(&mut app, &ctx, vec![button(from2, true)]);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
assert!(app.session.ruler_guide_dragging(), "the drag started with Trim View off");
app.ui.view.trim_view = true;
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(pos2(at.x + 5.0, at.y))]);
assert!(!app.session.ruler_guide_dragging(), "ended");
assert!(!shapes(&mut app, &ctx).iter().any(across), "no guide previews");
frame(&mut app, &ctx, vec![button(at, false)]);
assert_eq!(count(&app), 0, "no guide from the drag Trim View interrupted");
assert_eq!(steps(&app), before, "no undo step");
// With Trim View off again, a drag makes a guide as before.
app.ui.view.trim_view = false;
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]);
frame(&mut app, &ctx, vec![button(from, true)]);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
frame(&mut app, &ctx, vec![button(at, false)]);
assert_eq!(count(&app), 1);
assert!(app.ui.view.guides, "the new guide shows");
}
/// #8363: a guide drag Trim View cancelled stays cancelled until the button is released. Trim
/// View turned off again before the release does not start a new guide: the release makes none
/// and adds no undo step. The next drag works as before.
#[test]
fn a_ruler_drag_trim_view_cancelled_stays_cancelled_until_released() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
app.ui.view.rulers = true;
app.ui.view.smart_guides = false;
app.ui.view.snap_to_point = false;
let ctx = egui::Context::default();
frame(&mut app, &ctx, vec![]);
let rect = app.canvas_rect.unwrap();
let from = pos2(rect.center().x, rect.top() - RULER / 2.0);
let at = pos2(rect.center().x, rect.top() + 120.0);
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
let count = |app: &VectorcraftApp| app.session.active().unwrap().doc.ruler_guides().len();
let steps = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len();
let before = steps(&app);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]);
frame(&mut app, &ctx, vec![button(from, true)]);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
assert!(app.session.ruler_guide_dragging());
app.ui.view.trim_view = true;
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(pos2(at.x, at.y + 5.0))]);
assert!(!app.session.ruler_guide_dragging(), "Trim View ends the drag");
app.ui.view.trim_view = false;
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(pos2(at.x, at.y + 10.0))]);
assert!(!app.session.ruler_guide_dragging(), "turned off again, no new guide starts");
frame(&mut app, &ctx, vec![button(pos2(at.x, at.y + 10.0), false)]);
assert_eq!(count(&app), 0, "the release makes no guide");
assert_eq!(steps(&app), before, "no undo step");
// The next drag makes a guide.
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]);
frame(&mut app, &ctx, vec![button(from, true)]);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
frame(&mut app, &ctx, vec![button(at, false)]);
assert_eq!(count(&app), 1);
}
/// #8363: Trim View turned on or off during a drag of the rulers' origin out of their corner
/// cancels it, as hiding the rulers does: the snap targets gathered at its start would hold
/// guides Trim View hides. The origin is left where it was. A drag wholly with Trim View on, or
/// wholly off, sets it.
#[test]
fn trim_view_toggled_during_a_ruler_origin_drag_cancels_it() {
for (start, end, sets) in [(false, true, false), (true, false, false), (true, true, true), (false, false, true)] {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
app.session.execute("guide.add", &json!({"vertical": true, "pos": 150})).unwrap();
app.ui.view.rulers = true;
app.ui.view.trim_view = start;
let ctx = egui::Context::default();
frame(&mut app, &ctx, vec![]);
let rect = app.canvas_rect.unwrap();
let xf = Xf::new(rect, app.view().unwrap());
let origin = |app: &VectorcraftApp| {
let d = &app.session.active().unwrap().doc;
format!("{:?} {:?}", d.ruler_origin, d.artboard_ruler_origins)
};
let was = origin(&app);
let from = pos2(rect.left() - RULER / 2.0, rect.top() - RULER / 2.0);
let at = xf.to_screen(Point::new(151.0, 100.0));
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]);
frame(&mut app, &ctx, vec![button(from, true)]);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
assert!(crate::canvas::ruler_origin_dragging(&ctx), "{start} {end}: dragging");
app.ui.view.trim_view = end;
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at + vec2(1.0, 0.0))]);
frame(&mut app, &ctx, vec![button(at + vec2(1.0, 0.0), false)]);
assert_eq!(origin(&app) != was, sets, "Trim View {start} then {end}: origin set {sets}");
}
}
/// #8363: a Selection move begun with the guides shown gathers the ruler guides to snap to. When
/// they stop showing during the move (Trim View or Hide Guides turned on), it no longer snaps to
/// them; with them shown throughout, it does.
#[test]
fn a_move_stops_snapping_to_guides_hidden_during_it() {
// What hides the guides mid-move (none: they stay shown), and whether the move then snaps.
for (hide, snaps) in [(None, true), (Some("trim"), false), (Some("guides"), false)] {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 50, "height": 50})).unwrap();
app.session.execute("guide.add", &json!({"vertical": true, "pos": 200})).unwrap();
app.select_tool("selection");
app.ui.view.smart_guides = false;
app.ui.view.snap_to_point = true;
app.ui.view.guides = true;
let ctx = egui::Context::default();
frame(&mut app, &ctx, vec![]);
let rect = app.canvas_rect.unwrap();
let xf = Xf::new(rect, app.view().unwrap());
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
// Grabbed at its centre, moved first well away from the guide, then 1.5 px short of it.
let grab = xf.to_screen(Point::new(75.0, 75.0));
let away = xf.to_screen(Point::new(120.0, 75.0));
let near = xf.to_screen(Point::new(200.0, 75.0)) - vec2(1.5, 0.0);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(grab)]);
frame(&mut app, &ctx, vec![button(grab, true)]);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(away)]);
match hide {
Some("trim") => app.ui.view.trim_view = true,
Some(_) => app.ui.view.guides = false,
None => {}
}
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(near)]);
frame(&mut app, &ctx, vec![button(near, false)]);
let b = app.session.active().unwrap().doc.art_bounds().unwrap();
let centre = (b.x0 + b.x1) / 2.0;
assert_eq!((centre - 200.0).abs() < 1e-6, snaps, "{hide:?}: the grabbed centre at {centre}");
assert!((centre - xf.to_doc(near).x).abs() < 1e-6 || snaps, "{hide:?}: unsnapped, it follows the pointer: {centre}");
}
}
+2 -1
View File
@@ -209,7 +209,8 @@ pub(super) fn info_text(app: &VectorcraftApp) -> (String, Option<u64>) {
(text, Some(next))
}
StatusBarShow::Undos => {
let text = st.map(|d| format!("{}: {} {}: {}", tl!("Undos"), d.history.undo.len(), tl!("Redos"), d.history.redo.len()));
let (undos, redos) = (crate::i18n::colon(tl!("Undos")), crate::i18n::colon(tl!("Redos")));
let text = st.map(|d| format!("{undos} {} {redos} {}", d.history.undo.len(), d.history.redo.len()));
(text.unwrap_or_default(), None)
}
StatusBarShow::ColorProfile => (st.map(|d| color_profile_name(&d.doc)).unwrap_or_default(), None),
+6
View File
@@ -1127,6 +1127,12 @@ fn the_status_bar_info_field_shows_the_chosen_readout() {
app.run("edit.undo", json!({})).unwrap();
assert_eq!(counts(&app), format!("Undos: {before} Redos: 1"));
assert!(status_after(&mut app, &ctx, 0.1, vec![]).iter().any(|t| t.text == counts(&app)), "the redo step counts");
// The labels take the UI language's colon (#7991).
let fr = crate::i18n::Lang::from_code("fr").unwrap();
crate::i18n::set_current(fr);
let (french, _) = super::status_bar::info_text(&app);
crate::i18n::set_current(crate::i18n::Lang::EN);
assert_eq!(french, format!("{}\u{a0}: {before} {}\u{a0}: 1", crate::i18n::tr(fr, "Undos"), crate::i18n::tr(fr, "Redos")));
app.run("view.statusBarShow", json!({"show": "colorProfile"})).unwrap();
let working = vectorcraft_color::cms::working_settings();
+5
View File
@@ -268,6 +268,11 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value {
"pinned": app.ui.task_bar_place.pinned,
"rect": crate::canvas::task_bar_rect(ctx).map(|r| json!([r.left(), r.top(), r.width(), r.height()])),
},
// The Quick Pen toolbar: pinned (not saved either) and where it shows.
"quickPenToolbar": {
"pinned": app.ui.quick_pen_bar_place.pinned,
"rect": crate::canvas::quick_pen_bar_rect(ctx).map(|r| json!([r.left(), r.top(), r.width(), r.height()])),
},
// The Free Transform tool's widget, where it shows.
"freeTransformWidget": crate::free_transform::rect(ctx).map(|r| json!([r.left(), r.top(), r.width(), r.height()])),
"view": app.view().map(|v| serde_json::to_value(v).unwrap_or_default()),
+6
View File
@@ -25,6 +25,7 @@ pub mod brush_replace_art;
pub mod bullets_numbering;
pub mod char_style_options;
pub mod check_spelling;
pub mod circle_options;
pub mod color_balance;
pub mod color_group_options;
pub mod color_guide_options;
@@ -155,6 +156,7 @@ mod tiff_bmp_tga;
pub mod tile_edge_color;
mod tools;
pub mod trace_presets;
pub mod tracing_presets;
pub(crate) mod transform;
pub mod transform_each;
pub mod variables;
@@ -381,6 +383,9 @@ registry! {
FlattenTransparency: [flatten::KIND] => flatten::SPEC,
FlattenerPresets: [flattener_presets::KIND] => flattener_presets::SPEC,
ImageTracePreset: [trace_presets::KIND] => trace_presets::SPEC,
TracingPresets: [tracing_presets::KIND] => tracing_presets::SPEC,
TracingPreset: [tracing_presets::PRESET_KIND] => tracing_presets::PRESET_SPEC,
TracingPresetsReplace: [tracing_presets::REPLACE_KIND] => tracing_presets::REPLACE_SPEC,
SaveStyleLibrary: [save_style_library::KIND] => save_style_library::SPEC,
SaveSymbolLibrary: [save_symbol_library::KIND] => save_symbol_library::SPEC,
SaveBrushLibrary: [save_brush_library::KIND] => save_brush_library::SPEC,
@@ -472,6 +477,7 @@ registry! {
FreehandOptions: [freehand::KIND] => freehand::SPEC,
ShapeBuilderOptions: [shape_builder_options::KIND] => shape_builder_options::SPEC,
ObjectsOnPathOptions: [objects_on_path_options::KIND] => objects_on_path_options::SPEC,
CircleOptions: [circle_options::KIND] => circle_options::SPEC,
ThreePointArcOptions: [three_point_arc_options::KIND] => three_point_arc_options::SPEC,
FlareOptions: [flare_options::KIND] => flare_options::SPEC,
SymbolOptions: [symbol_options::KIND] => symbol_options::SPEC,
@@ -0,0 +1,169 @@
//! Circle Tool Options (double-click the Circle tool, or `tool.options`): Show Center, Show Radii
//! and Show Diameter switch the center cross, the radius lines and the diameter label the tool
//! shows while a circle is drawn; Color is the color of the cross and the lines; Anchors at
//! Standard Positions off puts the circle's anchors at the points it was drawn through; Third
//! Point by Dragging off places the second point with a click and the third with another. OK sets
//! them with `tool.setOption {tool: "circle", values}`; they last across tool switches and are
//! saved with the preferences.
use serde_json::{Map, Value, json};
use vectorcraft_tools::circle::{COLORS, ID as TOOL};
use super::{DialogSpec, run_and_close};
use crate::state::Dialog;
use crate::{VectorcraftApp, widgets};
/// The dialog kind of Circle Tool Options.
pub const KIND: &str = "circleOptions";
pub(super) const SPEC: DialogSpec = DialogSpec { heading, body, confirm, min_width: 300.0, ..DialogSpec::FORM };
/// The options the dialog edits, in the order it shows its check boxes, with their labels.
const SWITCHES: [(&str, &str); 5] = [
("center", "Show Center"),
("radii", "Show Radii"),
("diameter", "Show Diameter"),
("standardAnchors", "Anchors at Standard Positions"),
("dragThird", "Third Point by Dragging"),
];
/// The labels of [`COLORS`], in its order.
const COLOR_LABELS: [&str; 6] = ["Red", "Blue", "Magenta", "Green", "Black", "Gray"];
/// Width of the label column.
const LABEL_W: f32 = 60.0;
fn heading(_: &Dialog) -> String {
let label = vectorcraft_tools::tool_info(TOOL).map_or("", |t| t.label);
crate::i18n::fmt(tl!("{tool} Options"), &[("tool", tl!(label))])
}
/// Open the tool's options with their current values.
pub fn open(app: &mut VectorcraftApp) -> Value {
let o = app.session.tool_options_of(TOOL);
let keys = SWITCHES.iter().map(|(key, _)| *key).chain(["color"]);
let fields: Map<String, Value> = keys.filter_map(|key| Some((key.to_string(), o.get(key)?.clone()))).collect();
app.ui.dialog = Some(Dialog { kind: KIND.into(), fields });
json!({ "dialog": KIND })
}
fn check(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str) {
let on = d.bool(key);
if widgets::check(ui, tl!(label), on, true) {
d.fields.insert(key.into(), json!(!on));
}
}
fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
for (key, label) in &SWITCHES[..3] {
check(ui, d, key, label);
}
let color = d.str("color");
let at = COLORS.iter().position(|(name, _)| *name == color).unwrap_or(1);
widgets::label_row(ui, tl!("Color:"), LABEL_W, |ui| {
let shown = COLOR_LABELS.get(at).copied().unwrap_or("Blue");
if let Some((name, _)) =
widgets::dropdown_named(ui, "circle-options-color", Some(tl!("Color:")), shown, &COLOR_LABELS, 110.0).and_then(|i| COLORS.get(i))
{
d.fields.insert("color".into(), json!(name));
}
});
ui.add_space(8.0);
for (key, label) in &SWITCHES[3..] {
check(ui, d, key, label);
}
false
}
/// OK: set the tool's options.
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
let keys = SWITCHES.iter().map(|(key, _)| *key).chain(["color"]);
let values: Map<String, Value> = keys.filter_map(|key| Some((key.to_string(), d.fields.get(key)?.clone()))).collect();
run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values }))
}
#[cfg(test)]
mod tests {
use super::*;
use vectorcraft_engine::Session;
fn app() -> VectorcraftApp {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
app
}
/// The labels the open dialog paints.
fn painted(app: &mut VectorcraftApp) -> String {
crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx()))
}
/// Every label the dialog shows has a row for each of [`COLORS`].
#[test]
fn every_color_has_a_label() {
assert_eq!(COLOR_LABELS.len(), COLORS.len());
for (label, (name, _)) in COLOR_LABELS.iter().zip(COLORS) {
assert_eq!(label.to_lowercase(), *name);
}
}
#[test]
fn double_clicking_the_tool_opens_its_options_and_ok_sets_them() {
let mut app = app();
let o = app.session.tool_options_of(TOOL);
for key in ["center", "radii", "diameter", "standardAnchors", "dragThird"] {
assert_eq!(o[key], json!(true), "{key}");
}
assert_eq!(o["color"], json!("blue"));
let r = app.run("tool.options", json!({"tool": TOOL})).unwrap();
assert_eq!(r["dialog"], json!(KIND));
let text = painted(&mut app);
for label in [
"Circle Tool Options",
"Show Center",
"Show Radii",
"Show Diameter",
"Color:",
"Blue",
"Anchors at Standard Positions",
"Third Point by Dragging",
"OK",
"Cancel",
] {
assert!(text.contains(label), "{label} in {text}");
}
let d = app.ui.dialog.as_mut().unwrap();
for key in ["radii", "standardAnchors", "dragThird"] {
assert!(d.bool(key), "{key}");
d.fields.insert(key.into(), json!(false));
}
d.fields.insert("color".into(), json!("magenta"));
super::super::confirm(&mut app).unwrap();
assert!(app.ui.dialog.is_none());
let o = app.session.tool_options_of(TOOL);
let got: Vec<&Value> = ["center", "radii", "diameter", "standardAnchors", "dragThird", "color"].iter().map(|k| &o[*k]).collect();
assert_eq!(got, [&json!(true), &json!(false), &json!(true), &json!(false), &json!(false), &json!("magenta")]);
// They last while another tool is chosen, and the dialog opens on them again.
app.select_tool(TOOL);
app.select_tool("selection");
app.run("tool.options", json!({"tool": TOOL})).unwrap();
let d = app.ui.dialog.as_ref().unwrap();
assert!(!d.bool("standardAnchors") && d.bool("center"));
assert_eq!(d.str("color"), "magenta");
}
/// `tool.setOption` takes only the values the options take, and an invalid one changes none.
#[test]
fn invalid_values_are_errors_and_change_nothing() {
let mut app = app();
for (values, error) in [
(json!({"center": false, "radii": "no"}), "`radii` must be true or false"),
(json!({"center": false, "color": "orange"}), "`color` must be one of red, blue, magenta, green, black, gray"),
(json!({"center": false, "size": 3}), "unknown Circle tool option `size`"),
] {
let e = app.run("tool.setOption", json!({"tool": TOOL, "values": values})).unwrap_err();
assert!(e.contains(error), "{e}");
assert_eq!(app.session.tool_options_of(TOOL)["center"], json!(true));
}
}
}
+107 -15
View File
@@ -9,8 +9,12 @@
//! For Fractions; OK runs `graph.column`.
//! Marker: the design the selected graph series draw their data points with, or None (the default
//! square marker); OK runs `graph.marker`.
//! Column and Marker also list, under each library's name, the graph designs of the documents
//! Window › Swatch Libraries › Other Library… loaded that the document lacks; OK on one copies it
//! into the document with the resources its art uses.
//!
//! Fields: `selected` (the selected designs' names; Column and Marker: one name, null for None),
//! in Column and Marker `library` (the library of the selected design, null for the document's),
//! in Graph Design `name` (the name Rename gives), and in Column `columnType`, `each` and
//! `fractions`.
@@ -46,6 +50,7 @@ pub(super) const COLUMN_SPEC: DialogSpec = DialogSpec {
confirm: |app, d| {
let p = json!({
"design": d.fields.get("selected").and_then(Value::as_str),
"library": library_of(d),
"columnType": d.str("columnType"),
"each": d.f64("each", vectorcraft_doc::ColumnDesign::EACH),
"fractions": d.str("fractions"),
@@ -59,7 +64,9 @@ pub(super) const COLUMN_SPEC: DialogSpec = DialogSpec {
pub(super) const MARKER_SPEC: DialogSpec = DialogSpec {
heading: |_| tl!("Graph Marker").into(),
body: marker_body,
confirm: |app, d| run_and_close(app, "graph.marker", json!({ "design": d.fields.get("selected").and_then(Value::as_str) })),
confirm: |app, d| {
run_and_close(app, "graph.marker", json!({ "design": d.fields.get("selected").and_then(Value::as_str), "library": library_of(d) }))
},
min_width: 300.0,
..DialogSpec::FORM
};
@@ -95,6 +102,24 @@ fn names(app: &VectorcraftApp) -> Result<Vec<String>, String> {
Ok(st.doc.graph_designs.iter().map(|d| d.name.clone()).collect())
}
/// The designs of the loaded libraries that the document lacks (the document's own design of a name
/// is the one used), by library: its id, its name and the design names, libraries with none left
/// out.
fn library_designs(app: &VectorcraftApp) -> Vec<(String, String, Vec<String>)> {
let own = names(app).unwrap_or_default();
app.session
.graph_design_libraries
.iter()
.map(|l| (l.id.clone(), l.name.clone(), l.doc.graph_designs.iter().map(|g| g.name.clone()).filter(|n| !own.contains(n)).collect::<Vec<_>>()))
.filter(|(.., names)| !names.is_empty())
.collect()
}
/// Column and Marker's `library`: the library of the selected design, `None` for the document's.
fn library_of(d: &Dialog) -> Option<&str> {
d.fields.get("library").and_then(Value::as_str)
}
/// Graph Design's selected designs.
fn selected(d: &Dialog) -> Vec<String> {
d.fields.get("selected").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default()
@@ -105,8 +130,9 @@ fn select(d: &mut Dialog, names: Vec<String>) {
d.fields.insert("selected".into(), json!(names));
}
/// A design's art drawn in `r` (cached by the art's identity).
fn preview(ui: &egui::Ui, app: &VectorcraftApp, name: &str, r: egui::Rect) {
/// A design's art drawn in `r` (cached by the art's identity): the document's design `name`, or
/// with `library` that loaded library's.
fn preview(ui: &egui::Ui, app: &VectorcraftApp, library: Option<&str>, name: &str, r: egui::Rect) {
use std::cell::RefCell;
use std::collections::HashMap;
thread_local! {
@@ -114,11 +140,18 @@ fn preview(ui: &egui::Ui, app: &VectorcraftApp, name: &str, r: egui::Rect) {
static CACHE: crate::graphics::TexCache<HashMap<usize, egui::TextureHandle>> = crate::graphics::TexCache::default();
}
let Some(st) = app.session.active() else { return };
let Some(art) = st.doc.graph_designs.iter().find(|x| x.name == name).map(|x| x.art.clone()) else { return };
let doc = match library {
Some(id) => match app.session.graph_design_libraries.get(id) {
Some(l) => &l.doc,
None => return,
},
None => &st.doc,
};
let Some(art) = doc.graph_designs.iter().find(|x| x.name == name).map(|x| x.art.clone()) else { return };
let key = std::sync::Arc::as_ptr(&art) as usize;
let px = (r.width() * ui.ctx().pixels_per_point()).round() as u32;
let tex = CACHE.with(|c| c.borrow().get(&key).cloned()).or_else(|| {
let img = RENDERER.with(|rr| rr.borrow_mut().render_node_thumbnail(&st.doc, &art, px.max(16), Some([255, 255, 255, 255])))?;
let img = RENDERER.with(|rr| rr.borrow_mut().render_node_thumbnail(doc, &art, px.max(16), Some([255, 255, 255, 255])))?;
let color = crate::canvas::color_image(&img);
let tex = ui.ctx().load_texture(format!("graph-design-{key}"), color, egui::TextureOptions::LINEAR);
CACHE.with(|c| {
@@ -177,7 +210,7 @@ fn design_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> b
let (r, _) = ui.allocate_exact_size(egui::vec2(PREVIEW, PREVIEW), egui::Sense::hover());
ui.painter().rect_stroke(r, 0.0, egui::Stroke::new(1.0, egui::Color32::from_gray(160)), egui::StrokeKind::Inside);
if let Some(n) = &one {
preview(ui, app, n, r.shrink(4.0));
preview(ui, app, None, n, r.shrink(4.0));
}
ui.add_space(6.0);
let button =
@@ -220,37 +253,66 @@ fn design_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> b
false
}
/// The list of Column and Marker: None, then the designs `names`; a click picks one into `selected` (null for None).
fn one_design_list(ui: &mut egui::Ui, d: &mut Dialog, names: &[String], salt: &str) {
/// The list of Column and Marker: None, the document's designs `names`, then each loaded library's
/// name and the designs of it in `libraries` ([`library_designs`]); a click picks one into
/// `selected` (null for None) and its library into `library` (null for the document's).
fn one_design_list(ui: &mut egui::Ui, d: &mut Dialog, names: &[String], libraries: &[(String, String, Vec<String>)], salt: &str) {
widgets::list_box(ui, |ui| {
egui::ScrollArea::vertical().id_salt(salt).min_scrolled_height(160.0).max_height(160.0).show(ui, |ui| {
ui.set_width(ui.available_width());
ui.set_min_height(160.0);
let current = d.fields.get("selected").and_then(Value::as_str).map(str::to_string);
let from = library_of(d).map(str::to_string);
let pick = |d: &mut Dialog, name: Option<&str>, library: Option<&str>| {
d.fields.insert("selected".into(), json!(name));
d.fields.insert("library".into(), json!(library));
};
if ui.selectable_label(current.is_none(), tl!("None")).clicked() {
d.fields.insert("selected".into(), Value::Null);
pick(d, None, None);
}
for n in names {
if ui.selectable_label(current.as_deref() == Some(n.as_str()), n.as_str()).clicked() {
d.fields.insert("selected".into(), json!(n));
if ui.selectable_label(from.is_none() && current.as_deref() == Some(n.as_str()), n.as_str()).clicked() {
pick(d, Some(n), None);
}
}
for (id, library, designs) in libraries {
ui.add_space(4.0);
// The library's own name, not interface text.
widgets::dim_name(ui, library);
for n in designs {
let on = from.as_deref() == Some(id.as_str()) && current.as_deref() == Some(n.as_str());
if ui.selectable_label(on, n.as_str()).clicked() {
pick(d, Some(n), Some(id));
}
}
}
});
});
}
/// The design Column or Marker has selected, with its library (`None`: the document's), when the
/// document or that library still has it.
fn shown_design(d: &Dialog, names: &[String], libraries: &[(String, String, Vec<String>)]) -> Option<(Option<String>, String)> {
let n = d.fields.get("selected").and_then(Value::as_str)?;
match library_of(d) {
None => names.iter().any(|x| x == n).then(|| (None, n.to_string())),
Some(id) => libraries.iter().any(|(l, _, designs)| l == id && designs.iter().any(|x| x == n)).then(|| (Some(id.to_string()), n.to_string())),
}
}
fn column_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
let names = names(app).unwrap_or_default();
let libraries = library_designs(app);
ui.horizontal_top(|ui| {
ui.vertical(|ui| {
ui.set_width(220.0);
one_design_list(ui, d, &names, "graph-columns");
one_design_list(ui, d, &names, &libraries, "graph-columns");
});
ui.add_space(10.0);
let (r, _) = ui.allocate_exact_size(egui::vec2(PREVIEW, PREVIEW), egui::Sense::hover());
ui.painter().rect_stroke(r, 0.0, egui::Stroke::new(1.0, egui::Color32::from_gray(160)), egui::StrokeKind::Inside);
if let Some(n) = d.fields.get("selected").and_then(Value::as_str).filter(|n| names.iter().any(|x| x == n)) {
preview(ui, app, n, r.shrink(4.0));
if let Some((library, n)) = shown_design(d, &names, &libraries) {
preview(ui, app, library.as_deref(), &n, r.shrink(4.0));
}
});
ui.add_space(8.0);
@@ -277,9 +339,10 @@ const EACH_RANGE: std::ops::RangeInclusive<f64> = 0.0001..=1_000_000_000.0;
fn marker_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
let names = names(app).unwrap_or_default();
let libraries = library_designs(app);
// A list as wide as Graph Design's, not the whole window.
ui.set_width(220.0);
one_design_list(ui, d, &names, "graph-markers");
one_design_list(ui, d, &names, &libraries, "graph-markers");
false
}
@@ -377,4 +440,33 @@ mod tests {
(super::COLUMN_SPEC.confirm)(&mut app, &d).unwrap();
assert_eq!(app.session.execute("graph.column", &json!({})).unwrap()["design"], json!(null));
}
#[test]
fn marker_lists_a_loaded_documents_designs_and_ok_copies_the_one_picked_in() {
// A document with design "New Design", loaded as a swatch library (Other Library…).
let src = app_with_design();
let bytes = vectorcraft_format::save_file(&src.session.active().unwrap().doc);
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Dots.vectorcraft"});
app.run("swatch.library.load", p).unwrap();
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let g = app.run("graph.create", json!({"type": "line", "x": 100, "y": 100, "width": 200, "height": 100})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [g]})).unwrap();
let libraries = super::library_designs(&app);
assert_eq!(libraries.len(), 1);
let (id, _, designs) = &libraries[0];
assert_eq!(designs, &["New Design".to_string()]);
crate::menus::invoke(&mut app, "graph.marker", json!({}));
frame(&mut app);
let mut d: Dialog = app.ui.dialog.take().unwrap();
d.fields.insert("selected".into(), json!("New Design"));
d.fields.insert("library".into(), json!(id));
app.ui.dialog = Some(d.clone());
frame(&mut app);
(super::MARKER_SPEC.confirm)(&mut app, &d).unwrap();
assert_eq!(app.session.execute("graph.marker", &json!({})).unwrap()["design"], "New Design");
assert_eq!(super::names(&app).unwrap(), ["New Design"]);
// The document has it now, so the library lists it no more.
assert!(super::library_designs(&app).is_empty());
}
}
+12 -2
View File
@@ -8,7 +8,8 @@
//! an option or artboard choice the export refuses, or a save panel shown in line that is canceled,
//! keeps the dialog open. A canceled save panel keeps the options remembered before. Opened by Export
//! Selection, it checks and writes the selection alone. A typed Curve Tolerance is kept within 0.01
//! to 10 points.
//! to 10 points. OK after another document has become the active one closes the dialog and writes
//! nothing.
use serde_json::{Map, Value, json};
use vectorcraft_cad::hpgl::write::{DEFAULT_TOLERANCE, MAX_PENS, TOLERANCE_RANGE};
@@ -42,6 +43,9 @@ const SET_ASIDE: &str = "__pens";
/// Why Pen Table could not start from the art's pens, shown under the Pens row.
const PEN_ERROR: &str = "__penError";
/// The field that holds the uid of the document the dialog was opened for.
const DOC: &str = "__doc";
/// The Origin menu's names, in [`Origin::ALL`] order.
pub(crate) const ORIGIN_NAMES: [&str; 2] = ["Bottom Left", "Center"];
@@ -71,6 +75,7 @@ pub fn open(app: &mut VectorcraftApp, params: &Value) {
}
}
fields.insert("format".into(), json!("hpgl"));
fields.insert(DOC.into(), json!(app.session.active().map(|st| st.uid)));
app.ui.dialog = Some(Dialog::new(KIND, Value::Object(fields)));
}
@@ -236,8 +241,13 @@ fn rgb(hex: &str) -> Option<[u8; 3]> {
Some([byte(0)?, byte(2)?, byte(4)?])
}
/// Check the options, remember them, and write the file(s).
/// Check the options, remember them, and write the file(s). When another document has become the
/// active one since the dialog opened, it closes as Cancel does and writes nothing.
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
if d.fields.get(DOC).and_then(Value::as_u64) != app.session.active().map(|st| st.uid) {
app.ui.dialog = None;
return Ok(json!({}));
}
let params = super::form::params(d);
let st = app.session.active().ok_or("no document")?;
// A bad option or artboard choice, nothing selected, or no art to export keeps the dialog open.
+18
View File
@@ -258,6 +258,24 @@ fn pen_table_starts_from_the_pens_of_what_the_export_plots() {
assert_eq!(seed(&app), on_board);
}
/// OK after another document has become the active one closes HP-GL Options and writes nothing, so
/// the other document is not written to the path chosen for the first.
#[test]
fn hpgl_options_write_nothing_after_another_document_became_active() {
let (mut app, written) = app(1);
app.run("ui.hpglOptionsDialog", json!({"path": "/out/first.plt"})).unwrap();
app.run("file.new", json!({"width": 60, "height": 40})).unwrap();
assert_eq!(kind(&app), Some("hpglOptions"));
assert_eq!(confirm(&mut app).unwrap(), json!({}));
assert!(app.ui.dialog.is_none());
assert!(written.borrow().is_empty(), "nothing is written over the first document's path");
// Opened for the document that is active, OK writes it.
app.run("window.nextDocument", json!({})).unwrap();
app.run("ui.hpglOptionsDialog", json!({"path": "/out/first.plt"})).unwrap();
confirm(&mut app).unwrap();
assert_eq!(names(&written), ["/out/first.plt"]);
}
#[test]
fn the_hpgl_options_dialog_needs_a_document() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
@@ -1,13 +1,14 @@
//! The 3D and Materials panel's Materials tab: the document's Graphics (its symbols) as thumbnails,
//! Add as Single Graphic, and the graphics mapped onto the selected 3D object (its planar faces,
//! Extrude & Bevel's side, or Revolve's side) with their face, position, size and turn. Picking a thumbnail maps that graphic
//! Extrude & Bevel's side, Revolve's side, or Inflate's puffed faces) with their face, position, size and turn. Picking a
//! thumbnail maps that graphic
//! onto the selected objects (`threeD.mapGraphic`); art dropped on the thumbnails becomes a graphic
//! (`threeD.addGraphic`). Editing a mapped graphic changes the effect's `graphics` parameter, which
//! the panel sends as it sends every other setting.
use egui::{Sense, Stroke, StrokeKind, vec2};
use serde_json::{Value, json};
use vectorcraft_effects::{GRAPHICS, MappedGraphic, PlanarFace, REVOLVE, ROTATE};
use vectorcraft_effects::{GRAPHICS, INFLATE, MappedGraphic, PlanarFace, REVOLVE, ROTATE};
use super::revolve::{heading, label, number};
use crate::VectorcraftApp;
@@ -105,7 +106,7 @@ pub(crate) fn controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog)
}
ui.add_space(10.0);
if !takes {
dim_label(ui, tl!("Graphics map onto the Plane, Extrude and Revolve object types."));
dim_label(ui, tl!("Graphics map onto the Plane, Extrude, Revolve and Inflate object types."));
return;
}
let raw = d.fields.get(GRAPHICS).cloned().unwrap_or(Value::Null);
@@ -131,15 +132,18 @@ pub(crate) fn controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog)
let Some(g) = list.get(index).cloned() else { return };
let mut edited = g.clone();
// A plane has one face, and Revolve's graphics go on its side. Extrude & Bevel's graphics go on
// its front or back cap, or on its side (its walls and bevels).
// its front or back cap, or on its side (its walls and bevels). Inflate's go on its puffed front
// or back.
if effect != ROTATE && effect != REVOLVE {
let faces: &[PlanarFace] = if effect == INFLATE { &[PlanarFace::Front, PlanarFace::Back] } else { &PlanarFace::ALL };
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 6.0;
label(ui, tl!("Face"));
let labels = PlanarFace::ALL.map(face_label);
let at = PlanarFace::ALL.iter().position(|f| *f == g.face).unwrap_or(0);
if let Some(k) = widgets::dropdown(ui, "three-d-graphic-face", labels[at], &labels, 120.0)
&& let Some(face) = PlanarFace::ALL.get(k)
let labels: Vec<&str> = faces.iter().map(|f| face_label(*f)).collect();
let at = faces.iter().position(|f| *f == g.face).unwrap_or(0);
let current = labels.get(at).copied().unwrap_or_default();
if let Some(k) = widgets::dropdown(ui, "three-d-graphic-face", current, &labels, 120.0)
&& let Some(face) = faces.get(k)
{
edited.face = *face;
}
@@ -0,0 +1,519 @@
//! Edit → Tracing Presets: every tracing preset in a list (built-in ones in brackets, protected,
//! then the saved ones) with the selected one's settings beside it; New… (a preset starting from
//! the selected one), Edit… and Delete (saved presets), Import… and Export… (every saved preset)
//! under the list. New… and Edit… open the preset editor (kind `tracingPreset`): its OK saves the
//! preset with `imageTrace.presets.save` and comes back here on it, and its Cancel comes back with
//! nothing saved. An import whose file holds presets with the names of saved ones asks whether to
//! replace them (kind `tracingPresetsReplace`); Cancel keeps the saved ones. The saved presets are
//! the ones the Image Trace panel, the Control bar and Properties list.
//!
//! Fields: `selected` (a preset's name). The editor's: `name`, `params` (the tracing settings, as
//! `imageTrace.presets.save` takes them) and `editing` (the saved preset it edits; empty for a new
//! one). The question's: `names` (the presets the import skipped) and `file` (the file, as
//! `imageTrace.presets.import` takes it: `{path}` or `{dataBase64}`). Opening a `.vctracepresets`
//! file (File › Open, a drop, the web's Import… pick) imports it the same way.
use serde_json::{Value, json};
use vectorcraft_engine::cmd::swatchlib::DOCUMENT_SWATCHES;
use vectorcraft_engine::cmd::{TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES};
use super::{DialogSpec, form};
use crate::panels::image_trace::{self, MODES, PALETTES, Preset};
use crate::panels::swatches;
use crate::state::Dialog;
use crate::theme::Tokens;
use crate::{VectorcraftApp, widgets};
/// The dialog kind of Tracing Presets.
pub const KIND: &str = "tracingPresets";
/// The dialog kind of the tracing preset editor.
pub const PRESET_KIND: &str = "tracingPreset";
/// The dialog kind of the question whether an import replaces saved presets of the same names.
pub const REPLACE_KIND: &str = "tracingPresetsReplace";
/// The editor's field naming the saved preset it edits.
const EDITING: &str = "editing";
/// The tallest the tracing settings draw, in the manager and the editor, before they scroll (the
/// height of the manager's preset list), so the dialog's buttons stay on short screens.
const SETTINGS_HEIGHT: f32 = 300.0;
pub(super) const SPEC: DialogSpec = DialogSpec {
heading: |_| tl!("Tracing Presets").into(),
body,
confirm: |app, _| {
app.ui.dialog = None;
Ok(Value::Null)
},
ok: None,
min_width: 620.0,
..DialogSpec::FORM
};
pub(super) const PRESET_SPEC: DialogSpec = DialogSpec {
heading: |_| tl!("Save Preset").into(),
body: preset_body,
confirm: confirm_preset,
ok_enabled: Some(|_, d| !d.str("name").trim().is_empty()),
min_width: 380.0,
..DialogSpec::FORM
};
pub(super) const REPLACE_SPEC: DialogSpec = DialogSpec {
heading: |_| tl!("Replace the saved presets that have these names?").into(),
body: |_, ui, d| {
let names: Vec<&str> = d.fields.get("names").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect();
// A long list scrolls, so Replace and Cancel stay on screen.
super::modal::scrolled_rows(ui, "tracing-replace-names", |ui| {
ui.label(egui::RichText::new(names.join("\n")).color(Tokens::get(ui.ctx()).text_dim));
});
false
},
confirm: confirm_replace,
ok: Some("Replace"),
max_width: Some(420.0),
..DialogSpec::FORM
};
/// Open the presets manager on `selected` (default: the first preset, Default).
pub fn open(app: &mut VectorcraftApp, selected: Option<&str>) {
app.ui.dialog = Some(Dialog::new(KIND, json!({ "selected": selected.unwrap_or("Default") })));
}
/// The index in `all` of the preset `selected` names, found as the engine finds presets (the first
/// when none).
fn shown(all: &[Preset], selected: &str) -> usize {
image_trace::find_preset(all, selected).and_then(|p| all.iter().position(|q| std::ptr::eq(p, q))).unwrap_or(0)
}
/// A preset's name as the list shows it: a built-in one translated and in brackets, a saved one as
/// the user named it.
fn list_label(p: &Preset) -> String {
if p.3 { format!("[{}]", image_trace::preset_label(&p.0)) } else { p.0.clone() }
}
/// What a button asked for, done once the list and the settings are drawn.
enum Action {
Select(String),
New,
Edit,
Delete,
Import,
Export,
}
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
let t = Tokens::get(ui.ctx());
let all = image_trace::presets(app, ui.ctx());
let i = shown(&all, &d.str("selected"));
let Some(preset) = all.get(i).cloned() else { return false };
let builtin = preset.3;
let any_saved = all.iter().any(|p| !p.3);
let mut act = None;
ui.horizontal_top(|ui| {
ui.vertical(|ui| {
ui.set_width(260.0);
widgets::dim_label(ui, tl!("Presets:"));
widgets::list_box(ui, |ui| {
egui::ScrollArea::vertical().id_salt("tracing-presets").min_scrolled_height(300.0).max_height(300.0).show(ui, |ui| {
ui.set_width(ui.available_width());
ui.set_min_height(300.0);
for (k, p) in all.iter().enumerate() {
if ui.selectable_label(k == i, list_label(p)).clicked() {
act = Some(Action::Select(p.0.clone()));
}
}
});
});
ui.add_space(6.0);
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 4.0;
if widgets::flat_button(ui, tl!("New…"), 48.0).on_hover_text(tl!("A new preset starting from the selected one")).clicked() {
act = Some(Action::New);
}
if ui.add_enabled_ui(!builtin, |ui| widgets::flat_button(ui, tl!("Edit…"), 48.0)).inner.clicked() {
act = Some(Action::Edit);
}
if ui.add_enabled_ui(!builtin, |ui| widgets::flat_button(ui, tl!("Delete"), 52.0)).inner.clicked() {
act = Some(Action::Delete);
}
if widgets::flat_button(ui, tl!("Import…"), 60.0).clicked() {
act = Some(Action::Import);
}
if ui.add_enabled_ui(any_saved, |ui| widgets::flat_button(ui, tl!("Export…"), 60.0)).inner.clicked() {
act = Some(Action::Export);
}
});
});
ui.add_space(18.0);
ui.vertical(|ui| {
ui.set_width(320.0);
ui.label(egui::RichText::new(list_label(&preset)).color(t.text_strong).strong());
ui.add_space(8.0);
// The selected preset's settings, as the editor shows them, to read only. They scroll
// past the height of the preset list.
let mut params = preset.1.clone();
egui::ScrollArea::vertical().id_salt("tracing-preset-details").max_height(SETTINGS_HEIGHT).show(ui, |ui| {
ui.add_enabled_ui(false, |ui| settings_editor(app, ui, "tracing-presets", &mut params));
});
if builtin {
ui.add_space(6.0);
ui.label(egui::RichText::new(tl!("Built-in presets don't change: New makes a copy you can edit.")).color(t.text_dim).size(11.5));
}
});
});
if let Some(a) = act {
let r = match a {
// Their file dialogs, shown off the UI thread, import into or export from the dialog
// as it is then.
Action::Import | Action::Export => {
let export = matches!(a, Action::Export);
crate::picks::in_app_dialog(app, d, move |app, d| run(app, d, if export { Action::Export } else { Action::Import }, ""))
}
a => run(app, d, a, &preset.0),
};
if let Err(e) = r {
app.status(e);
}
}
false
}
fn select(d: &mut Dialog, name: &str) {
d.fields.insert("selected".into(), json!(name));
}
fn run(app: &mut VectorcraftApp, d: &mut Dialog, act: Action, current: &str) -> Result<(), String> {
match act {
Action::Select(name) => select(d, &name),
// The editor replaces this dialog; its OK and its Cancel come back here.
Action::New => *d = editor(app, d, current, false)?,
Action::Edit => *d = editor(app, d, current, true)?,
Action::Delete => {
let i = app.session.prefs.trace_presets.iter().position(|p| p.name == current);
app.run("imageTrace.presets.delete", json!({ "name": current }))?;
// The saved preset below it takes its place, else the one above it, else Default.
let saved = &app.session.prefs.trace_presets;
let next = i.and_then(|i| saved.get(i).or_else(|| i.checked_sub(1).and_then(|k| saved.get(k)))).map(|p| p.name.clone());
select(d, next.as_deref().unwrap_or("Default"));
}
Action::Import => {
// On the web the picked file arrives later and imports through `io::open_bytes`.
if crate::picks::open_async(app) {
return Ok(());
}
let pick = crate::FilePick { filters: vec![crate::FilePick::filter("Tracing presets", TRACE_PRESET_EXTS)], ..Default::default() };
let path = crate::picks::open(app, &pick).ok_or("cancelled")?;
import(app, d, json!({ "path": path }))?;
}
Action::Export => {
crate::io::save_command_output(app, "imageTrace.presets.export", TRACE_PRESET_FORMAT, json!({}))?;
}
}
Ok(())
}
/// Import the tracing presets file `file` (`{path}` or `{dataBase64}`) into the saved presets,
/// keeping saved presets of the same names → the presets the file added and the names it skipped.
fn import_file(app: &mut VectorcraftApp, file: &Value) -> Result<(Value, Vec<Value>), String> {
let r = crate::io::import_presets(app, "imageTrace.presets.import", "tracing presets", file.clone())?;
let skipped = r["skipped"].as_array().cloned().unwrap_or_default();
Ok((r["imported"].clone(), skipped))
}
/// The question whether the import of `file` replaces the saved presets `skipped` kept, over the
/// dialog `under` (Cancel shows it again).
fn ask_replace(under: Option<&Dialog>, skipped: Vec<Value>, file: Value) -> Dialog {
let under = under.and_then(|d| serde_json::to_value(d).ok()).unwrap_or(Value::Null);
Dialog::new(REPLACE_KIND, json!({ "names": skipped, "file": file, super::PARENT: under }))
}
/// The error for a tracing presets file over the size limit.
fn too_big() -> String {
format!("the tracing presets file is larger than {} MiB", TRACE_PRESET_MAX_BYTES >> 20)
}
/// The tracing presets file `file` as `{dataBase64}`: a `{path}` is read here, once, so the
/// question and its Replace act on the contents the first import checked.
fn file_contents(app: &VectorcraftApp, file: Value) -> Result<Value, String> {
let Some(path) = file.get("path").and_then(Value::as_str) else { return Ok(file) };
vectorcraft_engine::file_access::check_read(path)?;
if std::fs::metadata(path).is_ok_and(|m| m.len() > TRACE_PRESET_MAX_BYTES as u64) {
return Err(too_big());
}
// One byte past the limit tells a larger file apart without reading all of it.
let bytes = match (&app.services.read_head, &app.services.read) {
(Some(read_head), _) => read_head(path, TRACE_PRESET_MAX_BYTES + 1)?,
(None, Some(read)) => read(path)?,
(None, None) => return Err("no file reader".into()),
};
if bytes.len() > TRACE_PRESET_MAX_BYTES {
return Err(too_big());
}
Ok(json!({ "dataBase64": vectorcraft_format::base64_encode(&bytes) }))
}
/// Import… on the manager `d`: the import of `file` ([`import_file`]) selects the first preset it
/// added, and when it kept saved presets of the file's names, `d` goes under the question whether
/// to replace them.
fn import(app: &mut VectorcraftApp, d: &mut Dialog, file: Value) -> Result<(), String> {
let file = file_contents(app, file)?;
let (imported, skipped) = import_file(app, &file)?;
if let Some(first) = imported.get(0).and_then(Value::as_str) {
select(d, first);
}
if !skipped.is_empty() {
*d = ask_replace(Some(d), skipped, file);
}
Ok(())
}
/// A tracing presets file opened (File › Open, a drop, or the file picked for Import… on the web):
/// it imports as Import… does, over the dialog open now (the manager selects the first preset it
/// added), and asks whether to replace saved presets of the file's names.
pub(crate) fn open_file(app: &mut VectorcraftApp, bytes: &[u8]) -> Result<(), String> {
if bytes.len() > TRACE_PRESET_MAX_BYTES {
return Err(too_big());
}
open_import(app, json!({ "dataBase64": vectorcraft_format::base64_encode(bytes) }))
}
/// [`open_file`] for the tracing presets file at `path` (File › Open, a drop): the file is read no
/// further than one byte past the size limit, as Import… reads it.
pub(crate) fn open_path(app: &mut VectorcraftApp, path: &str) -> Result<(), String> {
let file = file_contents(app, json!({ "path": path }))?;
open_import(app, file)
}
/// The import of an opened tracing presets file `file` (`{dataBase64}`), over the dialog open now.
fn open_import(app: &mut VectorcraftApp, file: Value) -> Result<(), String> {
let (imported, skipped) = import_file(app, &file)?;
let mut under = app.ui.dialog.take();
if let (Some(d), Some(first)) = (under.as_mut().filter(|d| d.kind == KIND), imported.get(0).and_then(Value::as_str)) {
select(d, first);
}
app.ui.dialog = if skipped.is_empty() { under } else { Some(ask_replace(under.as_ref(), skipped, file)) };
Ok(())
}
/// Replace (the question's OK): the file imports again, replacing the saved presets of its names,
/// and the dialog it was asked over shows again (the manager on the first of them).
fn confirm_replace(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
let mut p = d.fields.get("file").cloned().filter(Value::is_object).ok_or("no tracing presets file")?;
p["replace"] = json!(true);
let r = app.run("imageTrace.presets.import", p)?;
let mut back = super::parent(d);
if let (Some(b), Some(first)) = (back.as_mut().filter(|b| b.kind == KIND), d.fields.get("names").and_then(|n| n.get(0)).and_then(Value::as_str)) {
select(b, first);
}
app.ui.dialog = back;
Ok(r)
}
/// The preset editor over the manager `d`: on the saved preset `name` (`edit`), else on a new
/// preset starting from the preset `name`, under the first free "Tracing Preset N".
fn editor(app: &mut VectorcraftApp, d: &Dialog, name: &str, edit: bool) -> Result<Dialog, String> {
let (editing, new_name, params) = if edit {
let saved = app.session.trace_preset(name).ok_or_else(|| format!("no saved preset named `{name}`"))?;
(saved.name.clone(), saved.name.clone(), serde_json::to_value(&saved.params).map_err(|e| e.to_string())?)
} else {
let params = app.session.execute("imageTrace.presets", &json!({})).map_err(|e| e.to_string())?["presets"]
.as_array()
.and_then(|all| {
let found = |p: &&Value| p["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(name));
all.iter().find(|p| p["builtIn"] != false && found(p)).or_else(|| all.iter().find(found)).map(|p| p["params"].clone())
})
.ok_or_else(|| format!("no preset named `{name}`"))?;
(String::new(), app.session.new_trace_preset_name(), params)
};
let under = serde_json::to_value(d).map_err(|e| e.to_string())?;
Ok(Dialog::new(PRESET_KIND, json!({ "name": new_name, "params": params, EDITING: editing, super::PARENT: under })))
}
fn preset_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
ui.horizontal(|ui| {
widgets::dim_label(ui, tl!("Name:"));
form::text(ui, d, "name", 240.0);
});
ui.add_space(8.0);
let mut params = d.fields.get("params").cloned().filter(Value::is_object).unwrap_or_else(|| json!({}));
let changed = egui::ScrollArea::vertical()
.id_salt("tracing-preset-settings")
.max_height(SETTINGS_HEIGHT)
.show(ui, |ui| settings_editor(app, ui, "tracing-preset", &mut params))
.inner;
if changed {
d.fields.insert("params".into(), params);
}
false
}
/// Save Preset (the editor's OK): `imageTrace.presets.save`, then back to the manager on the
/// preset. A preset may not take the name of a built-in preset, of Custom or of another saved
/// preset: the editor stays open to change it.
fn confirm_preset(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
let (name, editing) = (d.str("name"), d.str(EDITING));
let name = name.trim();
let params = d.fields.get("params").cloned().unwrap_or(Value::Null);
let p = if editing.is_empty() {
if app.session.trace_preset(name).is_some() {
return Err(format!("a preset named `{name}` exists"));
}
// The settings are whole: a new preset starts from none of the saved ones.
json!({ "name": name, "preset": "Default", "params": params })
} else {
json!({ "name": editing, "newName": name, "params": params })
};
let r = app.run("imageTrace.presets.save", p)?;
let mut back = super::parent(d).filter(|p| p.kind == KIND).unwrap_or_else(|| Dialog::new(KIND, json!({})));
select(&mut back, r["name"].as_str().unwrap_or_default());
app.ui.dialog = Some(back);
Ok(r)
}
/// The tracing settings `params` as the Image Trace panel shows them (mode, palette, the count or
/// threshold, Document Library's library and colors, and the Advanced settings), changed by the user
/// → whether they changed.
fn settings_editor(app: &VectorcraftApp, ui: &mut egui::Ui, id: &str, params: &mut Value) -> bool {
let mut changed = false;
let mode = params["mode"].as_str().unwrap_or("blackAndWhite").to_string();
ui.horizontal(|ui| {
widgets::dim_label(ui, tl!("Mode:"));
let label = MODES.iter().find(|m| m.0 == mode).map_or("Black and White", |m| m.1);
let labels: Vec<&str> = MODES.iter().map(|m| m.1).collect();
if let Some(i) = widgets::dropdown(ui, (id, "mode"), label, &labels, 170.0) {
if MODES[i].0 != "color" {
params["colorGroup"] = Value::Null;
}
params["mode"] = json!(MODES[i].0);
changed = true;
}
});
let palette = params["palette"].as_str().unwrap_or("limited").to_string();
if mode == "color" {
ui.horizontal(|ui| {
widgets::dim_label(ui, tl!("Palette:"));
let labels = PALETTES.map(image_trace::palette_label);
if let Some(p) =
widgets::dropdown_names(ui, (id, "palette"), image_trace::palette_label(&palette), &labels, 170.0).and_then(|i| PALETTES.get(i))
{
if *p != "documentLibrary" {
params["colorGroup"] = Value::Null;
}
params["palette"] = json!(p);
changed = true;
}
});
if palette == "documentLibrary" {
let key = params["library"].as_str().unwrap_or(DOCUMENT_SWATCHES).to_string();
ui.horizontal(|ui| {
widgets::dim_label(ui, tl!("Library:"));
let label = swatches::library_label(app, &key);
if let Some(k) = widgets::combo(ui, (id, "library"), &label, 170.0, |ui| swatches::library_list(app, ui, &key)) {
if k != DOCUMENT_SWATCHES {
params["colorGroup"] = Value::Null;
}
params["library"] = json!(k);
changed = true;
}
});
// The document's swatches: every one, or one color group's (kept by name, so a preset
// names a group the open document may not have).
if key == DOCUMENT_SWATCHES {
ui.horizontal(|ui| {
widgets::dim_label(ui, tl!("Colors:"));
let group = params["colorGroup"].as_str().filter(|g| !g.is_empty()).map(str::to_string);
let label = group.clone().unwrap_or_else(|| tl!("All").to_string());
if let Some(g) =
widgets::combo(ui, (id, "color-group"), &label, 170.0, |ui| image_trace::color_group_list(app, ui, group.as_deref()))
{
params["colorGroup"] = json!(g);
changed = true;
}
});
}
}
}
let (key, label, range, suffix) = match mode.as_str() {
"blackAndWhite" => ("threshold", tl!("Threshold"), 0.0..=255.0, ""),
"grayscale" => ("colors", tl!("Grays"), 2.0..=256.0, ""),
"logo" => ("colors", tl!("Colors"), 2.0..=10.0, ""),
_ if matches!(palette.as_str(), "fullTone" | "automatic") => ("colorDetail", tl!("Colors"), 0.0..=100.0, "%"),
_ => ("colors", tl!("Colors"), 2.0..=256.0, ""),
};
let mut slider = |params: &mut Value, key: &str, label: &str, range: std::ops::RangeInclusive<f64>, suffix: &str, whole: bool| {
let mut v = params[key].as_f64().unwrap_or(0.0);
if image_trace::slider(ui, label, &mut v, range, suffix).0 {
params[key] = if whole { json!(v.round() as u64) } else { json!(v.round()) };
changed = true;
}
};
slider(params, key, label, range, suffix, key != "colorDetail");
for (key, label, range, suffix) in
[("paths", tl!("Paths"), 0.0..=100.0, "%"), ("corners", tl!("Corners"), 0.0..=100.0, "%"), ("noise", tl!("Noise"), 1.0..=100.0, " px")]
{
slider(params, key, label, range, suffix, key == "noise");
}
if mode != "logo" {
ui.horizontal(|ui| {
widgets::dim_label(ui, tl!("Method:"));
for (m, l) in [("abutting", tl!("Abutting")), ("overlapping", tl!("Overlapping"))] {
if ui.selectable_label(params["method"] == m, l).clicked() && params["method"] != m {
params["method"] = json!(m);
changed = true;
}
}
});
// Create: Fills and/or Strokes (one of them stays on), and the widest line stroked.
let create = |p: &Value, key: &str| p[key].as_bool().unwrap_or(key == "fills");
ui.horizontal(|ui| {
widgets::dim_label(ui, tl!("Create:"));
for (key, other, label) in [("fills", "strokes", tl!("Fills")), ("strokes", "fills", tl!("Strokes"))] {
let on = create(params, key);
if widgets::check(ui, label, on, !on || create(params, other)) {
params[key] = json!(!on);
changed = true;
}
}
});
let mut v = params["strokeWidth"].as_f64().unwrap_or(10.0);
let strokes = create(params, "strokes");
if ui.add_enabled_ui(strokes, |ui| image_trace::slider(ui, tl!("Stroke"), &mut v, 1.0..=100.0, " px")).inner.0 {
params["strokeWidth"] = json!(v.round());
changed = true;
}
}
let gradients = mode == "grayscale" || mode == "color";
for (key, label, enabled) in [
("snapCurvesToLines", tl!("Snap Curves To Lines"), true),
("shapes", tl!("Shapes"), true),
("autoGrouping", tl!("Auto Grouping"), true),
("gradients", tl!("Gradients"), gradients),
] {
let on = params[key].as_bool().unwrap_or(false);
if widgets::check(ui, label, on, enabled) {
params[key] = json!(!on);
changed = true;
}
}
ui.horizontal(|ui| {
let on = params["ignoreWhite"].as_bool().unwrap_or(false);
if widgets::check(ui, tl!("Ignore Color"), on, true) {
params["ignoreWhite"] = json!(!on);
changed = true;
}
if on {
let mut rgb = image_trace::ignore_color(params);
if ui.color_edit_button_srgb(&mut rgb).changed() {
params["ignoreColor"] = json!(format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2]));
changed = true;
}
}
});
changed
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,441 @@
//! Edit → Tracing Presets: the menu item, New… and Edit… through the preset editor, Delete,
//! Import… (with the question about saved presets of the same names) and Export….
use serde_json::{Value, json};
use vectorcraft_engine::Session;
use super::*;
fn frame(app: &mut VectorcraftApp) {
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::super::show(app, ui.ctx()));
out.textures_delta.clear();
}
/// Press a manager button on the preset `current`, as the body does.
fn press(app: &mut VectorcraftApp, act: Action, current: &str) -> Result<(), String> {
let mut d = app.ui.dialog.take().expect("a dialog is open");
let r = run(app, &mut d, act, current);
app.ui.dialog = Some(d);
frame(app);
r
}
/// The texts the dialog paints on a 1200 × 900 window, once it has taken its sizing frame and
/// faded in (each frame is a quarter second on).
fn frame_texts(app: &mut VectorcraftApp) -> Vec<String> {
fn walk(s: &egui::Shape, out: &mut Vec<String>) {
match s {
egui::Shape::Text(t) => out.push(t.galley.text().to_string()),
egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)),
_ => {}
}
}
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0));
let mut texts = vec![];
for k in 0..4 {
let raw = egui::RawInput { screen_rect: Some(screen), time: Some(f64::from(k) * 0.25), ..Default::default() };
let mut out = ctx.run_ui(raw, |ui| super::super::show(app, ui.ctx()));
out.textures_delta.clear();
texts.clear();
out.shapes.iter().for_each(|c| walk(&c.shape, &mut texts));
}
texts
}
fn kind(app: &VectorcraftApp) -> Option<&str> {
app.ui.dialog.as_ref().map(|d| d.kind.as_str())
}
fn field(app: &VectorcraftApp, k: &str) -> Value {
app.ui.dialog.as_ref().and_then(|d| d.fields.get(k).cloned()).unwrap_or_default()
}
fn set(app: &mut VectorcraftApp, k: &str, v: Value) {
app.ui.dialog.as_mut().expect("a dialog is open").fields.insert(k.into(), v);
}
/// The tracing settings of the preset `name` as `imageTrace.presets` lists them.
fn listed(app: &mut VectorcraftApp, name: &str) -> Value {
let all = app.session.execute("imageTrace.presets", &json!({})).unwrap();
all["presets"].as_array().unwrap().iter().find(|p| p["name"] == name).map(|p| p["params"].clone()).unwrap_or_default()
}
fn saved_names(app: &VectorcraftApp) -> Vec<&str> {
app.session.prefs.trace_presets.iter().map(|p| p.name.as_str()).collect()
}
#[test]
fn edit_menu_opens_the_manager_without_a_document() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let entries = crate::menus::menu_entries(&app);
let item = entries.iter().find(|e| e.command.as_deref() == Some("ui.tracingPresetsDialog")).expect("Edit → Tracing Presets…");
assert!(item.path == ["Edit"] && item.label == "Tracing Presets…" && item.enabled);
app.run("ui.tracingPresetsDialog", json!({})).unwrap();
frame(&mut app);
assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("Default")));
app.run("ui.tracingPresetsDialog", json!({"selected": "[6 Colors]"})).unwrap();
frame(&mut app);
assert_eq!(field(&app, "selected"), json!("[6 Colors]"));
// Built-in presets can't be edited or deleted.
assert!(press(&mut app, Action::Edit, "6 Colors").is_err());
assert!(press(&mut app, Action::Delete, "6 Colors").is_err());
assert!(app.session.prefs.trace_presets.is_empty());
super::super::confirm(&mut app).unwrap();
assert!(app.ui.dialog.is_none(), "Close");
}
#[test]
fn new_and_edit_save_through_the_editor_and_cancel_saves_nothing() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let revision = app.session.trace_presets_revision();
app.run("ui.tracingPresetsDialog", json!({"selected": "6 Colors"})).unwrap();
frame(&mut app);
// New… starts from the selected built-in preset; Cancel comes back with nothing saved.
press(&mut app, Action::New, "6 Colors").unwrap();
assert_eq!((kind(&app), field(&app, "name")), (Some(PRESET_KIND), json!("Tracing Preset 1")));
let six = listed(&mut app, "6 Colors");
assert_eq!(field(&app, "params"), six);
set(&mut app, "name", json!("Poster"));
super::super::cancel(&mut app);
assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("6 Colors")), "back to the manager");
assert!(app.session.prefs.trace_presets.is_empty());
assert_eq!(app.session.trace_presets_revision(), revision);
// OK saves the preset with the editor's settings and selects it.
press(&mut app, Action::New, "6 Colors").unwrap();
set(&mut app, "name", json!(" Poster "));
let mut params = field(&app, "params");
params["noise"] = json!(40);
set(&mut app, "params", params);
frame(&mut app);
super::super::confirm(&mut app).unwrap();
assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("Poster")));
assert_eq!(saved_names(&app), ["Poster"]);
let poster = listed(&mut app, "Poster");
assert_eq!((poster["noise"].clone(), poster["colors"].clone()), (json!(40), six["colors"].clone()));
// The Image Trace panel's list (also the Control bar's and Properties') has it.
let ctx = egui::Context::default();
let all = crate::panels::image_trace::presets(&mut app, &ctx);
assert!(all.iter().any(|p| p.0 == "Poster" && !p.3));
// Edit… changes the saved preset; Cancel leaves it as it was.
frame(&mut app);
press(&mut app, Action::Edit, "Poster").unwrap();
assert_eq!((kind(&app), field(&app, "name"), field(&app, "params")), (Some(PRESET_KIND), json!("Poster"), poster.clone()));
let mut params = field(&app, "params");
params["noise"] = json!(3);
set(&mut app, "params", params);
super::super::cancel(&mut app);
assert_eq!(listed(&mut app, "Poster"), poster);
press(&mut app, Action::Edit, "Poster").unwrap();
let mut params = field(&app, "params");
params["noise"] = json!(3);
params["mode"] = json!("grayscale");
set(&mut app, "params", params);
set(&mut app, "name", json!("Posters"));
frame(&mut app);
super::super::confirm(&mut app).unwrap();
assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("Posters")));
assert_eq!(saved_names(&app), ["Posters"]);
let edited = listed(&mut app, "Posters");
assert_eq!((edited["noise"].clone(), edited["mode"].clone()), (json!(3), json!("grayscale")));
// New… from a saved preset starts from its settings.
press(&mut app, Action::New, "Posters").unwrap();
assert_eq!((field(&app, "name"), field(&app, "params")), (json!("Tracing Preset 1"), edited));
}
#[test]
fn the_editor_shows_document_library_s_library_and_colors() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("ui.tracingPresetsDialog", json!({})).unwrap();
frame(&mut app);
press(&mut app, Action::New, "Default").unwrap();
let mut params = field(&app, "params");
params["mode"] = json!("color");
params["palette"] = json!("documentLibrary");
params["colorGroup"] = json!("Brand Colors");
set(&mut app, "params", params.clone());
let texts = frame_texts(&mut app);
for t in ["Library:", "Colors:", "Brand Colors"] {
assert!(texts.iter().any(|s| s == t), "{t}: {texts:?}");
}
// Another library's colors are all its swatches: no Colors menu.
params["library"] = json!("lib:Other");
params["colorGroup"] = Value::Null;
set(&mut app, "params", params.clone());
let texts = frame_texts(&mut app);
assert!(texts.iter().any(|s| s == "Library:") && !texts.iter().any(|s| s == "Colors:"), "{texts:?}");
// Other palettes show neither.
params["palette"] = json!("limited");
set(&mut app, "params", params);
let texts = frame_texts(&mut app);
assert!(!texts.iter().any(|s| s == "Library:" || s == "Colors:"), "{texts:?}");
}
#[test]
fn a_taken_or_protected_name_keeps_the_editor_open() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("imageTrace.presets.save", json!({"name": "Ink", "params": {"threshold": 90}})).unwrap();
app.run("imageTrace.presets.save", json!({"name": "Poster", "params": {"noise": 40}})).unwrap();
let saved = app.session.prefs.trace_presets.clone();
app.run("ui.tracingPresetsDialog", json!({"selected": "Ink"})).unwrap();
frame(&mut app);
press(&mut app, Action::New, "Ink").unwrap();
for name in ["Default", "[6 Colors]", "custom", "poster"] {
set(&mut app, "name", json!(name));
assert!(super::super::confirm(&mut app).is_err(), "{name}");
assert_eq!((kind(&app), field(&app, "name")), (Some(PRESET_KIND), json!(name)), "{name}: stays open");
}
super::super::cancel(&mut app);
press(&mut app, Action::Edit, "Ink").unwrap();
for name in ["Poster", "Default", "Custom"] {
set(&mut app, "name", json!(name));
assert!(super::super::confirm(&mut app).is_err(), "{name}");
assert_eq!(kind(&app), Some(PRESET_KIND), "{name}: stays open");
}
assert_eq!(app.session.prefs.trace_presets, saved, "nothing changed");
}
#[test]
fn delete_selects_the_next_saved_preset_then_default() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
for name in ["A", "B", "C"] {
app.run("imageTrace.presets.save", json!({ "name": name })).unwrap();
}
app.run("ui.tracingPresetsDialog", json!({"selected": "B"})).unwrap();
frame(&mut app);
press(&mut app, Action::Delete, "B").unwrap();
assert_eq!((saved_names(&app), field(&app, "selected")), (vec!["A", "C"], json!("C")));
press(&mut app, Action::Delete, "C").unwrap();
assert_eq!((saved_names(&app), field(&app, "selected")), (vec!["A"], json!("A")));
press(&mut app, Action::Delete, "A").unwrap();
assert!(app.session.prefs.trace_presets.is_empty());
assert_eq!(field(&app, "selected"), json!("Default"));
}
#[test]
fn import_asks_before_replacing_saved_presets_and_export_writes_every_saved_one() {
let dir = std::env::temp_dir().join(format!("vc-tracing-presets-ui-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("mine.vctracepresets").to_string_lossy().to_string();
let picked = file.clone();
let services = crate::Services {
pick_save: Some(Box::new(move |_: &crate::FilePick| Some(picked.clone()))),
write: Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))),
read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))),
..Default::default()
};
let mut app = VectorcraftApp::new(Session::new(), services);
app.run("imageTrace.presets.save", json!({"name": "Poster", "params": {"noise": 40}})).unwrap();
app.run("imageTrace.presets.save", json!({"name": "Ink", "params": {"threshold": 90}})).unwrap();
app.run("ui.tracingPresetsDialog", json!({"selected": "Default"})).unwrap();
frame(&mut app);
press(&mut app, Action::Export, "").unwrap();
let text = std::fs::read_to_string(&file).unwrap();
let written: Value = serde_json::from_str(&text).unwrap();
let names: Vec<&str> = written["presets"].as_array().unwrap().iter().filter_map(|p| p["name"].as_str()).collect();
assert_eq!((written["format"].as_str(), names), (Some(TRACE_PRESET_FORMAT), vec!["Poster", "Ink"]));
// Saved presets of the same names stay unless the question's Replace is pressed.
app.run("imageTrace.presets.save", json!({"name": "Poster", "params": {"noise": 7}})).unwrap();
app.run("imageTrace.presets.delete", json!({"name": "Ink"})).unwrap();
let mut d = app.ui.dialog.take().unwrap();
import(&mut app, &mut d, json!({ "path": file })).unwrap();
app.ui.dialog = Some(d);
frame(&mut app);
assert_eq!((kind(&app), field(&app, "names")), (Some(REPLACE_KIND), json!(["Poster"])));
assert_eq!(saved_names(&app), ["Poster", "Ink"], "Ink came in");
super::super::cancel(&mut app);
assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("Ink")), "Cancel keeps the saved one");
assert_eq!(app.session.trace_preset("Poster").unwrap().params.noise, 7);
let mut d = app.ui.dialog.take().unwrap();
import(&mut app, &mut d, json!({ "path": file })).unwrap();
app.ui.dialog = Some(d);
// Replace acts on the contents the question was asked about, though the file changed since.
let changed =
r#"{"format": "vctracepresets", "version": 1, "presets": [{"name": "Poster", "params": {"noise": 3}}, {"name": "Extra", "params": {}}]}"#;
std::fs::write(&file, changed).unwrap();
super::super::confirm(&mut app).unwrap();
std::fs::write(&file, &text).unwrap();
assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("Poster")));
assert_eq!(app.session.trace_preset("Poster").unwrap().params.noise, 40);
assert_eq!(saved_names(&app), ["Poster", "Ink"]);
// Opening the file imports it, and asks the same question over the manager (also how the web's
// picked file arrives).
app.run("imageTrace.presets.save", json!({"name": "Poster", "params": {"noise": 7}})).unwrap();
app.run("imageTrace.presets.delete", json!({"name": "Ink"})).unwrap();
let bytes = std::fs::read(&file).unwrap();
crate::io::open_bytes(&mut app, &file, &bytes, Some(file.clone())).unwrap();
assert_eq!(saved_names(&app), ["Poster", "Ink"]);
assert!(app.ui.status.contains("tracing presets"), "{}", app.ui.status);
assert_eq!((kind(&app), field(&app, "names")), (Some(REPLACE_KIND), json!(["Poster"])));
frame(&mut app);
super::super::confirm(&mut app).unwrap();
assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("Poster")));
assert_eq!(app.session.trace_preset("Poster").unwrap().params.noise, 40);
// With no dialog open, Cancel keeps the saved preset and leaves no dialog.
app.ui.dialog = None;
app.run("imageTrace.presets.save", json!({"name": "Poster", "params": {"noise": 7}})).unwrap();
crate::io::open_bytes(&mut app, &file, &bytes, Some(file.clone())).unwrap();
assert_eq!(kind(&app), Some(REPLACE_KIND));
super::super::cancel(&mut app);
assert!(app.ui.dialog.is_none());
assert_eq!(app.session.trace_preset("Poster").unwrap().params.noise, 7);
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn a_file_with_a_fault_changes_nothing() {
let dir = std::env::temp_dir().join(format!("vc-tracing-presets-bad-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("bad.vctracepresets");
std::fs::write(
&file,
r#"{"format": "vctracepresets", "version": 1, "presets": [{"name": "Fine", "params": {}}, {"name": "Default", "params": {}}]}"#,
)
.unwrap();
// The file is read no further than one byte past the limit.
let read_head = |p: &str, max: usize| {
use std::io::Read as _;
assert_eq!(max, TRACE_PRESET_MAX_BYTES + 1);
let mut bytes = vec![];
std::fs::File::open(p).and_then(|f| f.take(max as u64).read_to_end(&mut bytes)).map_err(|e| e.to_string())?;
Ok(bytes)
};
let services = crate::Services { read_head: Some(Box::new(read_head)), ..Default::default() };
let mut app = VectorcraftApp::new(Session::new(), services);
app.run("ui.tracingPresetsDialog", json!({})).unwrap();
frame(&mut app);
let mut d = app.ui.dialog.take().unwrap();
let e = import(&mut app, &mut d, json!({ "path": file.to_string_lossy() })).unwrap_err();
assert!(e.contains("built-in preset"), "{e}");
assert_eq!(d.kind, KIND, "no question");
assert!(app.session.prefs.trace_presets.is_empty());
app.ui.dialog = Some(d);
// An opened file over the size limit is refused before its bytes are encoded for the import.
let big = vec![b' '; TRACE_PRESET_MAX_BYTES + 1];
let e = open_file(&mut app, &big).unwrap_err();
assert!(e.contains("tracing presets file is larger than 4 MiB"), "{e}");
assert_eq!(kind(&app), Some(KIND), "the manager stays open");
let big_file = dir.join("big.vctracepresets");
std::fs::write(&big_file, &big).unwrap();
let mut d = app.ui.dialog.take().unwrap();
let e = import(&mut app, &mut d, json!({ "path": big_file.to_string_lossy() })).unwrap_err();
assert!(e.contains("tracing presets file is larger than 4 MiB"), "{e}");
app.ui.dialog = Some(d);
assert!(app.session.prefs.trace_presets.is_empty());
let _ = std::fs::remove_dir_all(dir);
}
/// File › Open reads a tracing presets file no further than one byte past the size limit, and
/// refuses a larger one, without the whole-file reader.
#[test]
fn an_opened_file_is_read_no_further_than_the_limit() {
let dir = std::env::temp_dir().join(format!("vc-tracing-presets-open-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let fine = dir.join("fine.vctracepresets");
std::fs::write(&fine, r#"{"format": "vctracepresets", "version": 1, "presets": [{"name": "Fine", "params": {}}]}"#).unwrap();
let big = dir.join("big.vctracepresets");
std::fs::write(&big, vec![b' '; TRACE_PRESET_MAX_BYTES + 1]).unwrap();
let read_head = |p: &str, max: usize| {
use std::io::Read as _;
assert_eq!(max, TRACE_PRESET_MAX_BYTES + 1);
let mut bytes = vec![];
std::fs::File::open(p).and_then(|f| f.take(max as u64).read_to_end(&mut bytes)).map_err(|e| e.to_string())?;
Ok(bytes)
};
let read = |p: &str| -> Result<Vec<u8>, String> { Err(format!("`{p}` was read in full")) };
let services = crate::Services { read_head: Some(Box::new(read_head)), read: Some(Box::new(read)), ..Default::default() };
let mut app = VectorcraftApp::new(Session::new(), services);
crate::io::open_path(&mut app, &fine.to_string_lossy()).unwrap();
assert_eq!(saved_names(&app), ["Fine"]);
let e = crate::io::open_path(&mut app, &big.to_string_lossy()).unwrap_err();
assert!(e.contains("tracing presets file is larger than 4 MiB"), "{e}");
assert_eq!(saved_names(&app), ["Fine"]);
let _ = std::fs::remove_dir_all(dir);
}
/// The question's list of names scrolls, so a long one keeps Replace and Cancel on a small screen.
#[test]
fn a_long_list_of_names_keeps_replace_on_screen() {
fn walk(s: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) {
match s {
egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())),
egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)),
_ => {}
}
}
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let names: Vec<Value> = (0..200).map(|i| json!(format!("Tracing Preset {i}"))).collect();
app.ui.dialog = Some(ask_replace(None, names, json!({ "dataBase64": "" })));
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 600.0));
let mut texts = vec![];
for k in 0..6 {
let raw = egui::RawInput { screen_rect: Some(screen), time: Some(f64::from(k) * 0.25), ..Default::default() };
let mut out = ctx.run_ui(raw, |ui| super::super::show(&mut app, ui.ctx()));
out.textures_delta.clear();
texts.clear();
out.shapes.iter().for_each(|c| walk(&c.shape, &mut texts));
}
for button in ["Replace", "Cancel"] {
let rect = texts.iter().find(|(t, _)| t == button).map(|(_, r)| *r);
assert!(rect.is_some_and(|r| screen.contains_rect(r)), "{button} is drawn on screen: {rect:?}");
}
}
/// The tracing settings scroll past the height of the preset list, in the manager and in the
/// editor: a preset with every row shown (Color, Document Library, Ignore Color) makes neither
/// dialog taller than a Black and White one does.
#[test]
fn tall_settings_scroll_instead_of_growing_the_dialog() {
fn walk(s: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) {
match s {
egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())),
egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)),
_ => {}
}
}
/// The height from the dialog's heading to the bottom of its button `button`.
fn height(app: &mut VectorcraftApp, heading: &str, button: &str) -> f32 {
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 2000.0));
let mut texts = vec![];
for k in 0..6 {
let raw = egui::RawInput { screen_rect: Some(screen), time: Some(f64::from(k) * 0.25), ..Default::default() };
let mut out = ctx.run_ui(raw, |ui| super::super::show(app, ui.ctx()));
out.textures_delta.clear();
texts.clear();
out.shapes.iter().for_each(|c| walk(&c.shape, &mut texts));
}
let at = |t: &str| texts.iter().find(|(s, _)| s == t).map(|(_, r)| *r).unwrap_or_else(|| panic!("{t}: {texts:?}"));
at(button).max.y - at(heading).min.y
}
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let short = listed(&mut app, "Default");
let mut tall = short.clone();
tall["mode"] = json!("color");
tall["palette"] = json!("documentLibrary");
tall["colorGroup"] = json!("Brand Colors");
tall["ignoreWhite"] = json!(true);
for (name, params) in [("Short", &short), ("Tall", &tall)] {
app.run("imageTrace.presets.save", json!({ "name": name, "preset": "Default", "params": params })).unwrap();
}
app.run("ui.tracingPresetsDialog", json!({})).unwrap();
let mut heights = vec![];
for name in ["Short", "Tall"] {
set(&mut app, "selected", json!(name));
let manager = height(&mut app, "Tracing Presets", "Close");
press(&mut app, Action::Edit, name).unwrap();
assert_eq!(kind(&app), Some(PRESET_KIND));
let editor = height(&mut app, "Save Preset", "OK");
app.ui.dialog = super::super::parent(app.ui.dialog.as_ref().unwrap());
heights.push((manager, editor));
}
let [(manager, editor), (tall_manager, tall_editor)] = heights[..] else { panic!("{heights:?}") };
assert!(tall_manager <= manager + 0.5, "the manager grows from {manager} to {tall_manager}");
assert!(tall_editor <= editor + 0.5, "the editor grows from {editor} to {tall_editor}");
}
+24
View File
@@ -489,6 +489,10 @@ font-technology Variable Променливи
Circle Кръг
Circle Tool Инструмент Кръг
Circle too large Кръгът е твърде голям
Show Radii Показване на радиуси
Show Diameter Показване на диаметър
Anchors at Standard Positions Опорни точки в стандартни позиции
Third Point by Dragging Трета точка чрез плъзгане
Classic Defaults Класически по подразбиране
Clean Up… Почистване…
Clear Изчистване
@@ -590,6 +594,10 @@ font-technology Variable Променливи
Box Channel Канал на квадрата
Color box Цветови квадрат
Color Wheel Options Опции на цветното колело
Show Document Colors Показване на цветовете на документа
Document Colors Цветове на документа
Selection Colors Цветове на селекцията
@plural Used {n} time|Used {n} times Използван {n} път|Използван {n} пъти
Show Harmony Показване на хармонията
Harmony Rule Правило за хармония
Harmony color Цвят от хармонията
@@ -1831,6 +1839,10 @@ font-technology Variable Променливи
Rename Preset Преименуване на предварителна настройка
Save Image Trace Preset Запази предварителна настройка за трасиране на изображения
Delete Image Trace Preset Изтриване на предварителна настройка за трасиране на изображения
Tracing Presets… Предварителни настройки за трасиране…
Import Image Trace Presets Импортиране на предварителни настройки за трасиране на изображения
Export Image Trace Presets Експортиране на предварителни настройки за трасиране на изображения
Replace the saved presets that have these names? Да се заменят ли запазените предварителни настройки с тези имена?
Image Trace Presets Предварителни настройки за трасиране на изображения
Image: Изображение:
Images: Изображения:
@@ -2702,6 +2714,13 @@ font-technology Variable Променливи
Pen Tool Инструмент „Перо“
Quick Pen Tool Инструмент „Бързо перо“
Quick Pen Бързо перо
Quick Pen Toolbar Лента на бързото перо
Continuous Arc Непрекъсната дъга
Sharp Corner Arc Дъга с остър ъгъл
Flip Arc Обръщане на дъгата
Hide Toolbar Скриване на лентата с инструменти
Pin Toolbar Position Закачане на позицията на лентата с инструменти
Reset Toolbar Position Нулиране на позицията на лентата с инструменти
Pencil Молив
Pencil Tool Инструмент „Молив“
per slice на отрязък
@@ -7915,6 +7934,11 @@ breakText Glyphs Глифи
Flower Цвете
Tree Дърво
Mountain Планина
Ornamental Орнаментални
Scrollwork Завитък
Filigree Arrow Филигранна стрела
Petal Sweep Венчелистен замах
Twin Curl Двоен завитък
Vector Packs Векторни пакети
Compass Rose Роза на компаса
Botanical Sprig Ботаническо клонче
Can't render this file because it is too large.
+24
View File
@@ -823,6 +823,10 @@
Box Channel Kanal kvadrata
Color box Kvadrat boje
Color Wheel Options Opcije kotača boja
Show Document Colors Prikaži boje dokumenta
Document Colors Boje dokumenta
Selection Colors Boje odabira
@plural Used {n} time|Used {n} times Korišteno {n} put|Korišteno {n} puta|Korišteno {n} puta
Show Harmony Prikaži harmoniju
Harmony Rule Pravilo harmonije
Harmony color Boja harmonije
@@ -2054,6 +2058,10 @@ digits Malayalam Malajalam
Rename Preset Preimenuj unaprijed postavljeno
Save Image Trace Preset Sačuvaj unaprijed postavljeno praćenje slike
Delete Image Trace Preset Izbriši unaprijed postavljeno praćenje slike
Tracing Presets… Predlošci praćenja…
Import Image Trace Presets Uvezi predloške praćenja slike
Export Image Trace Presets Izvezi predloške praćenja slike
Replace the saved presets that have these names? Zamijeniti sačuvane predloške s ovim imenima?
Method: Metoda:
Pad Produži
Repeats Broj ponavljanja
@@ -4211,6 +4219,13 @@ theme Appearance Izgled
Pen Tool Alat pero
Quick Pen Tool Alat brzo pero
Quick Pen Brzo pero
Quick Pen Toolbar Traka Brzog pera
Continuous Arc Neprekidni luk
Sharp Corner Arc Luk s oštrim uglom
Flip Arc Preokreni luk
Hide Toolbar Sakrij traku s alatima
Pin Toolbar Position Prikvači položaj trake s alatima
Reset Toolbar Position Vrati položaj trake s alatima na početno
Picas Pice
Portuguese Portugalski
Preserve Appearance and Overprints Očuvaj izgled i pretiske
@@ -4860,6 +4875,10 @@ font-technology Variable Varijabilni
Circle Krug
Circle Tool Alat za krug
Circle too large Krug je prevelik
Show Radii Prikaži poluprečnike
Show Diameter Prikaži prečnik
Anchors at Standard Positions Sidrene tačke na standardnim položajima
Third Point by Dragging Treća tačka povlačenjem
Clip to Art Isijeci prema crtežu
Colorize Oboji
Gamma Gama
@@ -7970,6 +7989,11 @@ shape Open Otvoren
Flower Cvijet
Tree Drvo
Mountain Planina
Ornamental Ornamentalno
Scrollwork Ukrasni zavoj
Filigree Arrow Filigranska strelica
Petal Sweep Potez latica
Twin Curl Dvostruki zavoj
Vector Packs Vektorski paketi
Compass Rose Ruža kompasa
Botanical Sprig Botanička grančica
Can't render this file because it contains an unexpected character in line 2 and column 73.
+27 -1
View File
@@ -734,6 +734,10 @@ arrowhead Target Diana
Cusp Punta
Straight segment Segment recte
Circle too large El cercle és massa gran
Show Radii Mostra els radis
Show Diameter Mostra el diàmetre
Anchors at Standard Positions Punts d’ancoratge en posicions estàndard
Third Point by Dragging Tercer punt arrossegant
Circle (open) Cercle (obert)
Classic Clàssic
Classic Defaults Valors predeterminats clàssics
@@ -891,6 +895,10 @@ arrowhead Target Diana
Box Channel Canal del quadre
Color box Quadre de color
Color Wheel Options Opcions de la roda de colors
Show Document Colors Mostra els colors del document
Document Colors Colors del document
Selection Colors Colors de la selecció
@plural Used {n} time|Used {n} times Utilitzat {n} vegada|Utilitzat {n} vegades
Show Harmony Mostra l’harmonia
Harmony Rule Regla d’harmonia
Harmony color Color de l’harmonia
@@ -1222,6 +1230,10 @@ arrowhead Target Diana
Delete Guide Suprimeix la guia
Delete Guides Suprimeix les guies
Delete Image Trace Preset Suprimeix el preajust de traçat d’imatge
Tracing Presets… Preajustos de traçat…
Import Image Trace Presets Importa preajustos de traçat d’imatge
Export Image Trace Presets Exporta els preajustos de traçat d’imatge
Replace the saved presets that have these names? Voleu substituir els preajustos desats que tenen aquests noms?
Delete Layer Suprimeix la capa
Delete Library Suprimeix la biblioteca
Delete Library Group Suprimeix el grup de biblioteca
@@ -3458,6 +3470,13 @@ digits Malayalam Malaiàlam
Pen Tool Eina de ploma
Quick Pen Tool Eina de ploma ràpida
Quick Pen Ploma ràpida
Quick Pen Toolbar Barra d’eines de la ploma ràpida
Continuous Arc Arc continu
Sharp Corner Arc Arc de cantonada aguda
Flip Arc Inverteix l’arc
Hide Toolbar Amaga la barra d’eines
Pin Toolbar Position Fixa la posició de la barra d’eines
Reset Toolbar Position Restableix la posició de la barra d’eines
Pencil Llapis
Pencil Tool Eina de llapis
Pentagram Pentagrama
@@ -7298,8 +7317,10 @@ liquify-list-end {0}, {1} {0} i {1}
@msg `{GRAPHICS}` face must be front, back or side face de `{GRAPHICS}` ha de ser front, back o side
@msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} de `{GRAPHICS}` ha de ser un nombre de {lo} a {hi}
@msg `{GRAPHICS}` must be an array `{GRAPHICS}` ha de ser una matriu
@msg Graphics map onto the Plane, Extrude and Revolve object types Els gràfics s’apliquen als tipus d’objecte Pla, Extrusió i Revolució
@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Els gràfics s’apliquen als tipus d’objecte Pla, Extrusió, Revolució i Infla
@msg Revolve maps graphics onto its side: map them onto the front Revoluciona aplica els gràfics al seu lateral: aplica’ls a la cara davantera
@msg Inflate maps graphics onto its front and back, not onto a side Infla aplica els gràfics a la cara davantera i a la posterior, no a un lateral
@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on l’objecte {_1}: la cara posterior d’Infla només admet gràfics amb Tots dos costats i Tapa activats
@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Els gràfics són massa complexos per a aquesta superfície: simplifica la il·lustració dels símbols o redueix Segments
@msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` admet com a màxim {MAX_GRAPHICS} gràfics
@msg A plane has one face: map its graphics onto the front Un pla té una sola cara: aplica’n els gràfics a la cara davantera
@@ -8958,6 +8979,11 @@ breakText Glyphs Glifs
Flower Flor
Tree Arbre
Mountain Muntanya
Ornamental Ornamental
Scrollwork Voluta
Filigree Arrow Fletxa de filigrana
Petal Sweep Traç de pètals
Twin Curl Voluta doble
Vector Packs Paquets vectorials
Compass Rose Rosa dels vents
Botanical Sprig Branqueta botànica
Can't render this file because it is too large.
+27 -1
View File
@@ -835,6 +835,10 @@
Box Channel Kanál čtverce
Color box Barevný čtverec
Color Wheel Options Možnosti barevného kola
Show Document Colors Zobrazit barvy dokumentu
Document Colors Barvy dokumentu
Selection Colors Barvy výběru
@plural Used {n} time|Used {n} times Použito {n}krát|Použito {n}krát|Použito {n}krát
Show Harmony Zobrazit harmonii
Harmony Rule Pravidlo harmonie
Harmony color Barva harmonie
@@ -2126,6 +2130,10 @@ digits Malayalam Malajálamské
Rename Preset Přejmenovat přednastavení
Save Image Trace Preset Uložit přednastavení vektorizace obrazu
Delete Image Trace Preset Odstranit přednastavení vektorizace obrazu
Tracing Presets… Přednastavení vektorizace…
Import Image Trace Presets Importovat přednastavení vektorizace obrazu
Export Image Trace Presets Exportovat přednastavení vektorizace obrazu
Replace the saved presets that have these names? Nahradit uložená přednastavení s těmito názvy?
Method: Metoda:
Pad Prodloužit
Repeats Počet opakování
@@ -4318,6 +4326,13 @@ theme Appearance Motiv
Pen Tool Nástroj Pero
Quick Pen Tool Nástroj Rychlé pero
Quick Pen Rychlé pero
Quick Pen Toolbar Panel nástrojů rychlého pera
Continuous Arc Plynulý oblouk
Sharp Corner Arc Oblouk s ostrým rohem
Flip Arc Překlopit oblouk
Hide Toolbar Skrýt panel nástrojů
Pin Toolbar Position Připnout polohu panelu nástrojů
Reset Toolbar Position Obnovit polohu panelu nástrojů
Picas Pica
Portuguese Portugalština
Preserve Appearance and Overprints Zachovat vzhled a přetisky
@@ -4969,6 +4984,10 @@ font-technology Variable Variabilní
Cusp Hrot
Straight segment Přímý segment
Circle too large Kruh je příliš velký
Show Radii Zobrazit poloměry
Show Diameter Zobrazit průměr
Anchors at Standard Positions Kotevní body ve standardních polohách
Third Point by Dragging Třetí bod tažením
Clip to Art Oříznout podle kresby
Colorize Obarvit
Gamma Gama
@@ -6888,8 +6907,10 @@ mark-style Japanese Japonské
@msg `{GRAPHICS}` face must be front, back or side face v `{GRAPHICS}` musí být front, back nebo side
@msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} v `{GRAPHICS}` musí být číslo od {lo} do {hi}
@msg `{GRAPHICS}` must be an array `{GRAPHICS}` musí být pole
@msg Graphics map onto the Plane, Extrude and Revolve object types Grafika se mapuje na typy objektu Rovina, Vysunutí a Rotační těleso
@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafika se mapuje na typy objektu Rovina, Vysunutí, Rotační těleso a Nafouknutí
@msg Revolve maps graphics onto its side: map them onto the front Rotační těleso mapuje grafiku na svůj bok: umístěte ji na přední stranu
@msg Inflate maps graphics onto its front and back, not onto a side Nafouknutí mapuje grafiku na přední a zadní stranu, ne na bok
@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on objekt {_1}: zadní strana Nafouknutí přijímá grafiku jen se zapnutými volbami Obě strany a Uzávěr
@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafika je pro tento povrch příliš složitá: zjednodušte kresbu symbolů nebo snižte Segmenty
@msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` přijímá nejvýše {MAX_GRAPHICS} grafik
@msg A plane has one face: map its graphics onto the front Rovina má jednu stranu: umístěte její grafiku na přední stranu
@@ -10782,6 +10803,11 @@ breakText Glyphs Glyfy
Flower Květina
Tree Strom
Mountain Hora
Ornamental Ornamentální
Scrollwork Rozvilina
Filigree Arrow Filigránový šíp
Petal Sweep Tah okvětních lístků
Twin Curl Dvojitá rozvilina
Vector Packs Vektorové balíčky
Compass Rose Směrová růžice
Botanical Sprig Botanická větvička
Can't render this file because it is too large.
+27 -1
View File
@@ -461,8 +461,10 @@ liquify-list-end {0}, {1} {0} og {1}
@msg `{GRAPHICS}` face must be front, back or side `{GRAPHICS}`: face skal være front, back eller side
@msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}`: {key} skal være et tal fra {lo} til {hi}
@msg `{GRAPHICS}` must be an array `{GRAPHICS}` skal være et array
@msg Graphics map onto the Plane, Extrude and Revolve object types Grafik kortlægges på objekttyperne Plan, Ekstrudér og Omdrej
@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafik kortlægges på objekttyperne Plan, Ekstrudér, Omdrej og Pust op
@msg Revolve maps graphics onto its side: map them onto the front Omdrej kortlægger grafik på siden: kortlæg den på forsiden
@msg Inflate maps graphics onto its front and back, not onto a side Pust op kortlægger grafik på forsiden og bagsiden, ikke på en side
@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on objektet {_1}: bagsiden af Pust op tager kun imod grafik, når Begge sider og Kappe er slået til
@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafikken er for kompleks til denne overflade: forenkl symbolernes grafik, eller reducér Segmenter
@msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` tager højst {MAX_GRAPHICS} grafikelementer
@msg A plane has one face: map its graphics onto the front Et plan har én flade: kortlæg dets grafik på forsiden
@@ -3535,6 +3537,10 @@ liquify-list-end {0}, {1} {0} og {1}
Box Channel Kvadratets kanal
Color box Farvekvadrat
Color Wheel Options Indstillinger for farvehjul
Show Document Colors Vis dokumentfarver
Document Colors Dokumentfarver
Selection Colors Markeringens farver
@plural Used {n} time|Used {n} times Brugt {n} gang|Brugt {n} gange
Show Harmony Vis harmoni
Harmony Rule Harmoniregel
Harmony color Harmonifarve
@@ -4696,6 +4702,10 @@ digits Malayalam Malayalam
Rename Preset Omdøb forudindstilling
Save Image Trace Preset Gem forudindstilling til billedsporing
Delete Image Trace Preset Slet forudindstilling til billedsporing
Tracing Presets… Vektoriseringsforudindstillinger…
Import Image Trace Presets Importér forudindstillinger til billedsporing
Export Image Trace Presets Eksportér forudindstillinger til billedsporing
Replace the saved presets that have these names? Vil du erstatte de gemte forudindstillinger med disse navne?
Method: Metode:
Pad Forlæng
Repeats Gentagelser
@@ -6775,6 +6785,13 @@ theme Appearance Udseende
Pen Tool Pen-værktøj
Quick Pen Tool Hurtigpen-værktøj
Quick Pen Hurtigpen
Quick Pen Toolbar Hurtigpennens værktøjslinje
Continuous Arc Fortløbende bue
Sharp Corner Arc Bue med skarpt hjørne
Flip Arc Vend bue
Hide Toolbar Skjul værktøjslinjen
Pin Toolbar Position Fastgør værktøjslinjens placering
Reset Toolbar Position Nulstil værktøjslinjens placering
Picas Pica
Portuguese Portugisisk
Preserve Appearance and Overprints Bevar udseende og overprint
@@ -7415,6 +7432,10 @@ font-technology Variable Variable
Cusp Spids
Straight segment Lige segment
Circle too large Cirklen er for stor
Show Radii Vis radier
Show Diameter Vis diameter
Anchors at Standard Positions Ankerpunkter i standardpositioner
Third Point by Dragging Tredje punkt ved træk
Clip to Art Beskær til grafik
Colorize Farvelæg
Gamma Gamma
@@ -10844,6 +10865,11 @@ breakText Glyphs Glyffer
Flower Blomst
Tree Træ
Mountain Bjerg
Ornamental Ornamentik
Scrollwork Slyngværk
Filigree Arrow Filigranpil
Petal Sweep Kronbladssvirp
Twin Curl Dobbelt slyng
Vector Packs Vektorpakker
Compass Rose Kompasrose
Botanical Sprig Botanisk kvist
Can't render this file because it is too large.
+28 -1
View File
@@ -484,6 +484,11 @@ font-technology Variable Variabel
Cusp Spitze
Straight segment Gerades Segment
Circle too large Kreis zu groß
Show Radii Radien anzeigen
Show Diameter Durchmesser anzeigen
Anchors at Standard Positions Ankerpunkte an Standardpositionen
Third Point by Dragging Dritter Punkt durch Ziehen
Gray Grau
Classic Defaults Klassische Standardwerte
Clean Up… Aufräumen…
Clear Löschen
@@ -594,6 +599,10 @@ font-technology Variable Variabel
Box Channel Kanal des Quadrats
Color box Farbquadrat
Color Wheel Options Optionen für den Farbkreis
Show Document Colors Dokumentfarben einblenden
Document Colors Dokumentfarben
Selection Colors Farben der Auswahl
@plural Used {n} time|Used {n} times {n}-mal verwendet|{n}-mal verwendet
Show Harmony Harmonie einblenden
Harmony Rule Harmonieregel
Harmony color Harmoniefarbe
@@ -1908,6 +1917,10 @@ file-filter Templates Vorlagen
Rename Preset Vorgabe umbenennen
Save Image Trace Preset Bildnachzeichner-Vorgabe speichern
Delete Image Trace Preset Bildnachzeichner-Vorgabe löschen
Tracing Presets… Nachzeichnervorgaben…
Import Image Trace Presets Bildnachzeichner-Vorgaben importieren
Export Image Trace Presets Bildnachzeichner-Vorgaben exportieren
Replace the saved presets that have these names? Gespeicherte Vorgaben mit diesen Namen ersetzen?
Image Trace Presets Bildnachzeichner-Vorgaben
Image: Bild:
Images: Bilder:
@@ -2763,6 +2776,13 @@ file-filter Templates Vorlagen
Pen Tool Zeichenstift-Werkzeug
Quick Pen Tool Schnellzeichenstift-Werkzeug
Quick Pen Schnellzeichenstift
Quick Pen Toolbar Schnellzeichenstift-Werkzeugleiste
Continuous Arc Fortlaufender Bogen
Sharp Corner Arc Bogen mit scharfer Ecke
Flip Arc Bogen spiegeln
Hide Toolbar Werkzeugleiste ausblenden
Pin Toolbar Position Position der Werkzeugleiste fixieren
Reset Toolbar Position Position der Werkzeugleiste zurücksetzen
Pencil Buntstift
Pencil Tool Buntstift-Werkzeug
per slice pro Slice
@@ -6454,8 +6474,10 @@ lighting Light Licht
@msg `{GRAPHICS}` face must be front, back or side face in `{GRAPHICS}` muss front, back oder side sein
@msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} in `{GRAPHICS}` muss eine Zahl von {lo} bis {hi} sein
@msg `{GRAPHICS}` must be an array `{GRAPHICS}` muss ein Array sein
@msg Graphics map onto the Plane, Extrude and Revolve object types Grafiken werden auf die Objekttypen Ebene, Extrudieren und Kreiseln abgebildet
@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafiken werden auf die Objekttypen Ebene, Extrudieren, Kreiseln und Aufblasen abgebildet
@msg Revolve maps graphics onto its side: map them onto the front Kreiseln bildet Grafiken auf seiner Mantelfläche ab: Bilden Sie sie auf der Vorderseite ab
@msg Inflate maps graphics onto its front and back, not onto a side Aufblasen bildet Grafiken auf der Vorder- und Rückseite ab, nicht auf einer Seitenfläche
@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on Objekt {_1}: Die Rückseite von „Aufblasen“ nimmt Grafiken nur mit aktivierten Optionen „Beidseitig“ und „Deckflächen“ auf
@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Die Grafiken sind für diese Oberfläche zu komplex: Vereinfachen Sie das Bildmaterial der Symbole oder verringern Sie Segmente
@msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` nimmt höchstens {MAX_GRAPHICS} Grafiken auf
@msg A plane has one face: map its graphics onto the front Eine Ebene hat nur eine Seite: Bilden Sie ihre Grafiken auf der Vorderseite ab
@@ -10423,6 +10445,11 @@ breakText Glyphs Glyphen
Flower Blume
Tree Baum
Mountain Berg
Ornamental Ornamental
Scrollwork Schnörkel
Filigree Arrow Filigranpfeil
Petal Sweep Blütenblattschwung
Twin Curl Doppelschnörkel
Vector Packs Vektorpakete
Compass Rose Kompassrose
Botanical Sprig Botanischer Zweig
Can't render this file because it is too large.
+27 -1
View File
@@ -477,6 +477,10 @@ font-technology Variable Μεταβλητές
Cusp Ακίδα
Straight segment Ευθύ τμήμα
Circle too large Ο κύκλος είναι πολύ μεγάλος
Show Radii Εμφάνιση ακτίνων
Show Diameter Εμφάνιση διαμέτρου
Anchors at Standard Positions Σημεία αγκύρωσης σε τυπικές θέσεις
Third Point by Dragging Τρίτο σημείο με σύρσιμο
Classic Defaults Κλασικές προεπιλογές
Clean Up… Εκκαθάριση…
Clear Εκκαθάριση
@@ -569,6 +573,10 @@ font-technology Variable Μεταβλητές
Box Channel Κανάλι τετραγώνου
Color box Τετράγωνο χρώματος
Color Wheel Options Επιλογές χρωματικού τροχού
Show Document Colors Εμφάνιση χρωμάτων εγγράφου
Document Colors Χρώματα εγγράφου
Selection Colors Χρώματα επιλογής
@plural Used {n} time|Used {n} times Χρησιμοποιείται {n} φορά|Χρησιμοποιείται {n} φορές
Show Harmony Εμφάνιση αρμονίας
Harmony Rule Κανόνας χρωματικής αρμονίας
Harmony color Χρώμα αρμονίας
@@ -1817,6 +1825,10 @@ font-technology Variable Μεταβλητές
Rename Preset Μετονομασία προεπιλογής
Save Image Trace Preset Αποθήκευση προεπιλογής ανίχνευσης περιγραμμάτων εικόνας
Delete Image Trace Preset Διαγραφή προεπιλογής ανίχνευσης περιγραμμάτων εικόνας
Tracing Presets… Προεπιλογές ανίχνευσης περιγραμμάτων…
Import Image Trace Presets Εισαγωγή προεπιλογών ανίχνευσης περιγραμμάτων εικόνας
Export Image Trace Presets Εξαγωγή προεπιλογών ανίχνευσης περιγραμμάτων εικόνας
Replace the saved presets that have these names? Αντικατάσταση των αποθηκευμένων προεπιλογών με αυτά τα ονόματα;
Image Trace Presets Προεπιλογές ανίχνευσης περιγραμμάτων εικόνας
Image: Εικόνα:
Images: Εικόνες:
@@ -2168,6 +2180,13 @@ font-technology Variable Μεταβλητές
Pen Tool Πένα (Pen Tool)
Quick Pen Tool Εργαλείο γρήγορης πένας
Quick Pen Γρήγορη πένα
Quick Pen Toolbar Γραμμή εργαλείων γρήγορης πένας
Continuous Arc Συνεχές τόξο
Sharp Corner Arc Τόξο με αιχμηρή γωνία
Flip Arc Αναστροφή τόξου
Hide Toolbar Απόκρυψη γραμμής εργαλείων
Pin Toolbar Position Σταθεροποίηση θέσης γραμμής εργαλείων
Reset Toolbar Position Επαναφορά θέσης γραμμής εργαλείων
Pencil Μολύβι
Pencil Tool Μολύβι (Pencil Tool)
Percent: Ποσοστό:
@@ -6271,8 +6290,10 @@ variable-list-end {0}, {1} {0} και {1}
@msg `{GRAPHICS}` face must be front, back or side το face του `{GRAPHICS}` πρέπει να είναι front, back ή side
@msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} το {key} του `{GRAPHICS}` πρέπει να είναι αριθμός από {lo} έως {hi}
@msg `{GRAPHICS}` must be an array το `{GRAPHICS}` πρέπει να είναι πίνακας
@msg Graphics map onto the Plane, Extrude and Revolve object types Τα γραφικά αντιστοιχίζονται στους τύπους αντικειμένου Επίπεδο, Εξώθηση και Περιστροφή γύρω από άξονα
@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Τα γραφικά αντιστοιχίζονται στους τύπους αντικειμένου Επίπεδο, Εξώθηση, Περιστροφή γύρω από άξονα και Φούσκωμα
@msg Revolve maps graphics onto its side: map them onto the front Η Περιστροφή γύρω από άξονα αντιστοιχίζει τα γραφικά στην πλευρική της επιφάνεια: αντιστοιχίστε τα στην μπροστινή όψη
@msg Inflate maps graphics onto its front and back, not onto a side Το Φούσκωμα αντιστοιχίζει τα γραφικά στην μπροστινή και την πίσω όψη, όχι σε πλευρική επιφάνεια
@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on το αντικείμενο {_1}: η πίσω όψη του Φουσκώματος δέχεται γραφικά μόνο με ενεργά τα Και οι δύο πλευρές και Κλείσιμο άκρου
@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Τα γραφικά είναι πολύ σύνθετα για αυτή την επιφάνεια: απλοποιήστε το σχέδιο των συμβόλων ή μειώστε τα Τμήματα
@msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics το `{GRAPHICS}` δέχεται το πολύ {MAX_GRAPHICS} γραφικά
@msg A plane has one face: map its graphics onto the front Ένα επίπεδο έχει μία όψη: αντιστοιχίστε τα γραφικά του στην μπροστινή όψη
@@ -8931,6 +8952,11 @@ breakText Glyphs Γλύφοι
Flower Λουλούδι
Tree Δέντρο
Mountain Βουνό
Ornamental Διακοσμητικά μοτίβα
Scrollwork Σπείρα
Filigree Arrow Φιλιγκράν βέλος
Petal Sweep Καμπύλη πετάλων
Twin Curl Διπλή σπείρα
Vector Packs Διανυσματικά πακέτα
Compass Rose Ρόδο πυξίδας
Botanical Sprig Βοτανικό κλαδάκι
Can't render this file because it is too large.
+28 -2
View File
@@ -507,6 +507,10 @@ font-technology Variable Variables
Cusp Cúspide
Straight segment Segmento recto
Circle too large Círculo demasiado grande
Show Radii Mostrar radios
Show Diameter Mostrar diámetro
Anchors at Standard Positions Puntos de ancla en posiciones estándar
Third Point by Dragging Tercer punto arrastrando
Classic Defaults Valores predeterminados clásicos
Clean Up… Limpiar…
Clear Borrar
@@ -614,6 +618,10 @@ font-technology Variable Variables
Box Channel Canal del cuadro
Color box Cuadro de color
Color Wheel Options Opciones de la rueda de color
Show Document Colors Mostrar colores del documento
Document Colors Colores del documento
Selection Colors Colores de la selección
@plural Used {n} time|Used {n} times Usado {n} vez|Usado {n} veces
Show Harmony Mostrar armonía
Harmony Rule Regla de armonía
Harmony color Color de la armonía
@@ -1909,6 +1917,10 @@ font-technology Variable Variables
Rename Preset Cambiar nombre del preajuste
Save Image Trace Preset Guardar preajuste de calco de imagen
Delete Image Trace Preset Eliminar preajuste de calco de imagen
Tracing Presets… Preajustes de calco…
Import Image Trace Presets Importar preajustes de calco de imagen
Export Image Trace Presets Exportar preajustes de calco de imagen
Replace the saved presets that have these names? ¿Reemplazar los preajustes guardados que tienen estos nombres?
Image Trace Presets Preajustes de calco de imagen
Image: Imagen:
Images: Imágenes:
@@ -2805,6 +2817,13 @@ font-technology Variable Variables
Pen Tool Herramienta Pluma
Quick Pen Tool Herramienta Pluma rápida
Quick Pen Pluma rápida
Quick Pen Toolbar Barra de herramientas de Pluma rápida
Continuous Arc Arco continuo
Sharp Corner Arc Arco de esquina aguda
Flip Arc Voltear arco
Hide Toolbar Ocultar barra de herramientas
Pin Toolbar Position Fijar posición de la barra de herramientas
Reset Toolbar Position Restablecer posición de la barra de herramientas
Pencil Lápiz
Pencil Tool Herramienta Lápiz
per slice por sector
@@ -6861,9 +6880,11 @@ mark-style Japanese Japonesas
@msg `{GRAPHICS}` face must be front, back or side face de `{GRAPHICS}` debe ser front, back o side
@msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} de `{GRAPHICS}` debe ser un número de {lo} a {hi}
@msg `{GRAPHICS}` must be an array `{GRAPHICS}` debe ser una matriz
@msg Graphics map onto the Plane, Extrude and Revolve object types Los gráficos se asignan a los tipos de objeto Plano, Extrusión y Revolución
Graphics map onto the Plane, Extrude and Revolve object types. Los gráficos se asignan a los tipos de objeto Plano, Extrusión y Revolución.
@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Los gráficos se asignan a los tipos de objeto Plano, Extrusión, Revolución e Inflar
Graphics map onto the Plane, Extrude, Revolve and Inflate object types. Los gráficos se asignan a los tipos de objeto Plano, Extrusión, Revolución e Inflar.
@msg Revolve maps graphics onto its side: map them onto the front Revolución asigna los gráficos a su lateral: asígnelos a la cara frontal
@msg Inflate maps graphics onto its front and back, not onto a side Inflar asigna los gráficos a la cara frontal y a la posterior, no a un lateral
@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on el objeto {_1}: la cara posterior de Inflar admite gráficos solo con Ambos lados y Tapa activados
@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Los gráficos son demasiado complejos para esta superficie: simplifique la ilustración de los símbolos o reduzca Segmentos
@msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` admite como máximo {MAX_GRAPHICS} gráficos
@msg A plane has one face: map its graphics onto the front Un plano tiene una sola cara: asigne sus gráficos a la cara frontal
@@ -10675,6 +10696,11 @@ breakText Glyphs Glifos
Flower Flor
Tree Árbol
Mountain Montaña
Ornamental Ornamental
Scrollwork Voluta
Filigree Arrow Flecha de filigrana
Petal Sweep Trazo de pétalos
Twin Curl Voluta doble
Vector Packs Paquetes vectoriales
Compass Rose Rosa de los vientos
Botanical Sprig Ramita botánica
Can't render this file because it is too large.
+27 -1
View File
@@ -821,6 +821,10 @@
Box Channel Ruudun kanava
Color box Väriruutu
Color Wheel Options Väriympyrän asetukset
Show Document Colors Näytä asiakirjan värit
Document Colors Asiakirjan värit
Selection Colors Valinnan värit
@plural Used {n} time|Used {n} times Käytetty {n} kerran|Käytetty {n} kertaa
Show Harmony Näytä harmonia
Harmony Rule Harmoniasääntö
Harmony color Harmonian väri
@@ -2097,6 +2101,10 @@ digits Malayalam Malajalam
Rename Preset Nimeä esiasetus uudelleen
Save Image Trace Preset Tallenna kuvan jäljityksen esiasetus
Delete Image Trace Preset Poista kuvan jäljityksen esiasetus
Tracing Presets… Jäljityksen esiasetukset…
Import Image Trace Presets Tuo kuvan jäljityksen esiasetukset
Export Image Trace Presets Vie kuvan jäljityksen esiasetukset
Replace the saved presets that have these names? Korvataanko tallennetut esiasetukset, joilla on nämä nimet?
Method: Menetelmä:
Pad Jatka
Repeats Toistokerrat
@@ -4235,6 +4243,13 @@ theme Appearance Ulkoasu
Pen Tool Kynätyökalu
Quick Pen Tool Pikakynätyökalu
Quick Pen Pikakynä
Quick Pen Toolbar Pikakynän työkalurivi
Continuous Arc Jatkuva kaari
Sharp Corner Arc Terävän kulman kaari
Flip Arc Käännä kaari
Hide Toolbar Piilota työkalurivi
Pin Toolbar Position Kiinnitä työkalurivin sijainti
Reset Toolbar Position Palauta työkalurivin sijainti
Picas Picat
Portuguese Portugali
Preserve Appearance and Overprints Säilytä ulkoasu ja päällepainatukset
@@ -4879,6 +4894,10 @@ font-technology Variable Muuttuvat
Cusp Kärki
Straight segment Suora segmentti
Circle too large Ympyrä on liian suuri
Show Radii Näytä säteet
Show Diameter Näytä halkaisija
Anchors at Standard Positions Ankkuripisteet vakiokohdissa
Third Point by Dragging Kolmas piste vetämällä
Clip to Art Rajaa kuvitukseen
Colorize Väritä
Gamma Gamma
@@ -6789,8 +6808,10 @@ mark-style Japanese Japanilainen
@msg `{GRAPHICS}` face must be front, back or side `{GRAPHICS}`-kohteen face-arvon on oltava front, back tai side
@msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}`-kohteen {key}-arvon on oltava luku, joka on vähintään {lo} ja enintään {hi}
@msg `{GRAPHICS}` must be an array `{GRAPHICS}` on oltava taulukko
@msg Graphics map onto the Plane, Extrude and Revolve object types Grafiikat sijoitetaan objektityypeille Taso, Pursota ja Pyöräytä
@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafiikat sijoitetaan objektityypeille Taso, Pursota, Pyöräytä ja Täytä ilmalla
@msg Revolve maps graphics onto its side: map them onto the front Pyöräytä sijoittaa grafiikat kylkeensä: sijoita ne etupuolelle
@msg Inflate maps graphics onto its front and back, not onto a side Täytä ilmalla sijoittaa grafiikat etu- ja takapuolelle, ei kylkeen
@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on objekti {_1}: Täytä ilmalla -tehosteen takapuoli ottaa grafiikoita vain, kun Molemmat puolet ja Pääty ovat käytössä
@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafiikat ovat liian monimutkaisia tälle pinnalle: yksinkertaista symbolien kuvitusta tai pienennä Segmentit-arvoa
@msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` hyväksyy enintään {MAX_GRAPHICS} grafiikkaa
@msg A plane has one face: map its graphics onto the front Tasolla on yksi puoli: sijoita sen grafiikat etupuolelle
@@ -9014,6 +9035,11 @@ breakText Glyphs Merkit
Flower Kukka
Tree Puu
Mountain Vuori
Ornamental Koristekuviot
Scrollwork Kiemura
Filigree Arrow Filigraanin nuoli
Petal Sweep Terälehtipyyhkäisy
Twin Curl Kaksoiskiemura
Vector Packs Vektoripaketit
Compass Rose Kompassiruusu
Botanical Sprig Kasvinoksa
Can't render this file because it is too large.
+27 -1
View File
@@ -508,6 +508,10 @@ font-technology Variable Variables
Cusp Point de rebroussement
Straight segment Segment droit
Circle too large Cercle trop grand
Show Radii Afficher les rayons
Show Diameter Afficher le diamètre
Anchors at Standard Positions Points d’ancrage aux positions standard
Third Point by Dragging Troisième point par glissement
Classic Defaults Valeurs par défaut classiques
Clean Up… Nettoyer…
Clear Effacer
@@ -615,6 +619,10 @@ font-technology Variable Variables
Box Channel Couche du carré
Color box Carré de couleur
Color Wheel Options Options de la roue chromatique
Show Document Colors Afficher les couleurs du document
Document Colors Couleurs du document
Selection Colors Couleurs de la sélection
@plural Used {n} time|Used {n} times Utilisée {n} fois|Utilisée {n} fois
Show Harmony Afficher l’harmonie
Harmony Rule Règle d’harmonie
Harmony color Couleur de l’harmonie
@@ -1899,6 +1907,10 @@ font-technology Variable Variables
Rename Preset Renommer le paramètre prédéfini
Save Image Trace Preset Enregistrer le paramètre prédéfini de vectorisation de l’image
Delete Image Trace Preset Supprimer le paramètre prédéfini de vectorisation de l’image
Tracing Presets… Paramètres prédéfinis de vectorisation…
Import Image Trace Presets Importer des paramètres prédéfinis de vectorisation de l’image
Export Image Trace Presets Exporter les paramètres prédéfinis de vectorisation de l’image
Replace the saved presets that have these names? Remplacer les paramètres prédéfinis enregistrés qui portent ces noms ?
Image Trace Presets Paramètres prédéfinis de vectorisation de l’image
Image: Image :
Images: Images :
@@ -2793,6 +2805,13 @@ font-technology Variable Variables
Pen Tool Outil Plume
Quick Pen Tool Outil Plume rapide
Quick Pen Plume rapide
Quick Pen Toolbar Barre d’outils Plume rapide
Continuous Arc Arc continu
Sharp Corner Arc Arc à angle vif
Flip Arc Retourner l’arc
Hide Toolbar Masquer la barre d’outils
Pin Toolbar Position Épingler la position de la barre d’outils
Reset Toolbar Position Réinitialiser la position de la barre d’outils
Pencil Crayon
Pencil Tool Outil Crayon
per slice par tranche
@@ -6454,8 +6473,10 @@ lighting Light Lumière
@msg `{GRAPHICS}` face must be front or back face de `{GRAPHICS}` doit valoir front ou back
@msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} de `{GRAPHICS}` doit être un nombre de {lo} à {hi}
@msg `{GRAPHICS}` must be an array `{GRAPHICS}` doit être un tableau
@msg Graphics map onto the Plane, Extrude and Revolve object types Les graphiques s’appliquent aux types d’objet Plan, Extrusion et Révolution
@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Les graphiques s’appliquent aux types d’objet Plan, Extrusion, Révolution et Gonfler
@msg Revolve maps graphics onto its side: map them onto the front Révolution applique les graphiques sur sa face latérale : appliquez-les sur la face avant
@msg Inflate maps graphics onto its front and back, not onto a side Gonfler applique les graphiques sur la face avant et l’arrière, pas sur une face latérale
@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on objet {_1} : l’arrière de Gonfler n’accepte des graphiques qu’avec Deux côtés et Fermeture activés
@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Les graphiques sont trop complexes pour cette surface : simplifiez l’illustration des symboles ou réduisez Segments
@msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` accepte au plus {MAX_GRAPHICS} graphiques
@msg A plane has one face: map its graphics onto the front Un plan n’a qu’une face : appliquez ses graphiques sur la face avant
@@ -10745,6 +10766,11 @@ breakText Glyphs Glyphes
Flower Fleur
Tree Arbre
Mountain Montagne
Ornamental Ornemental
Scrollwork Volute
Filigree Arrow Flèche filigrane
Petal Sweep Courbe de pétales
Twin Curl Double volute
Vector Packs Packs vectoriels
Compass Rose Rose des vents
Botanical Sprig Rameau botanique
Can't render this file because it is too large.
+22 -1
View File
@@ -606,6 +606,11 @@
Circle વર્તુળ
Circle Tool વર્તુળ ટૂલ
Circle too large વર્તુળ ખૂબ મોટું છે
Show Radii ત્રિજ્યાઓ બતાવો
Show Diameter વ્યાસ બતાવો
Anchors at Standard Positions પ્રમાણભૂત સ્થાનો પર એન્કર બિંદુઓ
Third Point by Dragging ખેંચીને ત્રીજું બિંદુ
Gray રાખોડી
Circle: વર્તુળ:
Classic ક્લાસિક
Clean Up સાફ કરો
@@ -2818,6 +2823,13 @@
Pen Tool પેન ટૂલ
Quick Pen Tool ક્વિક પેન ટૂલ
Quick Pen ક્વિક પેન
Quick Pen Toolbar ક્વિક પેન ટૂલબાર
Continuous Arc સતત આર્ક
Sharp Corner Arc તીક્ષ્ણ ખૂણાવાળો આર્ક
Flip Arc આર્ક ફ્લિપ કરો
Hide Toolbar ટૂલબાર છુપાવો
Pin Toolbar Position ટૂલબાર સ્થિતિ પિન કરો
Reset Toolbar Position ટૂલબાર સ્થિતિ રીસેટ કરો
Pencil પેન્સિલ
Pencil Tool પેન્સિલ ટૂલ
Percent: ટકા:
@@ -4820,6 +4832,10 @@ arrowhead Feather પીંછું
Box Channel બૉક્સ ચેનલ
Color box રંગ બૉક્સ
Color Wheel Options રંગ વ્હીલ વિકલ્પો
Show Document Colors દસ્તાવેજના રંગો બતાવો
Document Colors દસ્તાવેજના રંગો
Selection Colors પસંદગીના રંગો
@plural Used {n} time|Used {n} times {n} વાર વપરાયો|{n} વાર વપરાયો
Show Harmony હાર્મની બતાવો
Harmony Rule હાર્મની નિયમ
Harmony color હાર્મની રંગ
@@ -5218,7 +5234,7 @@ antiAlias Sharp શાર્પ
Align On: આના પર સંરેખિત કરો:
Delete Tab ટૅબ કાઢી નાખો
Face સપાટી
Graphics map onto the Plane, Extrude and Revolve object types. ગ્રાફિક્સને Plane, Extrude અને Revolve પ્રકારના ઑબ્જેક્ટ્સ પર મેપ કરી શકાય છે.
Graphics map onto the Plane, Extrude, Revolve and Inflate object types. ગ્રાફિક્સને Plane, Extrude, Revolve અને Inflate પ્રકારના ઑબ્જેક્ટ્સ પર મેપ કરી શકાય છે.
Justify with last line aligned center છેલ્લી લાઇન મધ્યમાં રાખીને જસ્ટિફાઇ કરો
Justify with last line aligned right છેલ્લી લાઇન જમણે રાખીને જસ્ટિફાઇ કરો
Leader: લીડર:
@@ -5657,6 +5673,11 @@ swatch [Registration] [રજિસ્ટ્રેશન]
Flower ફૂલ
Tree વૃક્ષ
Mountain પર્વત
Ornamental અલંકારિક
Scrollwork વળાંકવાળી સજાવટ
Filigree Arrow નાજુક કોતરણીવાળું તીર
Petal Sweep પાંખડીઓનો વળાંક
Twin Curl બેવડો વળાંક
Vector Packs વેક્ટર પૅક
Compass Rose દિશાસૂચક ગુલાબ
Botanical Sprig વનસ્પતિ ડાળી
Can't render this file because it contains an unexpected character in line 72 and column 5.
+27 -1
View File
@@ -1108,6 +1108,10 @@ arrowhead Feather पंख
Cusp नुकीला बिंदु
Straight segment सीधा सेगमेंट
Circle too large वृत्त बहुत बड़ा है
Show Radii त्रिज्याएँ दिखाएँ
Show Diameter व्यास दिखाएँ
Anchors at Standard Positions मानक स्थानों पर एंकर पॉइंट्स
Third Point by Dragging खींचकर तीसरा बिंदु
Circle (open) सर्किल (ओपन)
Circle: वृत्त:
Classic क्लासिक
@@ -1277,6 +1281,10 @@ arrowhead Feather पंख
Box Channel बॉक्स चैनल
Color box कलर बॉक्स
Color Wheel Options कलर व्हील ऑप्शन्स
Show Document Colors डॉक्यूमेंट के रंग दिखाएँ
Document Colors डॉक्यूमेंट के रंग
Selection Colors चयन के रंग
@plural Used {n} time|Used {n} times {n} बार उपयोग किया गया|{n} बार उपयोग किया गया
Show Harmony सद्भाव दिखाएँ
Harmony Rule सद्भाव नियम
Harmony color सद्भाव रंग
@@ -1641,6 +1649,10 @@ arrowhead Feather पंख
Delete Guide गाइड हटाएँ
Delete Guides गाइड्स हटाएँ
Delete Image Trace Preset डिलीट इमेज ट्रेस प्रीसेट
Tracing Presets… ट्रेसिंग प्रीसेट…
Import Image Trace Presets आयात इमेज ट्रेस प्रीसेट्स
Export Image Trace Presets निर्यात इमेज ट्रेस प्रीसेट्स
Replace the saved presets that have these names? इन नामों वाले सेव किए गए प्रीसेट बदलें?
Delete Instances इंस्टेंस हटाएँ
Delete Layer लेयर हटाएँ
Delete Library लाइब्रेरी हटाएँ
@@ -4005,6 +4017,13 @@ arrowhead Feather पंख
Pen Tool पेन टूल
Quick Pen Tool क्विक पेन टूल
Quick Pen क्विक पेन
Quick Pen Toolbar क्विक पेन टूलबार
Continuous Arc सतत आर्क
Sharp Corner Arc तीखे कोने वाला आर्क
Flip Arc आर्क पलटें
Hide Toolbar टूलबार छिपाएँ
Pin Toolbar Position टूलबार स्थिति पिन करें
Reset Toolbar Position टूलबार स्थिति रीसेट करें
Pencil पेंसिल
Pencil Tool पेंसिल टूल
Pentagram पेंटाग्राम
@@ -9203,8 +9222,10 @@ liquify-list-end {0}, {1} {0} और {1}
@msg `{GRAPHICS}` face must be front, back or side `{GRAPHICS}` का face, front, back या side होना चाहिए
@msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}` का {key}, {lo} से {hi} तक की संख्या होना चाहिए
@msg `{GRAPHICS}` must be an array `{GRAPHICS}` एक ऐरे होना चाहिए
@msg Graphics map onto the Plane, Extrude and Revolve object types ग्राफ़िक्स समतल, एक्सट्रूड और रिवॉल्व ऑब्जेक्ट प्रकारों पर लगते हैं
@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types ग्राफ़िक्स समतल, एक्सट्रूड, रिवॉल्व और फुलाएँ ऑब्जेक्ट प्रकारों पर लगते हैं
@msg Revolve maps graphics onto its side: map them onto the front रिवॉल्व ग्राफ़िक्स को अपनी बगल वाली सतह पर लगाता है: उन्हें सामने वाले फ़ेस पर लगाएँ
@msg Inflate maps graphics onto its front and back, not onto a side फुलाएँ ग्राफ़िक्स को सामने और पिछले फ़ेस पर लगाता है, बगल वाली सतह पर नहीं
@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on ऑब्जेक्ट {_1}: फुलाएँ का पिछला फ़ेस ग्राफ़िक्स तभी लेता है जब दोनों तरफ़ और कैप चालू हों
@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments ग्राफ़िक्स इस सतह के लिए बहुत जटिल हैं: सिंबल्स के आर्ट को सरल बनाएँ या सेगमेंट कम करें
@msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` अधिकतम {MAX_GRAPHICS} ग्राफ़िक्स लेता है
@msg A plane has one face: map its graphics onto the front समतल का एक ही फ़ेस होता है: उसके ग्राफ़िक्स को सामने वाले फ़ेस पर लगाएँ
@@ -10388,6 +10409,11 @@ theme Appearance अपीयरेंस
Flower फूल
Tree पेड़
Mountain पर्वत
Ornamental अलंकरण
Scrollwork अलंकारी घुमाव
Filigree Arrow जालीदार तीर
Petal Sweep पंखुड़ियों का घुमाव
Twin Curl दोहरा घुमाव
Vector Packs वेक्टर पैक
Compass Rose दिशासूचक गुलाब
Botanical Sprig वनस्पति टहनी
Can't render this file because it is too large.
Loaded 100 of 161 files, more files were not shown because too many files have changed in this diff. Show more