mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b1db3026a2 | ||
|
|
91c7236e10 | ||
|
|
fa686d5063 | ||
|
|
7d8f124539 | ||
|
|
78a1be4059 | ||
|
|
a7ed5fcf0f | ||
|
|
48fe21ebe3 | ||
|
|
0ab2f21e47 | ||
|
|
d73bd34750 | ||
|
|
4f999ea73b | ||
|
|
80f9dbb992 | ||
|
|
9fd1011e1e | ||
|
|
3d4d7d1058 | ||
|
|
401cf1419a | ||
|
|
369671dc41 | ||
|
|
fe505edeff | ||
|
|
63a8befe4b | ||
|
|
3e380b8cd7 | ||
|
|
634c30bebf | ||
|
|
1e912de804 | ||
|
|
ea9c44e003 | ||
|
|
6a28b82b91 |
No files matched your search
Generated
+161
-23
@@ -1226,6 +1226,7 @@ dependencies = [
|
|||||||
"kurbo",
|
"kurbo",
|
||||||
"log",
|
"log",
|
||||||
"lyon_geom",
|
"lyon_geom",
|
||||||
|
"math-parser",
|
||||||
"node-macro",
|
"node-macro",
|
||||||
"num-derive",
|
"num-derive",
|
||||||
"num-traits",
|
"num-traits",
|
||||||
@@ -1238,7 +1239,7 @@ dependencies = [
|
|||||||
"rustc-hash 2.1.3",
|
"rustc-hash 2.1.3",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"skrifa",
|
"skrifa 0.44.0",
|
||||||
"tinyvec",
|
"tinyvec",
|
||||||
"tsify",
|
"tsify",
|
||||||
"wasm-bindgen",
|
"wasm-bindgen",
|
||||||
@@ -2135,6 +2136,9 @@ name = "float-cmp"
|
|||||||
version = "0.9.0"
|
version = "0.9.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
|
checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
|
||||||
|
dependencies = [
|
||||||
|
"num-traits",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "fnv"
|
name = "fnv"
|
||||||
@@ -2154,6 +2158,15 @@ version = "0.2.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
|
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "font-types"
|
||||||
|
version = "0.11.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "5b38ad915f6dadd993ced50848a8291a543bd41ca62bc10740d5e64e2ab4cfd7"
|
||||||
|
dependencies = [
|
||||||
|
"bytemuck",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "font-types"
|
name = "font-types"
|
||||||
version = "0.12.7"
|
version = "0.12.7"
|
||||||
@@ -2195,7 +2208,7 @@ dependencies = [
|
|||||||
"linebender_resource_handle",
|
"linebender_resource_handle",
|
||||||
"memmap2",
|
"memmap2",
|
||||||
"parlance",
|
"parlance",
|
||||||
"read-fonts",
|
"read-fonts 0.41.0",
|
||||||
"smallvec",
|
"smallvec",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -2534,18 +2547,6 @@ dependencies = [
|
|||||||
"smallvec",
|
"smallvec",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "graph-text"
|
|
||||||
version = "0.0.0"
|
|
||||||
dependencies = [
|
|
||||||
"convert_case 0.12.0",
|
|
||||||
"core-types",
|
|
||||||
"glam",
|
|
||||||
"log",
|
|
||||||
"proc-macro2",
|
|
||||||
"syn 3.0.9",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "graphene-animation"
|
name = "graphene-animation"
|
||||||
version = "0.0.0"
|
version = "0.0.0"
|
||||||
@@ -2676,7 +2677,6 @@ dependencies = [
|
|||||||
"futures",
|
"futures",
|
||||||
"glam",
|
"glam",
|
||||||
"graph-craft",
|
"graph-craft",
|
||||||
"graph-text",
|
|
||||||
"graphene-application-io",
|
"graphene-application-io",
|
||||||
"graphene-canvas-utils",
|
"graphene-canvas-utils",
|
||||||
"graphene-core",
|
"graphene-core",
|
||||||
@@ -3052,7 +3052,7 @@ checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"bitflags 2.13.2",
|
"bitflags 2.13.2",
|
||||||
"bytemuck",
|
"bytemuck",
|
||||||
"read-fonts",
|
"read-fonts 0.41.0",
|
||||||
"smallvec",
|
"smallvec",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -3087,6 +3087,40 @@ dependencies = [
|
|||||||
"foldhash 0.2.0",
|
"foldhash 0.2.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "hayro-ccitt"
|
||||||
|
version = "0.5.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "adbed896e99325bc312778bb9c9c289d795d51c12775c44dd5e4352f679c7e46"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "hayro-jbig2"
|
||||||
|
version = "0.4.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "eb5c7f3a4eb551c2bb7fa16e268f728d4bc2a5c9b090554b8dc0ee2503fb5840"
|
||||||
|
dependencies = [
|
||||||
|
"hayro-ccitt",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "hayro-jpeg2000"
|
||||||
|
version = "0.5.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "6e5e5f2b3de970707fc22fd956d8f44211602939d5e4588603afa919cb7b3740"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "hayro-syntax"
|
||||||
|
version = "0.9.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a6ced8279487b029813f6cc05399099fa34df6fa23d8f7b0d41d972c49d5b30d"
|
||||||
|
dependencies = [
|
||||||
|
"hayro-jbig2",
|
||||||
|
"hayro-jpeg2000",
|
||||||
|
"rustc-hash 2.1.3",
|
||||||
|
"smallvec",
|
||||||
|
"zune-jpeg",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "heck"
|
name = "heck"
|
||||||
version = "0.5.0"
|
version = "0.5.0"
|
||||||
@@ -3440,6 +3474,12 @@ dependencies = [
|
|||||||
"quick-error",
|
"quick-error",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "imagesize"
|
||||||
|
version = "0.14.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "09e54e57b4c48b40f7aec75635392b12b3421fa26fe8b4332e63138ed278459c"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "imagesize"
|
name = "imagesize"
|
||||||
version = "0.15.0"
|
version = "0.15.0"
|
||||||
@@ -3812,6 +3852,33 @@ dependencies = [
|
|||||||
"libc",
|
"libc",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "krilla"
|
||||||
|
version = "0.8.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "27da593198b20eeba65caeb73c2bbeec3e53ab08fa549898312ce81c4fce5e33"
|
||||||
|
dependencies = [
|
||||||
|
"base64 0.22.1",
|
||||||
|
"bumpalo",
|
||||||
|
"flate2",
|
||||||
|
"float-cmp",
|
||||||
|
"gif",
|
||||||
|
"image-webp",
|
||||||
|
"imagesize 0.14.0",
|
||||||
|
"indexmap",
|
||||||
|
"pdf-writer",
|
||||||
|
"png 0.18.1",
|
||||||
|
"rustc-hash 2.1.3",
|
||||||
|
"siphasher",
|
||||||
|
"skrifa 0.42.1",
|
||||||
|
"smallvec",
|
||||||
|
"subsetter",
|
||||||
|
"tiny-skia-path",
|
||||||
|
"xmp-writer",
|
||||||
|
"yoke",
|
||||||
|
"zune-jpeg",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "kurbo"
|
name = "kurbo"
|
||||||
version = "0.13.1"
|
version = "0.13.1"
|
||||||
@@ -5045,7 +5112,7 @@ dependencies = [
|
|||||||
"parlance",
|
"parlance",
|
||||||
"parley_data",
|
"parley_data",
|
||||||
"parley_emoji",
|
"parley_emoji",
|
||||||
"skrifa",
|
"skrifa 0.44.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -5076,6 +5143,18 @@ dependencies = [
|
|||||||
"vector-types",
|
"vector-types",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "pdf-writer"
|
||||||
|
version = "0.15.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f5e456864a7a304047bff84977dc6fb162bd956475d40ba50b2dcecaada7f753"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags 2.13.2",
|
||||||
|
"itoa",
|
||||||
|
"memchr",
|
||||||
|
"ryu",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "peer-transport"
|
name = "peer-transport"
|
||||||
version = "0.0.0"
|
version = "0.0.0"
|
||||||
@@ -5878,6 +5957,16 @@ dependencies = [
|
|||||||
"yasna",
|
"yasna",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "read-fonts"
|
||||||
|
version = "0.39.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c4ed38b89c2c77ff968c524145ad65fb010f38af5c7a224b53b81d47ac2daa81"
|
||||||
|
dependencies = [
|
||||||
|
"bytemuck",
|
||||||
|
"font-types 0.11.3",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "read-fonts"
|
name = "read-fonts"
|
||||||
version = "0.41.0"
|
version = "0.41.0"
|
||||||
@@ -5885,7 +5974,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709"
|
checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bytemuck",
|
"bytemuck",
|
||||||
"font-types",
|
"font-types 0.12.7",
|
||||||
"once_cell",
|
"once_cell",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -6031,13 +6120,15 @@ dependencies = [
|
|||||||
"graphene-hash",
|
"graphene-hash",
|
||||||
"graphene-resource",
|
"graphene-resource",
|
||||||
"graphic-types",
|
"graphic-types",
|
||||||
|
"hayro-syntax",
|
||||||
|
"krilla",
|
||||||
"kurbo",
|
"kurbo",
|
||||||
"log",
|
"log",
|
||||||
"num-traits",
|
"num-traits",
|
||||||
"parley",
|
"parley",
|
||||||
"raster-kernels",
|
"raster-kernels",
|
||||||
"serde",
|
"serde",
|
||||||
"skrifa",
|
"skrifa 0.44.0",
|
||||||
"text-nodes",
|
"text-nodes",
|
||||||
"usvg",
|
"usvg",
|
||||||
"vector-types",
|
"vector-types",
|
||||||
@@ -6615,6 +6706,12 @@ version = "1.0.23"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ryu"
|
||||||
|
version = "1.0.23"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "same-file"
|
name = "same-file"
|
||||||
version = "1.0.6"
|
version = "1.0.6"
|
||||||
@@ -6976,6 +7073,16 @@ version = "1.0.4"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"
|
checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "skrifa"
|
||||||
|
version = "0.42.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0c34617370ae968efb7161bb2beb517d9084659aae19e24b89e3db25b46e4564"
|
||||||
|
dependencies = [
|
||||||
|
"bytemuck",
|
||||||
|
"read-fonts 0.39.2",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "skrifa"
|
name = "skrifa"
|
||||||
version = "0.44.0"
|
version = "0.44.0"
|
||||||
@@ -6983,7 +7090,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68"
|
checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bytemuck",
|
"bytemuck",
|
||||||
"read-fonts",
|
"read-fonts 0.41.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -7162,6 +7269,18 @@ version = "0.11.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
|
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "subsetter"
|
||||||
|
version = "0.2.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "38803281d1c23166c5ebcb455439a5d2afe711cc909cf88af72448c297756ad6"
|
||||||
|
dependencies = [
|
||||||
|
"kurbo",
|
||||||
|
"rustc-hash 2.1.3",
|
||||||
|
"skrifa 0.42.1",
|
||||||
|
"write-fonts",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "substring"
|
name = "substring"
|
||||||
version = "1.4.5"
|
version = "1.4.5"
|
||||||
@@ -7344,7 +7463,7 @@ dependencies = [
|
|||||||
"rand",
|
"rand",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"skrifa",
|
"skrifa 0.44.0",
|
||||||
"thiserror 2.0.21",
|
"thiserror 2.0.21",
|
||||||
"titlecase",
|
"titlecase",
|
||||||
"tsify",
|
"tsify",
|
||||||
@@ -7944,14 +8063,14 @@ dependencies = [
|
|||||||
"flate2",
|
"flate2",
|
||||||
"fontdb",
|
"fontdb",
|
||||||
"harfrust",
|
"harfrust",
|
||||||
"imagesize",
|
"imagesize 0.15.0",
|
||||||
"kurbo",
|
"kurbo",
|
||||||
"log",
|
"log",
|
||||||
"pico-args",
|
"pico-args",
|
||||||
"roxmltree 0.21.2",
|
"roxmltree 0.21.2",
|
||||||
"simplecss",
|
"simplecss",
|
||||||
"siphasher",
|
"siphasher",
|
||||||
"skrifa",
|
"skrifa 0.44.0",
|
||||||
"strict-num",
|
"strict-num",
|
||||||
"svgtypes",
|
"svgtypes",
|
||||||
"tiny-skia-path",
|
"tiny-skia-path",
|
||||||
@@ -9294,6 +9413,19 @@ dependencies = [
|
|||||||
"toml 0.5.11",
|
"toml 0.5.11",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "write-fonts"
|
||||||
|
version = "0.48.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "cb731d4c4d93eacc69a1ad2f270f905788a98e4a3438267bcafbe08d3431c8d8"
|
||||||
|
dependencies = [
|
||||||
|
"font-types 0.11.3",
|
||||||
|
"indexmap",
|
||||||
|
"kurbo",
|
||||||
|
"log",
|
||||||
|
"read-fonts 0.39.2",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "writeable"
|
name = "writeable"
|
||||||
version = "0.6.4"
|
version = "0.6.4"
|
||||||
@@ -9434,6 +9566,12 @@ version = "0.1.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
|
checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "xmp-writer"
|
||||||
|
version = "0.3.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "yansi"
|
name = "yansi"
|
||||||
version = "1.0.1"
|
version = "1.0.1"
|
||||||
|
|||||||
+2
-1
@@ -93,7 +93,6 @@ graphene-application-io = { path = "node-graph/libraries/application-io" }
|
|||||||
graphene-resource = { path = "node-graph/libraries/resources" }
|
graphene-resource = { path = "node-graph/libraries/resources" }
|
||||||
graphene-animation = { path = "node-graph/libraries/animation" }
|
graphene-animation = { path = "node-graph/libraries/animation" }
|
||||||
core-types = { path = "node-graph/libraries/core-types" }
|
core-types = { path = "node-graph/libraries/core-types" }
|
||||||
graph-text = { path = "node-graph/libraries/graph-text" }
|
|
||||||
raster-types = { path = "node-graph/libraries/raster-types" }
|
raster-types = { path = "node-graph/libraries/raster-types" }
|
||||||
vector-types = { path = "node-graph/libraries/vector-types" }
|
vector-types = { path = "node-graph/libraries/vector-types" }
|
||||||
graphic-types = { path = "node-graph/libraries/graphic-types" }
|
graphic-types = { path = "node-graph/libraries/graphic-types" }
|
||||||
@@ -224,6 +223,8 @@ skrifa = "0.44"
|
|||||||
polycool = "0.4"
|
polycool = "0.4"
|
||||||
color = "0.3"
|
color = "0.3"
|
||||||
# Linebender ecosystem (END)
|
# Linebender ecosystem (END)
|
||||||
|
krilla = { version = "0.8", default-features = false, features = ["raster-images"] }
|
||||||
|
hayro-syntax = { version = "0.9", default-features = false, features = ["std"] }
|
||||||
rand = { version = "0.10", default-features = false, features = ["std_rng"] }
|
rand = { version = "0.10", default-features = false, features = ["std_rng"] }
|
||||||
rand_chacha = "0.10"
|
rand_chacha = "0.10"
|
||||||
glam = { version = "0.34", default-features = false, features = [
|
glam = { version = "0.34", default-features = false, features = [
|
||||||
|
|||||||
@@ -57,6 +57,10 @@ pub mod network {
|
|||||||
pub const IMPORT_METADATA: &str = "ui::import_metadata";
|
pub const IMPORT_METADATA: &str = "ui::import_metadata";
|
||||||
pub const EXPORT_NAMES: &str = "ui::export_names";
|
pub const EXPORT_NAMES: &str = "ui::export_names";
|
||||||
pub const EXPORT_DESCRIPTIONS: &str = "ui::export_descriptions";
|
pub const EXPORT_DESCRIPTIONS: &str = "ui::export_descriptions";
|
||||||
|
|
||||||
|
/// How many pixels make an inch in the network's document, which sizes lengths typed in a physical unit. Absent where it
|
||||||
|
/// is the default, CSS's 96. Only the root network's applies.
|
||||||
|
pub const PIXELS_PER_INCH: &str = "pixels_per_inch";
|
||||||
}
|
}
|
||||||
|
|
||||||
pub mod delta {
|
pub mod delta {
|
||||||
|
|||||||
@@ -473,6 +473,12 @@ fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(
|
|||||||
.map_err(map_serialization_error(network::PINNED_ORDER))?;
|
.map_err(map_serialization_error(network::PINNED_ORDER))?;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if let Some(pixels_per_inch) = metadata.pixels_per_inch(location) {
|
||||||
|
attributes
|
||||||
|
.set_serialized(network::PIXELS_PER_INCH, &pixels_per_inch, timestamp)
|
||||||
|
.map_err(map_serialization_error(network::PIXELS_PER_INCH))?;
|
||||||
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -38,6 +38,8 @@ pub struct NetworkMetadataEntry {
|
|||||||
pub import_metadata: Vec<InputMetadataEntry>,
|
pub import_metadata: Vec<InputMetadataEntry>,
|
||||||
pub export_names: Vec<String>,
|
pub export_names: Vec<String>,
|
||||||
pub export_descriptions: Vec<String>,
|
pub export_descriptions: Vec<String>,
|
||||||
|
/// The document's pixels per inch, where it differs from the default.
|
||||||
|
pub pixels_per_inch: Option<f64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Editor metadata for one import of a subgraph. Mirrors `InputPersistentMetadata` but wraps strings in `Option` so
|
/// Editor metadata for one import of a subgraph. Mirrors `InputPersistentMetadata` but wraps strings in `Option` so
|
||||||
@@ -78,6 +80,11 @@ pub trait NodeMetadataSource {
|
|||||||
Vec::new()
|
Vec::new()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The network's pixels per inch, where it differs from the default.
|
||||||
|
fn pixels_per_inch(&self, _network: NetworkLocation) -> Option<f64> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
fn import_metadata(&self, _network: NetworkLocation) -> Vec<InputMetadataEntry> {
|
fn import_metadata(&self, _network: NetworkLocation) -> Vec<InputMetadataEntry> {
|
||||||
Vec::new()
|
Vec::new()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,9 +12,25 @@ use crate::{NetworkId, NodeMetadataSource, PeerId, Position, Registry, from_valu
|
|||||||
/// Note: This only works for complete networks with all inputs resolved.
|
/// Note: This only works for complete networks with all inputs resolved.
|
||||||
/// Test networks with Import inputs will fail compilation (which is expected).
|
/// Test networks with Import inputs will fail compilation (which is expected).
|
||||||
fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> {
|
fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> {
|
||||||
|
use graph_craft::document::value::TaggedValue;
|
||||||
|
|
||||||
let mut network = network.clone();
|
let mut network = network.clone();
|
||||||
network.inline_definitions().map_err(|e| format!("Inlining failed: {e}"))?;
|
network.inline_definitions().map_err(|e| format!("Inlining failed: {e}"))?;
|
||||||
|
|
||||||
|
// Nodes measuring in physical units read the document's resolution from the scope the runtime wraps every document in
|
||||||
|
let resolution_node = NodeId(u64::MAX);
|
||||||
|
network.nodes.insert(
|
||||||
|
resolution_node,
|
||||||
|
DocumentNode {
|
||||||
|
inputs: vec![NodeInput::value(TaggedValue::Number(core_types::units::DEFAULT_PIXELS_PER_INCH), false)],
|
||||||
|
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::PassthroughNode")),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
);
|
||||||
|
network
|
||||||
|
.scope_injections
|
||||||
|
.insert(core_types::units::PIXELS_PER_INCH_SCOPE.to_string(), (resolution_node, core_types::item!(f64)));
|
||||||
|
|
||||||
let compiler = Compiler {};
|
let compiler = Compiler {};
|
||||||
compiler.compile_single(network).map_err(|e| format!("Compilation failed: {:?}", e))?;
|
compiler.compile_single(network).map_err(|e| format!("Compilation failed: {:?}", e))?;
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
@@ -417,6 +417,7 @@ fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes,
|
|||||||
import_metadata: attributes.get_or_default(network::IMPORT_METADATA),
|
import_metadata: attributes.get_or_default(network::IMPORT_METADATA),
|
||||||
export_names: attributes.get_or_default(network::EXPORT_NAMES),
|
export_names: attributes.get_or_default(network::EXPORT_NAMES),
|
||||||
export_descriptions: attributes.get_or_default(network::EXPORT_DESCRIPTIONS),
|
export_descriptions: attributes.get_or_default(network::EXPORT_DESCRIPTIONS),
|
||||||
|
pixels_per_inch: attributes.get_typed(network::PIXELS_PER_INCH),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const RADIUS: usize = 1;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
Length(TypedLength),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLength {
|
||||||
|
value: f64,
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The radius is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||||
|
#[migration("blending_nodes::effects::BlurNode"@2 => @3)]
|
||||||
|
pub fn blur_v2(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let Some(slot) = node.inputs().get(RADIUS) else { return };
|
||||||
|
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||||
|
|
||||||
|
inputs.set(
|
||||||
|
RADIUS as u32,
|
||||||
|
literal(Tagged::Length(TypedLength {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&BlurV2, &contract());
|
||||||
|
check_undo(&BlurV2, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||||
|
let mut fixture = Fixture::new(&BlurV2);
|
||||||
|
let number = |number: f64| literal(Tagged::Number(number));
|
||||||
|
let blur = fixture.add(decl!("blending_nodes::effects::BlurNode"@2), vec![literal(Tagged::None), number(10.), number(0.), number(0.)]);
|
||||||
|
let migrated = fixture.migrate(&BlurV2).unwrap();
|
||||||
|
|
||||||
|
let radius = literal(Tagged::Length(TypedLength { value: 10., unit: LengthUnit::Pixel }));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, blur), [literal(Tagged::None), radius, number(0.), number(0.)]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
//! Migrations of the nodes in `blending_nodes`.
|
//! Migrations of the nodes in `blending_nodes`.
|
||||||
|
|
||||||
mod bevel_and_emboss_v1;
|
mod bevel_and_emboss_v1;
|
||||||
|
mod blur_v2;
|
||||||
mod drop_shadow_v1;
|
mod drop_shadow_v1;
|
||||||
mod inner_glow_v1;
|
mod inner_glow_v1;
|
||||||
mod inner_shadow_v1;
|
mod inner_shadow_v1;
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const DIAMETER: usize = 2;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
Length(TypedLength),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLength {
|
||||||
|
value: f64,
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The diameter is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||||
|
#[migration("brush_nodes::BrushStrokesNode"@1 => @2)]
|
||||||
|
pub fn brush_strokes_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let Some(slot) = node.inputs().get(DIAMETER) else { return };
|
||||||
|
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||||
|
|
||||||
|
inputs.set(
|
||||||
|
DIAMETER as u32,
|
||||||
|
literal(Tagged::Length(TypedLength {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(5, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&BrushStrokesV1, &contract());
|
||||||
|
check_undo(&BrushStrokesV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||||
|
let mut fixture = Fixture::new(&BrushStrokesV1);
|
||||||
|
let number = |number: f64| literal(Tagged::Number(number));
|
||||||
|
let brush_strokes = fixture.add(decl!("brush_nodes::BrushStrokesNode"@1), vec![literal(Tagged::None), number(0.), number(40.), number(0.), number(100.)]);
|
||||||
|
let migrated = fixture.migrate(&BrushStrokesV1).unwrap();
|
||||||
|
|
||||||
|
let diameter = literal(Tagged::Length(TypedLength { value: 40., unit: LengthUnit::Pixel }));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, brush_strokes), [literal(Tagged::None), number(0.), diameter, number(0.), number(100.)]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
//! Migrations of the nodes in `brush_nodes`.
|
||||||
|
|
||||||
|
mod brush_strokes_v1;
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const DISTANCE: usize = 1;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
Length(TypedLength),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLength {
|
||||||
|
value: f64,
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The distance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||||
|
#[migration("core_types::vector::BevelNode"@1 => @2)]
|
||||||
|
pub fn bevel_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let Some(slot) = node.inputs().get(DISTANCE) else { return };
|
||||||
|
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||||
|
|
||||||
|
inputs.set(
|
||||||
|
DISTANCE as u32,
|
||||||
|
literal(Tagged::Length(TypedLength {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&BevelV1, &contract());
|
||||||
|
check_undo(&BevelV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||||
|
let mut fixture = Fixture::new(&BevelV1);
|
||||||
|
let number = |number: f64| literal(Tagged::Number(number));
|
||||||
|
let bevel = fixture.add(decl!("core_types::vector::BevelNode"@1), vec![literal(Tagged::None), number(10.)]);
|
||||||
|
let migrated = fixture.migrate(&BevelV1).unwrap();
|
||||||
|
|
||||||
|
let distance = literal(Tagged::Length(TypedLength { value: 10., unit: LengthUnit::Pixel }));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, bevel), [literal(Tagged::None), distance]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const TOLERANCE: usize = 1;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
Length(TypedLength),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLength {
|
||||||
|
value: f64,
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The tolerance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||||
|
#[migration("core_types::vector::DecimateNode"@1 => @2)]
|
||||||
|
pub fn decimate_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let Some(slot) = node.inputs().get(TOLERANCE) else { return };
|
||||||
|
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||||
|
|
||||||
|
inputs.set(
|
||||||
|
TOLERANCE as u32,
|
||||||
|
literal(Tagged::Length(TypedLength {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&DecimateV1, &contract());
|
||||||
|
check_undo(&DecimateV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||||
|
let mut fixture = Fixture::new(&DecimateV1);
|
||||||
|
let number = |number: f64| literal(Tagged::Number(number));
|
||||||
|
let decimate = fixture.add(decl!("core_types::vector::DecimateNode"@1), vec![literal(Tagged::None), number(5.)]);
|
||||||
|
let migrated = fixture.migrate(&DecimateV1).unwrap();
|
||||||
|
|
||||||
|
let tolerance = literal(Tagged::Length(TypedLength { value: 5., unit: LengthUnit::Pixel }));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, decimate), [literal(Tagged::None), tolerance]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const DIRECTION: usize = 1;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
DVec2([f64; 2]),
|
||||||
|
LengthVec2(TypedLengthVec2),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLengthVec2 {
|
||||||
|
value: [f64; 2],
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The direction is a pair of lengths, which keeps the pixels it held. A wired Vec2 still feeds it, read as pixels.
|
||||||
|
#[migration("core_types::vector::ExtrudeNode"@1 => @2)]
|
||||||
|
pub fn extrude_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let Some(slot) = node.inputs().get(DIRECTION) else { return };
|
||||||
|
let Some(Tagged::DVec2(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||||
|
|
||||||
|
inputs.set(DIRECTION as u32, lengths(pixels));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lengths(pixels: [f64; 2]) -> NodeInput {
|
||||||
|
literal(Tagged::LengthVec2(TypedLengthVec2 {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(3, |random, slot| match slot {
|
||||||
|
DIRECTION => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
|
||||||
|
_ => literal(Tagged::None),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&ExtrudeV1, &contract());
|
||||||
|
check_undo(&ExtrudeV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_vec2_of_pixels_becomes_lengths_in_pixels() {
|
||||||
|
let mut fixture = Fixture::new(&ExtrudeV1);
|
||||||
|
let node = fixture.add(
|
||||||
|
decl!("core_types::vector::ExtrudeNode"@1),
|
||||||
|
vec![literal(Tagged::None), literal(Tagged::DVec2([30., 40.])), literal(Tagged::None)],
|
||||||
|
);
|
||||||
|
let migrated = fixture.migrate(&ExtrudeV1).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(fixture.inputs(&migrated, node), [literal(Tagged::None), lengths([30., 40.]), literal(Tagged::None)]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const MAX_DISTANCE: usize = 1;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
Length(TypedLength),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLength {
|
||||||
|
value: f64,
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The max distance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||||
|
#[migration("core_types::vector::JitterPointsNode"@1 => @2)]
|
||||||
|
pub fn jitter_points_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let Some(slot) = node.inputs().get(MAX_DISTANCE) else { return };
|
||||||
|
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||||
|
|
||||||
|
inputs.set(
|
||||||
|
MAX_DISTANCE as u32,
|
||||||
|
literal(Tagged::Length(TypedLength {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&JitterPointsV1, &contract());
|
||||||
|
check_undo(&JitterPointsV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||||
|
let mut fixture = Fixture::new(&JitterPointsV1);
|
||||||
|
let number = |number: f64| literal(Tagged::Number(number));
|
||||||
|
let jitter_points = fixture.add(decl!("core_types::vector::JitterPointsNode"@1), vec![literal(Tagged::None), number(5.), number(0.), number(1.)]);
|
||||||
|
let migrated = fixture.migrate(&JitterPointsV1).unwrap();
|
||||||
|
|
||||||
|
let max_distance = literal(Tagged::Length(TypedLength { value: 5., unit: LengthUnit::Pixel }));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, jitter_points), [literal(Tagged::None), max_distance, number(0.), number(1.)]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
//! Migrations of the nodes in `core_types`.
|
||||||
|
|
||||||
|
mod bevel_v1;
|
||||||
|
mod decimate_v1;
|
||||||
|
mod extrude_v1;
|
||||||
|
mod jitter_points_v1;
|
||||||
|
mod offset_path_v1;
|
||||||
|
mod offset_points_v1;
|
||||||
|
mod point_inside_v1;
|
||||||
|
mod round_corners_v1;
|
||||||
|
mod sample_polyline_v1;
|
||||||
|
mod scatter_points_v2;
|
||||||
|
mod simplify_v1;
|
||||||
|
mod weld_v1;
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const DISTANCE: usize = 1;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
Length(TypedLength),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLength {
|
||||||
|
value: f64,
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The distance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||||
|
#[migration("core_types::vector::OffsetPathNode"@1 => @2)]
|
||||||
|
pub fn offset_path_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let Some(slot) = node.inputs().get(DISTANCE) else { return };
|
||||||
|
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||||
|
|
||||||
|
inputs.set(
|
||||||
|
DISTANCE as u32,
|
||||||
|
literal(Tagged::Length(TypedLength {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&OffsetPathV1, &contract());
|
||||||
|
check_undo(&OffsetPathV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||||
|
let mut fixture = Fixture::new(&OffsetPathV1);
|
||||||
|
let number = |number: f64| literal(Tagged::Number(number));
|
||||||
|
let offset_path = fixture.add(decl!("core_types::vector::OffsetPathNode"@1), vec![literal(Tagged::None), number(10.), number(0.), number(4.)]);
|
||||||
|
let migrated = fixture.migrate(&OffsetPathV1).unwrap();
|
||||||
|
|
||||||
|
let distance = literal(Tagged::Length(TypedLength { value: 10., unit: LengthUnit::Pixel }));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, offset_path), [literal(Tagged::None), distance, number(0.), number(4.)]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const DISTANCE: usize = 1;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
Length(TypedLength),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLength {
|
||||||
|
value: f64,
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The distance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||||
|
#[migration("core_types::vector::OffsetPointsNode"@1 => @2)]
|
||||||
|
pub fn offset_points_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let Some(slot) = node.inputs().get(DISTANCE) else { return };
|
||||||
|
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||||
|
|
||||||
|
inputs.set(
|
||||||
|
DISTANCE as u32,
|
||||||
|
literal(Tagged::Length(TypedLength {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&OffsetPointsV1, &contract());
|
||||||
|
check_undo(&OffsetPointsV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||||
|
let mut fixture = Fixture::new(&OffsetPointsV1);
|
||||||
|
let number = |number: f64| literal(Tagged::Number(number));
|
||||||
|
let offset_points = fixture.add(decl!("core_types::vector::OffsetPointsNode"@1), vec![literal(Tagged::None), number(10.)]);
|
||||||
|
let migrated = fixture.migrate(&OffsetPointsV1).unwrap();
|
||||||
|
|
||||||
|
let distance = literal(Tagged::Length(TypedLength { value: 10., unit: LengthUnit::Pixel }));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, offset_points), [literal(Tagged::None), distance]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const POINT: usize = 1;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
DVec2([f64; 2]),
|
||||||
|
LengthVec2(TypedLengthVec2),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLengthVec2 {
|
||||||
|
value: [f64; 2],
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The point is a pair of lengths, which keeps the pixels it held. A wired Vec2 still feeds it, read as pixels.
|
||||||
|
#[migration("core_types::vector::PointInsideNode"@1 => @2)]
|
||||||
|
pub fn point_inside_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let Some(slot) = node.inputs().get(POINT) else { return };
|
||||||
|
let Some(Tagged::DVec2(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||||
|
|
||||||
|
inputs.set(POINT as u32, lengths(pixels));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lengths(pixels: [f64; 2]) -> NodeInput {
|
||||||
|
literal(Tagged::LengthVec2(TypedLengthVec2 {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(2, |random, slot| match slot {
|
||||||
|
POINT => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
|
||||||
|
_ => literal(Tagged::None),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&PointInsideV1, &contract());
|
||||||
|
check_undo(&PointInsideV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_vec2_of_pixels_becomes_lengths_in_pixels() {
|
||||||
|
let mut fixture = Fixture::new(&PointInsideV1);
|
||||||
|
let node = fixture.add(decl!("core_types::vector::PointInsideNode"@1), vec![literal(Tagged::None), literal(Tagged::DVec2([30., 40.]))]);
|
||||||
|
let migrated = fixture.migrate(&PointInsideV1).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(fixture.inputs(&migrated, node), [literal(Tagged::None), lengths([30., 40.])]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const RADIUS: usize = 1;
|
||||||
|
const MIN_ANGLE_THRESHOLD: usize = 4;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
Length(TypedLength),
|
||||||
|
Angle(TypedAngle),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLength {
|
||||||
|
value: f64,
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedAngle {
|
||||||
|
value: f64,
|
||||||
|
unit: AngleUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum AngleUnit {
|
||||||
|
Degree,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The radius is a length and the minimum angle threshold is an angle, which keep the numbers of pixels and degrees they held. Wired numbers still feed them, read as pixels and degrees.
|
||||||
|
#[migration("core_types::vector::RoundCornersNode"@1 => @2)]
|
||||||
|
pub fn round_corners_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||||
|
Some(Tagged::Number(number)) => Some(number),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Some(pixels) = number_at(RADIUS) {
|
||||||
|
inputs.set(RADIUS as u32, length(pixels));
|
||||||
|
}
|
||||||
|
if let Some(degrees) = number_at(MIN_ANGLE_THRESHOLD) {
|
||||||
|
inputs.set(MIN_ANGLE_THRESHOLD as u32, angle(degrees));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn length(pixels: f64) -> NodeInput {
|
||||||
|
literal(Tagged::Length(TypedLength {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn angle(degrees: f64) -> NodeInput {
|
||||||
|
literal(Tagged::Angle(TypedAngle {
|
||||||
|
value: degrees,
|
||||||
|
unit: AngleUnit::Degree,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(5, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&RoundCornersV1, &contract());
|
||||||
|
check_undo(&RoundCornersV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn numbers_of_pixels_and_degrees_become_a_length_and_an_angle() {
|
||||||
|
let mut fixture = Fixture::new(&RoundCornersV1);
|
||||||
|
let number = |number: f64| literal(Tagged::Number(number));
|
||||||
|
let round_corners = fixture.add(
|
||||||
|
decl!("core_types::vector::RoundCornersNode"@1),
|
||||||
|
vec![literal(Tagged::None), number(10.), number(0.5), number(100.), number(5.)],
|
||||||
|
);
|
||||||
|
let migrated = fixture.migrate(&RoundCornersV1).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(fixture.inputs(&migrated, round_corners), [literal(Tagged::None), length(10.), number(0.5), number(100.), angle(5.)]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const SEPARATION: usize = 2;
|
||||||
|
const START_OFFSET: usize = 4;
|
||||||
|
const STOP_OFFSET: usize = 5;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
Length(TypedLength),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLength {
|
||||||
|
value: f64,
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The separation and start and stop offsets are lengths, which keep the numbers of pixels they held. Wired numbers still feed them, read as pixels.
|
||||||
|
#[migration("core_types::vector::SamplePolylineNode"@1 => @2)]
|
||||||
|
pub fn sample_polyline_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||||
|
Some(Tagged::Number(number)) => Some(number),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
for slot in [SEPARATION, START_OFFSET, STOP_OFFSET] {
|
||||||
|
if let Some(pixels) = number_at(slot) {
|
||||||
|
inputs.set(slot as u32, length(pixels));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn length(pixels: f64) -> NodeInput {
|
||||||
|
literal(Tagged::Length(TypedLength {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(7, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&SamplePolylineV1, &contract());
|
||||||
|
check_undo(&SamplePolylineV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn numbers_of_pixels_become_lengths_in_pixels() {
|
||||||
|
let mut fixture = Fixture::new(&SamplePolylineV1);
|
||||||
|
let number = |number: f64| literal(Tagged::Number(number));
|
||||||
|
let sample_polyline = fixture.add(
|
||||||
|
decl!("core_types::vector::SamplePolylineNode"@1),
|
||||||
|
vec![literal(Tagged::None), number(0.), number(100.), number(100.), number(10.), number(20.), number(0.)],
|
||||||
|
);
|
||||||
|
let migrated = fixture.migrate(&SamplePolylineV1).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
fixture.inputs(&migrated, sample_polyline),
|
||||||
|
[literal(Tagged::None), number(0.), length(100.), number(100.), length(10.), length(20.), number(0.)]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const SEPARATION: usize = 1;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
Length(TypedLength),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLength {
|
||||||
|
value: f64,
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The separation is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||||
|
#[migration("core_types::vector::ScatterPointsNode"@2 => @3)]
|
||||||
|
pub fn scatter_points_v2(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let Some(slot) = node.inputs().get(SEPARATION) else { return };
|
||||||
|
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||||
|
|
||||||
|
inputs.set(
|
||||||
|
SEPARATION as u32,
|
||||||
|
literal(Tagged::Length(TypedLength {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(3, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&ScatterPointsV2, &contract());
|
||||||
|
check_undo(&ScatterPointsV2, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||||
|
let mut fixture = Fixture::new(&ScatterPointsV2);
|
||||||
|
let number = |number: f64| literal(Tagged::Number(number));
|
||||||
|
let scatter_points = fixture.add(decl!("core_types::vector::ScatterPointsNode"@2), vec![literal(Tagged::None), number(10.), number(0.)]);
|
||||||
|
let migrated = fixture.migrate(&ScatterPointsV2).unwrap();
|
||||||
|
|
||||||
|
let separation = literal(Tagged::Length(TypedLength { value: 10., unit: LengthUnit::Pixel }));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, scatter_points), [literal(Tagged::None), separation, number(0.)]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const TOLERANCE: usize = 1;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
Length(TypedLength),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLength {
|
||||||
|
value: f64,
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The tolerance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||||
|
#[migration("core_types::vector::SimplifyNode"@1 => @2)]
|
||||||
|
pub fn simplify_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let Some(slot) = node.inputs().get(TOLERANCE) else { return };
|
||||||
|
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||||
|
|
||||||
|
inputs.set(
|
||||||
|
TOLERANCE as u32,
|
||||||
|
literal(Tagged::Length(TypedLength {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&SimplifyV1, &contract());
|
||||||
|
check_undo(&SimplifyV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||||
|
let mut fixture = Fixture::new(&SimplifyV1);
|
||||||
|
let number = |number: f64| literal(Tagged::Number(number));
|
||||||
|
let simplify = fixture.add(decl!("core_types::vector::SimplifyNode"@1), vec![literal(Tagged::None), number(5.)]);
|
||||||
|
let migrated = fixture.migrate(&SimplifyV1).unwrap();
|
||||||
|
|
||||||
|
let tolerance = literal(Tagged::Length(TypedLength { value: 5., unit: LengthUnit::Pixel }));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, simplify), [literal(Tagged::None), tolerance]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const DISTANCE: usize = 1;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
Length(TypedLength),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLength {
|
||||||
|
value: f64,
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The distance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||||
|
#[migration("core_types::vector::WeldNode"@1 => @2)]
|
||||||
|
pub fn weld_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let Some(slot) = node.inputs().get(DISTANCE) else { return };
|
||||||
|
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||||
|
|
||||||
|
inputs.set(
|
||||||
|
DISTANCE as u32,
|
||||||
|
literal(Tagged::Length(TypedLength {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(3, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&WeldV1, &contract());
|
||||||
|
check_undo(&WeldV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||||
|
let mut fixture = Fixture::new(&WeldV1);
|
||||||
|
let number = |number: f64| literal(Tagged::Number(number));
|
||||||
|
let weld = fixture.add(decl!("core_types::vector::WeldNode"@1), vec![literal(Tagged::None), number(0.1), number(0.)]);
|
||||||
|
let migrated = fixture.migrate(&WeldV1).unwrap();
|
||||||
|
|
||||||
|
let distance = literal(Tagged::Length(TypedLength { value: 0.1, unit: LengthUnit::Pixel }));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, weld), [literal(Tagged::None), distance, number(0.)]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
//! Migrations of the nodes in `graphene_core`.
|
//! Migrations of the nodes in `graphene_core`.
|
||||||
|
|
||||||
|
mod pack_strips_v1;
|
||||||
mod passthrough_from_upload_texture_node;
|
mod passthrough_from_upload_texture_node;
|
||||||
mod renames;
|
mod renames;
|
||||||
|
mod stroke_v1;
|
||||||
mod vary_colors_from_assign_colors;
|
mod vary_colors_from_assign_colors;
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const SEPARATION: usize = 1;
|
||||||
|
const STRIP_MAX_LENGTH: usize = 2;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
Length(TypedLength),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLength {
|
||||||
|
value: f64,
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The separation and strip max length are lengths, which keep the numbers of pixels they held. Wired numbers still feed them, read as pixels.
|
||||||
|
#[migration("graphene_core::vector::PackStripsNode"@1 => @2)]
|
||||||
|
pub fn pack_strips_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||||
|
Some(Tagged::Number(number)) => Some(number),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
for slot in [SEPARATION, STRIP_MAX_LENGTH] {
|
||||||
|
if let Some(pixels) = number_at(slot) {
|
||||||
|
inputs.set(slot as u32, length(pixels));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn length(pixels: f64) -> NodeInput {
|
||||||
|
literal(Tagged::Length(TypedLength {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&PackStripsV1, &contract());
|
||||||
|
check_undo(&PackStripsV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn numbers_of_pixels_become_lengths_in_pixels() {
|
||||||
|
let mut fixture = Fixture::new(&PackStripsV1);
|
||||||
|
let number = |number: f64| literal(Tagged::Number(number));
|
||||||
|
let pack_strips = fixture.add(decl!("graphene_core::vector::PackStripsNode"@1), vec![literal(Tagged::None), number(10.), number(1000.), number(0.)]);
|
||||||
|
let migrated = fixture.migrate(&PackStripsV1).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(fixture.inputs(&migrated, pack_strips), [literal(Tagged::None), length(10.), length(1000.), number(0.)]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const WEIGHT: usize = 2;
|
||||||
|
const DASH_OFFSET: usize = 8;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
Length(TypedLength),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLength {
|
||||||
|
value: f64,
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The weight and dash offset are lengths, which keep the numbers of pixels they held. Wired numbers still feed them, read as pixels.
|
||||||
|
#[migration("graphene_core::vector::StrokeNode"@1 => @2)]
|
||||||
|
pub fn stroke_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||||
|
Some(Tagged::Number(number)) => Some(number),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
for slot in [WEIGHT, DASH_OFFSET] {
|
||||||
|
if let Some(pixels) = number_at(slot) {
|
||||||
|
inputs.set(slot as u32, length(pixels));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn length(pixels: f64) -> NodeInput {
|
||||||
|
literal(Tagged::Length(TypedLength {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(9, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&StrokeV1, &contract());
|
||||||
|
check_undo(&StrokeV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn numbers_of_pixels_become_lengths_in_pixels() {
|
||||||
|
let mut fixture = Fixture::new(&StrokeV1);
|
||||||
|
let number = |number: f64| literal(Tagged::Number(number));
|
||||||
|
let stroke = fixture.add(
|
||||||
|
decl!("graphene_core::vector::StrokeNode"@1),
|
||||||
|
vec![literal(Tagged::None), number(0.), number(2.), number(0.), number(0.), number(0.), number(4.), number(0.), number(5.)],
|
||||||
|
);
|
||||||
|
let migrated = fixture.migrate(&StrokeV1).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
fixture.inputs(&migrated, stroke),
|
||||||
|
[literal(Tagged::None), number(0.), length(2.), number(0.), number(0.), number(0.), number(4.), number(0.), length(5.)]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
//! Migrations of the nodes in `graphene_std`.
|
//! Migrations of the nodes in `graphene_std`.
|
||||||
|
|
||||||
mod renames;
|
mod renames;
|
||||||
|
mod text_v1;
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const SIZE: usize = 3;
|
||||||
|
const LETTER_SPACING: usize = 5;
|
||||||
|
const LETTER_TILT: usize = 6;
|
||||||
|
const MAX_WIDTH: usize = 8;
|
||||||
|
const MAX_HEIGHT: usize = 10;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
Length(TypedLength),
|
||||||
|
Angle(TypedAngle),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLength {
|
||||||
|
value: f64,
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedAngle {
|
||||||
|
value: f64,
|
||||||
|
unit: AngleUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum AngleUnit {
|
||||||
|
Degree,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The size, letter spacing, and max sizes are lengths and the letter tilt is an angle, which keep the numbers of pixels and degrees they held. Wired numbers still feed them, read as pixels and degrees.
|
||||||
|
#[migration("graphene_std::text::TextNode"@1 => @2)]
|
||||||
|
pub fn text_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||||
|
Some(Tagged::Number(number)) => Some(number),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
for slot in [SIZE, LETTER_SPACING, MAX_WIDTH, MAX_HEIGHT] {
|
||||||
|
if let Some(pixels) = number_at(slot) {
|
||||||
|
inputs.set(slot as u32, length(pixels));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(degrees) = number_at(LETTER_TILT) {
|
||||||
|
inputs.set(LETTER_TILT as u32, angle(degrees));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn length(pixels: f64) -> NodeInput {
|
||||||
|
literal(Tagged::Length(TypedLength {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn angle(degrees: f64) -> NodeInput {
|
||||||
|
literal(Tagged::Angle(TypedAngle {
|
||||||
|
value: degrees,
|
||||||
|
unit: AngleUnit::Degree,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(12, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&TextV1, &contract());
|
||||||
|
check_undo(&TextV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn numbers_of_pixels_and_degrees_become_lengths_and_an_angle() {
|
||||||
|
let mut fixture = Fixture::new(&TextV1);
|
||||||
|
let number = |number: f64| literal(Tagged::Number(number));
|
||||||
|
let text = fixture.add(
|
||||||
|
decl!("graphene_std::text::TextNode"@1),
|
||||||
|
vec![
|
||||||
|
literal(Tagged::None),
|
||||||
|
number(0.),
|
||||||
|
number(0.),
|
||||||
|
number(24.),
|
||||||
|
number(1.2),
|
||||||
|
number(2.),
|
||||||
|
number(10.),
|
||||||
|
number(0.),
|
||||||
|
number(100.),
|
||||||
|
number(0.),
|
||||||
|
number(100.),
|
||||||
|
number(0.),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
let migrated = fixture.migrate(&TextV1).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
fixture.inputs(&migrated, text),
|
||||||
|
[
|
||||||
|
literal(Tagged::None),
|
||||||
|
number(0.),
|
||||||
|
number(0.),
|
||||||
|
length(24.),
|
||||||
|
number(1.2),
|
||||||
|
length(2.),
|
||||||
|
angle(10.),
|
||||||
|
number(0.),
|
||||||
|
length(100.),
|
||||||
|
number(0.),
|
||||||
|
length(100.),
|
||||||
|
number(0.)
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const LOCATION: usize = 1;
|
||||||
|
const DIMENSIONS: usize = 2;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
DVec2([f64; 2]),
|
||||||
|
LengthVec2(TypedLengthVec2),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLengthVec2 {
|
||||||
|
value: [f64; 2],
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The location and dimensions are pairs of lengths, which keep the pixels they held. Wired Vec2s still feed them, read as pixels.
|
||||||
|
#[migration("graphic_nodes::artboard::CreateArtboardNode"@1 => @2)]
|
||||||
|
pub fn create_artboard_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
for slot in [LOCATION, DIMENSIONS] {
|
||||||
|
if let Some(Tagged::DVec2(pixels)) = node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||||
|
inputs.set(slot as u32, lengths(pixels));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lengths(pixels: [f64; 2]) -> NodeInput {
|
||||||
|
literal(Tagged::LengthVec2(TypedLengthVec2 {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(5, |random, slot| match slot {
|
||||||
|
LOCATION | DIMENSIONS => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
|
||||||
|
_ => literal(Tagged::None),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&CreateArtboardV1, &contract());
|
||||||
|
check_undo(&CreateArtboardV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn vec2s_of_pixels_become_lengths_in_pixels() {
|
||||||
|
let mut fixture = Fixture::new(&CreateArtboardV1);
|
||||||
|
let none = || literal(Tagged::None);
|
||||||
|
let artboard = fixture.add(
|
||||||
|
decl!("graphic_nodes::artboard::CreateArtboardNode"@1),
|
||||||
|
vec![none(), literal(Tagged::DVec2([10., 20.])), literal(Tagged::DVec2([1920., 1080.])), none(), none()],
|
||||||
|
);
|
||||||
|
let migrated = fixture.migrate(&CreateArtboardV1).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(fixture.inputs(&migrated, artboard), [none(), lengths([10., 20.]), lengths([1920., 1080.]), none(), none()]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const OFFSET: usize = 2;
|
||||||
|
const ANGLE: usize = 3;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
Length(TypedLength),
|
||||||
|
Angle(TypedAngle),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLength {
|
||||||
|
value: f64,
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedAngle {
|
||||||
|
value: f64,
|
||||||
|
unit: AngleUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum AngleUnit {
|
||||||
|
Degree,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The offset is a length and the angle is an angle, which keep the numbers of pixels and degrees they held. Wired numbers still feed them, read as pixels and degrees.
|
||||||
|
#[migration("graphic_nodes::graphic::MirrorNode"@1 => @2)]
|
||||||
|
pub fn mirror_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||||
|
Some(Tagged::Number(number)) => Some(number),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Some(pixels) = number_at(OFFSET) {
|
||||||
|
inputs.set(OFFSET as u32, length(pixels));
|
||||||
|
}
|
||||||
|
if let Some(degrees) = number_at(ANGLE) {
|
||||||
|
inputs.set(ANGLE as u32, angle(degrees));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn length(pixels: f64) -> NodeInput {
|
||||||
|
literal(Tagged::Length(TypedLength {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn angle(degrees: f64) -> NodeInput {
|
||||||
|
literal(Tagged::Angle(TypedAngle {
|
||||||
|
value: degrees,
|
||||||
|
unit: AngleUnit::Degree,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(5, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&MirrorV1, &contract());
|
||||||
|
check_undo(&MirrorV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn numbers_of_pixels_and_degrees_become_a_length_and_an_angle() {
|
||||||
|
let mut fixture = Fixture::new(&MirrorV1);
|
||||||
|
let number = |number: f64| literal(Tagged::Number(number));
|
||||||
|
let mirror = fixture.add(
|
||||||
|
decl!("graphic_nodes::graphic::MirrorNode"@1),
|
||||||
|
vec![literal(Tagged::None), number(0.), number(20.), number(45.), number(1.)],
|
||||||
|
);
|
||||||
|
let migrated = fixture.migrate(&MirrorV1).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(fixture.inputs(&migrated, mirror), [literal(Tagged::None), number(0.), length(20.), angle(45.), number(1.)]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
//! Migrations of the nodes in `graphic_nodes`.
|
||||||
|
|
||||||
|
mod create_artboard_v1;
|
||||||
|
mod mirror_v1;
|
||||||
@@ -2,8 +2,13 @@
|
|||||||
//! `cargo run migration new <identifier>` after bumping a node's `version(N)`.
|
//! `cargo run migration new <identifier>` after bumping a node's `version(N)`.
|
||||||
|
|
||||||
mod blending_nodes;
|
mod blending_nodes;
|
||||||
|
mod brush_nodes;
|
||||||
|
mod core_types;
|
||||||
mod graphene_core;
|
mod graphene_core;
|
||||||
mod graphene_std;
|
mod graphene_std;
|
||||||
|
mod graphic_nodes;
|
||||||
mod math_nodes;
|
mod math_nodes;
|
||||||
mod raster_nodes;
|
mod raster_nodes;
|
||||||
|
mod repeat_nodes;
|
||||||
|
mod transform_nodes;
|
||||||
mod vector_nodes;
|
mod vector_nodes;
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
use migration_core::{Inputs, NodeInput, migration};
|
||||||
|
|
||||||
|
/// Reads the document's resolution from the scope, which sizes the physical lengths an expression measures.
|
||||||
|
#[migration("math_nodes::MathFormulaNode"@2 => @3)]
|
||||||
|
pub fn math_formula_v2(inputs: &mut Inputs) {
|
||||||
|
inputs.push(NodeInput::Scope("pixels-per-inch".into()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::{decl, literal};
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants the node's inputs hold in version 2.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
Number(f64),
|
||||||
|
String(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(3, |random, slot| match slot {
|
||||||
|
1 => literal(Tagged::String("a + b".to_string())),
|
||||||
|
_ => literal(Tagged::Number(random.below(10) as f64)),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&MathFormulaV2, &contract());
|
||||||
|
check_undo(&MathFormulaV2, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_resolution_is_read_from_the_scope() {
|
||||||
|
let inputs = vec![literal(Tagged::Number(2.)), literal(Tagged::String("a * 2".to_string())), literal(Tagged::Number(0.))];
|
||||||
|
|
||||||
|
let mut fixture = Fixture::new(&MathFormulaV2);
|
||||||
|
let formula = fixture.add(decl!("math_nodes::MathFormulaNode"@2), inputs.clone());
|
||||||
|
let migrated = fixture.migrate(&MathFormulaV2).unwrap();
|
||||||
|
|
||||||
|
let expected: Vec<NodeInput> = inputs.into_iter().chain([NodeInput::Scope("pixels-per-inch".into())]).collect();
|
||||||
|
assert_eq!(fixture.inputs(&migrated, formula), expected);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
use migration_core::{Inputs, NodeInput, migration};
|
||||||
|
|
||||||
|
/// Reads the document's resolution from the scope, which sizes the physical lengths an expression measures.
|
||||||
|
#[migration("math_nodes::MathFunctionNode"@2 => @3)]
|
||||||
|
pub fn math_function_v2(inputs: &mut Inputs) {
|
||||||
|
inputs.push(NodeInput::Scope("pixels-per-inch".into()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::{decl, literal};
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants the node's inputs hold in version 2.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
Number(f64),
|
||||||
|
String(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(3, |random, slot| match slot {
|
||||||
|
1 => literal(Tagged::String("x".to_string())),
|
||||||
|
_ => literal(Tagged::Number(random.below(10) as f64)),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&MathFunctionV2, &contract());
|
||||||
|
check_undo(&MathFunctionV2, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_resolution_is_read_from_the_scope() {
|
||||||
|
let inputs = vec![literal(Tagged::Number(2.)), literal(Tagged::String("x * 2".to_string())), literal(Tagged::Number(0.))];
|
||||||
|
|
||||||
|
let mut fixture = Fixture::new(&MathFunctionV2);
|
||||||
|
let function = fixture.add(decl!("math_nodes::MathFunctionNode"@2), inputs.clone());
|
||||||
|
let migrated = fixture.migrate(&MathFunctionV2).unwrap();
|
||||||
|
|
||||||
|
let expected: Vec<NodeInput> = inputs.into_iter().chain([NodeInput::Scope("pixels-per-inch".into())]).collect();
|
||||||
|
assert_eq!(fixture.inputs(&migrated, function), expected);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
//! Migrations of the nodes in `math_nodes`.
|
//! Migrations of the nodes in `math_nodes`.
|
||||||
|
|
||||||
mod math_formula_from_math_f;
|
mod math_formula_from_math_f;
|
||||||
|
mod math_formula_v2;
|
||||||
|
mod math_function_v2;
|
||||||
mod renames;
|
mod renames;
|
||||||
@@ -3,3 +3,21 @@
|
|||||||
use migration_core::rename;
|
use migration_core::rename;
|
||||||
|
|
||||||
rename!("math_nodes::MathFxNode"@1 => "math_nodes::MathFunctionNode"@2);
|
rename!("math_nodes::MathFxNode"@1 => "math_nodes::MathFunctionNode"@2);
|
||||||
|
|
||||||
|
// Version 2 takes lengths and angles too, with its output type following them, and stored nodes already have its layout
|
||||||
|
rename!("math_nodes::SineNode"@1 => @2);
|
||||||
|
rename!("math_nodes::CosineNode"@1 => @2);
|
||||||
|
rename!("math_nodes::TangentNode"@1 => @2);
|
||||||
|
rename!("math_nodes::SignNode"@1 => @2);
|
||||||
|
rename!("math_nodes::SumNode"@1 => @2);
|
||||||
|
rename!("math_nodes::AverageNode"@1 => @2);
|
||||||
|
rename!("math_nodes::MinimumNode"@1 => @2);
|
||||||
|
rename!("math_nodes::MaximumNode"@1 => @2);
|
||||||
|
|
||||||
|
// Version 2 reads a number beside a length or angle in pixels or degrees, and stored nodes already have its layout
|
||||||
|
rename!("math_nodes::LerpNode"@1 => @2);
|
||||||
|
rename!("math_nodes::ClampNode"@1 => @2);
|
||||||
|
rename!("math_nodes::LessThanNode"@1 => @2);
|
||||||
|
rename!("math_nodes::GreaterThanNode"@1 => @2);
|
||||||
|
rename!("math_nodes::EqualsNode"@1 => @2);
|
||||||
|
rename!("math_nodes::NotEqualsNode"@1 => @2);
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const RADIUS: usize = 1;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
Length(TypedLength),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLength {
|
||||||
|
value: f64,
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The radius is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||||
|
#[migration("raster_nodes::filter::MedianFilterNode"@1 => @2)]
|
||||||
|
pub fn median_filter_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let Some(slot) = node.inputs().get(RADIUS) else { return };
|
||||||
|
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||||
|
|
||||||
|
inputs.set(
|
||||||
|
RADIUS as u32,
|
||||||
|
literal(Tagged::Length(TypedLength {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&MedianFilterV1, &contract());
|
||||||
|
check_undo(&MedianFilterV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||||
|
let mut fixture = Fixture::new(&MedianFilterV1);
|
||||||
|
let number = |number: f64| literal(Tagged::Number(number));
|
||||||
|
let median_filter = fixture.add(decl!("raster_nodes::filter::MedianFilterNode"@1), vec![literal(Tagged::None), number(5.)]);
|
||||||
|
let migrated = fixture.migrate(&MedianFilterV1).unwrap();
|
||||||
|
|
||||||
|
let radius = literal(Tagged::Length(TypedLength { value: 5., unit: LengthUnit::Pixel }));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, median_filter), [literal(Tagged::None), radius]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
mod mandelbrot_v1;
|
mod mandelbrot_v1;
|
||||||
mod mandelbrot_v2;
|
mod mandelbrot_v2;
|
||||||
|
mod median_filter_v1;
|
||||||
mod mix_colors_from_mix_node;
|
mod mix_colors_from_mix_node;
|
||||||
mod noise_pattern_v1;
|
mod noise_pattern_v1;
|
||||||
mod pattern_square;
|
mod pattern_square;
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
//! Migrations of the nodes in `repeat_nodes`.
|
||||||
|
|
||||||
|
mod repeat_array_v1;
|
||||||
|
mod repeat_radial_v1;
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const DIRECTION: usize = 1;
|
||||||
|
const ANGLE: usize = 2;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
DVec2([f64; 2]),
|
||||||
|
Angle(TypedAngle),
|
||||||
|
LengthVec2(TypedLengthVec2),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLengthVec2 {
|
||||||
|
value: [f64; 2],
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedAngle {
|
||||||
|
value: f64,
|
||||||
|
unit: AngleUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum AngleUnit {
|
||||||
|
Degree,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The direction is a pair of lengths and the angle is an angle, which keep the pixels and degrees they held. Wired values still feed them, read in those units.
|
||||||
|
#[migration("repeat_nodes::repeat_nodes::RepeatArrayNode"@1 => @2)]
|
||||||
|
pub fn repeat_array_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let literal_at = |slot: usize| node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input));
|
||||||
|
|
||||||
|
if let Some(Tagged::DVec2(pixels)) = literal_at(DIRECTION) {
|
||||||
|
inputs.set(DIRECTION as u32, direction(pixels));
|
||||||
|
}
|
||||||
|
if let Some(Tagged::Number(degrees)) = literal_at(ANGLE) {
|
||||||
|
inputs.set(ANGLE as u32, angle(degrees));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn direction(pixels: [f64; 2]) -> NodeInput {
|
||||||
|
literal(Tagged::LengthVec2(TypedLengthVec2 {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn angle(degrees: f64) -> NodeInput {
|
||||||
|
literal(Tagged::Angle(TypedAngle {
|
||||||
|
value: degrees,
|
||||||
|
unit: AngleUnit::Degree,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(4, |random, slot| match slot {
|
||||||
|
0 => literal(Tagged::None),
|
||||||
|
DIRECTION => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
|
||||||
|
_ => literal(Tagged::Number(random.below(100) as f64)),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&RepeatArrayV1, &contract());
|
||||||
|
check_undo(&RepeatArrayV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_number_of_degrees_becomes_an_angle_in_degrees() {
|
||||||
|
let mut fixture = Fixture::new(&RepeatArrayV1);
|
||||||
|
let number = |number: f64| literal(Tagged::Number(number));
|
||||||
|
let repeat_array = fixture.add(
|
||||||
|
decl!("repeat_nodes::repeat_nodes::RepeatArrayNode"@1),
|
||||||
|
vec![literal(Tagged::None), literal(Tagged::DVec2([100., 50.])), number(90.), number(5.)],
|
||||||
|
);
|
||||||
|
let migrated = fixture.migrate(&RepeatArrayV1).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(fixture.inputs(&migrated, repeat_array), [literal(Tagged::None), direction([100., 50.]), angle(90.), number(5.)]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const START_ANGLE: usize = 1;
|
||||||
|
const RADIUS: usize = 2;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
Length(TypedLength),
|
||||||
|
Angle(TypedAngle),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLength {
|
||||||
|
value: f64,
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedAngle {
|
||||||
|
value: f64,
|
||||||
|
unit: AngleUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum AngleUnit {
|
||||||
|
Degree,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The start angle is an angle and the radius is a length, which keep the numbers of degrees and pixels they held. Wired numbers still feed them, read as degrees and pixels.
|
||||||
|
#[migration("repeat_nodes::repeat_nodes::RepeatRadialNode"@1 => @2)]
|
||||||
|
pub fn repeat_radial_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||||
|
Some(Tagged::Number(number)) => Some(number),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Some(pixels) = number_at(RADIUS) {
|
||||||
|
inputs.set(RADIUS as u32, length(pixels));
|
||||||
|
}
|
||||||
|
if let Some(degrees) = number_at(START_ANGLE) {
|
||||||
|
inputs.set(START_ANGLE as u32, angle(degrees));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn length(pixels: f64) -> NodeInput {
|
||||||
|
literal(Tagged::Length(TypedLength {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn angle(degrees: f64) -> NodeInput {
|
||||||
|
literal(Tagged::Angle(TypedAngle {
|
||||||
|
value: degrees,
|
||||||
|
unit: AngleUnit::Degree,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&RepeatRadialV1, &contract());
|
||||||
|
check_undo(&RepeatRadialV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn numbers_of_degrees_and_pixels_become_an_angle_and_a_length() {
|
||||||
|
let mut fixture = Fixture::new(&RepeatRadialV1);
|
||||||
|
let number = |number: f64| literal(Tagged::Number(number));
|
||||||
|
let repeat_radial = fixture.add(
|
||||||
|
decl!("repeat_nodes::repeat_nodes::RepeatRadialNode"@1),
|
||||||
|
vec![literal(Tagged::None), number(45.), number(5.), number(5.)],
|
||||||
|
);
|
||||||
|
let migrated = fixture.migrate(&RepeatRadialV1).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(fixture.inputs(&migrated, repeat_radial), [literal(Tagged::None), angle(45.), length(5.), number(5.)]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
//! Migrations of the nodes in `transform_nodes`.
|
||||||
|
|
||||||
|
mod transform_v1;
|
||||||
|
mod vary_rotations_v2;
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const TRANSLATION: usize = 1;
|
||||||
|
const ROTATION: usize = 2;
|
||||||
|
const SKEW: usize = 4;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
DVec2([f64; 2]),
|
||||||
|
Angle(TypedAngle),
|
||||||
|
LengthVec2(TypedLengthVec2),
|
||||||
|
AngleVec2(TypedAngleVec2),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedAngle {
|
||||||
|
value: f64,
|
||||||
|
unit: AngleUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLengthVec2 {
|
||||||
|
value: [f64; 2],
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedAngleVec2 {
|
||||||
|
value: [f64; 2],
|
||||||
|
unit: AngleUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum AngleUnit {
|
||||||
|
Degree,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The translation is a pair of lengths and the rotation and skew are angles, which keep the pixels and degrees they held. Wired values still feed them, read in those units.
|
||||||
|
#[migration("transform_nodes::transform_nodes::TransformNode"@1 => @2)]
|
||||||
|
pub fn transform_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let literal_at = |slot: usize| node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input));
|
||||||
|
|
||||||
|
if let Some(Tagged::DVec2(pixels)) = literal_at(TRANSLATION) {
|
||||||
|
inputs.set(TRANSLATION as u32, translation(pixels));
|
||||||
|
}
|
||||||
|
if let Some(Tagged::Number(degrees)) = literal_at(ROTATION) {
|
||||||
|
inputs.set(ROTATION as u32, rotation(degrees));
|
||||||
|
}
|
||||||
|
if let Some(Tagged::DVec2(degrees)) = literal_at(SKEW) {
|
||||||
|
inputs.set(SKEW as u32, skew(degrees));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The whole-list counterpart of the Transform node, with parameters that migrate the same way.
|
||||||
|
#[migration("transform_nodes::transform_nodes::TransformListNode"@1 => @2)]
|
||||||
|
pub fn transform_list_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
transform_v1(node, inputs);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn translation(pixels: [f64; 2]) -> NodeInput {
|
||||||
|
literal(Tagged::LengthVec2(TypedLengthVec2 {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rotation(degrees: f64) -> NodeInput {
|
||||||
|
literal(Tagged::Angle(TypedAngle {
|
||||||
|
value: degrees,
|
||||||
|
unit: AngleUnit::Degree,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn skew(degrees: [f64; 2]) -> NodeInput {
|
||||||
|
literal(Tagged::AngleVec2(TypedAngleVec2 {
|
||||||
|
value: degrees,
|
||||||
|
unit: AngleUnit::Degree,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(5, |random, slot| match slot {
|
||||||
|
0 => literal(Tagged::None),
|
||||||
|
ROTATION => literal(Tagged::Number(random.below(360) as f64)),
|
||||||
|
_ => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&TransformV1, &contract());
|
||||||
|
check_undo(&TransformV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pixels_and_degrees_become_typed_lengths_and_angles() {
|
||||||
|
let mut fixture = Fixture::new(&TransformV1);
|
||||||
|
let vec2 = |x: f64, y: f64| literal(Tagged::DVec2([x, y]));
|
||||||
|
let transform = fixture.add(
|
||||||
|
decl!("transform_nodes::transform_nodes::TransformNode"@1),
|
||||||
|
vec![literal(Tagged::None), vec2(10., 20.), literal(Tagged::Number(45.)), vec2(2., 3.), vec2(15., 0.)],
|
||||||
|
);
|
||||||
|
let migrated = fixture.migrate(&TransformV1).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
fixture.inputs(&migrated, transform),
|
||||||
|
[literal(Tagged::None), translation([10., 20.]), rotation(45.), vec2(2., 3.), skew([15., 0.])]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const MIN: usize = 1;
|
||||||
|
const MAX: usize = 2;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
Angle(TypedAngle),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedAngle {
|
||||||
|
value: f64,
|
||||||
|
unit: AngleUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum AngleUnit {
|
||||||
|
Degree,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The ends of the range are angles, which keep the numbers of degrees they held. Wired numbers still feed them, read as degrees.
|
||||||
|
#[migration("transform_nodes::transform_nodes::VaryRotationsNode"@2 => @3)]
|
||||||
|
pub fn vary_rotations_v2(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||||
|
Some(Tagged::Number(number)) => Some(number),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
for slot in [MIN, MAX] {
|
||||||
|
if let Some(degrees) = number_at(slot) {
|
||||||
|
inputs.set(slot as u32, angle(degrees));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn angle(degrees: f64) -> NodeInput {
|
||||||
|
literal(Tagged::Angle(TypedAngle {
|
||||||
|
value: degrees,
|
||||||
|
unit: AngleUnit::Degree,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(8, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&VaryRotationsV2, &contract());
|
||||||
|
check_undo(&VaryRotationsV2, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn numbers_of_degrees_become_angles_in_degrees() {
|
||||||
|
let mut fixture = Fixture::new(&VaryRotationsV2);
|
||||||
|
let number = |number: f64| literal(Tagged::Number(number));
|
||||||
|
let vary_rotations = fixture.add(
|
||||||
|
decl!("transform_nodes::transform_nodes::VaryRotationsNode"@2),
|
||||||
|
vec![literal(Tagged::None), number(-180.), number(180.), number(0.5), number(0.), number(1.), number(0.), number(0.)],
|
||||||
|
);
|
||||||
|
let migrated = fixture.migrate(&VaryRotationsV2).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
fixture.inputs(&migrated, vary_rotations),
|
||||||
|
[literal(Tagged::None), angle(-180.), angle(180.), number(0.5), number(0.), number(1.), number(0.), number(0.)]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const RADIUS: usize = 1;
|
||||||
|
const START_ANGLE: usize = 2;
|
||||||
|
const SWEEP_ANGLE: usize = 3;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
Length(TypedLength),
|
||||||
|
Angle(TypedAngle),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLength {
|
||||||
|
value: f64,
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedAngle {
|
||||||
|
value: f64,
|
||||||
|
unit: AngleUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum AngleUnit {
|
||||||
|
Degree,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The radius is a length and the start and sweep angles are angles, which keep the numbers of pixels and degrees they held. Wired numbers still feed them, read as pixels and degrees.
|
||||||
|
#[migration("vector_nodes::generator_nodes::ArcNode"@1 => @2)]
|
||||||
|
pub fn arc_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||||
|
Some(Tagged::Number(number)) => Some(number),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Some(pixels) = number_at(RADIUS) {
|
||||||
|
inputs.set(RADIUS as u32, length(pixels));
|
||||||
|
}
|
||||||
|
for slot in [START_ANGLE, SWEEP_ANGLE] {
|
||||||
|
if let Some(degrees) = number_at(slot) {
|
||||||
|
inputs.set(slot as u32, angle(degrees));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn length(pixels: f64) -> NodeInput {
|
||||||
|
literal(Tagged::Length(TypedLength {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn angle(degrees: f64) -> NodeInput {
|
||||||
|
literal(Tagged::Angle(TypedAngle {
|
||||||
|
value: degrees,
|
||||||
|
unit: AngleUnit::Degree,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(5, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&ArcV1, &contract());
|
||||||
|
check_undo(&ArcV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn numbers_of_pixels_and_degrees_become_a_length_and_angles() {
|
||||||
|
let mut fixture = Fixture::new(&ArcV1);
|
||||||
|
let number = |number: f64| literal(Tagged::Number(number));
|
||||||
|
let arc = fixture.add(
|
||||||
|
decl!("vector_nodes::generator_nodes::ArcNode"@1),
|
||||||
|
vec![literal(Tagged::None), number(50.), number(0.), number(270.), number(1.)],
|
||||||
|
);
|
||||||
|
let migrated = fixture.migrate(&ArcV1).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(fixture.inputs(&migrated, arc), [literal(Tagged::None), length(50.), angle(0.), angle(270.), number(1.)]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const ARROW_TO: usize = 1;
|
||||||
|
const SHAFT_WIDTH: usize = 2;
|
||||||
|
const HEAD_WIDTH: usize = 3;
|
||||||
|
const HEAD_LENGTH: usize = 4;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
DVec2([f64; 2]),
|
||||||
|
Length(TypedLength),
|
||||||
|
LengthVec2(TypedLengthVec2),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLength {
|
||||||
|
value: f64,
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLengthVec2 {
|
||||||
|
value: [f64; 2],
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The end point is a pair of lengths and the shaft and head sizes are lengths, which keep the pixels they held. Wired values still feed them, read as pixels.
|
||||||
|
#[migration("vector_nodes::generator_nodes::ArrowNode"@1 => @2)]
|
||||||
|
pub fn arrow_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||||
|
Some(Tagged::Number(number)) => Some(number),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Some(Tagged::DVec2(pixels)) = node.inputs().get(ARROW_TO).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||||
|
inputs.set(ARROW_TO as u32, lengths(pixels));
|
||||||
|
}
|
||||||
|
for slot in [SHAFT_WIDTH, HEAD_WIDTH, HEAD_LENGTH] {
|
||||||
|
if let Some(pixels) = number_at(slot) {
|
||||||
|
inputs.set(slot as u32, length(pixels));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lengths(pixels: [f64; 2]) -> NodeInput {
|
||||||
|
literal(Tagged::LengthVec2(TypedLengthVec2 {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn length(pixels: f64) -> NodeInput {
|
||||||
|
literal(Tagged::Length(TypedLength {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(5, |random, slot| match slot {
|
||||||
|
0 => literal(Tagged::None),
|
||||||
|
ARROW_TO => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
|
||||||
|
_ => literal(Tagged::Number(random.below(100) as f64)),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&ArrowV1, &contract());
|
||||||
|
check_undo(&ArrowV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn numbers_of_pixels_become_lengths_in_pixels() {
|
||||||
|
let mut fixture = Fixture::new(&ArrowV1);
|
||||||
|
let number = |number: f64| literal(Tagged::Number(number));
|
||||||
|
let arrow = fixture.add(
|
||||||
|
decl!("vector_nodes::generator_nodes::ArrowNode"@1),
|
||||||
|
vec![literal(Tagged::None), literal(Tagged::DVec2([100., 0.])), number(10.), number(30.), number(20.)],
|
||||||
|
);
|
||||||
|
let migrated = fixture.migrate(&ArrowV1).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(fixture.inputs(&migrated, arrow), [literal(Tagged::None), lengths([100., 0.]), length(10.), length(30.), length(20.)]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const RADIUS: usize = 1;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
Length(TypedLength),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLength {
|
||||||
|
value: f64,
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The radius is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||||
|
#[migration("vector_nodes::generator_nodes::CircleNode"@1 => @2)]
|
||||||
|
pub fn circle_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let Some(slot) = node.inputs().get(RADIUS) else { return };
|
||||||
|
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||||
|
|
||||||
|
inputs.set(
|
||||||
|
RADIUS as u32,
|
||||||
|
literal(Tagged::Length(TypedLength {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&CircleV1, &contract());
|
||||||
|
check_undo(&CircleV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||||
|
let mut fixture = Fixture::new(&CircleV1);
|
||||||
|
let circle = fixture.add(decl!("vector_nodes::generator_nodes::CircleNode"@1), vec![literal(Tagged::None), literal(Tagged::Number(50.))]);
|
||||||
|
let migrated = fixture.migrate(&CircleV1).unwrap();
|
||||||
|
|
||||||
|
let radius = literal(Tagged::Length(TypedLength { value: 50., unit: LengthUnit::Pixel }));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, circle), [literal(Tagged::None), radius]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const RADIUS_X: usize = 1;
|
||||||
|
const RADIUS_Y: usize = 2;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
Length(TypedLength),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLength {
|
||||||
|
value: f64,
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The radii are lengths, which keep the numbers of pixels they held. Wired numbers still feed them, read as pixels.
|
||||||
|
#[migration("vector_nodes::generator_nodes::EllipseNode"@1 => @2)]
|
||||||
|
pub fn ellipse_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||||
|
Some(Tagged::Number(number)) => Some(number),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
for slot in [RADIUS_X, RADIUS_Y] {
|
||||||
|
if let Some(pixels) = number_at(slot) {
|
||||||
|
inputs.set(slot as u32, length(pixels));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn length(pixels: f64) -> NodeInput {
|
||||||
|
literal(Tagged::Length(TypedLength {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(3, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&EllipseV1, &contract());
|
||||||
|
check_undo(&EllipseV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn numbers_of_pixels_become_lengths_in_pixels() {
|
||||||
|
let mut fixture = Fixture::new(&EllipseV1);
|
||||||
|
let number = |number: f64| literal(Tagged::Number(number));
|
||||||
|
let ellipse = fixture.add(decl!("vector_nodes::generator_nodes::EllipseNode"@1), vec![literal(Tagged::None), number(50.), number(25.)]);
|
||||||
|
let migrated = fixture.migrate(&EllipseV1).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(fixture.inputs(&migrated, ellipse), [literal(Tagged::None), length(50.), length(25.)]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const SPACING: usize = 6;
|
||||||
|
const ANGLES: usize = 7;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
DVec2([f64; 2]),
|
||||||
|
LengthVec2(TypedLengthVec2),
|
||||||
|
AngleVec2(TypedAngleVec2),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLengthVec2 {
|
||||||
|
value: [f64; 2],
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedAngleVec2 {
|
||||||
|
value: [f64; 2],
|
||||||
|
unit: AngleUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum AngleUnit {
|
||||||
|
Degree,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The spacing is a pair of lengths, filled from one number in both axes, and the isometric angles are a pair of angles, which keep the pixels and degrees they held. Wired values still feed them, read in those units.
|
||||||
|
#[migration("vector_nodes::generator_nodes::GridNode"@1 => @2)]
|
||||||
|
pub fn grid_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let literal_at = |slot: usize| node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input));
|
||||||
|
|
||||||
|
match literal_at(SPACING) {
|
||||||
|
Some(Tagged::Number(pixels)) => inputs.set(SPACING as u32, lengths([pixels, pixels])),
|
||||||
|
Some(Tagged::DVec2(pixels)) => inputs.set(SPACING as u32, lengths(pixels)),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
if let Some(Tagged::DVec2(degrees)) = literal_at(ANGLES) {
|
||||||
|
inputs.set(ANGLES as u32, angles(degrees));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lengths(pixels: [f64; 2]) -> NodeInput {
|
||||||
|
literal(Tagged::LengthVec2(TypedLengthVec2 {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn angles(degrees: [f64; 2]) -> NodeInput {
|
||||||
|
literal(Tagged::AngleVec2(TypedAngleVec2 {
|
||||||
|
value: degrees,
|
||||||
|
unit: AngleUnit::Degree,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(8, |random, slot| match slot {
|
||||||
|
SPACING if random.below(2) == 0 => literal(Tagged::Number(random.below(100) as f64)),
|
||||||
|
SPACING | ANGLES => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
|
||||||
|
_ => literal(Tagged::None),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&GridV1, &contract());
|
||||||
|
check_undo(&GridV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pixels_and_degrees_become_typed_lengths_and_angles() {
|
||||||
|
let mut fixture = Fixture::new(&GridV1);
|
||||||
|
let none = || literal(Tagged::None);
|
||||||
|
let square = fixture.add(
|
||||||
|
decl!("vector_nodes::generator_nodes::GridNode"@1),
|
||||||
|
vec![none(), none(), none(), none(), none(), none(), literal(Tagged::Number(10.)), literal(Tagged::DVec2([30., 30.]))],
|
||||||
|
);
|
||||||
|
let rectangular = fixture.add(
|
||||||
|
decl!("vector_nodes::generator_nodes::GridNode"@1),
|
||||||
|
vec![none(), none(), none(), none(), none(), none(), literal(Tagged::DVec2([10., 20.])), literal(Tagged::DVec2([30., 60.]))],
|
||||||
|
);
|
||||||
|
let migrated = fixture.migrate(&GridV1).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
fixture.inputs(&migrated, square),
|
||||||
|
[none(), none(), none(), none(), none(), none(), lengths([10., 10.]), angles([30., 30.])]
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
fixture.inputs(&migrated, rectangular),
|
||||||
|
[none(), none(), none(), none(), none(), none(), lengths([10., 20.]), angles([30., 60.])]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const TIP_ANGLE: usize = 6;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
Angle(TypedAngle),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedAngle {
|
||||||
|
value: f64,
|
||||||
|
unit: AngleUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum AngleUnit {
|
||||||
|
Degree,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The tip angle is an angle, which keeps the number of degrees it held. A wired number still feeds it, read as degrees.
|
||||||
|
#[migration("vector_nodes::generator_nodes::HeartNode"@1 => @2)]
|
||||||
|
pub fn heart_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let Some(slot) = node.inputs().get(TIP_ANGLE) else { return };
|
||||||
|
let Some(Tagged::Number(degrees)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||||
|
|
||||||
|
inputs.set(
|
||||||
|
TIP_ANGLE as u32,
|
||||||
|
literal(Tagged::Angle(TypedAngle {
|
||||||
|
value: degrees,
|
||||||
|
unit: AngleUnit::Degree,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(7, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&HeartV1, &contract());
|
||||||
|
check_undo(&HeartV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_number_of_degrees_becomes_an_angle_in_degrees() {
|
||||||
|
let mut fixture = Fixture::new(&HeartV1);
|
||||||
|
let number = |number: f64| literal(Tagged::Number(number));
|
||||||
|
let heart = fixture.add(
|
||||||
|
decl!("vector_nodes::generator_nodes::HeartNode"@1),
|
||||||
|
vec![literal(Tagged::None), number(70.), number(0.), number(0.), number(70.), number(50.), number(75.)],
|
||||||
|
);
|
||||||
|
let migrated = fixture.migrate(&HeartV1).unwrap();
|
||||||
|
|
||||||
|
let tip_angle = literal(Tagged::Angle(TypedAngle { value: 75., unit: AngleUnit::Degree }));
|
||||||
|
assert_eq!(
|
||||||
|
fixture.inputs(&migrated, heart),
|
||||||
|
[literal(Tagged::None), number(70.), number(0.), number(0.), number(70.), number(50.), tip_angle]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const LINE_TO: usize = 1;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
DVec2([f64; 2]),
|
||||||
|
LengthVec2(TypedLengthVec2),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLengthVec2 {
|
||||||
|
value: [f64; 2],
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The end point is a pair of lengths, which keeps the pixels it held. A wired Vec2 still feeds it, read as pixels.
|
||||||
|
#[migration("vector_nodes::generator_nodes::LineNode"@1 => @2)]
|
||||||
|
pub fn line_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let Some(slot) = node.inputs().get(LINE_TO) else { return };
|
||||||
|
let Some(Tagged::DVec2(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||||
|
|
||||||
|
inputs.set(LINE_TO as u32, lengths(pixels));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lengths(pixels: [f64; 2]) -> NodeInput {
|
||||||
|
literal(Tagged::LengthVec2(TypedLengthVec2 {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(2, |random, slot| match slot {
|
||||||
|
LINE_TO => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
|
||||||
|
_ => literal(Tagged::None),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&LineV1, &contract());
|
||||||
|
check_undo(&LineV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_vec2_of_pixels_becomes_lengths_in_pixels() {
|
||||||
|
let mut fixture = Fixture::new(&LineV1);
|
||||||
|
let node = fixture.add(decl!("vector_nodes::generator_nodes::LineNode"@1), vec![literal(Tagged::None), literal(Tagged::DVec2([30., 40.]))]);
|
||||||
|
let migrated = fixture.migrate(&LineV1).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(fixture.inputs(&migrated, node), [literal(Tagged::None), lengths([30., 40.])]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,16 @@
|
|||||||
//! Migrations of the nodes in `vector_nodes`.
|
//! Migrations of the nodes in `vector_nodes`.
|
||||||
|
|
||||||
|
mod arc_v1;
|
||||||
|
mod arrow_v1;
|
||||||
|
mod circle_v1;
|
||||||
|
mod ellipse_v1;
|
||||||
|
mod grid_v1;
|
||||||
|
mod heart_v1;
|
||||||
|
mod line_v1;
|
||||||
mod path_from_path_network;
|
mod path_from_path_network;
|
||||||
|
mod qr_code_v1;
|
||||||
|
mod rectangle_v1;
|
||||||
|
mod regular_polygon_v1;
|
||||||
mod renames;
|
mod renames;
|
||||||
|
mod spiral_v1;
|
||||||
|
mod star_v1;
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const SIZE: usize = 3;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
Length(TypedLength),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLength {
|
||||||
|
value: f64,
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The size is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||||
|
#[migration("vector_nodes::generator_nodes::QrCodeNode"@1 => @2)]
|
||||||
|
pub fn qr_code_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let Some(slot) = node.inputs().get(SIZE) else { return };
|
||||||
|
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||||
|
|
||||||
|
inputs.set(SIZE as u32, length(pixels));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn length(pixels: f64) -> NodeInput {
|
||||||
|
literal(Tagged::Length(TypedLength {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(6, |random, slot| if slot == SIZE { literal(Tagged::Number(random.below(100) as f64)) } else { literal(Tagged::None) })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&QrCodeV1, &contract());
|
||||||
|
check_undo(&QrCodeV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||||
|
let mut fixture = Fixture::new(&QrCodeV1);
|
||||||
|
let none = || literal(Tagged::None);
|
||||||
|
let qr_code = fixture.add(
|
||||||
|
decl!("vector_nodes::generator_nodes::QrCodeNode"@1),
|
||||||
|
vec![none(), none(), none(), literal(Tagged::Number(200.)), none(), none()],
|
||||||
|
);
|
||||||
|
let migrated = fixture.migrate(&QrCodeV1).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(fixture.inputs(&migrated, qr_code), [none(), none(), none(), length(200.), none(), none()]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const WIDTH: usize = 1;
|
||||||
|
const HEIGHT: usize = 2;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
Length(TypedLength),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLength {
|
||||||
|
value: f64,
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The width and height are lengths, which keep the numbers of pixels they held. Wired numbers still feed them, read as pixels.
|
||||||
|
#[migration("vector_nodes::generator_nodes::RectangleNode"@1 => @2)]
|
||||||
|
pub fn rectangle_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||||
|
Some(Tagged::Number(number)) => Some(number),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
for slot in [WIDTH, HEIGHT] {
|
||||||
|
if let Some(pixels) = number_at(slot) {
|
||||||
|
inputs.set(slot as u32, length(pixels));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn length(pixels: f64) -> NodeInput {
|
||||||
|
literal(Tagged::Length(TypedLength {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(6, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&RectangleV1, &contract());
|
||||||
|
check_undo(&RectangleV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn numbers_of_pixels_become_lengths_in_pixels() {
|
||||||
|
let mut fixture = Fixture::new(&RectangleV1);
|
||||||
|
let number = |number: f64| literal(Tagged::Number(number));
|
||||||
|
let rectangle = fixture.add(
|
||||||
|
decl!("vector_nodes::generator_nodes::RectangleNode"@1),
|
||||||
|
vec![literal(Tagged::None), number(100.), number(80.), number(0.), number(1.), number(0.)],
|
||||||
|
);
|
||||||
|
let migrated = fixture.migrate(&RectangleV1).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
fixture.inputs(&migrated, rectangle),
|
||||||
|
[literal(Tagged::None), length(100.), length(80.), number(0.), number(1.), number(0.)]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const RADIUS: usize = 2;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
Length(TypedLength),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLength {
|
||||||
|
value: f64,
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The radius is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||||
|
#[migration("vector_nodes::generator_nodes::RegularPolygonNode"@1 => @2)]
|
||||||
|
pub fn regular_polygon_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let Some(slot) = node.inputs().get(RADIUS) else { return };
|
||||||
|
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||||
|
|
||||||
|
inputs.set(
|
||||||
|
RADIUS as u32,
|
||||||
|
literal(Tagged::Length(TypedLength {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(3, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&RegularPolygonV1, &contract());
|
||||||
|
check_undo(&RegularPolygonV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||||
|
let mut fixture = Fixture::new(&RegularPolygonV1);
|
||||||
|
let number = |number: f64| literal(Tagged::Number(number));
|
||||||
|
let polygon = fixture.add(decl!("vector_nodes::generator_nodes::RegularPolygonNode"@1), vec![literal(Tagged::None), number(6.), number(50.)]);
|
||||||
|
let migrated = fixture.migrate(&RegularPolygonV1).unwrap();
|
||||||
|
|
||||||
|
let radius = literal(Tagged::Length(TypedLength { value: 50., unit: LengthUnit::Pixel }));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, polygon), [literal(Tagged::None), number(6.), radius]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const START_ANGLE: usize = 3;
|
||||||
|
const INNER_RADIUS: usize = 4;
|
||||||
|
const OUTER_RADIUS: usize = 5;
|
||||||
|
const ANGULAR_RESOLUTION: usize = 6;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
Length(TypedLength),
|
||||||
|
Angle(TypedAngle),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLength {
|
||||||
|
value: f64,
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedAngle {
|
||||||
|
value: f64,
|
||||||
|
unit: AngleUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum AngleUnit {
|
||||||
|
Degree,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The radii are lengths and the start angle and angular resolution are angles, which keep the numbers of pixels and degrees they held. Wired numbers still feed them, read as pixels and degrees.
|
||||||
|
#[migration("vector_nodes::generator_nodes::SpiralNode"@1 => @2)]
|
||||||
|
pub fn spiral_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||||
|
Some(Tagged::Number(number)) => Some(number),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
for slot in [INNER_RADIUS, OUTER_RADIUS] {
|
||||||
|
if let Some(pixels) = number_at(slot) {
|
||||||
|
inputs.set(slot as u32, length(pixels));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for slot in [START_ANGLE, ANGULAR_RESOLUTION] {
|
||||||
|
if let Some(degrees) = number_at(slot) {
|
||||||
|
inputs.set(slot as u32, angle(degrees));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn length(pixels: f64) -> NodeInput {
|
||||||
|
literal(Tagged::Length(TypedLength {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn angle(degrees: f64) -> NodeInput {
|
||||||
|
literal(Tagged::Angle(TypedAngle {
|
||||||
|
value: degrees,
|
||||||
|
unit: AngleUnit::Degree,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(7, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&SpiralV1, &contract());
|
||||||
|
check_undo(&SpiralV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn numbers_of_pixels_and_degrees_become_lengths_and_angles() {
|
||||||
|
let mut fixture = Fixture::new(&SpiralV1);
|
||||||
|
let number = |number: f64| literal(Tagged::Number(number));
|
||||||
|
let spiral = fixture.add(
|
||||||
|
decl!("vector_nodes::generator_nodes::SpiralNode"@1),
|
||||||
|
vec![literal(Tagged::None), number(0.), number(5.), number(0.), number(0.), number(25.), number(90.)],
|
||||||
|
);
|
||||||
|
let migrated = fixture.migrate(&SpiralV1).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
fixture.inputs(&migrated, spiral),
|
||||||
|
[literal(Tagged::None), number(0.), number(5.), angle(0.), length(0.), length(25.), angle(90.)]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const RADIUS_1: usize = 2;
|
||||||
|
const RADIUS_2: usize = 3;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
Length(TypedLength),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLength {
|
||||||
|
value: f64,
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The radii are lengths, which keep the numbers of pixels they held. Wired numbers still feed them, read as pixels.
|
||||||
|
#[migration("vector_nodes::generator_nodes::StarNode"@1 => @2)]
|
||||||
|
pub fn star_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||||
|
Some(Tagged::Number(number)) => Some(number),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
for slot in [RADIUS_1, RADIUS_2] {
|
||||||
|
if let Some(pixels) = number_at(slot) {
|
||||||
|
inputs.set(slot as u32, length(pixels));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn length(pixels: f64) -> NodeInput {
|
||||||
|
literal(Tagged::Length(TypedLength {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&StarV1, &contract());
|
||||||
|
check_undo(&StarV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn numbers_of_pixels_become_lengths_in_pixels() {
|
||||||
|
let mut fixture = Fixture::new(&StarV1);
|
||||||
|
let number = |number: f64| literal(Tagged::Number(number));
|
||||||
|
let star = fixture.add(decl!("vector_nodes::generator_nodes::StarNode"@1), vec![literal(Tagged::None), number(5.), number(50.), number(25.)]);
|
||||||
|
let migrated = fixture.migrate(&StarV1).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(fixture.inputs(&migrated, star), [literal(Tagged::None), number(5.), length(50.), length(25.)]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,6 +6,8 @@ use crate::messages::prelude::*;
|
|||||||
pub enum DialogMessage {
|
pub enum DialogMessage {
|
||||||
// Sub-messages
|
// Sub-messages
|
||||||
#[child]
|
#[child]
|
||||||
|
DocumentSetupDialog(DocumentSetupDialogMessage),
|
||||||
|
#[child]
|
||||||
ExportDialog(ExportDialogMessage),
|
ExportDialog(ExportDialogMessage),
|
||||||
#[child]
|
#[child]
|
||||||
NewDocumentDialog(NewDocumentDialogMessage),
|
NewDocumentDialog(NewDocumentDialogMessage),
|
||||||
@@ -34,6 +36,7 @@ pub enum DialogMessage {
|
|||||||
localized_commit_year: String,
|
localized_commit_year: String,
|
||||||
},
|
},
|
||||||
RequestDemoArtworkDialog,
|
RequestDemoArtworkDialog,
|
||||||
|
RequestDocumentSetupDialog,
|
||||||
RequestExportDialog,
|
RequestExportDialog,
|
||||||
RequestLicensesDialogWithLocalizedCommitDate {
|
RequestLicensesDialogWithLocalizedCommitDate {
|
||||||
localized_commit_year: String,
|
localized_commit_year: String,
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ use crate::messages::dialog::simple_dialogs::{ConfirmRestartDialog, LicensesThir
|
|||||||
use crate::messages::frontend::utility_types::ExportBounds;
|
use crate::messages::frontend::utility_types::ExportBounds;
|
||||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||||
use crate::messages::prelude::*;
|
use crate::messages::prelude::*;
|
||||||
|
use graphene_std::units::{DEFAULT_PIXELS_PER_INCH, TypedLength};
|
||||||
|
|
||||||
#[derive(ExtractField)]
|
#[derive(ExtractField)]
|
||||||
pub struct DialogMessageContext<'a> {
|
pub struct DialogMessageContext<'a> {
|
||||||
@@ -16,6 +17,7 @@ pub struct DialogMessageContext<'a> {
|
|||||||
pub struct DialogMessageHandler {
|
pub struct DialogMessageHandler {
|
||||||
on_dismiss: Option<Message>,
|
on_dismiss: Option<Message>,
|
||||||
redisplay: Option<Message>,
|
redisplay: Option<Message>,
|
||||||
|
document_setup_dialog: DocumentSetupDialogMessageHandler,
|
||||||
export_dialog: ExportDialogMessageHandler,
|
export_dialog: ExportDialogMessageHandler,
|
||||||
new_document_dialog: NewDocumentDialogMessageHandler,
|
new_document_dialog: NewDocumentDialogMessageHandler,
|
||||||
preferences_dialog: PreferencesDialogMessageHandler,
|
preferences_dialog: PreferencesDialogMessageHandler,
|
||||||
@@ -27,6 +29,7 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
|
|||||||
let DialogMessageContext { portfolio, preferences } = context;
|
let DialogMessageContext { portfolio, preferences } = context;
|
||||||
|
|
||||||
match message {
|
match message {
|
||||||
|
DialogMessage::DocumentSetupDialog(message) => self.document_setup_dialog.process_message(message, responses, ()),
|
||||||
DialogMessage::ExportDialog(message) => self.export_dialog.process_message(message, responses, ExportDialogMessageContext { portfolio }),
|
DialogMessage::ExportDialog(message) => self.export_dialog.process_message(message, responses, ExportDialogMessageContext { portfolio }),
|
||||||
DialogMessage::NewDocumentDialog(message) => self.new_document_dialog.process_message(message, responses, ()),
|
DialogMessage::NewDocumentDialog(message) => self.new_document_dialog.process_message(message, responses, ()),
|
||||||
DialogMessage::PreferencesDialog(message) => self.preferences_dialog.process_message(message, responses, PreferencesDialogMessageContext { preferences }),
|
DialogMessage::PreferencesDialog(message) => self.preferences_dialog.process_message(message, responses, PreferencesDialogMessageContext { preferences }),
|
||||||
@@ -100,30 +103,25 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
|
|||||||
let dialog = DemoArtworkDialog;
|
let dialog = DemoArtworkDialog;
|
||||||
dialog.send_dialog_to_frontend(responses);
|
dialog.send_dialog_to_frontend(responses);
|
||||||
}
|
}
|
||||||
|
DialogMessage::RequestDocumentSetupDialog => {
|
||||||
|
self.on_dismiss = Some(DialogMessage::Close.into());
|
||||||
|
if let Some(document) = portfolio.active_document() {
|
||||||
|
self.document_setup_dialog = DocumentSetupDialogMessageHandler {
|
||||||
|
pixels_per_inch: document.network_interface.pixels_per_inch(),
|
||||||
|
};
|
||||||
|
self.document_setup_dialog.send_dialog_to_frontend(responses);
|
||||||
|
}
|
||||||
|
}
|
||||||
DialogMessage::RequestExportDialog => {
|
DialogMessage::RequestExportDialog => {
|
||||||
self.on_dismiss = Some(DialogMessage::Close.into());
|
self.on_dismiss = Some(DialogMessage::Close.into());
|
||||||
if let Some(document) = portfolio.active_document() {
|
if let Some(document) = portfolio.active_document() {
|
||||||
let artboards = document
|
self.export_dialog.artboards = document.artboard_names();
|
||||||
.metadata()
|
|
||||||
.all_layers()
|
|
||||||
.filter(|&layer| document.network_interface.is_artboard(&layer.to_node(), &[]))
|
|
||||||
.map(|layer| {
|
|
||||||
let name = document
|
|
||||||
.network_interface
|
|
||||||
.node_metadata(&layer.to_node(), &[])
|
|
||||||
.map(|node| node.persistent_metadata.display_name.clone())
|
|
||||||
.filter(|name| !name.is_empty())
|
|
||||||
.unwrap_or_else(|| "Artboard".to_string());
|
|
||||||
(layer, name)
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
self.export_dialog.artboards = artboards;
|
|
||||||
|
|
||||||
if let ExportBounds::Artboard(layer) = self.export_dialog.bounds
|
if let ExportBounds::Artboard(layer) = self.export_dialog.bounds
|
||||||
&& !self.export_dialog.artboards.contains_key(&layer)
|
&& !self.export_dialog.artboards.iter().any(|(artboard, _)| *artboard == layer)
|
||||||
{
|
{
|
||||||
self.export_dialog.bounds = ExportBounds::AllArtwork;
|
self.export_dialog.bounds = self.export_dialog.default_bounds();
|
||||||
|
self.export_dialog.bounds_chosen = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
self.export_dialog.has_selection = document.network_interface.selected_nodes().selected_layers(document.metadata()).next().is_some();
|
self.export_dialog.has_selection = document.network_interface.selected_nodes().selected_layers(document.metadata()).next().is_some();
|
||||||
@@ -145,7 +143,9 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
|
|||||||
self.new_document_dialog = NewDocumentDialogMessageHandler {
|
self.new_document_dialog = NewDocumentDialogMessageHandler {
|
||||||
name: portfolio.generate_new_document_name(None),
|
name: portfolio.generate_new_document_name(None),
|
||||||
infinite: false,
|
infinite: false,
|
||||||
dimensions: glam::UVec2::new(1920, 1080),
|
width: TypedLength::pixels(1920.),
|
||||||
|
height: TypedLength::pixels(1080.),
|
||||||
|
pixels_per_inch: DEFAULT_PIXELS_PER_INCH,
|
||||||
};
|
};
|
||||||
self.new_document_dialog.send_dialog_to_frontend(responses);
|
self.new_document_dialog.send_dialog_to_frontend(responses);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
use crate::messages::prelude::*;
|
||||||
|
|
||||||
|
#[impl_message(Message, DialogMessage, DocumentSetupDialog)]
|
||||||
|
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||||
|
pub enum DocumentSetupDialogMessage {
|
||||||
|
Resolution { pixels_per_inch: f64 },
|
||||||
|
|
||||||
|
Submit,
|
||||||
|
}
|
||||||
+158
@@ -0,0 +1,158 @@
|
|||||||
|
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||||
|
use crate::messages::prelude::*;
|
||||||
|
use graphene_std::units::DEFAULT_PIXELS_PER_INCH;
|
||||||
|
|
||||||
|
/// A dialog to allow users to change the settings of the active document.
|
||||||
|
#[derive(Debug, Clone, ExtractField)]
|
||||||
|
pub struct DocumentSetupDialogMessageHandler {
|
||||||
|
pub pixels_per_inch: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for DocumentSetupDialogMessageHandler {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
pixels_per_inch: DEFAULT_PIXELS_PER_INCH,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[message_handler_data]
|
||||||
|
impl MessageHandler<DocumentSetupDialogMessage, ()> for DocumentSetupDialogMessageHandler {
|
||||||
|
fn process_message(&mut self, message: DocumentSetupDialogMessage, responses: &mut VecDeque<Message>, _: ()) {
|
||||||
|
match message {
|
||||||
|
DocumentSetupDialogMessage::Resolution { pixels_per_inch } => self.pixels_per_inch = pixels_per_inch,
|
||||||
|
|
||||||
|
DocumentSetupDialogMessage::Submit => {
|
||||||
|
// The settings apply as one undo step, which ending the transaction drops if nothing changed
|
||||||
|
responses.add(DocumentMessage::StartTransaction);
|
||||||
|
responses.add(DocumentMessage::SetPixelsPerInch {
|
||||||
|
pixels_per_inch: self.pixels_per_inch,
|
||||||
|
});
|
||||||
|
responses.add(DocumentMessage::EndTransaction);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
self.send_dialog_to_frontend(responses);
|
||||||
|
}
|
||||||
|
|
||||||
|
advertise_actions!(DocumentSetupDialogUpdate;
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DialogLayoutHolder for DocumentSetupDialogMessageHandler {
|
||||||
|
const ICON: &'static str = "File";
|
||||||
|
const TITLE: &'static str = "Document Setup";
|
||||||
|
|
||||||
|
fn layout_buttons(&self) -> Layout {
|
||||||
|
let widgets = vec![
|
||||||
|
TextButton::new("OK")
|
||||||
|
.emphasized(true)
|
||||||
|
.on_update(|_| {
|
||||||
|
DialogMessage::CloseAndThen {
|
||||||
|
followups: vec![DocumentSetupDialogMessage::Submit.into()],
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
})
|
||||||
|
.widget_instance(),
|
||||||
|
TextButton::new("Cancel").on_update(|_| DialogMessage::Close.into()).widget_instance(),
|
||||||
|
];
|
||||||
|
|
||||||
|
Layout(vec![LayoutGroup::row(widgets)])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LayoutHolder for DocumentSetupDialogMessageHandler {
|
||||||
|
fn layout(&self) -> Layout {
|
||||||
|
let resolution = resolution_row(self.pixels_per_inch, |pixels_per_inch| DocumentSetupDialogMessage::Resolution { pixels_per_inch }.into());
|
||||||
|
|
||||||
|
Layout(vec![LayoutGroup::row(resolution)])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The labeled field for a document's resolution in pixels per inch, shared by the dialogs that set it.
|
||||||
|
pub fn resolution_row(pixels_per_inch: f64, on_update: impl Fn(f64) -> Message + Send + Sync + 'static) -> Vec<WidgetInstance> {
|
||||||
|
let description = "How many pixels make an inch, which sizes the lengths typed in physical units like millimeters and inches, and the physical size of exported files.";
|
||||||
|
|
||||||
|
vec![
|
||||||
|
TextLabel::new("Resolution")
|
||||||
|
.table_align(true)
|
||||||
|
.sizing(WidgetSizing::fixed(90))
|
||||||
|
.tooltip_label("Resolution")
|
||||||
|
.tooltip_description(description)
|
||||||
|
.widget_instance(),
|
||||||
|
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||||
|
NumberInput::new(Some(pixels_per_inch))
|
||||||
|
.unit(" PPI")
|
||||||
|
.min(1.)
|
||||||
|
.max(100_000.)
|
||||||
|
.tooltip_label("Resolution")
|
||||||
|
.tooltip_description(description)
|
||||||
|
// Matches the width of the New Document dialog's Name field
|
||||||
|
.sizing(WidgetSizing::default().min_width(204))
|
||||||
|
.on_update(move |number_input: &NumberInput| on_update(number_input.value.unwrap_or(DEFAULT_PIXELS_PER_INCH)))
|
||||||
|
.widget_instance(),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use crate::test_utils::test_prelude::*;
|
||||||
|
|
||||||
|
fn pixels_per_inch(editor: &EditorTestUtils) -> f64 {
|
||||||
|
editor.active_document().network_interface.pixels_per_inch()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn open_and_set_resolution(editor: &mut EditorTestUtils, pixels_per_inch: f64) {
|
||||||
|
editor.handle_message(DialogMessage::RequestDocumentSetupDialog).await;
|
||||||
|
editor.handle_message(DocumentSetupDialogMessage::Resolution { pixels_per_inch }).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn confirm(editor: &mut EditorTestUtils) {
|
||||||
|
editor
|
||||||
|
.handle_message(DialogMessage::CloseAndThen {
|
||||||
|
followups: vec![DocumentSetupDialogMessage::Submit.into()],
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn confirming_a_resolution_applies_it_as_one_undo_step() {
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.new_document().await;
|
||||||
|
editor.draw_rect(0., 0., 100., 100.).await;
|
||||||
|
let layer_count = editor.active_document().metadata().all_layers().count();
|
||||||
|
|
||||||
|
open_and_set_resolution(&mut editor, 300.).await;
|
||||||
|
assert_eq!(pixels_per_inch(&editor), 96., "the dialog applies nothing before it is confirmed");
|
||||||
|
confirm(&mut editor).await;
|
||||||
|
assert_eq!(pixels_per_inch(&editor), 300.);
|
||||||
|
|
||||||
|
// Undoing reverts only the resolution, leaving the rectangle drawn before it
|
||||||
|
editor.handle_message(DocumentMessage::Undo).await;
|
||||||
|
assert_eq!(pixels_per_inch(&editor), 96.);
|
||||||
|
assert_eq!(editor.active_document().metadata().all_layers().count(), layer_count);
|
||||||
|
|
||||||
|
editor.handle_message(DocumentMessage::Redo).await;
|
||||||
|
assert_eq!(pixels_per_inch(&editor), 300.);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn canceling_or_confirming_an_unchanged_resolution_adds_no_undo_step() {
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.new_document().await;
|
||||||
|
open_and_set_resolution(&mut editor, 300.).await;
|
||||||
|
confirm(&mut editor).await;
|
||||||
|
|
||||||
|
open_and_set_resolution(&mut editor, 150.).await;
|
||||||
|
editor.handle_message(DialogMessage::Close).await;
|
||||||
|
assert_eq!(pixels_per_inch(&editor), 300., "canceling discards the dialog's resolution");
|
||||||
|
|
||||||
|
// Reopening starts from the document's resolution, so confirming it unchanged has nothing to apply
|
||||||
|
editor.handle_message(DialogMessage::RequestDocumentSetupDialog).await;
|
||||||
|
confirm(&mut editor).await;
|
||||||
|
assert_eq!(pixels_per_inch(&editor), 300.);
|
||||||
|
|
||||||
|
editor.handle_message(DocumentMessage::Undo).await;
|
||||||
|
assert_eq!(pixels_per_inch(&editor), 96., "the one undo step is the resolution's first change");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
mod document_setup_dialog_message;
|
||||||
|
mod document_setup_dialog_message_handler;
|
||||||
|
|
||||||
|
#[doc(inline)]
|
||||||
|
pub use document_setup_dialog_message::{DocumentSetupDialogMessage, DocumentSetupDialogMessageDiscriminant};
|
||||||
|
#[doc(inline)]
|
||||||
|
pub use document_setup_dialog_message_handler::{DocumentSetupDialogMessageHandler, resolution_row};
|
||||||
@@ -14,7 +14,10 @@ pub struct ExportDialogMessageHandler {
|
|||||||
pub file_type: FileType,
|
pub file_type: FileType,
|
||||||
pub scale_factor: f64,
|
pub scale_factor: f64,
|
||||||
pub bounds: ExportBounds,
|
pub bounds: ExportBounds,
|
||||||
pub artboards: HashMap<LayerNodeIdentifier, String>,
|
/// Whether the bounds were picked in the dialog, rather than left at the default of the file type, which a change of file type replaces.
|
||||||
|
pub bounds_chosen: bool,
|
||||||
|
/// Each artboard with its name, from the top of the Layers panel down.
|
||||||
|
pub artboards: Vec<(LayerNodeIdentifier, String)>,
|
||||||
pub has_selection: bool,
|
pub has_selection: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -24,6 +27,7 @@ impl Default for ExportDialogMessageHandler {
|
|||||||
file_type: Default::default(),
|
file_type: Default::default(),
|
||||||
scale_factor: 1.,
|
scale_factor: 1.,
|
||||||
bounds: Default::default(),
|
bounds: Default::default(),
|
||||||
|
bounds_chosen: false,
|
||||||
artboards: Default::default(),
|
artboards: Default::default(),
|
||||||
has_selection: false,
|
has_selection: false,
|
||||||
}
|
}
|
||||||
@@ -36,20 +40,23 @@ impl MessageHandler<ExportDialogMessage, ExportDialogMessageContext<'_>> for Exp
|
|||||||
let ExportDialogMessageContext { portfolio } = context;
|
let ExportDialogMessageContext { portfolio } = context;
|
||||||
|
|
||||||
match message {
|
match message {
|
||||||
ExportDialogMessage::FileType { file_type } => self.file_type = file_type,
|
ExportDialogMessage::FileType { file_type } => {
|
||||||
|
self.file_type = file_type;
|
||||||
|
if !self.bounds_chosen {
|
||||||
|
self.bounds = self.default_bounds();
|
||||||
|
}
|
||||||
|
}
|
||||||
ExportDialogMessage::ScaleFactor { factor } => self.scale_factor = factor,
|
ExportDialogMessage::ScaleFactor { factor } => self.scale_factor = factor,
|
||||||
ExportDialogMessage::ExportBounds { bounds } => self.bounds = bounds,
|
ExportDialogMessage::ExportBounds { bounds } => {
|
||||||
|
self.bounds = bounds;
|
||||||
|
self.bounds_chosen = true;
|
||||||
|
}
|
||||||
|
|
||||||
ExportDialogMessage::Submit => {
|
ExportDialogMessage::Submit => {
|
||||||
// Fall back to "All Artwork" if "Selection" was chosen but nothing is currently selected
|
let bounds = self.current_bounds();
|
||||||
let bounds = if !self.has_selection && self.bounds == ExportBounds::Selection {
|
|
||||||
ExportBounds::AllArtwork
|
|
||||||
} else {
|
|
||||||
self.bounds
|
|
||||||
};
|
|
||||||
|
|
||||||
let artboard_name = match bounds {
|
let artboard_name = match bounds {
|
||||||
ExportBounds::Artboard(layer) => self.artboards.get(&layer).cloned(),
|
ExportBounds::Artboard(layer) => self.artboards.iter().find(|(artboard, _)| *artboard == layer).map(|(_, name)| name.clone()),
|
||||||
_ => None,
|
_ => None,
|
||||||
};
|
};
|
||||||
responses.add_front(PortfolioMessage::SubmitDocumentExport {
|
responses.add_front(PortfolioMessage::SubmitDocumentExport {
|
||||||
@@ -70,6 +77,23 @@ impl MessageHandler<ExportDialogMessage, ExportDialogMessageContext<'_>> for Exp
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl ExportDialogMessageHandler {
|
||||||
|
/// The bounds a file type starts with: each artboard as its own page for a PDF, or otherwise all the artwork.
|
||||||
|
pub fn default_bounds(&self) -> ExportBounds {
|
||||||
|
if self.file_type == FileType::Pdf { ExportBounds::AllArtboards } else { ExportBounds::AllArtwork }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The chosen bounds, falling back to the default and then "All Artwork" in place of a choice that isn't currently available.
|
||||||
|
fn current_bounds(&self) -> ExportBounds {
|
||||||
|
let available = |bounds: &ExportBounds| match bounds {
|
||||||
|
ExportBounds::Selection => self.has_selection,
|
||||||
|
ExportBounds::AllArtboards => self.file_type == FileType::Pdf && !self.artboards.is_empty(),
|
||||||
|
ExportBounds::AllArtwork | ExportBounds::Artboard(_) => true,
|
||||||
|
};
|
||||||
|
[self.bounds, self.default_bounds()].into_iter().find(available).unwrap_or(ExportBounds::AllArtwork)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl DialogLayoutHolder for ExportDialogMessageHandler {
|
impl DialogLayoutHolder for ExportDialogMessageHandler {
|
||||||
const ICON: &'static str = "File";
|
const ICON: &'static str = "File";
|
||||||
const TITLE: &'static str = "Export";
|
const TITLE: &'static str = "Export";
|
||||||
@@ -94,9 +118,9 @@ impl DialogLayoutHolder for ExportDialogMessageHandler {
|
|||||||
|
|
||||||
impl LayoutHolder for ExportDialogMessageHandler {
|
impl LayoutHolder for ExportDialogMessageHandler {
|
||||||
fn layout(&self) -> Layout {
|
fn layout(&self) -> Layout {
|
||||||
// The vector type, then the raster ones
|
// The vector types, then the raster ones
|
||||||
let file_types = [
|
let file_types = [
|
||||||
vec![(FileType::Svg, "SVG")],
|
vec![(FileType::Svg, "SVG"), (FileType::Pdf, "PDF")],
|
||||||
vec![
|
vec![
|
||||||
(FileType::Png, "PNG"),
|
(FileType::Png, "PNG"),
|
||||||
(FileType::Jpg, "JPG"),
|
(FileType::Jpg, "JPG"),
|
||||||
@@ -139,7 +163,7 @@ impl LayoutHolder for ExportDialogMessageHandler {
|
|||||||
.min(0.)
|
.min(0.)
|
||||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||||
.increment_step(0.5)
|
.increment_step(0.5)
|
||||||
.disabled(self.file_type == FileType::Svg)
|
.disabled(matches!(self.file_type, FileType::Svg | FileType::Pdf))
|
||||||
.on_update(|number_input: &NumberInput| ExportDialogMessage::ScaleFactor { factor: number_input.value.unwrap() }.into())
|
.on_update(|number_input: &NumberInput| ExportDialogMessage::ScaleFactor { factor: number_input.value.unwrap() }.into())
|
||||||
.sizing(WidgetSizing::default().min_width(200))
|
.sizing(WidgetSizing::default().min_width(200))
|
||||||
.widget_instance(),
|
.widget_instance(),
|
||||||
@@ -149,15 +173,12 @@ impl LayoutHolder for ExportDialogMessageHandler {
|
|||||||
(ExportBounds::AllArtwork, "All Artwork".to_string(), false),
|
(ExportBounds::AllArtwork, "All Artwork".to_string(), false),
|
||||||
(ExportBounds::Selection, "Selection".to_string(), !self.has_selection),
|
(ExportBounds::Selection, "Selection".to_string(), !self.has_selection),
|
||||||
];
|
];
|
||||||
let artboards = self.artboards.iter().map(|(&layer, name)| (ExportBounds::Artboard(layer), name.to_string(), false)).collect();
|
// Only a PDF can hold every artboard, each as its own page
|
||||||
let choices = [standard_bounds, artboards];
|
let all_artboards = (!self.artboards.is_empty()).then(|| (ExportBounds::AllArtboards, "All Artboards".to_string(), self.file_type != FileType::Pdf));
|
||||||
|
let artboards = self.artboards.iter().map(|(layer, name)| (ExportBounds::Artboard(*layer), name.to_string(), false));
|
||||||
|
let choices = [standard_bounds, all_artboards.into_iter().chain(artboards).collect()];
|
||||||
|
|
||||||
// Fall back to "All Artwork" if "Selection" was chosen but nothing is currently selected
|
let current_bounds = self.current_bounds();
|
||||||
let current_bounds = if !self.has_selection && self.bounds == ExportBounds::Selection {
|
|
||||||
ExportBounds::AllArtwork
|
|
||||||
} else {
|
|
||||||
self.bounds
|
|
||||||
};
|
|
||||||
let index = choices.iter().flatten().position(|(bounds, _, _)| *bounds == current_bounds).unwrap_or(0);
|
let index = choices.iter().flatten().position(|(bounds, _, _)| *bounds == current_bounds).unwrap_or(0);
|
||||||
|
|
||||||
let mut entries = choices
|
let mut entries = choices
|
||||||
@@ -188,3 +209,44 @@ impl LayoutHolder for ExportDialogMessageHandler {
|
|||||||
Layout(vec![LayoutGroup::row(export_type), LayoutGroup::row(resolution), LayoutGroup::row(export_area)])
|
Layout(vec![LayoutGroup::row(export_type), LayoutGroup::row(resolution), LayoutGroup::row(export_area)])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::test_utils::EditorTestUtils;
|
||||||
|
use graphene_std::uuid::NodeId;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_pdf_defaults_to_every_artboard_as_a_page() {
|
||||||
|
let editor = EditorTestUtils::create();
|
||||||
|
let portfolio = editor.portfolio_message_handler();
|
||||||
|
let mut dialog = ExportDialogMessageHandler {
|
||||||
|
artboards: vec![(LayerNodeIdentifier::new_unchecked(NodeId(1)), "Artboard".to_string())],
|
||||||
|
has_selection: true,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let send = |dialog: &mut ExportDialogMessageHandler, message: ExportDialogMessage| dialog.process_message(message, &mut VecDeque::new(), ExportDialogMessageContext { portfolio });
|
||||||
|
|
||||||
|
// Bounds left at the default follow the file type between PDF and a single image
|
||||||
|
send(&mut dialog, ExportDialogMessage::FileType { file_type: FileType::Pdf });
|
||||||
|
assert_eq!(dialog.current_bounds(), ExportBounds::AllArtboards);
|
||||||
|
send(&mut dialog, ExportDialogMessage::FileType { file_type: FileType::Png });
|
||||||
|
assert_eq!(dialog.current_bounds(), ExportBounds::AllArtwork);
|
||||||
|
|
||||||
|
// A choice of other bounds stays through a change of file type
|
||||||
|
send(&mut dialog, ExportDialogMessage::ExportBounds { bounds: ExportBounds::Selection });
|
||||||
|
send(&mut dialog, ExportDialogMessage::FileType { file_type: FileType::Pdf });
|
||||||
|
assert_eq!(dialog.current_bounds(), ExportBounds::Selection);
|
||||||
|
|
||||||
|
// Even a choice of the bounds another file type defaults to
|
||||||
|
send(&mut dialog, ExportDialogMessage::ExportBounds { bounds: ExportBounds::AllArtwork });
|
||||||
|
send(&mut dialog, ExportDialogMessage::FileType { file_type: FileType::Png });
|
||||||
|
send(&mut dialog, ExportDialogMessage::FileType { file_type: FileType::Pdf });
|
||||||
|
assert_eq!(dialog.current_bounds(), ExportBounds::AllArtwork);
|
||||||
|
|
||||||
|
// Without artboards, a PDF falls back to one page of all the artwork
|
||||||
|
send(&mut dialog, ExportDialogMessage::ExportBounds { bounds: ExportBounds::AllArtboards });
|
||||||
|
dialog.artboards.clear();
|
||||||
|
assert_eq!(dialog.current_bounds(), ExportBounds::AllArtwork);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@
|
|||||||
mod dialog_message;
|
mod dialog_message;
|
||||||
mod dialog_message_handler;
|
mod dialog_message_handler;
|
||||||
|
|
||||||
|
pub mod document_setup_dialog;
|
||||||
pub mod export_dialog;
|
pub mod export_dialog;
|
||||||
pub mod new_document_dialog;
|
pub mod new_document_dialog;
|
||||||
pub mod preferences_dialog;
|
pub mod preferences_dialog;
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
use crate::messages::prelude::*;
|
use crate::messages::prelude::*;
|
||||||
|
use graphene_std::units::TypedLength;
|
||||||
|
|
||||||
#[impl_message(Message, DialogMessage, NewDocumentDialog)]
|
#[impl_message(Message, DialogMessage, NewDocumentDialog)]
|
||||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||||
pub enum NewDocumentDialogMessage {
|
pub enum NewDocumentDialogMessage {
|
||||||
Name { name: String },
|
Name { name: String },
|
||||||
Infinite { infinite: bool },
|
Infinite { infinite: bool },
|
||||||
DimensionsX { width: f64 },
|
DimensionsX { width: TypedLength },
|
||||||
DimensionsY { height: f64 },
|
DimensionsY { height: TypedLength },
|
||||||
|
Resolution { pixels_per_inch: f64 },
|
||||||
|
|
||||||
Submit,
|
Submit,
|
||||||
}
|
}
|
||||||
+220
-29
@@ -1,16 +1,34 @@
|
|||||||
|
use crate::messages::dialog::document_setup_dialog::resolution_row;
|
||||||
|
use crate::messages::layout::layout_message_handler::unit_suffix;
|
||||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||||
|
use crate::messages::portfolio::document::node_graph::node_inspector::length_decimal_places;
|
||||||
use crate::messages::prelude::*;
|
use crate::messages::prelude::*;
|
||||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||||
use glam::UVec2;
|
use glam::DVec2;
|
||||||
use graph_craft::document::NodeId;
|
use graph_craft::document::NodeId;
|
||||||
use graphene_std::Color;
|
use graphene_std::Color;
|
||||||
|
use graphene_std::units::{DEFAULT_PIXELS_PER_INCH, LengthUnit, TypedLength, TypedLengthVec2};
|
||||||
|
|
||||||
/// A dialog to allow users to set some initial options about a new document.
|
/// A dialog to allow users to set some initial options about a new document.
|
||||||
#[derive(Debug, Clone, Default, ExtractField)]
|
#[derive(Debug, Clone, ExtractField)]
|
||||||
pub struct NewDocumentDialogMessageHandler {
|
pub struct NewDocumentDialogMessageHandler {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub infinite: bool,
|
pub infinite: bool,
|
||||||
pub dimensions: UVec2,
|
pub width: TypedLength,
|
||||||
|
pub height: TypedLength,
|
||||||
|
pub pixels_per_inch: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for NewDocumentDialogMessageHandler {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
name: String::new(),
|
||||||
|
infinite: false,
|
||||||
|
width: TypedLength::default(),
|
||||||
|
height: TypedLength::default(),
|
||||||
|
pixels_per_inch: DEFAULT_PIXELS_PER_INCH,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[message_handler_data]
|
#[message_handler_data]
|
||||||
@@ -19,24 +37,38 @@ impl MessageHandler<NewDocumentDialogMessage, ()> for NewDocumentDialogMessageHa
|
|||||||
match message {
|
match message {
|
||||||
NewDocumentDialogMessage::Name { name } => self.name = name,
|
NewDocumentDialogMessage::Name { name } => self.name = name,
|
||||||
NewDocumentDialogMessage::Infinite { infinite } => self.infinite = infinite,
|
NewDocumentDialogMessage::Infinite { infinite } => self.infinite = infinite,
|
||||||
NewDocumentDialogMessage::DimensionsX { width } => self.dimensions.x = width as u32,
|
NewDocumentDialogMessage::DimensionsX { width } => {
|
||||||
NewDocumentDialogMessage::DimensionsY { height } => self.dimensions.y = height as u32,
|
self.width = whole_pixels(width);
|
||||||
|
self.height = self.in_unit(self.height, self.width.unit);
|
||||||
|
}
|
||||||
|
NewDocumentDialogMessage::DimensionsY { height } => {
|
||||||
|
self.height = whole_pixels(height);
|
||||||
|
self.width = self.in_unit(self.width, self.height.unit);
|
||||||
|
}
|
||||||
|
NewDocumentDialogMessage::Resolution { pixels_per_inch } => self.pixels_per_inch = pixels_per_inch,
|
||||||
NewDocumentDialogMessage::Submit => {
|
NewDocumentDialogMessage::Submit => {
|
||||||
responses.add(PortfolioMessage::NewDocumentWithName { name: self.name.clone() });
|
responses.add(PortfolioMessage::NewDocumentWithName { name: self.name.clone() });
|
||||||
|
|
||||||
|
// Like the artboard, the resolution is part of the document's starting state rather than an undo step
|
||||||
|
responses.add(DocumentMessage::SetPixelsPerInch {
|
||||||
|
pixels_per_inch: self.pixels_per_inch,
|
||||||
|
});
|
||||||
|
|
||||||
|
let dimensions = self.artboard_dimensions();
|
||||||
|
let pixels = dimensions.to_length_vec2(self.pixels_per_inch).pixels();
|
||||||
if self.infinite {
|
if self.infinite {
|
||||||
// Infinite canvas: add a locked white background layer
|
// Infinite canvas: add a locked white background layer
|
||||||
graph_modification_utils::new_background_layer(0, responses);
|
graph_modification_utils::new_background_layer(0, responses);
|
||||||
} else if self.dimensions.x > 0 && self.dimensions.y > 0 {
|
} else if pixels.x > 0. && pixels.y > 0. {
|
||||||
// Finite canvas: create an artboard with the specified dimensions
|
// Finite canvas: create an artboard with the specified dimensions
|
||||||
responses.add(GraphOperationMessage::NewArtboard {
|
responses.add(GraphOperationMessage::NewArtboard {
|
||||||
id: NodeId::new(),
|
id: NodeId::new(),
|
||||||
location: glam::DVec2::ZERO,
|
location: DVec2::ZERO,
|
||||||
dimensions: self.dimensions.as_dvec2(),
|
dimensions,
|
||||||
background: Color::WHITE,
|
background: Color::WHITE,
|
||||||
clip: true,
|
clip: true,
|
||||||
});
|
});
|
||||||
responses.add(NavigationMessage::CanvasPan { delta: self.dimensions.as_dvec2() });
|
responses.add(NavigationMessage::CanvasPan { delta: pixels });
|
||||||
}
|
}
|
||||||
|
|
||||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||||
@@ -107,32 +139,191 @@ impl LayoutHolder for NewDocumentDialogMessageHandler {
|
|||||||
.widget_instance(),
|
.widget_instance(),
|
||||||
];
|
];
|
||||||
|
|
||||||
let scale = vec![
|
// Each dimension shows the unit it was typed in and keeps any length unit typed into it
|
||||||
|
let dimension_field = |length: TypedLength, label: &str| {
|
||||||
|
NumberInput::new(Some(length.value))
|
||||||
|
.label(label)
|
||||||
|
.unit(unit_suffix(length.unit.symbol()))
|
||||||
|
.display_decimal_places(length_decimal_places(length.unit, self.pixels_per_inch))
|
||||||
|
.kept_units(LengthUnit::ALL.iter().map(|unit| unit.symbol().to_string()).collect())
|
||||||
|
.pixels_per_inch(self.pixels_per_inch)
|
||||||
|
.min(0.)
|
||||||
|
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||||
|
.disabled(self.infinite)
|
||||||
|
.sizing(WidgetSizing::default().min_width(100))
|
||||||
|
};
|
||||||
|
let dimensions = vec![
|
||||||
TextLabel::new("Dimensions").table_align(true).sizing(WidgetSizing::fixed(90)).widget_instance(),
|
TextLabel::new("Dimensions").table_align(true).sizing(WidgetSizing::fixed(90)).widget_instance(),
|
||||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||||
NumberInput::new(Some(self.dimensions.x as f64))
|
dimension_field(self.width, "W")
|
||||||
.label("W")
|
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsX { width: typed_length(number_input) }.into())
|
||||||
.unit(" px")
|
|
||||||
.min(0.)
|
|
||||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
|
||||||
.is_integer(true)
|
|
||||||
.disabled(self.infinite)
|
|
||||||
.sizing(WidgetSizing::default().min_width(100))
|
|
||||||
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsX { width: number_input.value.unwrap() }.into())
|
|
||||||
.widget_instance(),
|
.widget_instance(),
|
||||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||||
NumberInput::new(Some(self.dimensions.y as f64))
|
dimension_field(self.height, "H")
|
||||||
.label("H")
|
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsY { height: typed_length(number_input) }.into())
|
||||||
.unit(" px")
|
|
||||||
.min(0.)
|
|
||||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
|
||||||
.is_integer(true)
|
|
||||||
.disabled(self.infinite)
|
|
||||||
.sizing(WidgetSizing::default().min_width(100))
|
|
||||||
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsY { height: number_input.value.unwrap() }.into())
|
|
||||||
.widget_instance(),
|
.widget_instance(),
|
||||||
];
|
];
|
||||||
|
|
||||||
Layout(vec![LayoutGroup::row(name), LayoutGroup::row(infinite), LayoutGroup::row(scale)])
|
let resolution = resolution_row(self.pixels_per_inch, |pixels_per_inch| NewDocumentDialogMessage::Resolution { pixels_per_inch }.into());
|
||||||
|
|
||||||
|
Layout(vec![LayoutGroup::row(name), LayoutGroup::row(infinite), LayoutGroup::row(dimensions), LayoutGroup::row(resolution)])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NewDocumentDialogMessageHandler {
|
||||||
|
/// A dimension converted into `unit` at the chosen resolution, keeping its size.
|
||||||
|
fn in_unit(&self, length: TypedLength, unit: LengthUnit) -> TypedLength {
|
||||||
|
whole_pixels(TypedLength {
|
||||||
|
value: length.unit.convert(length.value, unit, self.pixels_per_inch),
|
||||||
|
unit,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The artboard's size in the unit both dimensions share, like an A4 page in millimeters.
|
||||||
|
pub fn artboard_dimensions(&self) -> TypedLengthVec2 {
|
||||||
|
TypedLengthVec2 {
|
||||||
|
value: DVec2::new(self.width.value, self.height.value),
|
||||||
|
unit: self.width.unit,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The length a dimension field holds, in the unit it shows.
|
||||||
|
fn typed_length(number_input: &NumberInput) -> TypedLength {
|
||||||
|
let unit = math_parser::units::Unit::named(number_input.unit.trim()).and_then(LengthUnit::from_unit).unwrap_or_default();
|
||||||
|
TypedLength {
|
||||||
|
value: number_input.value.unwrap_or_default(),
|
||||||
|
unit,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rounds a dimension typed in pixels to a whole number of them, leaving one in a physical unit as typed.
|
||||||
|
fn whole_pixels(length: TypedLength) -> TypedLength {
|
||||||
|
if length.unit == LengthUnit::Pixel { TypedLength::pixels(length.value.round()) } else { length }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::NewDocumentDialogMessageHandler;
|
||||||
|
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||||
|
use crate::messages::portfolio::document::node_graph::document_node_definitions::ARTBOARD_DIMENSIONS_INPUT_INDEX;
|
||||||
|
use crate::test_utils::test_prelude::*;
|
||||||
|
use graph_craft::document::value::TaggedValue;
|
||||||
|
use graphene_std::units::{LengthUnit, TypedLengthVec2};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
/// Commits text into the dialog's number field with this label or tooltip label, as the frontend sends a typed entry.
|
||||||
|
fn type_into_field(editor: &mut EditorTestUtils, label: &str, text: &str) {
|
||||||
|
// A widget's ID follows from its place in the layout, which the dialog's state doesn't change
|
||||||
|
let mut layout = NewDocumentDialogMessageHandler::default().layout();
|
||||||
|
layout.replace_widget_ids(LayoutTarget::DialogColumn1, &mut Vec::new(), &HashMap::new());
|
||||||
|
let widget_id = layout.iter().find_map(|instance| match &*instance.widget {
|
||||||
|
Widget::NumberInput(number_input) if number_input.label == label || number_input.tooltip_label == label => Some(instance.widget_id),
|
||||||
|
_ => None,
|
||||||
|
});
|
||||||
|
let Some(widget_id) = widget_id else {
|
||||||
|
panic!("the dialog has no number field labeled \"{label}\"")
|
||||||
|
};
|
||||||
|
|
||||||
|
editor.dispatch(LayoutMessage::WidgetValueUpdate {
|
||||||
|
layout_target: LayoutTarget::DialogColumn1,
|
||||||
|
widget_id,
|
||||||
|
value: serde_json::Value::String(text.into()),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn create_document(editor: &mut EditorTestUtils) {
|
||||||
|
editor
|
||||||
|
.handle_message(DialogMessage::CloseAndThen {
|
||||||
|
followups: vec![NewDocumentDialogMessage::Submit.into()],
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn artboard_dimensions(editor: &EditorTestUtils) -> Option<TaggedValue> {
|
||||||
|
let network_interface = &editor.active_document().network_interface;
|
||||||
|
let artboard = network_interface.all_artboards().into_iter().next()?;
|
||||||
|
let node = network_interface.document_network().nodes.get(&artboard.to_node())?;
|
||||||
|
|
||||||
|
node.inputs.get(ARTBOARD_DIMENSIONS_INPUT_INDEX)?.as_value().cloned()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn artboard_pixels(editor: &EditorTestUtils) -> Option<DVec2> {
|
||||||
|
let pixels_per_inch = editor.active_document().network_interface.pixels_per_inch();
|
||||||
|
artboard_dimensions(editor)?.as_length_vec2_pixels(pixels_per_inch).map(DVec2::round)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_new_document_starts_at_the_chosen_resolution_without_an_undo_step() {
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.dispatch(DialogMessage::RequestNewDocumentDialog);
|
||||||
|
type_into_field(&mut editor, "Resolution", "300");
|
||||||
|
create_document(&mut editor).await;
|
||||||
|
assert_eq!(editor.active_document().network_interface.pixels_per_inch(), 300.);
|
||||||
|
assert_eq!(artboard_pixels(&editor), Some(DVec2::new(1920., 1080.)));
|
||||||
|
|
||||||
|
editor.handle_message(DocumentMessage::Undo).await;
|
||||||
|
assert_eq!(editor.active_document().network_interface.pixels_per_inch(), 300.);
|
||||||
|
assert_eq!(artboard_pixels(&editor), Some(DVec2::new(1920., 1080.)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn typing_a_unit_into_one_dimension_converts_the_other_into_it() {
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.dispatch(DialogMessage::RequestNewDocumentDialog);
|
||||||
|
type_into_field(&mut editor, "W", "210mm");
|
||||||
|
|
||||||
|
// The height of 1080 px at 96 PPI became 285.75 mm, so it grows with the resolution like the width
|
||||||
|
type_into_field(&mut editor, "Resolution", "300");
|
||||||
|
create_document(&mut editor).await;
|
||||||
|
assert_eq!(artboard_pixels(&editor), Some(DVec2::new(2480., 3375.)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn dimensions_typed_in_millimeters_convert_to_pixels_at_the_chosen_resolution() {
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.dispatch(DialogMessage::RequestNewDocumentDialog);
|
||||||
|
type_into_field(&mut editor, "W", "210mm");
|
||||||
|
type_into_field(&mut editor, "H", "297mm");
|
||||||
|
|
||||||
|
// The lengths stay in millimeters, so their size in pixels follows a resolution chosen after them
|
||||||
|
type_into_field(&mut editor, "Resolution", "300");
|
||||||
|
create_document(&mut editor).await;
|
||||||
|
assert_eq!(artboard_pixels(&editor), Some(DVec2::new(2480., 3508.)));
|
||||||
|
|
||||||
|
// The artboard keeps the millimeters, so changing the resolution later keeps the page's physical size
|
||||||
|
let a4 = TaggedValue::LengthVec2(TypedLengthVec2 {
|
||||||
|
value: DVec2::new(210., 297.),
|
||||||
|
unit: LengthUnit::Millimeter,
|
||||||
|
});
|
||||||
|
assert_eq!(artboard_dimensions(&editor), Some(a4));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn moving_an_artboard_sized_in_millimeters_keeps_its_millimeters() {
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.dispatch(DialogMessage::RequestNewDocumentDialog);
|
||||||
|
type_into_field(&mut editor, "W", "210mm");
|
||||||
|
type_into_field(&mut editor, "H", "297mm");
|
||||||
|
create_document(&mut editor).await;
|
||||||
|
let a4 = artboard_dimensions(&editor);
|
||||||
|
|
||||||
|
// Tools move and nudge an artboard by resizing it to its own size in whole pixels, which 793.7 x 1122.5 px rounds to
|
||||||
|
let layer = editor
|
||||||
|
.active_document()
|
||||||
|
.network_interface
|
||||||
|
.all_artboards()
|
||||||
|
.into_iter()
|
||||||
|
.next()
|
||||||
|
.expect("the document should have an artboard");
|
||||||
|
let dimensions = artboard_pixels(&editor).expect("the artboard should have dimensions");
|
||||||
|
editor
|
||||||
|
.handle_message(GraphOperationMessage::ResizeArtboard {
|
||||||
|
layer,
|
||||||
|
location: DVec2::new(10., 0.),
|
||||||
|
dimensions,
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
assert_eq!(artboard_dimensions(&editor), a4);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -78,6 +78,7 @@ pub enum FileType {
|
|||||||
Tga,
|
Tga,
|
||||||
Ico,
|
Ico,
|
||||||
Svg,
|
Svg,
|
||||||
|
Pdf,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FileType {
|
impl FileType {
|
||||||
@@ -91,6 +92,7 @@ impl FileType {
|
|||||||
FileType::Tga => "tga",
|
FileType::Tga => "tga",
|
||||||
FileType::Ico => "ico",
|
FileType::Ico => "ico",
|
||||||
FileType::Svg => "svg",
|
FileType::Svg => "svg",
|
||||||
|
FileType::Pdf => "pdf",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -104,6 +106,7 @@ impl FileType {
|
|||||||
FileType::Tga => "TGA Image",
|
FileType::Tga => "TGA Image",
|
||||||
FileType::Ico => "ICO Image",
|
FileType::Ico => "ICO Image",
|
||||||
FileType::Svg => "SVG Image",
|
FileType::Svg => "SVG Image",
|
||||||
|
FileType::Pdf => "PDF Document",
|
||||||
};
|
};
|
||||||
FileFilter {
|
FileFilter {
|
||||||
name: name.into(),
|
name: name.into(),
|
||||||
@@ -130,6 +133,7 @@ impl FileType {
|
|||||||
FileType::Tga => ImageFormat::Tga,
|
FileType::Tga => ImageFormat::Tga,
|
||||||
FileType::Ico => ImageFormat::Ico,
|
FileType::Ico => ImageFormat::Ico,
|
||||||
FileType::Svg => return Err("SVG cannot be exported from an image buffer".to_string()),
|
FileType::Svg => return Err("SVG cannot be exported from an image buffer".to_string()),
|
||||||
|
FileType::Pdf => return Err("PDF cannot be exported from an image buffer".to_string()),
|
||||||
};
|
};
|
||||||
if self == FileType::Ico && (width > 256 || height > 256) {
|
if self == FileType::Ico && (width > 256 || height > 256) {
|
||||||
return Err("An ICO image can be at most 256 pixels wide and tall. Lower the scale factor or choose a smaller export area.".to_string());
|
return Err("An ICO image can be at most 256 pixels wide and tall. Lower the scale factor or choose a smaller export area.".to_string());
|
||||||
@@ -164,6 +168,8 @@ pub enum ExportBounds {
|
|||||||
#[default]
|
#[default]
|
||||||
AllArtwork,
|
AllArtwork,
|
||||||
Selection,
|
Selection,
|
||||||
|
/// Each artboard as its own page, for a file type that holds pages.
|
||||||
|
AllArtboards,
|
||||||
Artboard(LayerNodeIdentifier),
|
Artboard(LayerNodeIdentifier),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -228,6 +234,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn file_types_that_cannot_hold_the_image_say_so() {
|
fn file_types_that_cannot_hold_the_image_say_so() {
|
||||||
assert!(FileType::Svg.encode(1, 1, vec![0; 4]).is_err());
|
assert!(FileType::Svg.encode(1, 1, vec![0; 4]).is_err());
|
||||||
|
assert!(FileType::Pdf.encode(1, 1, vec![0; 4]).is_err());
|
||||||
assert!(FileType::Png.encode(2, 2, vec![0; 4]).is_err());
|
assert!(FileType::Png.encode(2, 2, vec![0; 4]).is_err());
|
||||||
|
|
||||||
let too_large = FileType::Ico.encode(257, 1, vec![0; 257 * 4]).unwrap_err();
|
let too_large = FileType::Ico.encode(257, 1, vec![0; 257 * 4]).unwrap_err();
|
||||||
|
|||||||
@@ -417,16 +417,20 @@ impl LayoutMessageHandler {
|
|||||||
}
|
}
|
||||||
// A text-field commit sends the user's raw entry as a math expression to evaluate and validate.
|
// A text-field commit sends the user's raw entry as a math expression to evaluate and validate.
|
||||||
Value::String(expression) => {
|
Value::String(expression) => {
|
||||||
let Some(evaluated) = evaluate_and_validate_number_input(&expression, number_input) else { return };
|
let Some((evaluated, kept_unit)) = evaluate_and_validate_number_input(&expression, number_input) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let unit = kept_unit.map_or_else(|| number_input.unit.clone(), |symbol| unit_suffix(&symbol));
|
||||||
|
|
||||||
// Skip the update (and its history transaction) when the value is unchanged, since the network interface would short-circuit it anyway.
|
// Skip the update (and its history transaction) when the value is unchanged, since the network interface would short-circuit it anyway.
|
||||||
if number_input.value == Some(evaluated) {
|
if number_input.value == Some(evaluated) && number_input.unit == unit {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Snapshot the pre-change state for undo via `on_commit`, then apply the new value via `on_update`.
|
// Snapshot the pre-change state for undo via `on_commit`, then apply the new value via `on_update`.
|
||||||
responses.add((number_input.on_commit.callback)(&()));
|
responses.add((number_input.on_commit.callback)(&()));
|
||||||
number_input.value = Some(evaluated);
|
number_input.value = Some(evaluated);
|
||||||
|
number_input.unit = unit;
|
||||||
responses.add((number_input.on_update.callback)(number_input));
|
responses.add((number_input.on_update.callback)(number_input));
|
||||||
}
|
}
|
||||||
// The increment arrows send `{ "increment": "Increase" | "Decrease" }` to invoke the backend's directional step callback.
|
// The increment arrows send `{ "increment": "Increase" | "Decrease" }` to invoke the backend's directional step callback.
|
||||||
@@ -704,21 +708,41 @@ fn populate_computed_display_fields(layout: &mut Layout) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Evaluates a math expression committed in a `NumberInput`'s text field, then clamps and rounds it to the widget's constraints.
|
/// The suffix a field shows after a number in this unit: a space before a word like `mm`, and none before a symbol like `°` or `%`.
|
||||||
/// Returns `None` if the expression fails to parse, fails to evaluate, or yields a non-real number (such as `sqrt(-1)`).
|
pub fn unit_suffix(symbol: &str) -> String {
|
||||||
fn evaluate_and_validate_number_input(expression: &str, number_input: &NumberInput) -> Option<f64> {
|
if symbol.starts_with(char::is_alphabetic) { format!(" {symbol}") } else { symbol.to_string() }
|
||||||
let value = math_parser::evaluate(expression)
|
}
|
||||||
|
|
||||||
|
/// Evaluates a math expression committed in a `NumberInput`'s text field, then clamps and rounds it to the widget's constraints, giving
|
||||||
|
/// the unit it keeps where the field keeps the unit a value is typed in. Returns `None` if the expression fails to parse, fails to
|
||||||
|
/// evaluate, yields a non-real number (such as `sqrt(-1)`), or measures something the field doesn't (such as `5s` in a length field).
|
||||||
|
fn evaluate_and_validate_number_input(expression: &str, number_input: &NumberInput) -> Option<(f64, Option<String>)> {
|
||||||
|
let context = math_parser::context::EvalContext::default().with_pixels_per_inch(number_input.pixels_per_inch);
|
||||||
|
let value = math_parser::ast::Node::try_parse_from_str(expression)
|
||||||
.inspect_err(|err| error!("Math parser error on \"{expression}\": {err}"))
|
.inspect_err(|err| error!("Math parser error on \"{expression}\": {err}"))
|
||||||
.ok()?
|
.ok()?
|
||||||
|
.eval(&context)
|
||||||
.inspect_err(|err| error!("Math evaluate error on \"{expression}\": {err}"))
|
.inspect_err(|err| error!("Math evaluate error on \"{expression}\": {err}"))
|
||||||
.ok()?;
|
.ok()?;
|
||||||
|
|
||||||
let real = value.as_real()?;
|
// The result reads in the field's unit, where a plain number is already in it and a unit like `mm` converts into it
|
||||||
if real.is_nan() {
|
let field_unit = math_parser::units::Unit::named(number_input.unit.trim());
|
||||||
|
let (in_field_unit, quantity) = match (value.as_quantity(), field_unit) {
|
||||||
|
(Some(quantity), Some(unit)) => {
|
||||||
|
let read = quantity
|
||||||
|
.read_in(unit, number_input.pixels_per_inch)
|
||||||
|
.inspect_err(|_| error!("\"{expression}\" is {}, which a field in `{unit}` can't hold", quantity.dimension().description()))
|
||||||
|
.ok()?
|
||||||
|
.as_real()?;
|
||||||
|
(read, Some(*quantity))
|
||||||
|
}
|
||||||
|
_ => (value.as_real()?, None),
|
||||||
|
};
|
||||||
|
if in_field_unit.is_nan() {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut validated = real;
|
let mut validated = in_field_unit;
|
||||||
if let Some(min) = number_input.min {
|
if let Some(min) = number_input.min {
|
||||||
validated = validated.max(min);
|
validated = validated.max(min);
|
||||||
}
|
}
|
||||||
@@ -729,5 +753,17 @@ fn evaluate_and_validate_number_input(expression: &str, number_input: &NumberInp
|
|||||||
validated = validated.round();
|
validated = validated.round();
|
||||||
}
|
}
|
||||||
|
|
||||||
Some(validated)
|
// A value typed in a unit the field keeps stays in it, unless the field's limits moved it
|
||||||
|
let kept_unit = quantity.and_then(|quantity| {
|
||||||
|
let symbol = quantity.unit.single()?.definition().symbol;
|
||||||
|
number_input.kept_units.iter().any(|kept| kept == symbol).then_some((quantity, symbol))
|
||||||
|
});
|
||||||
|
if let Some((quantity, symbol)) = kept_unit
|
||||||
|
&& validated == in_field_unit
|
||||||
|
&& let Some(kept_value) = quantity.value.as_real()
|
||||||
|
{
|
||||||
|
return Some((kept_value, Some(symbol.to_string())));
|
||||||
|
}
|
||||||
|
|
||||||
|
Some((validated, None))
|
||||||
}
|
}
|
||||||
@@ -247,6 +247,14 @@ pub struct NumberInput {
|
|||||||
#[serde(rename = "unitIsHiddenWhenEditing")]
|
#[serde(rename = "unitIsHiddenWhenEditing")]
|
||||||
#[derivative(Default(value = "true"))]
|
#[derivative(Default(value = "true"))]
|
||||||
pub unit_is_hidden_when_editing: bool,
|
pub unit_is_hidden_when_editing: bool,
|
||||||
|
/// The units, by symbol, that a typed value keeps rather than converting into the field's `unit`, like `mm` in a length field
|
||||||
|
/// that remembers the unit a length was typed in. A kept unit becomes the field's `unit`.
|
||||||
|
#[serde(skip)]
|
||||||
|
pub kept_units: Vec<String>,
|
||||||
|
/// The size of a pixel against an inch for converting a typed physical length, the document's resolution.
|
||||||
|
#[serde(skip)]
|
||||||
|
#[derivative(Default(value = "96."))]
|
||||||
|
pub pixels_per_inch: f64,
|
||||||
|
|
||||||
// Tooltips
|
// Tooltips
|
||||||
#[serde(rename = "tooltipLabel")]
|
#[serde(rename = "tooltipLabel")]
|
||||||
@@ -607,6 +615,7 @@ pub enum MathExpressionRole {
|
|||||||
Function,
|
Function,
|
||||||
Keyword,
|
Keyword,
|
||||||
Operator,
|
Operator,
|
||||||
|
Unit,
|
||||||
Bracket,
|
Bracket,
|
||||||
MatrixLiteral,
|
MatrixLiteral,
|
||||||
Error,
|
Error,
|
||||||
@@ -623,6 +632,7 @@ impl From<math_parser::highlight::Role> for MathExpressionRole {
|
|||||||
Role::Function => Self::Function,
|
Role::Function => Self::Function,
|
||||||
Role::Keyword => Self::Keyword,
|
Role::Keyword => Self::Keyword,
|
||||||
Role::Operator => Self::Operator,
|
Role::Operator => Self::Operator,
|
||||||
|
Role::Unit => Self::Unit,
|
||||||
Role::Bracket => Self::Bracket,
|
Role::Bracket => Self::Bracket,
|
||||||
Role::MatrixLiteral => Self::MatrixLiteral,
|
Role::MatrixLiteral => Self::MatrixLiteral,
|
||||||
Role::Error => Self::Error,
|
Role::Error => Self::Error,
|
||||||
|
|||||||
@@ -181,6 +181,13 @@ impl LayoutHolder for MenuBarMessageHandler {
|
|||||||
.on_commit(|_| DialogMessage::RequestExportDialog.into())
|
.on_commit(|_| DialogMessage::RequestExportDialog.into())
|
||||||
.disabled(no_active_document),
|
.disabled(no_active_document),
|
||||||
],
|
],
|
||||||
|
vec![
|
||||||
|
MenuListEntry::new("Document Setup…")
|
||||||
|
.label("Document Setup…")
|
||||||
|
.icon("Settings")
|
||||||
|
.on_commit(|_| DialogMessage::RequestDocumentSetupDialog.into())
|
||||||
|
.disabled(no_active_document),
|
||||||
|
],
|
||||||
#[cfg(not(target_os = "macos"))]
|
#[cfg(not(target_os = "macos"))]
|
||||||
vec![preferences],
|
vec![preferences],
|
||||||
])
|
])
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
|
|||||||
use graphene_std::transfer_curve::TransferCurve;
|
use graphene_std::transfer_curve::TransferCurve;
|
||||||
use graphene_std::transform::Footprint;
|
use graphene_std::transform::Footprint;
|
||||||
use graphene_std::transform::{ReferencePoint, ScaleType};
|
use graphene_std::transform::{ReferencePoint, ScaleType};
|
||||||
|
use graphene_std::units::{Angle, AngleVec2, Length, LengthVec2};
|
||||||
use graphene_std::vector::misc::{
|
use graphene_std::vector::misc::{
|
||||||
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod,
|
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod,
|
||||||
WeldMethod,
|
WeldMethod,
|
||||||
@@ -401,6 +402,10 @@ macro_rules! inspectable_types {
|
|||||||
List<Generator>,
|
List<Generator>,
|
||||||
List<String>,
|
List<String>,
|
||||||
List<f64>,
|
List<f64>,
|
||||||
|
List<Length>,
|
||||||
|
List<Angle>,
|
||||||
|
List<LengthVec2>,
|
||||||
|
List<AngleVec2>,
|
||||||
List<i64>,
|
List<i64>,
|
||||||
List<bool>,
|
List<bool>,
|
||||||
List<DVec2>,
|
List<DVec2>,
|
||||||
@@ -461,6 +466,10 @@ macro_rules! inspectable_types {
|
|||||||
Item<Generator>,
|
Item<Generator>,
|
||||||
Item<String>,
|
Item<String>,
|
||||||
Item<f64>,
|
Item<f64>,
|
||||||
|
Item<Length>,
|
||||||
|
Item<Angle>,
|
||||||
|
Item<LengthVec2>,
|
||||||
|
Item<AngleVec2>,
|
||||||
Item<i64>,
|
Item<i64>,
|
||||||
Item<bool>,
|
Item<bool>,
|
||||||
Item<DVec2>,
|
Item<DVec2>,
|
||||||
@@ -1100,6 +1109,55 @@ impl TableItemLayout for f64 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl TableItemLayout for Length {
|
||||||
|
fn type_name() -> &'static str {
|
||||||
|
"Length"
|
||||||
|
}
|
||||||
|
fn identifier(&self) -> String {
|
||||||
|
format!("{} px", format_f64(round_away_float_noise(self.pixels())))
|
||||||
|
}
|
||||||
|
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||||
|
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TableItemLayout for Angle {
|
||||||
|
fn type_name() -> &'static str {
|
||||||
|
"Angle"
|
||||||
|
}
|
||||||
|
fn identifier(&self) -> String {
|
||||||
|
format!("{}°", format_f64(round_away_float_noise(self.degrees())))
|
||||||
|
}
|
||||||
|
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||||
|
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TableItemLayout for LengthVec2 {
|
||||||
|
fn type_name() -> &'static str {
|
||||||
|
"Length Vec2"
|
||||||
|
}
|
||||||
|
fn identifier(&self) -> String {
|
||||||
|
format_dvec2(self.pixels())
|
||||||
|
}
|
||||||
|
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||||
|
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TableItemLayout for AngleVec2 {
|
||||||
|
fn type_name() -> &'static str {
|
||||||
|
"Angle Vec2"
|
||||||
|
}
|
||||||
|
fn identifier(&self) -> String {
|
||||||
|
let degrees = self.degrees();
|
||||||
|
format!("({}°, {}°)", format_rounded(degrees.x, 3), format_rounded(degrees.y, 3))
|
||||||
|
}
|
||||||
|
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||||
|
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl TableItemLayout for u8 {
|
impl TableItemLayout for u8 {
|
||||||
fn type_name() -> &'static str {
|
fn type_name() -> &'static str {
|
||||||
"Byte"
|
"Byte"
|
||||||
|
|||||||
@@ -266,6 +266,11 @@ pub enum DocumentMessage {
|
|||||||
SetRenderMode {
|
SetRenderMode {
|
||||||
render_mode: RenderMode,
|
render_mode: RenderMode,
|
||||||
},
|
},
|
||||||
|
/// Sets how many pixels make an inch, which sizes the lengths typed in a physical unit and the physical size of exports.
|
||||||
|
/// The caller wraps it in a transaction to make it one undo step.
|
||||||
|
SetPixelsPerInch {
|
||||||
|
pixels_per_inch: f64,
|
||||||
|
},
|
||||||
ShowNodeInGraph {
|
ShowNodeInGraph {
|
||||||
node_id: NodeId,
|
node_id: NodeId,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -53,6 +53,7 @@ use graphene_std::vector::misc::dvec2_to_point;
|
|||||||
use graphene_std::vector::style::{GradientStops, RenderMode};
|
use graphene_std::vector::style::{GradientStops, RenderMode};
|
||||||
use kurbo::{Affine, BezPath, Line, PathSeg, Shape};
|
use kurbo::{Affine, BezPath, Line, PathSeg, Shape};
|
||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
|
use std::hash::{Hash, Hasher};
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
@@ -1694,6 +1695,16 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
|||||||
self.render_mode = render_mode;
|
self.render_mode = render_mode;
|
||||||
responses.add_front(NodeGraphMessage::RunDocumentGraph);
|
responses.add_front(NodeGraphMessage::RunDocumentGraph);
|
||||||
}
|
}
|
||||||
|
DocumentMessage::SetPixelsPerInch { pixels_per_inch } => {
|
||||||
|
if !pixels_per_inch.is_finite() || pixels_per_inch <= 0. || pixels_per_inch == self.network_interface.pixels_per_inch() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.network_interface.set_pixels_per_inch(pixels_per_inch);
|
||||||
|
|
||||||
|
// Lengths typed in a physical unit change their size in pixels, so the graph runs again
|
||||||
|
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||||
|
responses.add(InspectorMessage::Refresh);
|
||||||
|
}
|
||||||
DocumentMessage::ShowNodeInGraph { node_id } => {
|
DocumentMessage::ShowNodeInGraph { node_id } => {
|
||||||
// The node is in the document network, so the graph first leaves any nested network it's showing
|
// The node is in the document network, so the graph first leaves any nested network it's showing
|
||||||
if !self.breadcrumb_network_path.is_empty() {
|
if !self.breadcrumb_network_path.is_empty() {
|
||||||
@@ -2445,6 +2456,23 @@ impl DocumentMessageHandler {
|
|||||||
self.network_interface.document_metadata()
|
self.network_interface.document_metadata()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Each artboard with its name, from the top of the Layers panel down.
|
||||||
|
pub fn artboard_names(&self) -> Vec<(LayerNodeIdentifier, String)> {
|
||||||
|
self.metadata()
|
||||||
|
.all_layers()
|
||||||
|
.filter(|&layer| self.network_interface.is_artboard(&layer.to_node(), &[]))
|
||||||
|
.map(|layer| {
|
||||||
|
let name = self
|
||||||
|
.network_interface
|
||||||
|
.node_metadata(&layer.to_node(), &[])
|
||||||
|
.map(|node| node.persistent_metadata.display_name.clone())
|
||||||
|
.filter(|name| !name.is_empty())
|
||||||
|
.unwrap_or_else(|| "Artboard".to_string());
|
||||||
|
(layer, name)
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
pub fn breadcrumb_network_path(&self) -> &[NodeId] {
|
pub fn breadcrumb_network_path(&self) -> &[NodeId] {
|
||||||
&self.breadcrumb_network_path
|
&self.breadcrumb_network_path
|
||||||
}
|
}
|
||||||
@@ -3230,7 +3258,10 @@ impl DocumentMessageHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn current_hash(&self) -> u64 {
|
pub fn current_hash(&self) -> u64 {
|
||||||
self.network_interface.document_network().current_hash()
|
// The resolution lives in the network's metadata rather than the network, but changing it changes the document
|
||||||
|
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||||
|
(self.network_interface.document_network().current_hash(), self.network_interface.pixels_per_inch().to_bits()).hash(&mut hasher);
|
||||||
|
hasher.finish()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn is_auto_saved(&self) -> bool {
|
pub fn is_auto_saved(&self) -> bool {
|
||||||
@@ -5285,7 +5316,7 @@ mod document_message_handler_tests {
|
|||||||
.handle_message(GraphOperationMessage::NewArtboard {
|
.handle_message(GraphOperationMessage::NewArtboard {
|
||||||
id: NodeId::new(),
|
id: NodeId::new(),
|
||||||
location: DVec2::ZERO,
|
location: DVec2::ZERO,
|
||||||
dimensions: DVec2::splat(200.),
|
dimensions: graphene_std::units::TypedLengthVec2::pixels(DVec2::splat(200.)),
|
||||||
background: Color::WHITE,
|
background: Color::WHITE,
|
||||||
clip: true,
|
clip: true,
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ use graph_craft::document::NodeId;
|
|||||||
use graphene_std::Color;
|
use graphene_std::Color;
|
||||||
use graphene_std::raster::BlendMode;
|
use graphene_std::raster::BlendMode;
|
||||||
use graphene_std::text::{Font, TypesettingConfig};
|
use graphene_std::text::{Font, TypesettingConfig};
|
||||||
|
use graphene_std::units::TypedLengthVec2;
|
||||||
use graphene_std::vector::style::{GradientForm, GradientHueDirection, GradientInterpolation, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
|
use graphene_std::vector::style::{GradientForm, GradientHueDirection, GradientInterpolation, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
|
||||||
use graphene_std::vector::{Gradient, VectorModificationType};
|
use graphene_std::vector::{Gradient, VectorModificationType};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
@@ -136,7 +137,7 @@ pub enum GraphOperationMessage {
|
|||||||
NewArtboard {
|
NewArtboard {
|
||||||
id: NodeId,
|
id: NodeId,
|
||||||
location: DVec2,
|
location: DVec2,
|
||||||
dimensions: DVec2,
|
dimensions: TypedLengthVec2,
|
||||||
background: Color,
|
background: Color,
|
||||||
clip: bool,
|
clip: bool,
|
||||||
},
|
},
|
||||||
|
|||||||
+2
-1
@@ -14,6 +14,7 @@ use graph_craft::document::{NodeId, NodeInput};
|
|||||||
use graph_craft::list;
|
use graph_craft::list;
|
||||||
use graphene_std::renderer::convert_usvg_path::convert_usvg_path;
|
use graphene_std::renderer::convert_usvg_path::convert_usvg_path;
|
||||||
use graphene_std::text::{Font, TypesettingConfig};
|
use graphene_std::text::{Font, TypesettingConfig};
|
||||||
|
use graphene_std::units::TypedLength;
|
||||||
use graphene_std::vector::style::{Gradient, GradientForm, GradientSettings, GradientSpace, GradientSpread, GradientStop, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
use graphene_std::vector::style::{Gradient, GradientForm, GradientSettings, GradientSpace, GradientSpread, GradientStop, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
||||||
use graphene_std::{Artboard, Color};
|
use graphene_std::{Artboard, Color};
|
||||||
|
|
||||||
@@ -886,7 +887,7 @@ fn insert_brush_strokes_chain(network_interface: &mut NodeNetworkInterface, laye
|
|||||||
let strokes_node = strokes_node_type.node_template_input_override([
|
let strokes_node = strokes_node_type.node_template_input_override([
|
||||||
Some(NodeInput::value(TaggedValue::Strokes(Vec::new()), false)),
|
Some(NodeInput::value(TaggedValue::Strokes(Vec::new()), false)),
|
||||||
Some(NodeInput::value(TaggedValue::Color(color), false)),
|
Some(NodeInput::value(TaggedValue::Color(color), false)),
|
||||||
Some(NodeInput::value(TaggedValue::Number(diameter), false)),
|
Some(NodeInput::value(TaggedValue::Length(TypedLength::pixels(diameter)), false)),
|
||||||
Some(NodeInput::value(TaggedValue::Number(hardness), false)),
|
Some(NodeInput::value(TaggedValue::Number(hardness), false)),
|
||||||
Some(NodeInput::value(TaggedValue::Number(flow), false)),
|
Some(NodeInput::value(TaggedValue::Number(flow), false)),
|
||||||
]);
|
]);
|
||||||
|
|||||||
@@ -4,34 +4,40 @@ use graph_craft::document::value::TaggedValue;
|
|||||||
use graph_craft::document::{NodeId, NodeInput};
|
use graph_craft::document::{NodeId, NodeInput};
|
||||||
use graphene_std::transform::Transform;
|
use graphene_std::transform::Transform;
|
||||||
|
|
||||||
/// Update the inputs of the transform node to match a new transform
|
/// Update the inputs of the transform node to match a new transform, keeping each in the unit it was typed in.
|
||||||
pub fn update_transform(network_interface: &mut NodeNetworkInterface, node_id: &NodeId, transform: DAffine2) {
|
pub fn update_transform(network_interface: &mut NodeNetworkInterface, node_id: &NodeId, transform: DAffine2) {
|
||||||
|
use graphene_std::transform_nodes::transform::*;
|
||||||
|
|
||||||
let (rotation, scale, skew) = transform.decompose_rotation_scale_skew();
|
let (rotation, scale, skew) = transform.decompose_rotation_scale_skew();
|
||||||
let translation = transform.translation;
|
let translation = transform.translation;
|
||||||
|
|
||||||
let rotation = rotation.to_degrees();
|
let rotation = rotation.to_degrees();
|
||||||
let skew = DVec2::new(skew.atan().to_degrees(), 0.);
|
let skew = DVec2::new(skew.atan().to_degrees(), 0.);
|
||||||
|
|
||||||
network_interface.set_input(
|
let pixels_per_inch = network_interface.pixels_per_inch();
|
||||||
&InputConnector::node(*node_id, graphene_std::transform_nodes::transform::TranslationInput),
|
let [translation_input, rotation_input, scale_input, skew_input] = [
|
||||||
NodeInput::value(TaggedValue::DVec2(translation), false),
|
InputConnector::node(*node_id, TranslationInput),
|
||||||
&[],
|
InputConnector::node(*node_id, RotationInput),
|
||||||
);
|
InputConnector::node(*node_id, ScaleInput),
|
||||||
network_interface.set_input(
|
InputConnector::node(*node_id, SkewInput),
|
||||||
&InputConnector::node(*node_id, graphene_std::transform_nodes::transform::RotationInput),
|
];
|
||||||
NodeInput::value(TaggedValue::Number(rotation), false),
|
let existing = |input: &InputConnector| network_interface.input_from_connector(input, &[]).and_then(NodeInput::as_value).cloned().unwrap_or(TaggedValue::None);
|
||||||
&[],
|
let (existing_translation, existing_rotation, existing_skew) = (existing(&translation_input), existing(&rotation_input), existing(&skew_input));
|
||||||
);
|
|
||||||
network_interface.set_input(
|
// An input already holding the value is left as typed, so rotating a layer doesn't rewrite a translation typed in millimeters with float noise
|
||||||
&InputConnector::node(*node_id, graphene_std::transform_nodes::transform::ScaleInput),
|
let unchanged = |existing: Option<DVec2>, value: DVec2| existing.is_some_and(|existing| existing.abs_diff_eq(value, 1e-9));
|
||||||
NodeInput::value(TaggedValue::DVec2(scale), false),
|
|
||||||
&[],
|
if !unchanged(existing_translation.as_length_vec2_pixels(pixels_per_inch), translation) {
|
||||||
);
|
let translation = existing_translation.length_vec2_in_same_unit(translation, pixels_per_inch);
|
||||||
network_interface.set_input(
|
network_interface.set_input(&translation_input, NodeInput::value(translation, false), &[]);
|
||||||
&InputConnector::node(*node_id, graphene_std::transform_nodes::transform::SkewInput),
|
}
|
||||||
NodeInput::value(TaggedValue::DVec2(skew), false),
|
if !unchanged(existing_rotation.as_angle_degrees().map(DVec2::splat), DVec2::splat(rotation)) {
|
||||||
&[],
|
network_interface.set_input(&rotation_input, NodeInput::value(existing_rotation.angle_in_same_unit(rotation), false), &[]);
|
||||||
);
|
}
|
||||||
|
network_interface.set_input(&scale_input, NodeInput::value(TaggedValue::DVec2(scale), false), &[]);
|
||||||
|
if !unchanged(existing_skew.as_angle_vec2_degrees(), skew) {
|
||||||
|
network_interface.set_input(&skew_input, NodeInput::value(existing_skew.angle_vec2_in_same_unit(skew), false), &[]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: This should be extracted from the graph at the location of the transform node.
|
// TODO: This should be extracted from the graph at the location of the transform node.
|
||||||
@@ -63,16 +69,14 @@ impl LayerBounds {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the current affine transform from the transform node's inputs
|
/// Get the current affine transform from the transform node's inputs, sizing a translation in a physical unit by the document's resolution.
|
||||||
pub fn get_current_transform(inputs: &[NodeInput]) -> DAffine2 {
|
pub fn get_current_transform(inputs: &[NodeInput], pixels_per_inch: f64) -> DAffine2 {
|
||||||
let translation = if let Some(&TaggedValue::DVec2(translation)) = inputs[1].as_value() {
|
let value = |index: usize| inputs.get(index).and_then(NodeInput::as_value);
|
||||||
translation
|
|
||||||
} else {
|
let translation = value(1).and_then(|value| value.as_length_vec2_pixels(pixels_per_inch)).unwrap_or(DVec2::ZERO);
|
||||||
DVec2::ZERO
|
let rotation = value(2).and_then(TaggedValue::as_angle_degrees).unwrap_or(0.);
|
||||||
};
|
let scale = if let Some(&TaggedValue::DVec2(scale)) = value(3) { scale } else { DVec2::ONE };
|
||||||
let rotation = if let Some(&TaggedValue::Number(rotation)) = inputs[2].as_value() { rotation } else { 0. };
|
let skew = value(4).and_then(TaggedValue::as_angle_vec2_degrees).unwrap_or(DVec2::ZERO);
|
||||||
let scale = if let Some(&TaggedValue::DVec2(scale)) = inputs[3].as_value() { scale } else { DVec2::ONE };
|
|
||||||
let skew = if let Some(&TaggedValue::DVec2(skew)) = inputs[4].as_value() { skew } else { DVec2::ZERO };
|
|
||||||
|
|
||||||
let rotation = rotation.to_radians();
|
let rotation = rotation.to_radians();
|
||||||
let skew = DVec2::new(skew.x.to_radians().tan(), skew.y.to_radians().tan());
|
let skew = DVec2::new(skew.x.to_radians().tan(), skew.y.to_radians().tan());
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ use graph_craft::document::{NodeId, NodeInput};
|
|||||||
use graph_craft::{ProtoNodeIdentifier, list};
|
use graph_craft::{ProtoNodeIdentifier, list};
|
||||||
use graphene_std::raster::BlendMode;
|
use graphene_std::raster::BlendMode;
|
||||||
use graphene_std::text::{Font, TypesettingConfig};
|
use graphene_std::text::{Font, TypesettingConfig};
|
||||||
|
use graphene_std::units::{TypedAngle, TypedLength, TypedLengthVec2};
|
||||||
use graphene_std::vector::style::{GradientForm, GradientHueDirection, GradientInterpolation, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
|
use graphene_std::vector::style::{GradientForm, GradientHueDirection, GradientInterpolation, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
|
||||||
use graphene_std::vector::{Gradient, GradientRamp, Vector, VectorModification, VectorModificationType};
|
use graphene_std::vector::{Gradient, GradientRamp, Vector, VectorModification, VectorModificationType};
|
||||||
use graphene_std::{Artboard, Color, Graphic};
|
use graphene_std::{Artboard, Color, Graphic};
|
||||||
@@ -68,12 +69,12 @@ impl<'a> ModifyInputsContext<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Creates an artboard as the primary export for the document network.
|
/// Creates an artboard as the primary export for the document network.
|
||||||
pub fn create_artboard(&mut self, new_id: NodeId, location: DVec2, dimensions: DVec2, background: Color, clip: bool) -> LayerNodeIdentifier {
|
pub fn create_artboard(&mut self, new_id: NodeId, location: DVec2, dimensions: TypedLengthVec2, background: Color, clip: bool) -> LayerNodeIdentifier {
|
||||||
let artboard_node_template = resolve_network_node_type("Artboard").expect("Node").node_template_input_override([
|
let artboard_node_template = resolve_network_node_type("Artboard").expect("Node").node_template_input_override([
|
||||||
Some(NodeInput::type_default(list!(Artboard), true)),
|
Some(NodeInput::type_default(list!(Artboard), true)),
|
||||||
Some(NodeInput::type_default(list!(Graphic), true)),
|
Some(NodeInput::type_default(list!(Graphic), true)),
|
||||||
Some(NodeInput::value(TaggedValue::DVec2(location), false)),
|
Some(NodeInput::value(TaggedValue::LengthVec2(TypedLengthVec2::pixels(location)), false)),
|
||||||
Some(NodeInput::value(TaggedValue::DVec2(dimensions), false)),
|
Some(NodeInput::value(TaggedValue::LengthVec2(dimensions), false)),
|
||||||
Some(NodeInput::value(TaggedValue::Color(background), false)),
|
Some(NodeInput::value(TaggedValue::Color(background), false)),
|
||||||
Some(NodeInput::value(TaggedValue::Bool(clip), false)),
|
Some(NodeInput::value(TaggedValue::Bool(clip), false)),
|
||||||
]);
|
]);
|
||||||
@@ -196,14 +197,14 @@ impl<'a> ModifyInputsContext<'a> {
|
|||||||
Some(NodeInput::value(TaggedValue::None, false)),
|
Some(NodeInput::value(TaggedValue::None, false)),
|
||||||
Some(NodeInput::value(TaggedValue::String(text), false)),
|
Some(NodeInput::value(TaggedValue::String(text), false)),
|
||||||
Some(NodeInput::value(TaggedValue::Resource(font_resource_id), false)),
|
Some(NodeInput::value(TaggedValue::Resource(font_resource_id), false)),
|
||||||
Some(NodeInput::value(TaggedValue::Number(typesetting.font_size), false)),
|
Some(NodeInput::value(TaggedValue::Length(TypedLength::pixels(typesetting.font_size)), false)),
|
||||||
Some(NodeInput::value(TaggedValue::Number(typesetting.line_height_ratio), false)),
|
Some(NodeInput::value(TaggedValue::Number(typesetting.line_height_ratio), false)),
|
||||||
Some(NodeInput::value(TaggedValue::Number(typesetting.letter_spacing), false)),
|
Some(NodeInput::value(TaggedValue::Length(TypedLength::pixels(typesetting.letter_spacing)), false)),
|
||||||
Some(NodeInput::value(TaggedValue::Number(typesetting.letter_tilt), false)),
|
Some(NodeInput::value(TaggedValue::Angle(TypedAngle::degrees(typesetting.letter_tilt)), false)),
|
||||||
Some(NodeInput::value(TaggedValue::Bool(typesetting.max_width.is_some()), false)),
|
Some(NodeInput::value(TaggedValue::Bool(typesetting.max_width.is_some()), false)),
|
||||||
Some(NodeInput::value(TaggedValue::Number(typesetting.max_width.unwrap_or(100.)), false)),
|
Some(NodeInput::value(TaggedValue::Length(TypedLength::pixels(typesetting.max_width.unwrap_or(100.))), false)),
|
||||||
Some(NodeInput::value(TaggedValue::Bool(typesetting.max_height.is_some()), false)),
|
Some(NodeInput::value(TaggedValue::Bool(typesetting.max_height.is_some()), false)),
|
||||||
Some(NodeInput::value(TaggedValue::Number(typesetting.max_height.unwrap_or(100.)), false)),
|
Some(NodeInput::value(TaggedValue::Length(TypedLength::pixels(typesetting.max_height.unwrap_or(100.))), false)),
|
||||||
Some(NodeInput::value(TaggedValue::TextAlign(typesetting.align), false)),
|
Some(NodeInput::value(TaggedValue::TextAlign(typesetting.align), false)),
|
||||||
]);
|
]);
|
||||||
let text_to_vector = resolve_proto_node_type(graphene_std::text::text_to_vector::IDENTIFIER)
|
let text_to_vector = resolve_proto_node_type(graphene_std::text::text_to_vector::IDENTIFIER)
|
||||||
@@ -729,13 +730,14 @@ impl<'a> ModifyInputsContext<'a> {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// `composed_old` = T_n * T_{n-1} * ... * T_1, `prior_combined` = same product without T_n
|
// `composed_old` = T_n * T_{n-1} * ... * T_1, `prior_combined` = same product without T_n
|
||||||
|
let pixels_per_inch = self.network_interface.pixels_per_inch();
|
||||||
let compose = |ids: &[_]| {
|
let compose = |ids: &[_]| {
|
||||||
ids.iter().fold(DAffine2::IDENTITY, |acc, transform_id| {
|
ids.iter().fold(DAffine2::IDENTITY, |acc, transform_id| {
|
||||||
self.network_interface
|
self.network_interface
|
||||||
.document_network()
|
.document_network()
|
||||||
.nodes
|
.nodes
|
||||||
.get(transform_id)
|
.get(transform_id)
|
||||||
.map_or(acc, |document_node| acc * transform_utils::get_current_transform(&document_node.inputs))
|
.map_or(acc, |document_node| acc * transform_utils::get_current_transform(&document_node.inputs, pixels_per_inch))
|
||||||
})
|
})
|
||||||
};
|
};
|
||||||
let prior_combined = compose(prior_transforms);
|
let prior_combined = compose(prior_transforms);
|
||||||
@@ -871,7 +873,7 @@ impl<'a> ModifyInputsContext<'a> {
|
|||||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintInput);
|
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintInput);
|
||||||
self.set_input_with_refresh(input_connector, NodeInput::value(color.map_or_else(TaggedValue::no_paint, TaggedValue::Color), false), true);
|
self.set_input_with_refresh(input_connector, NodeInput::value(color.map_or_else(TaggedValue::no_paint, TaggedValue::Color), false), true);
|
||||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::WeightInput);
|
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::WeightInput);
|
||||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.weight), false), true);
|
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Length(TypedLength::pixels(stroke.weight)), false), true);
|
||||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::AlignInput);
|
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::AlignInput);
|
||||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::StrokeAlign(stroke.align), false), false);
|
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::StrokeAlign(stroke.align), false), false);
|
||||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::CapInput);
|
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::CapInput);
|
||||||
@@ -883,7 +885,7 @@ impl<'a> ModifyInputsContext<'a> {
|
|||||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashPatternInput);
|
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashPatternInput);
|
||||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::DashPattern(stroke.dash_lengths), false), true);
|
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::DashPattern(stroke.dash_lengths), false), true);
|
||||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput);
|
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput);
|
||||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.dash_offset), false), true);
|
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Length(TypedLength::pixels(stroke.dash_offset)), false), true);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Update the transform value of the upstream Transform node based a change to its existing value and the given parent transform.
|
/// Update the transform value of the upstream Transform node based a change to its existing value and the given parent transform.
|
||||||
@@ -894,7 +896,10 @@ impl<'a> ModifyInputsContext<'a> {
|
|||||||
.existing_proto_node_id(graphene_std::transform_nodes::transform::IDENTIFIER, false)
|
.existing_proto_node_id(graphene_std::transform_nodes::transform::IDENTIFIER, false)
|
||||||
.and_then(|transform_node_id| {
|
.and_then(|transform_node_id| {
|
||||||
let document_node = self.network_interface.document_network().nodes.get(&transform_node_id)?;
|
let document_node = self.network_interface.document_network().nodes.get(&transform_node_id)?;
|
||||||
Some((transform_utils::get_current_transform(&document_node.inputs), transform_node_id))
|
Some((
|
||||||
|
transform_utils::get_current_transform(&document_node.inputs, self.network_interface.pixels_per_inch()),
|
||||||
|
transform_node_id,
|
||||||
|
))
|
||||||
})
|
})
|
||||||
.unzip();
|
.unzip();
|
||||||
let layer_transform = layer_transform.unwrap_or_default();
|
let layer_transform = layer_transform.unwrap_or_default();
|
||||||
@@ -932,7 +937,7 @@ impl<'a> ModifyInputsContext<'a> {
|
|||||||
let local_transform = metadata.local_transforms.get(&layer.to_node()).copied().unwrap_or(DAffine2::IDENTITY);
|
let local_transform = metadata.local_transforms.get(&layer.to_node()).copied().unwrap_or(DAffine2::IDENTITY);
|
||||||
let current_transform_node_value = transform_node_id
|
let current_transform_node_value = transform_node_id
|
||||||
.and_then(|id| self.network_interface.document_network().nodes.get(&id))
|
.and_then(|id| self.network_interface.document_network().nodes.get(&id))
|
||||||
.map(|node| transform_utils::get_current_transform(&node.inputs))
|
.map(|node| transform_utils::get_current_transform(&node.inputs, self.network_interface.pixels_per_inch()))
|
||||||
.unwrap_or(DAffine2::IDENTITY);
|
.unwrap_or(DAffine2::IDENTITY);
|
||||||
parent_inverse * transform * local_transform.inverse() * current_transform_node_value
|
parent_inverse * transform * local_transform.inverse() * current_transform_node_value
|
||||||
} else {
|
} else {
|
||||||
@@ -1020,16 +1025,37 @@ impl<'a> ModifyInputsContext<'a> {
|
|||||||
dimensions.y = -dimensions.y;
|
dimensions.y = -dimensions.y;
|
||||||
location.y -= dimensions.y;
|
location.y -= dimensions.y;
|
||||||
}
|
}
|
||||||
self.set_input_with_refresh(
|
|
||||||
InputConnector::node_at_index(artboard_node_id, ARTBOARD_LOCATION_INPUT_INDEX),
|
// Each stays in the unit it was typed in, and a component that already rounds to the requested whole pixels stays as typed, so moving an artboard sized in millimeters keeps them
|
||||||
NodeInput::value(TaggedValue::DVec2(location), false),
|
let pixels_per_inch = self.network_interface.pixels_per_inch();
|
||||||
false,
|
for (index, pixels) in [(ARTBOARD_LOCATION_INPUT_INDEX, location), (ARTBOARD_DIMENSIONS_INPUT_INDEX, dimensions)] {
|
||||||
);
|
let input_connector = InputConnector::node_at_index(artboard_node_id, index);
|
||||||
self.set_input_with_refresh(
|
let existing = self
|
||||||
InputConnector::node_at_index(artboard_node_id, ARTBOARD_DIMENSIONS_INPUT_INDEX),
|
.network_interface
|
||||||
NodeInput::value(TaggedValue::DVec2(dimensions), false),
|
.input_from_connector(&input_connector, &[])
|
||||||
false,
|
.and_then(NodeInput::as_value)
|
||||||
);
|
.cloned()
|
||||||
|
.unwrap_or(TaggedValue::None);
|
||||||
|
let existing_lengths = match existing {
|
||||||
|
TaggedValue::LengthVec2(lengths) => Some(lengths),
|
||||||
|
TaggedValue::DVec2(pixels) => Some(TypedLengthVec2::pixels(pixels)),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut value = existing.length_vec2_in_same_unit(pixels, pixels_per_inch);
|
||||||
|
if let (Some(existing_lengths), TaggedValue::LengthVec2(lengths)) = (existing_lengths, &mut value) {
|
||||||
|
let existing_pixels = existing_lengths.to_length_vec2(pixels_per_inch).pixels();
|
||||||
|
for axis in 0..2 {
|
||||||
|
if existing_pixels[axis].round() == pixels[axis] {
|
||||||
|
lengths.value[axis] = existing_lengths.value[axis];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if value != existing {
|
||||||
|
self.set_input_with_refresh(input_connector, NodeInput::value(value, false), false);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set the input, refresh the Inspector, and run the document graph if skip_rerender is false
|
/// Set the input, refresh the Inspector, and run the document graph if skip_rerender is false
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
+30
-422
@@ -1,17 +1,11 @@
|
|||||||
use super::DocumentNodeDefinition;
|
use super::DocumentNodeDefinition;
|
||||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||||
use crate::messages::portfolio::document::utility_types::network_interface::{
|
use crate::messages::portfolio::document::utility_types::network_interface::{InputMetadata, NodeTemplate, NodeTemplateImplementation, WidgetOverride};
|
||||||
InputMetadata, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, WidgetOverride,
|
|
||||||
};
|
|
||||||
use glam::IVec2;
|
|
||||||
use graph_craft::document::value::TaggedValue;
|
|
||||||
use graph_craft::document::{NodeId, NodeInput};
|
|
||||||
use graphene_std::registry::*;
|
use graphene_std::registry::*;
|
||||||
use graphene_std::*;
|
use graphene_std::*;
|
||||||
use std::collections::{HashMap, HashSet};
|
use std::collections::{HashMap, HashSet};
|
||||||
|
|
||||||
/// Generates every definition, from the node macro's metadata for proto nodes and the graph macro's for built-in subgraphs.
|
pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||||
pub(super) fn derive_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
|
||||||
let mut definitions_map = HashMap::new();
|
let mut definitions_map = HashMap::new();
|
||||||
|
|
||||||
// Add the protonodes from the macro.
|
// Add the protonodes from the macro.
|
||||||
@@ -81,7 +75,16 @@ pub(super) fn derive_definitions() -> HashMap<DefinitionIdentifier, DocumentNode
|
|||||||
inputs,
|
inputs,
|
||||||
call_argument: input_type.clone(),
|
call_argument: input_type.clone(),
|
||||||
implementation: NodeTemplateImplementation::ProtoNode(id.clone()),
|
implementation: NodeTemplateImplementation::ProtoNode(id.clone()),
|
||||||
input_metadata: input_metadata(fields),
|
// TODO: Store information for input overrides in the node macro
|
||||||
|
input_metadata: fields
|
||||||
|
.iter()
|
||||||
|
.map(|f| match f.widget_override {
|
||||||
|
RegistryWidgetOverride::None => (f.name, f.description).into(),
|
||||||
|
RegistryWidgetOverride::Hidden => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Hidden),
|
||||||
|
RegistryWidgetOverride::String(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::String(str.to_string())),
|
||||||
|
RegistryWidgetOverride::Custom(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Custom(str.to_string())),
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
output_names,
|
output_names,
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
@@ -93,241 +96,25 @@ pub(super) fn derive_definitions() -> HashMap<DefinitionIdentifier, DocumentNode
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
add_graph_definitions(graph_text::GRAPHS.clone(), &mut definitions_map);
|
// Add the hand-written network nodes to the map and add the metadata for their internal protonodes
|
||||||
|
for mut network_node in custom {
|
||||||
|
fill_proto_node_metadata(&mut network_node.node_template, &definitions_map);
|
||||||
|
|
||||||
|
// Set the reference to the node identifier
|
||||||
|
if let NodeTemplateImplementation::Network(network_template) = &mut network_node.node_template.implementation {
|
||||||
|
network_template.reference = Some(network_node.identifier.to_string());
|
||||||
|
// If it is not a merge node, then set the display name to the identifier/reference
|
||||||
|
if network_node.identifier != "Merge" {
|
||||||
|
network_node.node_template.display_name = network_node.identifier.to_string();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
definitions_map.insert(DefinitionIdentifier::Network(network_node.identifier.to_string()), network_node);
|
||||||
|
}
|
||||||
|
|
||||||
definitions_map
|
definitions_map
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The name, description, and any widget override of each parameter, for a proto node's fields or a graph's imports.
|
/// Recursively fills each nested proto node's editor metadata from its definition, preserving only the authored position.
|
||||||
/// The rest of a parameter's widget settings are read from its field when the Inspector draws it.
|
|
||||||
fn input_metadata(fields: &[FieldMetadata]) -> Vec<InputMetadata> {
|
|
||||||
fields
|
|
||||||
.iter()
|
|
||||||
.map(|field| {
|
|
||||||
let (name, description) = (field.name, field.description);
|
|
||||||
match field.widget_override {
|
|
||||||
RegistryWidgetOverride::None => (name, description).into(),
|
|
||||||
RegistryWidgetOverride::Hidden => InputMetadata::with_name_description_override(name, description, WidgetOverride::Hidden),
|
|
||||||
RegistryWidgetOverride::String(text) => InputMetadata::with_name_description_override(name, description, WidgetOverride::String(text.to_string())),
|
|
||||||
RegistryWidgetOverride::Custom(key) => InputMetadata::with_name_description_override(name, description, WidgetOverride::Custom(key.to_string())),
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Why a graph text node has no definition yet, or can't have one.
|
|
||||||
enum GraphDefinitionError {
|
|
||||||
/// A node inside it has no definition, which may be another graph not yet added.
|
|
||||||
MissingNode(String),
|
|
||||||
/// The graph's wiring is invalid, so it's left out of the catalog.
|
|
||||||
Invalid(String),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Adds the nodes defined as subgraphs in graph text, each once the definitions of the nodes inside it exist.
|
|
||||||
fn add_graph_definitions(graphs: Vec<GraphMetadata>, definitions_map: &mut HashMap<DefinitionIdentifier, DocumentNodeDefinition>) {
|
|
||||||
// Every graph sharing an identifier is left out, so the catalog doesn't depend on registration order
|
|
||||||
let mut identifier_counts = HashMap::new();
|
|
||||||
for graph in &graphs {
|
|
||||||
*identifier_counts.entry(graph.identifier).or_insert(0) += 1;
|
|
||||||
}
|
|
||||||
let mut rejected = HashSet::new();
|
|
||||||
let mut pending_graphs: Vec<(GraphMetadata, String)> = graphs
|
|
||||||
.into_iter()
|
|
||||||
.filter(|graph| {
|
|
||||||
let taken = identifier_counts[graph.identifier] > 1;
|
|
||||||
if taken {
|
|
||||||
log::error!("The '{}' graph has no definition, since another graph has the same identifier", graph.identifier);
|
|
||||||
rejected.insert(graph.identifier);
|
|
||||||
}
|
|
||||||
!taken
|
|
||||||
})
|
|
||||||
.map(|graph| (graph, String::new()))
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
loop {
|
|
||||||
let pending_count = pending_graphs.len();
|
|
||||||
|
|
||||||
let mut ready = Vec::new();
|
|
||||||
pending_graphs.retain_mut(|(graph, missing)| {
|
|
||||||
// A graph built on a left-out graph is left out too, rather than embedding another definition of that name
|
|
||||||
let rejected_inner_graph = graph.nodes.iter().find_map(|node| match node.implementation {
|
|
||||||
GraphNodeImplementation::Graph(identifier) if rejected.contains(identifier) => Some(identifier),
|
|
||||||
_ => None,
|
|
||||||
});
|
|
||||||
if let Some(inner_graph) = rejected_inner_graph {
|
|
||||||
log::error!("The '{}' graph has no definition, since the '{inner_graph}' graph inside it has none", graph.identifier);
|
|
||||||
rejected.insert(graph.identifier);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
match graph_definition(graph, definitions_map) {
|
|
||||||
Ok(definition) => {
|
|
||||||
ready.push(definition);
|
|
||||||
false
|
|
||||||
}
|
|
||||||
Err(GraphDefinitionError::MissingNode(missing_node)) => {
|
|
||||||
*missing = missing_node;
|
|
||||||
true
|
|
||||||
}
|
|
||||||
Err(GraphDefinitionError::Invalid(reason)) => {
|
|
||||||
log::error!("The '{}' graph has no definition, since {reason}", graph.identifier);
|
|
||||||
rejected.insert(graph.identifier);
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
for definition in ready {
|
|
||||||
let definition = prepare_network_definition(definition, definitions_map);
|
|
||||||
definitions_map.insert(DefinitionIdentifier::Network(definition.identifier.to_string()), definition);
|
|
||||||
}
|
|
||||||
|
|
||||||
if pending_graphs.is_empty() || pending_graphs.len() == pending_count {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (graph, missing_node) in pending_graphs {
|
|
||||||
log::error!("The '{}' graph has no definition, since the '{missing_node}' node inside it has none", graph.identifier);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Fills a network definition's nested proto node metadata and points its network at the definition.
|
|
||||||
fn prepare_network_definition(mut network_node: DocumentNodeDefinition, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) -> DocumentNodeDefinition {
|
|
||||||
fill_proto_node_metadata(&mut network_node.node_template, definitions_map);
|
|
||||||
|
|
||||||
// Set the reference to the node identifier
|
|
||||||
if let NodeTemplateImplementation::Network(network_template) = &mut network_node.node_template.implementation {
|
|
||||||
network_template.reference = Some(network_node.identifier.to_string());
|
|
||||||
// If it is not a merge node, then set the display name to the identifier/reference
|
|
||||||
if network_node.identifier != "Merge" {
|
|
||||||
network_node.node_template.display_name = network_node.identifier.to_string();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
network_node
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Builds the catalog definition of a node defined as a subgraph in graph text.
|
|
||||||
fn graph_definition(graph: &GraphMetadata, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) -> Result<DocumentNodeDefinition, GraphDefinitionError> {
|
|
||||||
let mut nodes = HashMap::new();
|
|
||||||
for (index, node) in graph.nodes.iter().enumerate() {
|
|
||||||
// Start from the node's own definition, so each input the graph leaves out matches a new instance of it
|
|
||||||
let (identifier, name) = match &node.implementation {
|
|
||||||
GraphNodeImplementation::ProtoNode(identifier) => (DefinitionIdentifier::ProtoNode(identifier.clone()), identifier.as_str().to_string()),
|
|
||||||
GraphNodeImplementation::Graph(identifier) => (DefinitionIdentifier::Network(identifier.to_string()), identifier.to_string()),
|
|
||||||
};
|
|
||||||
let Some(definition) = definitions_map.get(&identifier) else {
|
|
||||||
return Err(GraphDefinitionError::MissingNode(name));
|
|
||||||
};
|
|
||||||
let mut template = definition.default_node_template();
|
|
||||||
|
|
||||||
template.visible = !node.hidden;
|
|
||||||
template.locked = node.locked;
|
|
||||||
template.pinned = node.pinned;
|
|
||||||
if let Some(display_name) = node.display_name {
|
|
||||||
template.display_name = display_name.to_string();
|
|
||||||
}
|
|
||||||
|
|
||||||
let position = IVec2::from(node.position);
|
|
||||||
template.node_type_metadata = if node.layer {
|
|
||||||
NodeTypePersistentMetadata::layer(position)
|
|
||||||
} else {
|
|
||||||
NodeTypePersistentMetadata::node(position)
|
|
||||||
};
|
|
||||||
|
|
||||||
for (input_index, source) in &node.inputs {
|
|
||||||
let Some(input) = template.inputs.get_mut(*input_index) else {
|
|
||||||
return Err(GraphDefinitionError::Invalid(format!("its node {index}, '{name}', has no input {input_index} for it to set")));
|
|
||||||
};
|
|
||||||
|
|
||||||
// An input the compiler fills in can't be set
|
|
||||||
if matches!(input, NodeInput::Scope(_) | NodeInput::Reflection(_)) {
|
|
||||||
return Err(GraphDefinitionError::Invalid(format!(
|
|
||||||
"it sets input {input_index} of its node {index}, '{name}', which the compiler fills in"
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
|
|
||||||
*input = graph_input(source, input).map_err(|reason| GraphDefinitionError::Invalid(format!("input {input_index} of its node {index}, '{name}', is invalid: {reason}")))?;
|
|
||||||
}
|
|
||||||
|
|
||||||
nodes.insert(NodeId(index as u64), template);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Each import starts from its `#[default(...)]` or else its type, as a proto node's parameter does
|
|
||||||
let inputs = preprocessor::node_inputs(&graph.imports, &NodeIOTypes::empty());
|
|
||||||
|
|
||||||
let exports = graph
|
|
||||||
.exports
|
|
||||||
.iter()
|
|
||||||
.map(|export| graph_input(&export.source, &NodeInput::value(TaggedValue::None, false)))
|
|
||||||
.collect::<Result<_, _>>()
|
|
||||||
.map_err(GraphDefinitionError::Invalid)?;
|
|
||||||
|
|
||||||
Ok(DocumentNodeDefinition {
|
|
||||||
identifier: graph.identifier,
|
|
||||||
version: graph.version,
|
|
||||||
category: graph.category,
|
|
||||||
icon: graph.icon,
|
|
||||||
description: Cow::Borrowed(graph.description),
|
|
||||||
inspector: None,
|
|
||||||
node_template: NodeTemplate {
|
|
||||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate { exports, nodes, ..Default::default() }),
|
|
||||||
inputs,
|
|
||||||
input_metadata: input_metadata(&graph.imports),
|
|
||||||
output_names: graph.exports.iter().map(|export| export.name.to_string()).collect(),
|
|
||||||
output_descriptions: graph.exports.iter().map(|export| export.description.to_string()).collect(),
|
|
||||||
node_type_metadata: if graph.layer {
|
|
||||||
NodeTypePersistentMetadata::layer(IVec2::ZERO)
|
|
||||||
} else {
|
|
||||||
NodeTypePersistentMetadata::node(IVec2::ZERO)
|
|
||||||
},
|
|
||||||
..Default::default()
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The input a graph definition writes, where `default` is what the node's own definition starts that input with.
|
|
||||||
/// A value must have the type of that default, if it has one.
|
|
||||||
fn graph_input(source: &GraphInputSource, default: &NodeInput) -> Result<NodeInput, String> {
|
|
||||||
Ok(match source {
|
|
||||||
GraphInputSource::Node { node, output } => NodeInput::node(NodeId(*node as u64), *output),
|
|
||||||
GraphInputSource::Import { index, ty } => NodeInput::import(ty.clone(), *index),
|
|
||||||
GraphInputSource::Value { value, exposed } => {
|
|
||||||
let value = graph_value(value);
|
|
||||||
if let NodeInput::Value { tagged_value, .. } = default
|
|
||||||
&& **tagged_value != TaggedValue::None
|
|
||||||
&& element_type(&tagged_value.ty()) != element_type(&value.ty())
|
|
||||||
{
|
|
||||||
return Err(format!("its value `{value:?}` doesn't have the input's type, `{:?}`", tagged_value.ty()));
|
|
||||||
}
|
|
||||||
NodeInput::value(value, exposed.unwrap_or(default.is_exposed()))
|
|
||||||
}
|
|
||||||
GraphInputSource::Scope(key) => NodeInput::scope(*key),
|
|
||||||
GraphInputSource::NodePath => NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath),
|
|
||||||
GraphInputSource::SourceId => NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The type of the elements a wire of this type carries, past any `Item`, `List`, or lazy wrapping.
|
|
||||||
fn element_type(ty: &Type) -> Type {
|
|
||||||
let mut element = ty;
|
|
||||||
while let Type::Item(inner) | Type::List(inner) | Type::Fn(_, inner) = element {
|
|
||||||
element = inner;
|
|
||||||
}
|
|
||||||
element.clone()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn graph_value(value: &GraphValue) -> TaggedValue {
|
|
||||||
match value {
|
|
||||||
GraphValue::Integer(integer) => TaggedValue::Integer(*integer),
|
|
||||||
GraphValue::Number(number) => TaggedValue::Number(*number),
|
|
||||||
GraphValue::Bool(boolean) => TaggedValue::Bool(*boolean),
|
|
||||||
GraphValue::String(string) => TaggedValue::String(string.clone()),
|
|
||||||
GraphValue::Vec2(vec2) => TaggedValue::DVec2(*vec2),
|
|
||||||
GraphValue::Color(color) => TaggedValue::Color(*color),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Recursively gives each nested proto node its definition's input and output metadata, and its display name if the network's author gave none.
|
|
||||||
fn fill_proto_node_metadata(node_template: &mut NodeTemplate, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) {
|
fn fill_proto_node_metadata(node_template: &mut NodeTemplate, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) {
|
||||||
match &mut node_template.implementation {
|
match &mut node_template.implementation {
|
||||||
NodeTemplateImplementation::Network(network_template) => {
|
NodeTemplateImplementation::Network(network_template) => {
|
||||||
@@ -341,192 +128,13 @@ fn fill_proto_node_metadata(node_template: &mut NodeTemplate, definitions_map: &
|
|||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
|
||||||
// A display name, lock, or pin the network's author gave the node is kept
|
|
||||||
let definition_template = &definition.node_template;
|
let definition_template = &definition.node_template;
|
||||||
if node_template.display_name.is_empty() {
|
node_template.display_name = definition_template.display_name.clone();
|
||||||
node_template.display_name = definition_template.display_name.clone();
|
|
||||||
}
|
|
||||||
node_template.input_metadata = definition_template.input_metadata.clone();
|
node_template.input_metadata = definition_template.input_metadata.clone();
|
||||||
node_template.output_names = definition_template.output_names.clone();
|
node_template.output_names = definition_template.output_names.clone();
|
||||||
node_template.locked |= definition_template.locked;
|
node_template.locked = definition_template.locked;
|
||||||
node_template.pinned |= definition_template.pinned;
|
node_template.pinned = definition_template.pinned;
|
||||||
}
|
}
|
||||||
NodeTemplateImplementation::Definition(_) => {}
|
NodeTemplateImplementation::Definition(_) => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
|
|
||||||
|
|
||||||
fn number_import() -> FieldMetadata {
|
|
||||||
FieldMetadata {
|
|
||||||
name: "Value",
|
|
||||||
identifier: "value",
|
|
||||||
description: "",
|
|
||||||
internal: false,
|
|
||||||
exposed: true,
|
|
||||||
widget_override: RegistryWidgetOverride::None,
|
|
||||||
value_source: RegistryValueSource::None,
|
|
||||||
default_colors: None,
|
|
||||||
default_type: Some(Type::Item(Box::new(concrete!(f64)))),
|
|
||||||
number_soft_min: None,
|
|
||||||
number_soft_max: None,
|
|
||||||
number_hard_min: None,
|
|
||||||
number_hard_max: None,
|
|
||||||
number_mode_range: false,
|
|
||||||
number_display_decimal_places: None,
|
|
||||||
number_step: None,
|
|
||||||
unit: None,
|
|
||||||
multiline: false,
|
|
||||||
progression: false,
|
|
||||||
constant: false,
|
|
||||||
labels: None,
|
|
||||||
integer: false,
|
|
||||||
blank_assist: true,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A graph exporting one node, which is fed by the given inputs.
|
|
||||||
fn one_node_graph(identifier: &'static str, implementation: GraphNodeImplementation, inputs: Vec<(usize, GraphInputSource)>) -> GraphMetadata {
|
|
||||||
GraphMetadata {
|
|
||||||
identifier,
|
|
||||||
path: identifier,
|
|
||||||
category: "Test",
|
|
||||||
icon: None,
|
|
||||||
description: "",
|
|
||||||
version: 1,
|
|
||||||
layer: false,
|
|
||||||
imports: vec![number_import()],
|
|
||||||
exports: vec![GraphExportMetadata {
|
|
||||||
name: "Out",
|
|
||||||
identifier: "out",
|
|
||||||
description: "",
|
|
||||||
source: GraphInputSource::Node { node: 0, output: 0 },
|
|
||||||
}],
|
|
||||||
nodes: vec![GraphNodeMetadata {
|
|
||||||
implementation,
|
|
||||||
inputs,
|
|
||||||
position: (0, 0),
|
|
||||||
layer: false,
|
|
||||||
display_name: None,
|
|
||||||
hidden: false,
|
|
||||||
locked: false,
|
|
||||||
pinned: false,
|
|
||||||
}],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn from_import() -> Vec<(usize, GraphInputSource)> {
|
|
||||||
let ty = Type::Item(Box::new(concrete!(f64)));
|
|
||||||
vec![(0, GraphInputSource::Import { index: 0, ty })]
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The definitions a test graph builds on: only the As Number proto node.
|
|
||||||
fn proto_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
|
||||||
let identifier = DefinitionIdentifier::ProtoNode(math_nodes::as_number::IDENTIFIER);
|
|
||||||
let definition = resolve_document_node_type(&identifier).expect("As Number should have a definition").clone();
|
|
||||||
HashMap::from([(identifier, definition)])
|
|
||||||
}
|
|
||||||
|
|
||||||
fn has_graph(definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>, identifier: &str) -> bool {
|
|
||||||
definitions_map.contains_key(&DefinitionIdentifier::Network(identifier.to_string()))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_graph_resolves_when_registered_before_a_graph_inside_it() {
|
|
||||||
let outer = one_node_graph("Test Outer", GraphNodeImplementation::Graph("Test Inner"), from_import());
|
|
||||||
let inner = one_node_graph("Test Inner", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), from_import());
|
|
||||||
|
|
||||||
let mut definitions_map = proto_definitions();
|
|
||||||
add_graph_definitions(vec![outer, inner], &mut definitions_map);
|
|
||||||
|
|
||||||
assert!(has_graph(&definitions_map, "Test Inner"));
|
|
||||||
assert!(has_graph(&definitions_map, "Test Outer"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_graph_setting_an_input_its_node_lacks_is_left_out() {
|
|
||||||
let mut inputs = from_import();
|
|
||||||
inputs.push((
|
|
||||||
100,
|
|
||||||
GraphInputSource::Value {
|
|
||||||
value: GraphValue::Number(1.),
|
|
||||||
exposed: None,
|
|
||||||
},
|
|
||||||
));
|
|
||||||
let graph = one_node_graph("Test Missing Input", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), inputs);
|
|
||||||
|
|
||||||
let mut definitions_map = proto_definitions();
|
|
||||||
add_graph_definitions(vec![graph], &mut definitions_map);
|
|
||||||
|
|
||||||
assert!(!has_graph(&definitions_map, "Test Missing Input"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn graphs_sharing_an_identifier_and_graphs_built_on_them_are_left_out() {
|
|
||||||
let first = one_node_graph("Test Twin", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), from_import());
|
|
||||||
let second = one_node_graph("Test Twin", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), from_import());
|
|
||||||
let dependent = one_node_graph("Test Dependent", GraphNodeImplementation::Graph("Test Twin"), from_import());
|
|
||||||
|
|
||||||
let mut definitions_map = proto_definitions();
|
|
||||||
add_graph_definitions(vec![first, second, dependent], &mut definitions_map);
|
|
||||||
|
|
||||||
assert!(!has_graph(&definitions_map, "Test Twin"));
|
|
||||||
assert!(!has_graph(&definitions_map, "Test Dependent"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_value_must_have_the_type_of_the_input_it_feeds() {
|
|
||||||
let number_input = NodeInput::value(TaggedValue::Number(0.), false);
|
|
||||||
let value = |value| GraphInputSource::Value { value, exposed: None };
|
|
||||||
|
|
||||||
assert!(graph_input(&value(GraphValue::Integer(3)), &number_input).is_err());
|
|
||||||
assert!(matches!(graph_input(&value(GraphValue::Number(3.)), &number_input), Ok(NodeInput::Value { .. })));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn imports_start_from_their_default_or_type() {
|
|
||||||
let unit_primary = FieldMetadata {
|
|
||||||
default_type: Some(concrete!(())),
|
|
||||||
..number_import()
|
|
||||||
};
|
|
||||||
let with_default = FieldMetadata {
|
|
||||||
value_source: RegistryValueSource::Default("2.5"),
|
|
||||||
..number_import()
|
|
||||||
};
|
|
||||||
let graph = GraphMetadata {
|
|
||||||
imports: vec![unit_primary, with_default],
|
|
||||||
..one_node_graph("Test Defaults", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), from_import())
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut definitions_map = proto_definitions();
|
|
||||||
add_graph_definitions(vec![graph], &mut definitions_map);
|
|
||||||
let inputs = &definitions_map[&DefinitionIdentifier::Network("Test Defaults".to_string())].node_template.inputs;
|
|
||||||
|
|
||||||
// A `()` primary has nothing to connect, and an exposed parameter's default is parsed by its type
|
|
||||||
assert!(!inputs[0].is_exposed());
|
|
||||||
assert!(matches!(inputs[1].as_value(), Some(TaggedValue::Number(value)) if *value == 2.5));
|
|
||||||
assert!(inputs[1].is_exposed());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_graph_nodes_widget_settings_come_from_its_import() {
|
|
||||||
use crate::messages::prelude::DocumentMessageHandler;
|
|
||||||
|
|
||||||
let node_id = NodeId(1);
|
|
||||||
let mut document = DocumentMessageHandler::default();
|
|
||||||
let artboard = resolve_document_node_type(&DefinitionIdentifier::Network("Artboard".into())).expect("Artboard should exist");
|
|
||||||
document.network_interface.insert_node(node_id, artboard.default_node_template(), &[]);
|
|
||||||
|
|
||||||
let location = graphene_std::graph_text::import_index("Artboard", "location").expect("Artboard should have a location import");
|
|
||||||
let field = document
|
|
||||||
.network_interface
|
|
||||||
.field_metadata(&node_id, location, &[])
|
|
||||||
.expect("the location input should have its import's settings");
|
|
||||||
assert_eq!(field.labels, Some(("X", "Y")));
|
|
||||||
assert!(field.integer);
|
|
||||||
assert!(!document.network_interface.is_internal_input(&node_id, location, &[]));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -45,11 +45,6 @@ pub enum NodeGraphMessage {
|
|||||||
xy: Option<(i32, i32)>,
|
xy: Option<(i32, i32)>,
|
||||||
add_transaction: bool,
|
add_transaction: bool,
|
||||||
},
|
},
|
||||||
/// Adds a subgraph with nothing in it, at the given grid position or else in view, and selects it.
|
|
||||||
CreateEmptySubgraph {
|
|
||||||
node_id: Option<NodeId>,
|
|
||||||
xy: Option<(i32, i32)>,
|
|
||||||
},
|
|
||||||
CreateWire {
|
CreateWire {
|
||||||
output_connector: OutputConnector,
|
output_connector: OutputConnector,
|
||||||
input_connector: InputConnector,
|
input_connector: InputConnector,
|
||||||
@@ -388,7 +383,6 @@ impl NodeGraphMessage {
|
|||||||
| Self::SetImportExportDescriptionImpl { .. } => Some(breadcrumb_network_path),
|
| Self::SetImportExportDescriptionImpl { .. } => Some(breadcrumb_network_path),
|
||||||
Self::AddNodes { .. }
|
Self::AddNodes { .. }
|
||||||
| Self::CreateNodeFromContextMenu { .. }
|
| Self::CreateNodeFromContextMenu { .. }
|
||||||
| Self::CreateEmptySubgraph { .. }
|
|
||||||
| Self::CreateWire { .. }
|
| Self::CreateWire { .. }
|
||||||
| Self::CreateWires { .. }
|
| Self::CreateWires { .. }
|
||||||
| Self::ConnectUpstreamOutputToInput { .. }
|
| Self::ConnectUpstreamOutputToInput { .. }
|
||||||
|
|||||||
@@ -5,14 +5,13 @@ use crate::messages::input_mapper::utility_types::macros::{action_shortcut, acti
|
|||||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||||
use crate::messages::portfolio::document::document_message_handler::navigation_controls;
|
use crate::messages::portfolio::document::document_message_handler::navigation_controls;
|
||||||
use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext;
|
use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext;
|
||||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type};
|
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type, resolve_network_node_type};
|
||||||
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, FrontendGraphDataType, NodeEvaluationError, NodeGraphErrorDiagnostic};
|
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, FrontendGraphDataType, NodeEvaluationError, NodeGraphErrorDiagnostic};
|
||||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||||
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
|
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
|
||||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||||
use crate::messages::portfolio::document::utility_types::network_interface::{
|
use crate::messages::portfolio::document::utility_types::network_interface::{
|
||||||
self, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeNetworkInterface, NodeTemplate, NodeTypePersistentMetadata, OutputConnector, TransactionCheckpoint,
|
self, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeNetworkInterface, NodeTypePersistentMetadata, OutputConnector, TransactionCheckpoint, TransactionStatus,
|
||||||
TransactionStatus,
|
|
||||||
};
|
};
|
||||||
use crate::messages::portfolio::document::utility_types::nodes::{CollapsedLayers, LayerPanelChainInsertion, LayerPanelChainNode, LayerPanelEntry};
|
use crate::messages::portfolio::document::utility_types::nodes::{CollapsedLayers, LayerPanelChainInsertion, LayerPanelChainNode, LayerPanelEntry};
|
||||||
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_vector_wire};
|
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_vector_wire};
|
||||||
@@ -423,23 +422,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
|||||||
});
|
});
|
||||||
responses.add(NodeGraphMessage::SendGraph);
|
responses.add(NodeGraphMessage::SendGraph);
|
||||||
}
|
}
|
||||||
NodeGraphMessage::CreateEmptySubgraph { node_id, xy } => {
|
|
||||||
let node_id = node_id.unwrap_or_else(NodeId::new);
|
|
||||||
let (x, y) = xy.unwrap_or_else(|| {
|
|
||||||
network_interface
|
|
||||||
.node_graph_ptz(breadcrumb_network_path)
|
|
||||||
.map_or((0, 0), |ptz| ((-ptz.pan.x / GRID_SIZE as f64) as i32, (-ptz.pan.y / GRID_SIZE as f64) as i32))
|
|
||||||
});
|
|
||||||
|
|
||||||
responses.add(DocumentMessage::AddTransaction);
|
|
||||||
responses.add(NodeGraphMessage::InsertNode {
|
|
||||||
node_id,
|
|
||||||
node_template: Box::new(NodeTemplate::empty_subgraph()),
|
|
||||||
});
|
|
||||||
responses.add(NodeGraphMessage::ShiftNodePosition { node_id, x, y });
|
|
||||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] });
|
|
||||||
responses.add(NodeGraphMessage::SendGraph);
|
|
||||||
}
|
|
||||||
NodeGraphMessage::ConnectUpstreamOutputToInput { downstream_input, input_connector } => {
|
NodeGraphMessage::ConnectUpstreamOutputToInput { downstream_input, input_connector } => {
|
||||||
let Some(upstream_node) = network_interface.upstream_output_connector(&downstream_input, selection_network_path) else {
|
let Some(upstream_node) = network_interface.upstream_output_connector(&downstream_input, selection_network_path) else {
|
||||||
log::error!("Failed to find upstream node for downstream_input");
|
log::error!("Failed to find upstream node for downstream_input");
|
||||||
@@ -787,19 +769,24 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add an empty subgraph, then set its imports and exports, paste the nodes inside, and connect them to the imports and exports
|
// Use the network interface to add a default node, then set the imports, exports, paste the nodes inside, and connect them to the imports/exports
|
||||||
let encapsulating_node_id = NodeId::new();
|
let encapsulating_node_id = NodeId::new();
|
||||||
let mut subgraph_template = NodeTemplate::empty_subgraph();
|
let mut default_node_template = resolve_network_node_type("Custom Node").expect("Custom Node should exist").default_node_template();
|
||||||
let Some(center_of_selected_nodes) = network_interface.selected_nodes_bounding_box(breadcrumb_network_path).map(|[a, b]| (a + b) / 2.) else {
|
let Some(center_of_selected_nodes) = network_interface.selected_nodes_bounding_box(breadcrumb_network_path).map(|[a, b]| (a + b) / 2.) else {
|
||||||
log::error!("Could not get center of selected_nodes");
|
log::error!("Could not get center of selected_nodes");
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
let center_of_selected_nodes_grid_space = IVec2::new((center_of_selected_nodes.x / 24. + 0.5).floor() as i32, (center_of_selected_nodes.y / 24. + 0.5).floor() as i32);
|
let center_of_selected_nodes_grid_space = IVec2::new((center_of_selected_nodes.x / 24. + 0.5).floor() as i32, (center_of_selected_nodes.y / 24. + 0.5).floor() as i32);
|
||||||
subgraph_template.node_type_metadata = NodeTypePersistentMetadata::node(center_of_selected_nodes_grid_space - IVec2::new(3, 1));
|
default_node_template.node_type_metadata = NodeTypePersistentMetadata::node(center_of_selected_nodes_grid_space - IVec2::new(3, 1));
|
||||||
responses.add(DocumentMessage::AddTransaction);
|
responses.add(DocumentMessage::AddTransaction);
|
||||||
responses.add(NodeGraphMessage::InsertNode {
|
responses.add(NodeGraphMessage::InsertNode {
|
||||||
node_id: encapsulating_node_id,
|
node_id: encapsulating_node_id,
|
||||||
node_template: Box::new(subgraph_template),
|
node_template: Box::new(default_node_template),
|
||||||
|
});
|
||||||
|
responses.add(NodeGraphMessage::SetDisplayNameImpl {
|
||||||
|
node_id: encapsulating_node_id,
|
||||||
|
network_path: selection_network_path.to_vec(),
|
||||||
|
alias: "Untitled Node".to_string(),
|
||||||
});
|
});
|
||||||
|
|
||||||
responses.add(DocumentMessage::EnterNestedNetwork { node_id: encapsulating_node_id });
|
responses.add(DocumentMessage::EnterNestedNetwork { node_id: encapsulating_node_id });
|
||||||
@@ -3439,13 +3426,6 @@ impl NodeGraphMessageHandler {
|
|||||||
})
|
})
|
||||||
.disabled(read_only)
|
.disabled(read_only)
|
||||||
.widget_instance(),
|
.widget_instance(),
|
||||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
|
||||||
TextButton::new("New Custom Node")
|
|
||||||
.tooltip_label("New Custom Node")
|
|
||||||
.tooltip_description("Add an empty subgraph, which can be entered to build a node of your own out of other nodes.")
|
|
||||||
.on_update(|_| NodeGraphMessage::CreateEmptySubgraph { node_id: None, xy: None }.into())
|
|
||||||
.disabled(read_only)
|
|
||||||
.widget_instance(),
|
|
||||||
//
|
//
|
||||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||||
//
|
//
|
||||||
|
|||||||
@@ -2,13 +2,14 @@
|
|||||||
|
|
||||||
use super::document_node_definitions::{NODE_OVERRIDES, NodeInspectorContext};
|
use super::document_node_definitions::{NODE_OVERRIDES, NodeInspectorContext};
|
||||||
use super::utility_types::FrontendGraphDataType;
|
use super::utility_types::FrontendGraphDataType;
|
||||||
|
use crate::messages::layout::layout_message_handler::unit_suffix;
|
||||||
use crate::messages::layout::utility_types::math_expression::{MathExpressionTokens, math_expression_error, math_expression_error_ranges, math_expression_tokens};
|
use crate::messages::layout::utility_types::math_expression::{MathExpressionTokens, math_expression_error, math_expression_error_ranges, math_expression_tokens};
|
||||||
use crate::messages::layout::utility_types::tooltip_markdown::{escape_markdown, markdown_code_span};
|
use crate::messages::layout::utility_types::tooltip_markdown::{escape_markdown, markdown_code_span};
|
||||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||||
use crate::messages::portfolio::document::data_panel::node_reference_button;
|
use crate::messages::portfolio::document::data_panel::node_reference_button;
|
||||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
|
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
|
||||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, LAYER_SECONDARY_INPUT_INDEX, NodeNetworkInterface, OutputConnector};
|
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, LAYER_SECONDARY_INPUT_INDEX, NodeNetworkInterface, OutputConnector, wire_feeds_proto_input};
|
||||||
use crate::messages::portfolio::fonts::utility_types::FontCatalogStyle;
|
use crate::messages::portfolio::fonts::utility_types::FontCatalogStyle;
|
||||||
use crate::messages::portfolio::ingest::utility_types::{DataTransferItem, IngestAction, TypeFilter};
|
use crate::messages::portfolio::ingest::utility_types::{DataTransferItem, IngestAction, TypeFilter};
|
||||||
use crate::messages::prelude::*;
|
use crate::messages::prelude::*;
|
||||||
@@ -31,6 +32,7 @@ use graphene_std::text::{Font, TextAlign};
|
|||||||
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
|
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
|
||||||
use graphene_std::transfer_curve::TransferCurve;
|
use graphene_std::transfer_curve::TransferCurve;
|
||||||
use graphene_std::transform::{Footprint, ReferencePoint, ScaleType, Transform};
|
use graphene_std::transform::{Footprint, ReferencePoint, ScaleType, Transform};
|
||||||
|
use graphene_std::units::{Angle, AngleUnit, AngleVec2, Length, LengthUnit, LengthVec2, TypedAngle, TypedAngleVec2, TypedLength, TypedLengthVec2};
|
||||||
use graphene_std::vector::misc::BooleanOperation;
|
use graphene_std::vector::misc::BooleanOperation;
|
||||||
use graphene_std::vector::misc::{
|
use graphene_std::vector::misc::{
|
||||||
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod,
|
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod,
|
||||||
@@ -238,7 +240,7 @@ pub fn start_widgets(parameter_widgets_info: &ParameterWidgetsInfo) -> Vec<Widge
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The presentation of a parameter's widget, sourced from the node's field metadata: numeric bounds, widget modes, and unit of measure.
|
/// The presentation of a parameter's widget, sourced from the node's field metadata: numeric bounds, widget modes, and unit of measure.
|
||||||
#[derive(Clone, Copy)]
|
#[derive(Clone, Copy, Default)]
|
||||||
pub(crate) struct ParameterOptions {
|
pub(crate) struct ParameterOptions {
|
||||||
pub soft_min: Option<f64>,
|
pub soft_min: Option<f64>,
|
||||||
pub soft_max: Option<f64>,
|
pub soft_max: Option<f64>,
|
||||||
@@ -250,50 +252,6 @@ pub(crate) struct ParameterOptions {
|
|||||||
pub unit: Option<&'static str>,
|
pub unit: Option<&'static str>,
|
||||||
pub display_decimal_places: Option<u32>,
|
pub display_decimal_places: Option<u32>,
|
||||||
pub step: Option<f64>,
|
pub step: Option<f64>,
|
||||||
pub labels: Option<(&'static str, &'static str)>,
|
|
||||||
pub integer: bool,
|
|
||||||
pub blank_assist: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for ParameterOptions {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self {
|
|
||||||
soft_min: None,
|
|
||||||
soft_max: None,
|
|
||||||
hard_min: None,
|
|
||||||
hard_max: None,
|
|
||||||
slider: false,
|
|
||||||
multiline: false,
|
|
||||||
progression: false,
|
|
||||||
unit: None,
|
|
||||||
display_decimal_places: None,
|
|
||||||
step: None,
|
|
||||||
labels: None,
|
|
||||||
integer: false,
|
|
||||||
blank_assist: true,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ParameterOptions {
|
|
||||||
/// The options a proto node's field or a graph's import gives its widget.
|
|
||||||
pub(crate) fn from_field(field: &graphene_std::registry::FieldMetadata) -> Self {
|
|
||||||
Self {
|
|
||||||
soft_min: field.number_soft_min,
|
|
||||||
soft_max: field.number_soft_max,
|
|
||||||
hard_min: field.number_hard_min,
|
|
||||||
hard_max: field.number_hard_max,
|
|
||||||
slider: field.number_mode_range,
|
|
||||||
multiline: field.multiline,
|
|
||||||
progression: field.progression,
|
|
||||||
unit: field.unit,
|
|
||||||
display_decimal_places: field.number_display_decimal_places,
|
|
||||||
step: field.number_step,
|
|
||||||
labels: field.labels,
|
|
||||||
integer: field.integer,
|
|
||||||
blank_assist: field.blank_assist,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The values a range slider's two ends map to linearly and the one its double-click restores, if known.
|
/// The values a range slider's two ends map to linearly and the one its double-click restores, if known.
|
||||||
@@ -322,6 +280,11 @@ impl SliderRange {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Builds a parameter's number field.
|
||||||
|
type FieldWidget = fn(ParameterWidgetsInfo<'_>, NumberInput) -> Vec<WidgetInstance>;
|
||||||
|
/// Builds a parameter's range slider beside its number field.
|
||||||
|
type SliderWidget = fn(ParameterWidgetsInfo<'_>, NumberInput, SliderRange) -> Vec<WidgetInstance>;
|
||||||
|
|
||||||
/// The number a parameter's definition gives it by default, which a slider's double-click restores.
|
/// The number a parameter's definition gives it by default, which a slider's double-click restores.
|
||||||
pub(crate) fn definition_default_number(parameter_widgets_info: &ParameterWidgetsInfo) -> Option<f64> {
|
pub(crate) fn definition_default_number(parameter_widgets_info: &ParameterWidgetsInfo) -> Option<f64> {
|
||||||
let identifier = parameter_widgets_info
|
let identifier = parameter_widgets_info
|
||||||
@@ -331,6 +294,7 @@ pub(crate) fn definition_default_number(parameter_widgets_info: &ParameterWidget
|
|||||||
|
|
||||||
match input.as_value()? {
|
match input.as_value()? {
|
||||||
TaggedValue::Number(value) => Some(*value),
|
TaggedValue::Number(value) => Some(*value),
|
||||||
|
TaggedValue::Angle(angle) => Some(angle.to_degrees()),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -347,12 +311,9 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
|||||||
unit,
|
unit,
|
||||||
display_decimal_places,
|
display_decimal_places,
|
||||||
step,
|
step,
|
||||||
labels,
|
|
||||||
integer,
|
|
||||||
blank_assist,
|
|
||||||
} = options;
|
} = options;
|
||||||
|
|
||||||
let mut number_input = NumberInput::default().is_integer(integer);
|
let mut number_input = NumberInput::default().pixels_per_inch(context.network_interface.pixels_per_inch());
|
||||||
if slider {
|
if slider {
|
||||||
number_input = number_input.mode_range();
|
number_input = number_input.mode_range();
|
||||||
}
|
}
|
||||||
@@ -384,18 +345,19 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
|||||||
// A range-mode number hard-clamped at both ends becomes a range slider beside its number input, unless a soft bound lets typing pass it
|
// A range-mode number hard-clamped at both ends becomes a range slider beside its number input, unless a soft bound lets typing pass it
|
||||||
let no_soft_bounds = soft_min.is_none() && soft_max.is_none();
|
let no_soft_bounds = soft_min.is_none() && soft_max.is_none();
|
||||||
let hard_both_ends = hard_min.is_some() && hard_max.is_some();
|
let hard_both_ends = hard_min.is_some() && hard_max.is_some();
|
||||||
let number_or_slider = |default_info: ParameterWidgetsInfo, number_input: NumberInput| -> LayoutGroup {
|
let field_or_slider = |default_info: ParameterWidgetsInfo, number_input: NumberInput, field: FieldWidget, slider: SliderWidget| -> LayoutGroup {
|
||||||
let fixed_extent = number_input.mode == NumberInputMode::Range && no_soft_bounds && hard_both_ends;
|
let fixed_extent = number_input.mode == NumberInputMode::Range && no_soft_bounds && hard_both_ends;
|
||||||
match (number_input.min, number_input.max) {
|
match (number_input.min, number_input.max) {
|
||||||
(Some(min), Some(max)) if fixed_extent && min.is_finite() && max.is_finite() && min < max => {
|
(Some(min), Some(max)) if fixed_extent && min.is_finite() && max.is_finite() && min < max => {
|
||||||
let default = definition_default_number(&default_info);
|
let default = definition_default_number(&default_info);
|
||||||
range_slider_widget(default_info, number_input.mode_increment(), SliderRange { min, max, default }).into()
|
slider(default_info, number_input.mode_increment(), SliderRange { min, max, default }).into()
|
||||||
}
|
}
|
||||||
_ => number_widget(default_info, number_input).into(),
|
_ => field(default_info, number_input).into(),
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
let number_or_slider = |default_info: ParameterWidgetsInfo, number_input: NumberInput| field_or_slider(default_info, number_input, number_widget, range_slider_widget);
|
||||||
|
|
||||||
let default_info = ParameterWidgetsInfo::at_index(node_id, index, blank_assist, context);
|
let default_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||||
|
|
||||||
// A type with no widget can only be supplied through the graph, labeled with a placeholder row
|
// A type with no widget can only be supplied through the graph, labeled with a placeholder row
|
||||||
let unsupported_widgets = |default_info: ParameterWidgetsInfo, type_label: String| {
|
let unsupported_widgets = |default_info: ParameterWidgetsInfo, type_label: String| {
|
||||||
@@ -434,15 +396,16 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
|||||||
false => number_or_slider(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)),
|
false => number_or_slider(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)),
|
||||||
},
|
},
|
||||||
Some(x) if id_is::<i64>(x) => number_widget(default_info, bounded(number_input.int(), f64::NEG_INFINITY, f64::INFINITY)).into(),
|
Some(x) if id_is::<i64>(x) => number_widget(default_info, bounded(number_input.int(), f64::NEG_INFINITY, f64::INFINITY)).into(),
|
||||||
|
Some(x) if id_is::<Length>(x) => length_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)).into(),
|
||||||
|
Some(x) if id_is::<Angle>(x) => field_or_slider(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY), angle_widget, angle_slider_widget),
|
||||||
Some(x) if id_is::<bool>(x) => bool_widget(default_info, CheckboxInput::default()).into(),
|
Some(x) if id_is::<bool>(x) => bool_widget(default_info, CheckboxInput::default()).into(),
|
||||||
Some(x) if id_is::<String>(x) => match multiline {
|
Some(x) if id_is::<String>(x) => match multiline {
|
||||||
true => text_area_widget(default_info).into(),
|
true => text_area_widget(default_info).into(),
|
||||||
false => text_widget(default_info).into(),
|
false => text_widget(default_info).into(),
|
||||||
},
|
},
|
||||||
Some(x) if id_is::<DVec2>(x) => {
|
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", unit.unwrap_or(""), None, false, false),
|
||||||
let (x_label, y_label) = labels.unwrap_or(("X", "Y"));
|
Some(x) if id_is::<LengthVec2>(x) => length_vec2_widget(default_info, "X", "Y", bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)),
|
||||||
vec2_widget(default_info, x_label, y_label, unit.unwrap_or(""), hard_min, hard_max, integer, false)
|
Some(x) if id_is::<AngleVec2>(x) => angle_vec2_widget(default_info, "X", "Y", bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)),
|
||||||
}
|
|
||||||
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
|
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
|
||||||
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||||
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||||
@@ -944,8 +907,9 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option<f64>, max: Option<f64>, is_integer: bool, disabled: bool) -> LayoutGroup {
|
pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option<f64>, is_integer: bool, disabled: bool) -> LayoutGroup {
|
||||||
let mut widgets = start_widgets(¶meter_widgets_info);
|
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||||
|
let pixels_per_inch = parameter_widgets_info.network_interface.pixels_per_inch();
|
||||||
|
|
||||||
let Some(input) = parameter_widgets_info.input() else {
|
let Some(input) = parameter_widgets_info.input() else {
|
||||||
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
||||||
@@ -959,9 +923,10 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
|||||||
.label(x)
|
.label(x)
|
||||||
.unit(unit)
|
.unit(unit)
|
||||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||||
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
|
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||||
.is_integer(is_integer)
|
.is_integer(is_integer)
|
||||||
.disabled(disabled)
|
.disabled(disabled)
|
||||||
|
.pixels_per_inch(pixels_per_inch)
|
||||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), dvec2.y))))
|
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), dvec2.y))))
|
||||||
.on_commit(commit_value)
|
.on_commit(commit_value)
|
||||||
.widget_instance(),
|
.widget_instance(),
|
||||||
@@ -970,9 +935,10 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
|||||||
.label(y)
|
.label(y)
|
||||||
.unit(unit)
|
.unit(unit)
|
||||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||||
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
|
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||||
.is_integer(is_integer)
|
.is_integer(is_integer)
|
||||||
.disabled(disabled)
|
.disabled(disabled)
|
||||||
|
.pixels_per_inch(pixels_per_inch)
|
||||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(dvec2.x, input.value.unwrap()))))
|
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(dvec2.x, input.value.unwrap()))))
|
||||||
.on_commit(commit_value)
|
.on_commit(commit_value)
|
||||||
.widget_instance(),
|
.widget_instance(),
|
||||||
@@ -985,9 +951,10 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
|||||||
.label(x)
|
.label(x)
|
||||||
.unit(unit)
|
.unit(unit)
|
||||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||||
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
|
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||||
.is_integer(is_integer)
|
.is_integer(is_integer)
|
||||||
.disabled(disabled)
|
.disabled(disabled)
|
||||||
|
.pixels_per_inch(pixels_per_inch)
|
||||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), value))))
|
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), value))))
|
||||||
.on_commit(commit_value)
|
.on_commit(commit_value)
|
||||||
.widget_instance(),
|
.widget_instance(),
|
||||||
@@ -996,9 +963,10 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
|||||||
.label(y)
|
.label(y)
|
||||||
.unit(unit)
|
.unit(unit)
|
||||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||||
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
|
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||||
.is_integer(is_integer)
|
.is_integer(is_integer)
|
||||||
.disabled(disabled)
|
.disabled(disabled)
|
||||||
|
.pixels_per_inch(pixels_per_inch)
|
||||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(value, input.value.unwrap()))))
|
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(value, input.value.unwrap()))))
|
||||||
.on_commit(commit_value)
|
.on_commit(commit_value)
|
||||||
.widget_instance(),
|
.widget_instance(),
|
||||||
@@ -1251,6 +1219,24 @@ pub fn progression_widget(parameter_widgets_info: ParameterWidgetsInfo, number_p
|
|||||||
/// A number row gated by the bool input at `bool_input_index`, drawn as a checkbox in the assist slot after the label like the
|
/// A number row gated by the bool input at `bool_input_index`, drawn as a checkbox in the assist slot after the label like the
|
||||||
/// Opacity node's toggles, so the caller passes `blank_assist = false`. Given a `slider`, a range slider spanning it sits between them.
|
/// Opacity node's toggles, so the caller passes `blank_assist = false`. Given a `slider`, a range slider spanning it sits between them.
|
||||||
pub fn optional_f64_widget(parameter_widgets_info: ParameterWidgetsInfo, bool_input_index: usize, number_props: NumberInput, slider: Option<SliderRange>) -> Vec<WidgetInstance> {
|
pub fn optional_f64_widget(parameter_widgets_info: ParameterWidgetsInfo, bool_input_index: usize, number_props: NumberInput, slider: Option<SliderRange>) -> Vec<WidgetInstance> {
|
||||||
|
optional_number_widget(parameter_widgets_info, bool_input_index, number_props, |parameter_widgets_info, number_props| match slider {
|
||||||
|
Some(slider) => range_slider_widget(parameter_widgets_info, number_props, slider),
|
||||||
|
None => number_widget(parameter_widgets_info, number_props),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Like [`optional_f64_widget`], for a length parameter. Its field keeps any length unit typed into it.
|
||||||
|
pub fn optional_length_widget(parameter_widgets_info: ParameterWidgetsInfo, bool_input_index: usize, number_props: NumberInput) -> Vec<WidgetInstance> {
|
||||||
|
optional_number_widget(parameter_widgets_info, bool_input_index, number_props, length_widget)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The row of an optional parameter, with its `field` built by the caller.
|
||||||
|
fn optional_number_widget(
|
||||||
|
parameter_widgets_info: ParameterWidgetsInfo,
|
||||||
|
bool_input_index: usize,
|
||||||
|
number_props: NumberInput,
|
||||||
|
field: impl FnOnce(ParameterWidgetsInfo, NumberInput) -> Vec<WidgetInstance>,
|
||||||
|
) -> Vec<WidgetInstance> {
|
||||||
let node_id = parameter_widgets_info.node_id;
|
let node_id = parameter_widgets_info.node_id;
|
||||||
let enabled = parameter_widgets_info
|
let enabled = parameter_widgets_info
|
||||||
.document_node
|
.document_node
|
||||||
@@ -1261,10 +1247,7 @@ pub fn optional_f64_widget(parameter_widgets_info: ParameterWidgetsInfo, bool_in
|
|||||||
let exposed = parameter_widgets_info.is_exposed();
|
let exposed = parameter_widgets_info.is_exposed();
|
||||||
|
|
||||||
let number_props = number_props.disabled(enabled == Some(false));
|
let number_props = number_props.disabled(enabled == Some(false));
|
||||||
let mut widgets = match slider {
|
let mut widgets = field(parameter_widgets_info, number_props);
|
||||||
Some(slider) => range_slider_widget(parameter_widgets_info, number_props, slider),
|
|
||||||
None => number_widget(parameter_widgets_info, number_props),
|
|
||||||
};
|
|
||||||
|
|
||||||
if !exposed {
|
if !exposed {
|
||||||
widgets.splice(label_count..label_count, optional_parameter_assist(enabled, node_id, bool_input_index));
|
widgets.splice(label_count..label_count, optional_parameter_assist(enabled, node_id, bool_input_index));
|
||||||
@@ -1361,12 +1344,302 @@ pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
|
|||||||
.on_commit(commit_value)
|
.on_commit(commit_value)
|
||||||
.widget_instance(),
|
.widget_instance(),
|
||||||
]),
|
]),
|
||||||
|
// A length or angle left over from rows that took one reads as the number its field showed, pixels or degrees
|
||||||
|
Some(TaggedValue::Length(_) | TaggedValue::Angle(_)) => {
|
||||||
|
let number = input
|
||||||
|
.as_non_exposed_value()
|
||||||
|
.and_then(|value| value.as_length_pixels(parameter_widgets_info.network_interface.pixels_per_inch()).or_else(|| value.as_angle_degrees()));
|
||||||
|
widgets.extend_from_slice(&[
|
||||||
|
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||||
|
number_props
|
||||||
|
.value(number)
|
||||||
|
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::Number(x.value.unwrap())))
|
||||||
|
.on_commit(commit_value)
|
||||||
|
.widget_instance(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
|
|
||||||
widgets
|
widgets
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Converts a field's bounds from the unit they're given in into the unit its value is shown in.
|
||||||
|
fn bounds_in_unit(number_input: NumberInput, convert: impl Fn(f64) -> f64) -> NumberInput {
|
||||||
|
let convert = |bound: Option<f64>| bound.map(|bound| if bound.is_finite() { convert(bound) } else { bound });
|
||||||
|
NumberInput {
|
||||||
|
min: convert(number_input.min),
|
||||||
|
max: convert(number_input.max),
|
||||||
|
range_min: convert(number_input.range_min),
|
||||||
|
range_max: convert(number_input.range_max),
|
||||||
|
..number_input
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A length's number field, which shows the length in the unit it was typed in and keeps any length unit typed into it, with the
|
||||||
|
/// field's bounds given in pixels.
|
||||||
|
pub fn length_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput) -> Vec<WidgetInstance> {
|
||||||
|
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||||
|
|
||||||
|
let Some(input) = parameter_widgets_info.input() else {
|
||||||
|
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
||||||
|
return vec![];
|
||||||
|
};
|
||||||
|
let length = match input.as_non_exposed_value() {
|
||||||
|
Some(&TaggedValue::Length(length)) => length,
|
||||||
|
Some(&TaggedValue::Number(pixels)) => TypedLength::pixels(pixels),
|
||||||
|
// A pair shows its `y`, which the "Grid" node's isometric spacing keeps from its rectangular height
|
||||||
|
Some(&TaggedValue::LengthVec2(lengths)) => TypedLength {
|
||||||
|
value: lengths.value.y,
|
||||||
|
unit: lengths.unit,
|
||||||
|
},
|
||||||
|
Some(&TaggedValue::DVec2(pixels)) => TypedLength::pixels(pixels.y),
|
||||||
|
_ => return widgets,
|
||||||
|
};
|
||||||
|
|
||||||
|
let pixels_per_inch = parameter_widgets_info.network_interface.pixels_per_inch();
|
||||||
|
let number_props = bounds_in_unit(number_props, |pixels| LengthUnit::Pixel.convert(pixels, length.unit, pixels_per_inch));
|
||||||
|
widgets.extend_from_slice(&[
|
||||||
|
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||||
|
number_props
|
||||||
|
.value(Some(length.value))
|
||||||
|
.unit(unit_suffix(length.unit.symbol()))
|
||||||
|
.display_decimal_places(length_decimal_places(length.unit, pixels_per_inch))
|
||||||
|
.kept_units(LengthUnit::ALL.iter().map(|unit| unit.symbol().to_string()).collect())
|
||||||
|
.pixels_per_inch(pixels_per_inch)
|
||||||
|
.on_update(parameter_widgets_info.update_value(|input: &NumberInput| {
|
||||||
|
let unit = math_parser::units::Unit::named(input.unit.trim()).and_then(LengthUnit::from_unit).unwrap_or_default();
|
||||||
|
TaggedValue::Length(TypedLength {
|
||||||
|
value: input.value.unwrap_or_default(),
|
||||||
|
unit,
|
||||||
|
})
|
||||||
|
}))
|
||||||
|
.on_commit(commit_value)
|
||||||
|
.widget_instance(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
widgets
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An angle's number field, which shows the angle in the unit it was typed in and keeps any angle unit typed into it, with the
|
||||||
|
/// field's bounds given in degrees.
|
||||||
|
pub fn angle_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput) -> Vec<WidgetInstance> {
|
||||||
|
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||||
|
|
||||||
|
let Some(input) = parameter_widgets_info.input() else {
|
||||||
|
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
||||||
|
return vec![];
|
||||||
|
};
|
||||||
|
let angle = match input.as_non_exposed_value() {
|
||||||
|
Some(&TaggedValue::Angle(angle)) => angle,
|
||||||
|
Some(&TaggedValue::Number(degrees)) => TypedAngle::degrees(degrees),
|
||||||
|
_ => return widgets,
|
||||||
|
};
|
||||||
|
|
||||||
|
let number_props = bounds_in_unit(number_props, |degrees| angle.unit.from_degrees(degrees));
|
||||||
|
widgets.extend_from_slice(&[
|
||||||
|
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||||
|
angle_field(number_props, angle).on_update(parameter_widgets_info.update_value(typed_angle)).widget_instance(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
widgets
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An angle's range slider beside its number field, which keeps the unit the angle was typed in, with the slider's bounds given in degrees.
|
||||||
|
pub fn angle_slider_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput, slider: SliderRange) -> Vec<WidgetInstance> {
|
||||||
|
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||||
|
|
||||||
|
let Some(input) = parameter_widgets_info.input() else {
|
||||||
|
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
||||||
|
return vec![];
|
||||||
|
};
|
||||||
|
let angle = match input.as_non_exposed_value() {
|
||||||
|
Some(&TaggedValue::Angle(angle)) => angle,
|
||||||
|
Some(&TaggedValue::Number(degrees)) => TypedAngle::degrees(degrees),
|
||||||
|
_ => return widgets,
|
||||||
|
};
|
||||||
|
let ParameterWidgetsInfo { node_id, index, .. } = parameter_widgets_info;
|
||||||
|
|
||||||
|
let unit = angle.unit;
|
||||||
|
let slid_to = move |position| {
|
||||||
|
let value = unit.from_degrees(slider.value(position));
|
||||||
|
TaggedValue::Angle(TypedAngle { value, unit })
|
||||||
|
};
|
||||||
|
let default_position = slider.default.map(|default| slider.position(default));
|
||||||
|
|
||||||
|
let number_props = bounds_in_unit(number_props, |degrees| unit.from_degrees(degrees));
|
||||||
|
widgets.extend_from_slice(&[
|
||||||
|
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||||
|
value_slider(node_id, index, GradientStops::default(), Color::WHITE, slider.position(angle.to_degrees()), default_position, slid_to)
|
||||||
|
.range_slider(true)
|
||||||
|
.disabled(number_props.disabled)
|
||||||
|
.widget_instance(),
|
||||||
|
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||||
|
// A unit spelled out, like `0.25 turn`, needs more room than a degree sign
|
||||||
|
angle_field(number_props, angle)
|
||||||
|
.sizing(WidgetSizing::fixed(if unit == AngleUnit::Degree { 60 } else { 90 }))
|
||||||
|
.on_update(update_value_at_index(typed_angle, node_id, index))
|
||||||
|
.widget_instance(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
widgets
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The decimal places a field shows a length in, resolving about a hundredth of a pixel in any unit, so `0.125 in` doesn't display as `0.13 in`.
|
||||||
|
pub(crate) fn length_decimal_places(unit: LengthUnit, pixels_per_inch: f64) -> u32 {
|
||||||
|
decimal_places_for_size(unit.convert(1., LengthUnit::Pixel, pixels_per_inch))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The decimal places a field shows an angle in, resolving about a hundredth of a degree in any unit.
|
||||||
|
fn angle_decimal_places(unit: AngleUnit) -> u32 {
|
||||||
|
decimal_places_for_size(unit.to_angle(1.).degrees())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Two decimal places for a unit the size of the field's base unit (a pixel or a degree), and one more for each power of ten larger it is.
|
||||||
|
fn decimal_places_for_size(base_units_per_unit: f64) -> u32 {
|
||||||
|
let extra = base_units_per_unit.log10().ceil();
|
||||||
|
if extra.is_finite() { (2. + extra.clamp(0., 7.)) as u32 } else { 2 }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The number field showing an angle in the unit it was typed in, which keeps any angle unit typed into it.
|
||||||
|
fn angle_field(number_props: NumberInput, angle: TypedAngle) -> NumberInput {
|
||||||
|
number_props
|
||||||
|
.value(Some(angle.value))
|
||||||
|
.unit(unit_suffix(angle.unit.symbol()))
|
||||||
|
.display_decimal_places(angle_decimal_places(angle.unit))
|
||||||
|
.kept_units(AngleUnit::ALL.iter().map(|unit| unit.symbol().to_string()).collect())
|
||||||
|
.on_commit(commit_value)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The angle in an angle field, in the unit typed into it.
|
||||||
|
fn typed_angle(input: &NumberInput) -> TaggedValue {
|
||||||
|
let unit = math_parser::units::Unit::named(input.unit.trim()).and_then(AngleUnit::from_unit).unwrap_or_default();
|
||||||
|
TaggedValue::Angle(TypedAngle {
|
||||||
|
value: input.value.unwrap_or_default(),
|
||||||
|
unit,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A pair of lengths' X and Y number fields, which share the unit the pair was typed in, with the fields' bounds given in pixels.
|
||||||
|
/// Typing another length unit into either field moves both into it, converting the other component so its length stays the same.
|
||||||
|
pub fn length_vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, number_props: NumberInput) -> LayoutGroup {
|
||||||
|
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||||
|
|
||||||
|
let Some(input) = parameter_widgets_info.input() else {
|
||||||
|
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
||||||
|
return LayoutGroup::row(vec![]);
|
||||||
|
};
|
||||||
|
let lengths = match input.as_non_exposed_value() {
|
||||||
|
Some(&TaggedValue::LengthVec2(lengths)) => lengths,
|
||||||
|
Some(&TaggedValue::DVec2(pixels)) => TypedLengthVec2::pixels(pixels),
|
||||||
|
// One length stands for both components, like the "Grid" node's isometric spacing
|
||||||
|
Some(&TaggedValue::Length(length)) => TypedLengthVec2 {
|
||||||
|
value: DVec2::splat(length.value),
|
||||||
|
unit: length.unit,
|
||||||
|
},
|
||||||
|
Some(&TaggedValue::Number(pixels)) => TypedLengthVec2::pixels(DVec2::splat(pixels)),
|
||||||
|
_ => return LayoutGroup::row(widgets),
|
||||||
|
};
|
||||||
|
|
||||||
|
let pixels_per_inch = parameter_widgets_info.network_interface.pixels_per_inch();
|
||||||
|
// A field limited to integers would convert a typed physical length into its pixels, so whole pixels are enforced only on a pair in pixels
|
||||||
|
let whole_pixels = number_props.is_integer;
|
||||||
|
let number_props = bounds_in_unit(number_props, |pixels| LengthUnit::Pixel.convert(pixels, lengths.unit, pixels_per_inch));
|
||||||
|
let field = |component: f64, label: &str| {
|
||||||
|
number_props
|
||||||
|
.clone()
|
||||||
|
.is_integer(false)
|
||||||
|
.label(label)
|
||||||
|
.value(Some(component))
|
||||||
|
.unit(unit_suffix(lengths.unit.symbol()))
|
||||||
|
.display_decimal_places(length_decimal_places(lengths.unit, pixels_per_inch))
|
||||||
|
.kept_units(LengthUnit::ALL.iter().map(|unit| unit.symbol().to_string()).collect())
|
||||||
|
.pixels_per_inch(pixels_per_inch)
|
||||||
|
.on_commit(commit_value)
|
||||||
|
};
|
||||||
|
|
||||||
|
// The edited component takes the typed unit, and the other converts into it
|
||||||
|
let typed = move |input: &NumberInput, edited_axis: usize| {
|
||||||
|
let unit = math_parser::units::Unit::named(input.unit.trim()).and_then(LengthUnit::from_unit).unwrap_or_default();
|
||||||
|
let mut value = DVec2::new(
|
||||||
|
lengths.unit.convert(lengths.value.x, unit, pixels_per_inch),
|
||||||
|
lengths.unit.convert(lengths.value.y, unit, pixels_per_inch),
|
||||||
|
);
|
||||||
|
value[edited_axis] = input.value.unwrap_or_default();
|
||||||
|
if whole_pixels && unit == LengthUnit::Pixel {
|
||||||
|
value = value.round();
|
||||||
|
}
|
||||||
|
TaggedValue::LengthVec2(TypedLengthVec2 { value, unit })
|
||||||
|
};
|
||||||
|
|
||||||
|
widgets.extend_from_slice(&[
|
||||||
|
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||||
|
field(lengths.value.x, x)
|
||||||
|
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| typed(input, 0)))
|
||||||
|
.widget_instance(),
|
||||||
|
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||||
|
field(lengths.value.y, y)
|
||||||
|
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| typed(input, 1)))
|
||||||
|
.widget_instance(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
LayoutGroup::row(widgets)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A pair of angles' X and Y number fields, which share the unit the pair was typed in, with the fields' bounds given in degrees.
|
||||||
|
/// Typing another angle unit into either field moves both into it, converting the other component so its angle stays the same.
|
||||||
|
pub fn angle_vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, number_props: NumberInput) -> LayoutGroup {
|
||||||
|
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||||
|
|
||||||
|
let Some(input) = parameter_widgets_info.input() else {
|
||||||
|
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
||||||
|
return LayoutGroup::row(vec![]);
|
||||||
|
};
|
||||||
|
let angles = match input.as_non_exposed_value() {
|
||||||
|
Some(&TaggedValue::AngleVec2(angles)) => angles,
|
||||||
|
Some(&TaggedValue::DVec2(degrees)) => TypedAngleVec2::degrees(degrees),
|
||||||
|
_ => return LayoutGroup::row(widgets),
|
||||||
|
};
|
||||||
|
|
||||||
|
let number_props = bounds_in_unit(number_props, |degrees| angles.unit.from_degrees(degrees));
|
||||||
|
let field = |component: f64, label: &str| {
|
||||||
|
number_props
|
||||||
|
.clone()
|
||||||
|
.label(label)
|
||||||
|
.value(Some(component))
|
||||||
|
.unit(unit_suffix(angles.unit.symbol()))
|
||||||
|
.display_decimal_places(angle_decimal_places(angles.unit))
|
||||||
|
.kept_units(AngleUnit::ALL.iter().map(|unit| unit.symbol().to_string()).collect())
|
||||||
|
.on_commit(commit_value)
|
||||||
|
};
|
||||||
|
|
||||||
|
// The edited component takes the typed unit, and the other converts into it
|
||||||
|
let typed = move |input: &NumberInput, edited_axis: usize| {
|
||||||
|
let unit = math_parser::units::Unit::named(input.unit.trim()).and_then(AngleUnit::from_unit).unwrap_or_default();
|
||||||
|
let degrees = angles.to_degrees();
|
||||||
|
let mut value = if unit == angles.unit {
|
||||||
|
angles.value
|
||||||
|
} else {
|
||||||
|
DVec2::new(unit.from_degrees(degrees.x), unit.from_degrees(degrees.y))
|
||||||
|
};
|
||||||
|
value[edited_axis] = input.value.unwrap_or_default();
|
||||||
|
TaggedValue::AngleVec2(TypedAngleVec2 { value, unit })
|
||||||
|
};
|
||||||
|
|
||||||
|
widgets.extend_from_slice(&[
|
||||||
|
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||||
|
field(angles.value.x, x)
|
||||||
|
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| typed(input, 0)))
|
||||||
|
.widget_instance(),
|
||||||
|
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||||
|
field(angles.value.y, y)
|
||||||
|
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| typed(input, 1)))
|
||||||
|
.widget_instance(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
LayoutGroup::row(widgets)
|
||||||
|
}
|
||||||
|
|
||||||
// TODO: Auto-generate this enum dropdown menu widget
|
// TODO: Auto-generate this enum dropdown menu widget
|
||||||
pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> LayoutGroup {
|
pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> LayoutGroup {
|
||||||
let mut widgets = start_widgets(¶meter_widgets_info);
|
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||||
@@ -1462,11 +1735,80 @@ fn wire_element(ty: &Type) -> Type {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The length or angle type of the field an unwired input shows, where the node's rows take one there among other types.
|
||||||
|
/// The rows fitting the node's other known inputs decide it when they all need one type there. Otherwise a length or angle the input holds keeps its field.
|
||||||
|
fn measurement_input_type(node_id: NodeId, input_index: usize, identifier: &graph_craft::ProtoNodeIdentifier, network_interface: &NodeNetworkInterface, network_path: &[NodeId]) -> Option<Type> {
|
||||||
|
let rows = interpreted_executor::node_registry::NODE_REGISTRY.get(identifier)?;
|
||||||
|
let measurements = [concrete!(Length), concrete!(Angle)];
|
||||||
|
let element_at = |inputs: &[Type], index: usize| inputs.get(index).map(wire_element);
|
||||||
|
|
||||||
|
let offered: Vec<Type> = rows.keys().filter_map(|row| element_at(&row.inputs, input_index)).collect();
|
||||||
|
if !offered.iter().any(|element| measurements.contains(element)) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only an unwired input shows a field
|
||||||
|
let held_measurement = |index: usize| match network_interface.input_from_connector(&InputConnector::node_at_index(node_id, index), network_path) {
|
||||||
|
Some(NodeInput::Value { tagged_value, .. }) => Some(wire_element(&tagged_value.ty())).filter(|element| measurements.contains(element)),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
let Some(NodeInput::Value { .. }) = network_interface.input_from_connector(&InputConnector::node_at_index(node_id, input_index), network_path) else {
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
let held = held_measurement(input_index).filter(|held| offered.contains(held));
|
||||||
|
|
||||||
|
// Wired inputs, through the conversions ahead of them, and inputs holding a length or angle decide which rows fit, unlike a plain number, which may be the one to change
|
||||||
|
enum Known {
|
||||||
|
Wired(Type),
|
||||||
|
Held(Type),
|
||||||
|
}
|
||||||
|
let known_inputs: Vec<(usize, Known)> = (0..network_interface.number_of_inputs(&node_id, network_path))
|
||||||
|
.filter(|&index| index != input_index)
|
||||||
|
.filter_map(|index| match network_interface.input_from_connector(&InputConnector::node_at_index(node_id, index), network_path)? {
|
||||||
|
NodeInput::Node { .. } | NodeInput::Import { .. } => {
|
||||||
|
let wired = network_interface.input_type_not_invalid(&InputConnector::node_at_index(node_id, index), network_path);
|
||||||
|
Some((index, Known::Wired(wired.compiled_nested_type()?.clone())))
|
||||||
|
}
|
||||||
|
NodeInput::Value { .. } => Some((index, Known::Held(held_measurement(index)?))),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
if known_inputs.is_empty() {
|
||||||
|
return held;
|
||||||
|
}
|
||||||
|
|
||||||
|
let fits = |row: &graphene_std::NodeIOTypes, exactly: bool| {
|
||||||
|
known_inputs.iter().all(|(index, known)| match known {
|
||||||
|
Known::Wired(source) if exactly => element_at(&row.inputs, *index) == Some(wire_element(source)),
|
||||||
|
Known::Wired(source) => row.inputs.get(*index).is_some_and(|connector| wire_feeds_proto_input(identifier, *index, source, connector)),
|
||||||
|
Known::Held(element) => element_at(&row.inputs, *index).as_ref() == Some(element),
|
||||||
|
})
|
||||||
|
};
|
||||||
|
|
||||||
|
// The compiler takes a row the wires feed as they are over one they would be converted into
|
||||||
|
let exact: Vec<&graphene_std::NodeIOTypes> = rows.keys().filter(|row| fits(row, true)).collect();
|
||||||
|
let fitting = if exact.is_empty() { rows.keys().filter(|row| fits(row, false)).collect() } else { exact };
|
||||||
|
let needed: Vec<(Type, Type)> = fitting
|
||||||
|
.iter()
|
||||||
|
.filter_map(|row| Some((element_at(&row.inputs, input_index)?, wire_element(&row.return_value))))
|
||||||
|
.collect();
|
||||||
|
let Some((first, _)) = needed.first() else { return held };
|
||||||
|
|
||||||
|
// A number reads in pixels or degrees where it gives what a length or angle would, so rows taking either call for the length or angle
|
||||||
|
let plain = concrete!(f64);
|
||||||
|
match needed.iter().find(|(element, _)| measurements.contains(element)) {
|
||||||
|
Some((measurement, output)) if needed.iter().all(|(element, result)| element == measurement || (*element == plain && result == output)) => Some(measurement.clone()),
|
||||||
|
None if needed.iter().all(|(element, _)| element == first) => None,
|
||||||
|
_ => held,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// The canonical order and grouping of the graph's types, which a type choice renders as dropdown sections divided by separators.
|
/// The canonical order and grouping of the graph's types, which a type choice renders as dropdown sections divided by separators.
|
||||||
/// Enums stay unlisted on purpose, joining any other unnamed type in a trailing alphabetical section.
|
/// Enums stay unlisted on purpose, joining any other unnamed type in a trailing alphabetical section.
|
||||||
fn type_choice_sections(offered: &[Type]) -> Vec<Vec<Type>> {
|
fn type_choice_sections(offered: &[Type]) -> Vec<Vec<Type>> {
|
||||||
let vocabulary = [
|
let vocabulary = [
|
||||||
vec![concrete!(bool), concrete!(i64), concrete!(f64)],
|
vec![concrete!(bool), concrete!(i64), concrete!(f64)],
|
||||||
|
vec![concrete!(Length), concrete!(Angle)],
|
||||||
vec![concrete!(DVec2)],
|
vec![concrete!(DVec2)],
|
||||||
vec![concrete!(DAffine2)],
|
vec![concrete!(DAffine2)],
|
||||||
vec![concrete!(Artboard)],
|
vec![concrete!(Artboard)],
|
||||||
@@ -2834,14 +3176,14 @@ pub(crate) fn grid_inspector(node_id: NodeId, context: &mut NodeInspectorContext
|
|||||||
|
|
||||||
if let Some(grid_type) = grid_type {
|
if let Some(grid_type) = grid_type {
|
||||||
if grid_type.is_isometric() {
|
if grid_type.is_isometric() {
|
||||||
let spacing = LayoutGroup::row(number_widget(
|
let spacing = LayoutGroup::row(length_widget(
|
||||||
ParameterWidgetsInfo::new(node_id, SpacingInput, true, context),
|
ParameterWidgetsInfo::new(node_id, SpacingInput, true, context),
|
||||||
NumberInput::default().label("H").min(0.).unit(" px"),
|
NumberInput::default().label("H").min(0.),
|
||||||
));
|
));
|
||||||
let angles = vec2_widget(ParameterWidgetsInfo::new(node_id, AnglesInput, true, context), "", "", "°", None, None, false, false);
|
let angles = angle_vec2_widget(ParameterWidgetsInfo::new(node_id, AnglesInput, true, context), "", "", NumberInput::default());
|
||||||
widgets.extend([spacing, angles]);
|
widgets.extend([spacing, angles]);
|
||||||
} else {
|
} else {
|
||||||
let spacing = vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", " px", Some(0.), None, false, false);
|
let spacing = length_vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", NumberInput::default().min(0.));
|
||||||
widgets.push(spacing);
|
widgets.push(spacing);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2856,7 +3198,7 @@ pub(crate) fn spiral_inspector(node_id: NodeId, context: &mut NodeInspectorConte
|
|||||||
.for_socket(ParameterWidgetsInfo::new(node_id, SpiralTypeInput, true, context))
|
.for_socket(ParameterWidgetsInfo::new(node_id, SpiralTypeInput, true, context))
|
||||||
.inspector_row();
|
.inspector_row();
|
||||||
let turns = number_widget(ParameterWidgetsInfo::new(node_id, TurnsInput, true, context), NumberInput::default().min(0.1));
|
let turns = number_widget(ParameterWidgetsInfo::new(node_id, TurnsInput, true, context), NumberInput::default().min(0.1));
|
||||||
let start_angle = number_widget(ParameterWidgetsInfo::new(node_id, StartAngleInput, true, context), NumberInput::default().unit("°"));
|
let start_angle = angle_widget(ParameterWidgetsInfo::new(node_id, StartAngleInput, true, context), NumberInput::default());
|
||||||
|
|
||||||
let mut widgets = vec![spiral_type, LayoutGroup::row(turns), LayoutGroup::row(start_angle)];
|
let mut widgets = vec![spiral_type, LayoutGroup::row(turns), LayoutGroup::row(start_angle)];
|
||||||
|
|
||||||
@@ -2875,35 +3217,23 @@ pub(crate) fn spiral_inspector(node_id: NodeId, context: &mut NodeInspectorConte
|
|||||||
if let Some(&TaggedValue::SpiralType(spiral_type)) = spiral_type_input.as_non_exposed_value() {
|
if let Some(&TaggedValue::SpiralType(spiral_type)) = spiral_type_input.as_non_exposed_value() {
|
||||||
match spiral_type {
|
match spiral_type {
|
||||||
SpiralType::Archimedean => {
|
SpiralType::Archimedean => {
|
||||||
let inner_radius = LayoutGroup::row(number_widget(
|
let inner_radius = LayoutGroup::row(length_widget(ParameterWidgetsInfo::new(node_id, InnerRadiusInput, true, context), NumberInput::default().min(0.)));
|
||||||
ParameterWidgetsInfo::new(node_id, InnerRadiusInput, true, context),
|
|
||||||
NumberInput::default().min(0.).unit(" px"),
|
|
||||||
));
|
|
||||||
|
|
||||||
let outer_radius = LayoutGroup::row(number_widget(ParameterWidgetsInfo::new(node_id, OuterRadiusInput, true, context), NumberInput::default().unit(" px")));
|
let outer_radius = LayoutGroup::row(length_widget(ParameterWidgetsInfo::new(node_id, OuterRadiusInput, true, context), NumberInput::default()));
|
||||||
|
|
||||||
widgets.extend([inner_radius, outer_radius]);
|
widgets.extend([inner_radius, outer_radius]);
|
||||||
}
|
}
|
||||||
SpiralType::Logarithmic => {
|
SpiralType::Logarithmic => {
|
||||||
let inner_radius = LayoutGroup::row(number_widget(
|
let inner_radius = LayoutGroup::row(length_widget(ParameterWidgetsInfo::new(node_id, InnerRadiusInput, true, context), NumberInput::default().min(0.)));
|
||||||
ParameterWidgetsInfo::new(node_id, InnerRadiusInput, true, context),
|
|
||||||
NumberInput::default().min(0.).unit(" px"),
|
|
||||||
));
|
|
||||||
|
|
||||||
let outer_radius = LayoutGroup::row(number_widget(
|
let outer_radius = LayoutGroup::row(length_widget(ParameterWidgetsInfo::new(node_id, OuterRadiusInput, true, context), NumberInput::default().min(0.1)));
|
||||||
ParameterWidgetsInfo::new(node_id, OuterRadiusInput, true, context),
|
|
||||||
NumberInput::default().min(0.1).unit(" px"),
|
|
||||||
));
|
|
||||||
|
|
||||||
widgets.extend([inner_radius, outer_radius]);
|
widgets.extend([inner_radius, outer_radius]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let angular_resolution = number_widget(
|
let angular_resolution = angle_widget(ParameterWidgetsInfo::new(node_id, AngularResolutionInput, true, context), NumberInput::default().min(1.).max(180.));
|
||||||
ParameterWidgetsInfo::new(node_id, AngularResolutionInput, true, context),
|
|
||||||
NumberInput::default().min(1.).max(180.).unit("°"),
|
|
||||||
);
|
|
||||||
|
|
||||||
widgets.push(LayoutGroup::row(angular_resolution));
|
widgets.push(LayoutGroup::row(angular_resolution));
|
||||||
|
|
||||||
@@ -2934,10 +3264,10 @@ pub(crate) fn sample_polyline_inspector(node_id: NodeId, context: &mut NodeInspe
|
|||||||
let spacing = enum_choice::<PointSpacingType>()
|
let spacing = enum_choice::<PointSpacingType>()
|
||||||
.for_socket(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context))
|
.for_socket(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context))
|
||||||
.inspector_row();
|
.inspector_row();
|
||||||
let separation = number_widget(ParameterWidgetsInfo::new(node_id, SeparationInput, true, context), NumberInput::default().min(0.).unit(" px"));
|
let separation = length_widget(ParameterWidgetsInfo::new(node_id, SeparationInput, true, context), NumberInput::default().min(0.));
|
||||||
let quantity = number_widget(ParameterWidgetsInfo::new(node_id, QuantityInput, true, context), NumberInput::default().min(2.).int());
|
let quantity = number_widget(ParameterWidgetsInfo::new(node_id, QuantityInput, true, context), NumberInput::default().min(2.).int());
|
||||||
let start_offset = number_widget(ParameterWidgetsInfo::new(node_id, StartOffsetInput, true, context), NumberInput::default().min(0.).unit(" px"));
|
let start_offset = length_widget(ParameterWidgetsInfo::new(node_id, StartOffsetInput, true, context), NumberInput::default().min(0.));
|
||||||
let stop_offset = number_widget(ParameterWidgetsInfo::new(node_id, StopOffsetInput, true, context), NumberInput::default().min(0.).unit(" px"));
|
let stop_offset = length_widget(ParameterWidgetsInfo::new(node_id, StopOffsetInput, true, context), NumberInput::default().min(0.));
|
||||||
let adaptive_spacing = bool_widget(ParameterWidgetsInfo::new(node_id, AdaptiveSpacingInput, true, context), CheckboxInput::default().disabled(is_quantity));
|
let adaptive_spacing = bool_widget(ParameterWidgetsInfo::new(node_id, AdaptiveSpacingInput, true, context), CheckboxInput::default().disabled(is_quantity));
|
||||||
|
|
||||||
vec![
|
vec![
|
||||||
@@ -3263,10 +3593,10 @@ pub(crate) fn rectangle_inspector(node_id: NodeId, context: &mut NodeInspectorCo
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Size X
|
// Size X
|
||||||
let size_x = number_widget(ParameterWidgetsInfo::new(node_id, WidthInput, true, context), NumberInput::default());
|
let size_x = length_widget(ParameterWidgetsInfo::new(node_id, WidthInput, true, context), NumberInput::default());
|
||||||
|
|
||||||
// Size Y
|
// Size Y
|
||||||
let size_y = number_widget(ParameterWidgetsInfo::new(node_id, HeightInput, true, context), NumberInput::default());
|
let size_y = length_widget(ParameterWidgetsInfo::new(node_id, HeightInput, true, context), NumberInput::default());
|
||||||
|
|
||||||
// Clamped
|
// Clamped
|
||||||
let clamped = bool_widget(ParameterWidgetsInfo::new(node_id, ClampedInput, true, context), CheckboxInput::default());
|
let clamped = bool_widget(ParameterWidgetsInfo::new(node_id, ClampedInput, true, context), CheckboxInput::default());
|
||||||
@@ -3304,20 +3634,44 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
|
|||||||
}
|
}
|
||||||
|
|
||||||
let row = context.call_widget_override(&node_id, input_index).unwrap_or_else(|| {
|
let row = context.call_widget_override(&node_id, input_index).unwrap_or_else(|| {
|
||||||
let field = context.network_interface.field_metadata(&node_id, input_index, context.selection_network_path);
|
|
||||||
let options = field.as_ref().map(ParameterOptions::from_field).unwrap_or_default();
|
|
||||||
|
|
||||||
let Some(implementation) = context.network_interface.implementation(&node_id, context.selection_network_path) else {
|
let Some(implementation) = context.network_interface.implementation(&node_id, context.selection_network_path) else {
|
||||||
log::error!("Could not get implementation for node {node_id}");
|
log::error!("Could not get implementation for node {node_id}");
|
||||||
return Vec::new();
|
return Vec::new();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let mut options = ParameterOptions::default();
|
||||||
let input_type = match implementation {
|
let input_type = match implementation {
|
||||||
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => 'early_return: {
|
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => 'early_return: {
|
||||||
// Clone to end the `network_interface` borrow held via `implementation`, freeing the mutable borrow `input_type` needs below
|
// Clone to end the `network_interface` borrow held via `implementation`, freeing the mutable borrow `input_type` needs below
|
||||||
let proto_node_identifier = proto_node_identifier.clone();
|
let proto_node_identifier = proto_node_identifier.clone();
|
||||||
|
|
||||||
if let Some(default) = field.and_then(|field| field.default_type) {
|
let mut default_type = None;
|
||||||
|
if let Some(field) = graphene_std::registry::NODE_METADATA
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.get(&proto_node_identifier)
|
||||||
|
.and_then(|metadata| metadata.fields.get(input_index))
|
||||||
|
{
|
||||||
|
options = ParameterOptions {
|
||||||
|
soft_min: field.number_soft_min,
|
||||||
|
soft_max: field.number_soft_max,
|
||||||
|
hard_min: field.number_hard_min,
|
||||||
|
hard_max: field.number_hard_max,
|
||||||
|
slider: field.number_mode_range,
|
||||||
|
multiline: field.multiline,
|
||||||
|
progression: field.progression,
|
||||||
|
unit: field.unit,
|
||||||
|
display_decimal_places: field.number_display_decimal_places,
|
||||||
|
step: field.number_step,
|
||||||
|
};
|
||||||
|
default_type = field.default_type.clone();
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(measurement) = measurement_input_type(node_id, input_index, &proto_node_identifier, context.network_interface, context.selection_network_path) {
|
||||||
|
break 'early_return measurement;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(default) = default_type {
|
||||||
break 'early_return default;
|
break 'early_return default;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3333,21 +3687,12 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
|
|||||||
let Some(input_type) = input_type else { return Vec::new() };
|
let Some(input_type) = input_type else { return Vec::new() };
|
||||||
input_type.clone()
|
input_type.clone()
|
||||||
}
|
}
|
||||||
_ => {
|
_ => context
|
||||||
// A graph import's declared type still picks its widget while its wire's type is unresolved, such as during an error inside the subgraph
|
.network_interface
|
||||||
let declared_type = field.and_then(|field| field.default_type).map(|declared_type| match declared_type {
|
.input_type(&InputConnector::node_at_index(node_id, input_index), context.selection_network_path)
|
||||||
Type::Item(element) => *element,
|
.compiled_nested_type()
|
||||||
declared_type => declared_type,
|
.cloned()
|
||||||
});
|
.unwrap_or(concrete!(())),
|
||||||
|
|
||||||
context
|
|
||||||
.network_interface
|
|
||||||
.input_type(&InputConnector::node_at_index(node_id, input_index), context.selection_network_path)
|
|
||||||
.compiled_nested_type()
|
|
||||||
.cloned()
|
|
||||||
.or(declared_type)
|
|
||||||
.unwrap_or(concrete!(()))
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
inspector_row_from_type(node_id, input_index, &input_type, options, context).unwrap_or_else(|value| value)
|
inspector_row_from_type(node_id, input_index, &input_type, options, context).unwrap_or_else(|value| value)
|
||||||
@@ -3754,7 +4099,7 @@ pub fn stroke_inspector(node_id: NodeId, context: &mut NodeInspectorContext) ->
|
|||||||
ParameterWidgetsInfo::new(node_id, PaintInput, true, context),
|
ParameterWidgetsInfo::new(node_id, PaintInput, true, context),
|
||||||
crate::messages::layout::utility_types::widgets::button_widgets::ColorInput::default(),
|
crate::messages::layout::utility_types::widgets::button_widgets::ColorInput::default(),
|
||||||
);
|
);
|
||||||
let weight = number_widget(ParameterWidgetsInfo::new(node_id, WeightInput, true, context), NumberInput::default().unit(" px").min(0.));
|
let weight = length_widget(ParameterWidgetsInfo::new(node_id, WeightInput, true, context), NumberInput::default().min(0.));
|
||||||
let align = enum_choice::<StrokeAlign>().for_socket(ParameterWidgetsInfo::new(node_id, AlignInput, true, context)).inspector_row();
|
let align = enum_choice::<StrokeAlign>().for_socket(ParameterWidgetsInfo::new(node_id, AlignInput, true, context)).inspector_row();
|
||||||
let cap = enum_choice::<StrokeCap>().for_socket(ParameterWidgetsInfo::new(node_id, CapInput, true, context)).inspector_row();
|
let cap = enum_choice::<StrokeCap>().for_socket(ParameterWidgetsInfo::new(node_id, CapInput, true, context)).inspector_row();
|
||||||
let join = enum_choice::<StrokeJoin>().for_socket(ParameterWidgetsInfo::new(node_id, JoinInput, true, context)).inspector_row();
|
let join = enum_choice::<StrokeJoin>().for_socket(ParameterWidgetsInfo::new(node_id, JoinInput, true, context)).inspector_row();
|
||||||
@@ -3763,10 +4108,10 @@ pub fn stroke_inspector(node_id: NodeId, context: &mut NodeInspectorContext) ->
|
|||||||
ParameterWidgetsInfo::new(node_id, MiterLimitInput, true, context),
|
ParameterWidgetsInfo::new(node_id, MiterLimitInput, true, context),
|
||||||
NumberInput::default().min(0.).disabled(miter_limit_disabled),
|
NumberInput::default().min(0.).disabled(miter_limit_disabled),
|
||||||
);
|
);
|
||||||
let disabled_number_input = NumberInput::default().unit(" px").disabled(has_dash_lengths);
|
let disabled_number_input = NumberInput::default().disabled(has_dash_lengths);
|
||||||
let dash_lengths = dash_pattern_widget(ParameterWidgetsInfo::new(node_id, DashPatternInput, true, context), TextInput::default().centered(true));
|
let dash_lengths = dash_pattern_widget(ParameterWidgetsInfo::new(node_id, DashPatternInput, true, context), TextInput::default().centered(true));
|
||||||
let number_input = disabled_number_input;
|
let number_input = disabled_number_input;
|
||||||
let dash_offset = number_widget(ParameterWidgetsInfo::new(node_id, DashOffsetInput, true, context), number_input);
|
let dash_offset = length_widget(ParameterWidgetsInfo::new(node_id, DashOffsetInput, true, context), number_input);
|
||||||
|
|
||||||
vec![
|
vec![
|
||||||
color,
|
color,
|
||||||
@@ -3783,8 +4128,7 @@ pub fn stroke_inspector(node_id: NodeId, context: &mut NodeInspectorContext) ->
|
|||||||
pub fn offset_path_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
pub fn offset_path_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||||
use graphene_std::vector::offset_path::*;
|
use graphene_std::vector::offset_path::*;
|
||||||
|
|
||||||
let number_input = NumberInput::default().unit(" px");
|
let distance = length_widget(ParameterWidgetsInfo::new(node_id, DistanceInput, true, context), NumberInput::default());
|
||||||
let distance = number_widget(ParameterWidgetsInfo::new(node_id, DistanceInput, true, context), number_input);
|
|
||||||
|
|
||||||
let join = enum_choice::<StrokeJoin>().for_socket(ParameterWidgetsInfo::new(node_id, JoinInput, true, context)).inspector_row();
|
let join = enum_choice::<StrokeJoin>().for_socket(ParameterWidgetsInfo::new(node_id, JoinInput, true, context)).inspector_row();
|
||||||
|
|
||||||
@@ -4070,6 +4414,46 @@ mod tests {
|
|||||||
assert_ne!(wire_element(&TaggedValue::Integer(0).ty()), wire_element(&item!(f64)));
|
assert_ne!(wire_element(&TaggedValue::Integer(0).ty()), wire_element(&item!(f64)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The field the second input of a node shows with a length wired into its first, which feeds a circle's radius so it compiles.
|
||||||
|
async fn second_input_field_beside_a_wired_length(target: graph_craft::ProtoNodeIdentifier) -> Option<Type> {
|
||||||
|
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||||
|
|
||||||
|
let mut editor = crate::test_utils::EditorTestUtils::create();
|
||||||
|
editor.new_document().await;
|
||||||
|
|
||||||
|
// The length comes from an Add of two lengths
|
||||||
|
let add = graphene_std::math_nodes::add::IDENTIFIER;
|
||||||
|
let source = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(add), 0, 0).await;
|
||||||
|
for input_index in 0..2 {
|
||||||
|
let value = Box::new(TaggedValue::Length(graphene_std::units::TypedLength::pixels(1.)));
|
||||||
|
editor.handle_message(NodeGraphMessage::SetInputValue { node_id: source, input_index, value }).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only the nodes feeding the document's output are compiled, which resolves the types of their wires
|
||||||
|
let node = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(target.clone()), 10, 0).await;
|
||||||
|
let circle = editor
|
||||||
|
.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::circle::IDENTIFIER), 20, 0)
|
||||||
|
.await;
|
||||||
|
for (output_connector, input_connector) in [
|
||||||
|
(OutputConnector::node(source, 0), InputConnector::primary_input(node)),
|
||||||
|
(OutputConnector::node(node, 0), InputConnector::node_at_index(circle, 1)),
|
||||||
|
(OutputConnector::node(circle, 0), InputConnector::Export(0)),
|
||||||
|
] {
|
||||||
|
editor.handle_message(NodeGraphMessage::CreateWire { output_connector, input_connector }).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
measurement_input_type(node, 1, &target, &editor.active_document().network_interface, &[])
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_number_beside_a_wired_length_shows_as_a_length_where_it_reads_in_pixels() {
|
||||||
|
assert_eq!(second_input_field_beside_a_wired_length(graphene_std::math_nodes::add::IDENTIFIER).await, Some(concrete!(Length)));
|
||||||
|
assert_eq!(second_input_field_beside_a_wired_length(graphene_std::math_nodes::clamp::IDENTIFIER).await, Some(concrete!(Length)));
|
||||||
|
|
||||||
|
// A divisor of a length is a plain number, which a length would turn into a ratio
|
||||||
|
assert_eq!(second_input_field_beside_a_wired_length(graphene_std::math_nodes::divide::IDENTIFIER).await, None);
|
||||||
|
}
|
||||||
|
|
||||||
fn description(expression: &str) -> Option<String> {
|
fn description(expression: &str) -> Option<String> {
|
||||||
math_expression_error(expression, false).map(|error| math_expression_error_description(&error))
|
math_expression_error(expression, false).map(|error| math_expression_error_description(&error))
|
||||||
}
|
}
|
||||||
@@ -4095,7 +4479,10 @@ mod tests {
|
|||||||
fn math_expression_errors_quote_the_expression_safely() {
|
fn math_expression_errors_quote_the_expression_safely() {
|
||||||
// The expression's own text sits in code it can't close, while the message's own code keeps its formatting
|
// The expression's own text sits in code it can't close, while the message's own code keeps its formatting
|
||||||
assert_eq!(description("`abc").as_deref(), Some("`` `abc `` is not recognized"));
|
assert_eq!(description("`abc").as_deref(), Some("`` `abc `` is not recognized"));
|
||||||
assert_eq!(description("7 % 3").as_deref(), Some("`%` is reserved for percentages, so the remainder is written `mod(a, b)`"));
|
assert_eq!(
|
||||||
|
description("7 % 3").as_deref(),
|
||||||
|
Some("`%` makes the number before it a percentage, so the remainder is written `mod(a, b)`")
|
||||||
|
);
|
||||||
|
|
||||||
// A quoted token like `*` is a code span, so it can't pair with another into italics
|
// A quoted token like `*` is a code span, so it can't pair with another into italics
|
||||||
let error = description("2 * * 3").unwrap();
|
let error = description("2 * * 3").unwrap();
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ impl FrontendGraphDataType {
|
|||||||
"Color" => Self::Color,
|
"Color" => Self::Color,
|
||||||
"Gradient" => Self::Gradient,
|
"Gradient" => Self::Gradient,
|
||||||
"String" => Self::Typography,
|
"String" => Self::Typography,
|
||||||
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
|
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" | "Length" | "Angle" | "LengthVec2" | "AngleVec2" => Self::Number,
|
||||||
// A generator draws pixels like an image, at whatever resolution is needed
|
// A generator draws pixels like an image, at whatever resolution is needed
|
||||||
"Generator" => Self::Raster,
|
"Generator" => Self::Raster,
|
||||||
raster if raster.starts_with("Raster") => Self::Raster,
|
raster if raster.starts_with("Raster") => Self::Raster,
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ use graph_craft::document::{NodeId, NodeNetwork};
|
|||||||
use graphene_std::list::{Item, List};
|
use graphene_std::list::{Item, List};
|
||||||
use graphene_std::math::quad::Quad;
|
use graphene_std::math::quad::Quad;
|
||||||
use graphene_std::renderer::RenderMetadata;
|
use graphene_std::renderer::RenderMetadata;
|
||||||
|
use graphene_std::renderer::scene_builder::SceneBuilder;
|
||||||
use graphene_std::renderer::vello_scene_builder::VelloSceneBuilder;
|
use graphene_std::renderer::vello_scene_builder::VelloSceneBuilder;
|
||||||
use graphene_std::text::{TextAlign, TextContext, TypesettingConfig};
|
use graphene_std::text::{TextAlign, TextContext, TypesettingConfig};
|
||||||
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
|
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
|
||||||
|
|||||||
@@ -296,6 +296,29 @@ fn pinned_order_round_trips_through_the_registry() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The document's resolution is shared document state, so it survives a registry round trip, and the default is stored as its absence.
|
||||||
|
#[test]
|
||||||
|
fn pixels_per_inch_round_trips_through_the_registry() {
|
||||||
|
let round_trip = |pixels_per_inch: f64| {
|
||||||
|
let mut document = open_demo("changing-seasons.graphite");
|
||||||
|
document.network_interface.set_pixels_per_inch(pixels_per_inch);
|
||||||
|
|
||||||
|
let network = document.network_interface.document_network().clone();
|
||||||
|
let view = StorageMetadataView::new(&document.network_interface);
|
||||||
|
let conversion = Registry::convert_from_runtime(&network, &view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
|
||||||
|
let declarations = conversion.declarations;
|
||||||
|
let (rebuilt_network, node_entries, network_entries) = conversion.registry.to_runtime_with_full_metadata(&declarations, &conversion.blob_bytes).expect("to_runtime failed");
|
||||||
|
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries);
|
||||||
|
(
|
||||||
|
rebuilt.pixels_per_inch(),
|
||||||
|
rebuilt.network_metadata(&[]).expect("the rebuilt document network should resolve").persistent_metadata.pixels_per_inch,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
assert_eq!(round_trip(300.), (300., Some(300.)));
|
||||||
|
assert_eq!(round_trip(96.), (96., None));
|
||||||
|
}
|
||||||
|
|
||||||
/// Per-peer view settings (`ui::doc::*`) survive the `session.json` round-trip: serialize them into
|
/// Per-peer view settings (`ui::doc::*`) survive the `session.json` round-trip: serialize them into
|
||||||
/// the view map, then apply it onto a fresh handler and confirm each field matches.
|
/// the view map, then apply it onto a fresh handler and confirm each field matches.
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -190,7 +190,9 @@ impl DocumentMetadata {
|
|||||||
let transform = local_transform.unwrap_or_else(|| {
|
let transform = local_transform.unwrap_or_else(|| {
|
||||||
let transform_node_id = ModifyInputsContext::locate_node_in_layer_chain(&DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER), layer, network_interface);
|
let transform_node_id = ModifyInputsContext::locate_node_in_layer_chain(&DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER), layer, network_interface);
|
||||||
let transform_node = transform_node_id.and_then(|id| network_interface.document_node(&id, &[]));
|
let transform_node = transform_node_id.and_then(|id| network_interface.document_node(&id, &[]));
|
||||||
transform_node.map(|node| transform_utils::get_current_transform(node.inputs.as_slice())).unwrap_or_default()
|
transform_node
|
||||||
|
.map(|node| transform_utils::get_current_transform(node.inputs.as_slice(), network_interface.pixels_per_inch()))
|
||||||
|
.unwrap_or_default()
|
||||||
});
|
});
|
||||||
|
|
||||||
footprint * transform
|
footprint * transform
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ mod view;
|
|||||||
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
|
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
|
||||||
pub use layout_pass::NetworkLayout;
|
pub use layout_pass::NetworkLayout;
|
||||||
pub use reconcile::{ReconcileError, Reconciled};
|
pub use reconcile::{ReconcileError, Reconciled};
|
||||||
|
pub(crate) use resolved_types::wire_feeds_proto_input;
|
||||||
use store::Guarded;
|
use store::Guarded;
|
||||||
pub use store::NodeLocator;
|
pub use store::NodeLocator;
|
||||||
pub use structure::vector_outline_targets;
|
pub use structure::vector_outline_targets;
|
||||||
@@ -57,6 +58,7 @@ use crate::messages::portfolio::document::utility_types::network_interface::reso
|
|||||||
use crate::messages::portfolio::document::utility_types::text_metrics::text_width;
|
use crate::messages::portfolio::document::utility_types::text_metrics::text_width;
|
||||||
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_thick_wire_center_line, build_vector_wire};
|
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_thick_wire_center_line, build_vector_wire};
|
||||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||||
|
use crate::messages::tool::tool_messages::tool_prelude::NumberInputMode;
|
||||||
use deserialization::deserialize_node_persistent_metadata;
|
use deserialization::deserialize_node_persistent_metadata;
|
||||||
use glam::{DAffine2, DVec2, IVec2};
|
use glam::{DAffine2, DVec2, IVec2};
|
||||||
use graph_craft::Type;
|
use graph_craft::Type;
|
||||||
@@ -71,7 +73,7 @@ use graphene_std::vector::click_target::{ClickTarget, ClickTargetType, FreePoint
|
|||||||
use graphene_std::vector::{Vector, VectorModificationType};
|
use graphene_std::vector::{Vector, VectorModificationType};
|
||||||
use kurbo::BezPath;
|
use kurbo::BezPath;
|
||||||
use memo_network::MemoNetwork;
|
use memo_network::MemoNetwork;
|
||||||
use serde_json::Value;
|
use serde_json::{Value, json};
|
||||||
use std::collections::{HashMap, HashSet, VecDeque};
|
use std::collections::{HashMap, HashSet, VecDeque};
|
||||||
use std::hash::Hash;
|
use std::hash::Hash;
|
||||||
use std::ops::Deref;
|
use std::ops::Deref;
|
||||||
|
|||||||
@@ -105,6 +105,7 @@ impl NodeNetworkInterface {
|
|||||||
match change {
|
match change {
|
||||||
NetworkMetadataChange::Reference(reference) => network.set_reference(reference.clone()),
|
NetworkMetadataChange::Reference(reference) => network.set_reference(reference.clone()),
|
||||||
NetworkMetadataChange::PinnedOrder(order) => network.set_pinned_order(order.clone()),
|
NetworkMetadataChange::PinnedOrder(order) => network.set_pinned_order(order.clone()),
|
||||||
|
NetworkMetadataChange::PixelsPerInch(pixels_per_inch) => network.set_pixels_per_inch(*pixels_per_inch),
|
||||||
NetworkMetadataChange::ImportMetadata(import_metadata) => network.set_import_metadata(import_metadata.clone()),
|
NetworkMetadataChange::ImportMetadata(import_metadata) => network.set_import_metadata(import_metadata.clone()),
|
||||||
NetworkMetadataChange::ExportNames(export_names) => network.set_export_names(export_names.clone()),
|
NetworkMetadataChange::ExportNames(export_names) => network.set_export_names(export_names.clone()),
|
||||||
NetworkMetadataChange::ExportDescriptions(export_descriptions) => network.set_export_descriptions(export_descriptions.clone()),
|
NetworkMetadataChange::ExportDescriptions(export_descriptions) => network.set_export_descriptions(export_descriptions.clone()),
|
||||||
|
|||||||
+3
-3
@@ -1,4 +1,4 @@
|
|||||||
use super::template::{NodeTemplate, NodeTemplateImplementation};
|
use super::template::NodeTemplateImplementation;
|
||||||
use super::{InputConnector, OutputConnector, catalog};
|
use super::{InputConnector, OutputConnector, catalog};
|
||||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{network_node_identifiers, resolve_network_node_type};
|
use crate::messages::portfolio::document::node_graph::document_node_definitions::{network_node_identifiers, resolve_network_node_type};
|
||||||
use crate::messages::portfolio::document::storage_tests::test_support::round_trip_through_gdd;
|
use crate::messages::portfolio::document::storage_tests::test_support::round_trip_through_gdd;
|
||||||
@@ -308,7 +308,7 @@ async fn undoing_the_unlock_of_an_open_catalog_node_shows_it_read_only_again() {
|
|||||||
async fn undoing_the_creation_of_an_open_subgraph_leaves_it() {
|
async fn undoing_the_creation_of_an_open_subgraph_leaves_it() {
|
||||||
let mut editor = EditorTestUtils::create();
|
let mut editor = EditorTestUtils::create();
|
||||||
editor.new_document().await;
|
editor.new_document().await;
|
||||||
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
let subgraph = editor.create_node_by_name(DefinitionIdentifier::Network("Custom Node".to_string())).await;
|
||||||
editor.handle_message(DocumentMessage::EnterNestedNetwork { node_id: subgraph }).await;
|
editor.handle_message(DocumentMessage::EnterNestedNetwork { node_id: subgraph }).await;
|
||||||
assert_eq!(editor.active_document().breadcrumb_network_path(), [subgraph]);
|
assert_eq!(editor.active_document().breadcrumb_network_path(), [subgraph]);
|
||||||
|
|
||||||
@@ -349,7 +349,7 @@ async fn a_subgraph_holding_a_catalog_node_pastes_into_a_document_without_it() {
|
|||||||
let custom = NodeId::new();
|
let custom = NodeId::new();
|
||||||
let blend = NodeId::new();
|
let blend = NodeId::new();
|
||||||
let interface = &mut editor.active_document_mut().network_interface;
|
let interface = &mut editor.active_document_mut().network_interface;
|
||||||
interface.insert_node(custom, NodeTemplate::empty_subgraph(), &[]);
|
interface.insert_node(custom, resolve_network_node_type("Custom Node").expect("Custom Node").default_node_template(), &[]);
|
||||||
interface.insert_node(blend, resolve_network_node_type("Blend").expect("Blend").default_node_template(), &[custom]);
|
interface.insert_node(blend, resolve_network_node_type("Blend").expect("Blend").default_node_template(), &[custom]);
|
||||||
let DocumentNodeImplementation::Definition(shipped) = interface.document_node(&blend, &[custom]).expect("the Blend").implementation else {
|
let DocumentNodeImplementation::Definition(shipped) = interface.document_node(&blend, &[custom]).expect("the Blend").implementation else {
|
||||||
panic!("the Blend should name a table entry")
|
panic!("the Blend should name a table entry")
|
||||||
|
|||||||
+7
-19
@@ -33,7 +33,7 @@ fn new_artboard_message(id: NodeId) -> GraphOperationMessage {
|
|||||||
GraphOperationMessage::NewArtboard {
|
GraphOperationMessage::NewArtboard {
|
||||||
id,
|
id,
|
||||||
location: DVec2::ZERO,
|
location: DVec2::ZERO,
|
||||||
dimensions: DVec2::new(400., 300.),
|
dimensions: graphene_std::units::TypedLengthVec2::pixels(DVec2::new(400., 300.)),
|
||||||
background: Color::WHITE,
|
background: Color::WHITE,
|
||||||
clip: false,
|
clip: false,
|
||||||
}
|
}
|
||||||
@@ -2614,7 +2614,7 @@ async fn shaking_a_node_spliced_in_by_a_secondary_input_keeps_the_dot_on_its_wir
|
|||||||
// Numbers to Vec2 hides its primary input, so it takes the flow by its first exposed input instead
|
// Numbers to Vec2 hides its primary input, so it takes the flow by its first exposed input instead
|
||||||
let source = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await;
|
let source = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await;
|
||||||
let shaken = editor
|
let shaken = editor
|
||||||
.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER), 10, 0)
|
.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER), 10, 0)
|
||||||
.await;
|
.await;
|
||||||
let dot = editor.create_node_by_name_at(passthrough_definition(), 20, 0).await;
|
let dot = editor.create_node_by_name_at(passthrough_definition(), 20, 0).await;
|
||||||
let consumer = editor.create_node_by_name_at(fill_definition(), 30, 0).await;
|
let consumer = editor.create_node_by_name_at(fill_definition(), 30, 0).await;
|
||||||
@@ -3119,7 +3119,7 @@ async fn imports_and_exports_keep_just_a_grid_cell_from_a_dot() {
|
|||||||
let mut editor = EditorTestUtils::create();
|
let mut editor = EditorTestUtils::create();
|
||||||
editor.new_document().await;
|
editor.new_document().await;
|
||||||
|
|
||||||
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
|
||||||
let path = [subgraph];
|
let path = [subgraph];
|
||||||
editor.enter_editable_network(subgraph).await;
|
editor.enter_editable_network(subgraph).await;
|
||||||
|
|
||||||
@@ -3506,7 +3506,7 @@ async fn a_press_right_after_dragging_a_wire_out_of_an_output_drags_another_wire
|
|||||||
|
|
||||||
/// Opens a new subgraph with one node inside, which is all that lies between its import and its export.
|
/// Opens a new subgraph with one node inside, which is all that lies between its import and its export.
|
||||||
async fn subgraph_holding_one_node(editor: &mut EditorTestUtils) -> (NodeId, NodeId) {
|
async fn subgraph_holding_one_node(editor: &mut EditorTestUtils) -> (NodeId, NodeId) {
|
||||||
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
|
||||||
editor.enter_editable_network(subgraph).await;
|
editor.enter_editable_network(subgraph).await;
|
||||||
editor.handle_message(NodeGraphMessage::AddImport).await;
|
editor.handle_message(NodeGraphMessage::AddImport).await;
|
||||||
editor.handle_message(NodeGraphMessage::AddPrimaryExport).await;
|
editor.handle_message(NodeGraphMessage::AddPrimaryExport).await;
|
||||||
@@ -4041,30 +4041,18 @@ async fn a_session_preview_of_a_removed_node_is_dropped() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn a_new_subgraph_is_its_own_definition() {
|
|
||||||
let mut editor = EditorTestUtils::create();
|
|
||||||
editor.new_document().await;
|
|
||||||
|
|
||||||
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
|
||||||
let network_interface = &editor.active_document().network_interface;
|
|
||||||
assert!(matches!(network_interface.implementation(&subgraph, &[]), Some(DocumentNodeImplementation::Definition(_))));
|
|
||||||
assert_eq!(network_interface.reference(&subgraph, &[]), None, "it shouldn't name a catalog definition");
|
|
||||||
assert_eq!(network_interface.display_name(&subgraph, &[]), "Subgraph");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn cannot_preview_node_without_outputs() {
|
async fn cannot_preview_node_without_outputs() {
|
||||||
let mut editor = EditorTestUtils::create();
|
let mut editor = EditorTestUtils::create();
|
||||||
editor.new_document().await;
|
editor.new_document().await;
|
||||||
|
|
||||||
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
let custom_node = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
|
||||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||||
|
|
||||||
assert_eq!(network_interface.number_of_outputs(&subgraph, &[]), 0);
|
assert_eq!(network_interface.number_of_outputs(&custom_node, &[]), 0);
|
||||||
|
|
||||||
// Attempting to toggle preview on a node without outputs should not enable previewing
|
// Attempting to toggle preview on a node without outputs should not enable previewing
|
||||||
network_interface.toggle_preview(subgraph, &[]);
|
network_interface.toggle_preview(custom_node, &[]);
|
||||||
assert_eq!(network_interface.previewing(&[]), Previewing::No);
|
assert_eq!(network_interface.previewing(&[]), Previewing::No);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -75,6 +75,7 @@ pub enum NetworkMetadataChange {
|
|||||||
Reference(Option<String>),
|
Reference(Option<String>),
|
||||||
/// The whole order, since the encoding is one array-valued attribute rather than a slot each.
|
/// The whole order, since the encoding is one array-valued attribute rather than a slot each.
|
||||||
PinnedOrder(Vec<NodeId>),
|
PinnedOrder(Vec<NodeId>),
|
||||||
|
PixelsPerInch(Option<f64>),
|
||||||
ImportMetadata(Vec<InputMetadata>),
|
ImportMetadata(Vec<InputMetadata>),
|
||||||
ExportNames(Vec<String>),
|
ExportNames(Vec<String>),
|
||||||
ExportDescriptions(Vec<String>),
|
ExportDescriptions(Vec<String>),
|
||||||
@@ -256,6 +257,12 @@ impl EditorDelta {
|
|||||||
value: (!stored.is_empty()).then(|| serialize_attribute(network_attr::PINNED_ORDER, &stored)).transpose()?,
|
value: (!stored.is_empty()).then(|| serialize_attribute(network_attr::PINNED_ORDER, &stored)).transpose()?,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
NetworkMetadataChange::PixelsPerInch(pixels_per_inch) => AttributeDelta {
|
||||||
|
key: network_attr::PIXELS_PER_INCH.to_string(),
|
||||||
|
value: pixels_per_inch
|
||||||
|
.map(|pixels_per_inch| serialize_attribute(network_attr::PIXELS_PER_INCH, &pixels_per_inch))
|
||||||
|
.transpose()?,
|
||||||
|
},
|
||||||
NetworkMetadataChange::ImportMetadata(import_metadata) => import_metadata_delta(import_metadata)?,
|
NetworkMetadataChange::ImportMetadata(import_metadata) => import_metadata_delta(import_metadata)?,
|
||||||
NetworkMetadataChange::ExportNames(export_names) => export_names_delta(export_names)?,
|
NetworkMetadataChange::ExportNames(export_names) => export_names_delta(export_names)?,
|
||||||
NetworkMetadataChange::ExportDescriptions(export_descriptions) => export_descriptions_delta(export_descriptions)?,
|
NetworkMetadataChange::ExportDescriptions(export_descriptions) => export_descriptions_delta(export_descriptions)?,
|
||||||
|
|||||||
@@ -1254,6 +1254,19 @@ impl NodeNetworkInterface {
|
|||||||
self.transaction_modified();
|
self.transaction_modified();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Sets how many pixels make an inch in the document, stored only where it differs from the default.
|
||||||
|
pub fn set_pixels_per_inch(&mut self, pixels_per_inch: f64) {
|
||||||
|
let stored = (pixels_per_inch != graphene_std::units::DEFAULT_PIXELS_PER_INCH).then_some(pixels_per_inch);
|
||||||
|
|
||||||
|
let Some(mut network) = self.network_mut(&[]) else {
|
||||||
|
log::error!("Could not get the root network in set_pixels_per_inch");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
network.set_pixels_per_inch(stored);
|
||||||
|
|
||||||
|
self.transaction_modified();
|
||||||
|
}
|
||||||
|
|
||||||
pub fn set_visibility(&mut self, node_id: &NodeId, network_path: &[NodeId], is_visible: bool) {
|
pub fn set_visibility(&mut self, node_id: &NodeId, network_path: &[NodeId], is_visible: bool) {
|
||||||
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else {
|
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else {
|
||||||
log::error!("Could not get node {node_id} in set_visibility");
|
log::error!("Could not get node {node_id} in set_visibility");
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
use super::*;
|
use super::*;
|
||||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::ARTBOARD_CLIP_INPUT_INDEX;
|
|
||||||
use std::hash::{Hash, Hasher};
|
use std::hash::{Hash, Hasher};
|
||||||
|
|
||||||
|
/// Index of the Artboard definition's Clip input, which must match the input order authored in document_node_definitions.rs.
|
||||||
|
pub(crate) const ARTBOARD_CLIP_INPUT_INDEX: usize = 5;
|
||||||
|
|
||||||
impl NodeNetworkInterface {
|
impl NodeNetworkInterface {
|
||||||
/// Runs a query against a resolved [`NetworkView`], logging any error at this message-boundary wrapper and mapping it to None.
|
/// Runs a query against a resolved [`NetworkView`], logging any error at this message-boundary wrapper and mapping it to None.
|
||||||
pub(crate) fn query<'a, 'p, T>(&'a self, network_path: &'p [NodeId], caller: &str, query: impl FnOnce(NetworkView<'a, 'p>) -> Result<T, NetworkError>) -> Option<T> {
|
pub(crate) fn query<'a, 'p, T>(&'a self, network_path: &'p [NodeId], caller: &str, query: impl FnOnce(NetworkView<'a, 'p>) -> Result<T, NetworkError>) -> Option<T> {
|
||||||
@@ -126,10 +128,18 @@ impl NodeNetworkInterface {
|
|||||||
});
|
});
|
||||||
|
|
||||||
let mut hasher = std::hash::DefaultHasher::new();
|
let mut hasher = std::hash::DefaultHasher::new();
|
||||||
(self.network.current_hash(), self.previewed_nodes(), layers_hash).hash(&mut hasher);
|
(self.network.current_hash(), self.previewed_nodes(), layers_hash, self.pixels_per_inch().to_bits()).hash(&mut hasher);
|
||||||
hasher.finish()
|
hasher.finish()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// How many pixels make an inch in the document, which sizes the lengths typed in a physical unit.
|
||||||
|
pub fn pixels_per_inch(&self) -> f64 {
|
||||||
|
self.network_metadata(&[])
|
||||||
|
.and_then(|metadata| metadata.persistent_metadata.pixels_per_inch)
|
||||||
|
.filter(|pixels_per_inch| pixels_per_inch.is_finite() && *pixels_per_inch > 0.)
|
||||||
|
.unwrap_or(graphene_std::units::DEFAULT_PIXELS_PER_INCH)
|
||||||
|
}
|
||||||
|
|
||||||
/// Get the specified document node in the nested network based on node_id and network_path
|
/// Get the specified document node in the nested network based on node_id and network_path
|
||||||
pub fn document_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<&DocumentNode> {
|
pub fn document_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<&DocumentNode> {
|
||||||
self.query(network_path, "document_node", |view| view.node(node_id))
|
self.query(network_path, "document_node", |view| view.node(node_id))
|
||||||
@@ -800,7 +810,7 @@ impl NodeNetworkInterface {
|
|||||||
self.query(network_path, "reference", |view| view.reference(node_id)).flatten()
|
self.query(network_path, "reference", |view| view.reference(node_id)).flatten()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The icon of the node's definition, or the generic subgraph icon when its definition has none or can't be found.
|
/// The icon of the node's definition, or the Custom Node icon when its definition has none or can't be found.
|
||||||
pub fn node_icon(&self, node_id: &NodeId, network_path: &[NodeId]) -> &'static str {
|
pub fn node_icon(&self, node_id: &NodeId, network_path: &[NodeId]) -> &'static str {
|
||||||
self.reference(node_id, network_path)
|
self.reference(node_id, network_path)
|
||||||
.and_then(|reference| resolve_document_node_type(&reference)?.icon)
|
.and_then(|reference| resolve_document_node_type(&reference)?.icon)
|
||||||
@@ -827,26 +837,17 @@ impl NodeNetworkInterface {
|
|||||||
self.view(network_path).ok().and_then(|view| view.persistent_input_metadata(node_id, index).ok())
|
self.view(network_path).ok().and_then(|view| view.persistent_input_metadata(node_id, index).ok())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether the input is internal state of its node (named with a leading `_`), which is never exposed to the graph.
|
/// Whether the input is internal state of its proto node (named with a leading `_`), which is never exposed to the graph.
|
||||||
pub fn is_internal_input(&self, node_id: &NodeId, index: usize, network_path: &[NodeId]) -> bool {
|
pub fn is_internal_input(&self, node_id: &NodeId, index: usize, network_path: &[NodeId]) -> bool {
|
||||||
self.field_metadata(node_id, index, network_path).is_some_and(|field| field.internal)
|
let Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) = self.implementation(node_id, network_path) else {
|
||||||
}
|
return false;
|
||||||
|
|
||||||
/// The metadata the node macro records for a proto node's parameter, or graph text describes for a graph node's import.
|
|
||||||
/// A graph node's input has it only while it still has that import's name, since an edited subgraph can reorder its imports.
|
|
||||||
pub fn field_metadata(&self, node_id: &NodeId, index: usize, network_path: &[NodeId]) -> Option<graphene_std::registry::FieldMetadata> {
|
|
||||||
if let Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) = self.implementation(node_id, network_path) {
|
|
||||||
let node_metadata = graphene_std::registry::NODE_METADATA.lock().ok()?;
|
|
||||||
return node_metadata.get(proto_node_identifier)?.fields.get(index).cloned();
|
|
||||||
}
|
|
||||||
|
|
||||||
let Some(DefinitionIdentifier::Network(identifier)) = self.reference(node_id, network_path) else {
|
|
||||||
return None;
|
|
||||||
};
|
};
|
||||||
let input_name = self.persistent_input_metadata(node_id, index, network_path)?.input_name.clone();
|
let Ok(node_metadata) = graphene_std::registry::NODE_METADATA.lock() else { return false };
|
||||||
|
|
||||||
let field = graphene_std::graph_text::GRAPHS.iter().find(|graph| graph.identifier == identifier)?.imports.get(index)?;
|
node_metadata
|
||||||
(field.name == input_name).then(|| field.clone())
|
.get(proto_node_identifier)
|
||||||
|
.and_then(|metadata| metadata.fields.get(index))
|
||||||
|
.is_some_and(|field| field.internal)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The description stored for a node's output, or else for a proto node, the doc comment on its field in the struct a multi-output node returns.
|
/// The description stored for a node's output, or else for a proto node, the doc comment on its field in the struct a multi-output node returns.
|
||||||
@@ -882,16 +883,16 @@ impl NodeNetworkInterface {
|
|||||||
node.set_widget_override(index, widget_override);
|
node.set_widget_override(index, widget_override);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed.
|
/// Returns the display name of the node. If the display name is empty, it will return "Untitled Node" or "Untitled Layer" depending on the node type.
|
||||||
pub fn display_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
|
pub fn display_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
|
||||||
self.query(network_path, "display_name", |view| Ok(view.display_name(node_id)))
|
self.query(network_path, "display_name", |view| Ok(view.display_name(node_id)))
|
||||||
.unwrap_or_else(|| "Subgraph".to_string())
|
.unwrap_or_else(|| "Custom Node".to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The uneditable name in the Inspector which represents the function name of the node implementation.
|
/// The uneditable name in the Inspector which represents the function name of the node implementation.
|
||||||
pub fn implementation_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
|
pub fn implementation_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
|
||||||
self.query(network_path, "implementation_name", |view| Ok(view.implementation_name(node_id)))
|
self.query(network_path, "implementation_name", |view| Ok(view.implementation_name(node_id)))
|
||||||
.unwrap_or_else(|| "Subgraph".to_string())
|
.unwrap_or_else(|| "Custom Node".to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn is_locked(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
|
pub fn is_locked(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
|
||||||
|
|||||||
@@ -143,6 +143,9 @@ impl NodeNetworkInterface {
|
|||||||
if current_metadata.pinned_node_order != target.metadata.pinned_order {
|
if current_metadata.pinned_node_order != target.metadata.pinned_order {
|
||||||
deltas.push(change(NetworkMetadataChange::PinnedOrder(target.metadata.pinned_order.clone())));
|
deltas.push(change(NetworkMetadataChange::PinnedOrder(target.metadata.pinned_order.clone())));
|
||||||
}
|
}
|
||||||
|
if current_metadata.pixels_per_inch != target.metadata.pixels_per_inch {
|
||||||
|
deltas.push(change(NetworkMetadataChange::PixelsPerInch(target.metadata.pixels_per_inch)));
|
||||||
|
}
|
||||||
// An empty list states nothing, since a catalog entry's interface comes from the catalog rather than storage
|
// An empty list states nothing, since a catalog entry's interface comes from the catalog rather than storage
|
||||||
let import_metadata: Vec<_> = target.metadata.import_metadata.iter().cloned().map(input_metadata_entry_to_runtime).collect();
|
let import_metadata: Vec<_> = target.metadata.import_metadata.iter().cloned().map(input_metadata_entry_to_runtime).collect();
|
||||||
if !import_metadata.is_empty() && current_metadata.import_metadata != import_metadata {
|
if !import_metadata.is_empty() && current_metadata.import_metadata != import_metadata {
|
||||||
|
|||||||
+6
@@ -95,6 +95,12 @@ fn type_feeds_input(source: &Type, connector: &Type, conversions: Option<&Adapte
|
|||||||
.any(|adapted| adapted == connector || Promotion::exists_between(adapted, connector))
|
.any(|adapted| adapted == connector || Promotion::exists_between(adapted, connector))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether a wire of the `source` type can feed the proto node's input at `input_index`, registered as `connector`, through the conversions
|
||||||
|
/// the compiler places ahead of that input.
|
||||||
|
pub(crate) fn wire_feeds_proto_input(proto_node_identifier: &ProtoNodeIdentifier, input_index: usize, source: &Type, connector: &Type) -> bool {
|
||||||
|
type_feeds_input(source, connector, input_conversions(proto_node_identifier).get(input_index).copied().flatten())
|
||||||
|
}
|
||||||
|
|
||||||
// This file contains utility methods for interfacing with the resolved types returned from the compiler
|
// This file contains utility methods for interfacing with the resolved types returned from the compiler
|
||||||
#[derive(Debug, Default)]
|
#[derive(Debug, Default)]
|
||||||
pub struct ResolvedDocumentNodeTypes {
|
pub struct ResolvedDocumentNodeTypes {
|
||||||
|
|||||||
+5
@@ -111,6 +111,10 @@ impl NodeMetadataSource for StorageMetadataView<'_> {
|
|||||||
fn pinned_order(&self, network: NetworkLocation) -> Vec<NodeId> {
|
fn pinned_order(&self, network: NetworkLocation) -> Vec<NodeId> {
|
||||||
self.network_persistent(network).map(|persistent| persistent.pinned_node_order.clone()).unwrap_or_default()
|
self.network_persistent(network).map(|persistent| persistent.pinned_node_order.clone()).unwrap_or_default()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn pixels_per_inch(&self, network: NetworkLocation) -> Option<f64> {
|
||||||
|
self.network_persistent(network)?.pixels_per_inch
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DocumentSettings<'_> {
|
impl DocumentSettings<'_> {
|
||||||
@@ -307,6 +311,7 @@ fn apply_network_entries_into_tree(metadata: &mut NodeNetworkMetadata, entries:
|
|||||||
network_metadata.persistent_metadata.reference = Some(reference);
|
network_metadata.persistent_metadata.reference = Some(reference);
|
||||||
}
|
}
|
||||||
network_metadata.persistent_metadata.pinned_node_order = entry.pinned_order;
|
network_metadata.persistent_metadata.pinned_node_order = entry.pinned_order;
|
||||||
|
network_metadata.persistent_metadata.pixels_per_inch = entry.pixels_per_inch;
|
||||||
network_metadata.persistent_metadata.import_metadata = entry.import_metadata.into_iter().map(input_metadata_entry_to_runtime).collect();
|
network_metadata.persistent_metadata.import_metadata = entry.import_metadata.into_iter().map(input_metadata_entry_to_runtime).collect();
|
||||||
network_metadata.persistent_metadata.export_names = entry.export_names;
|
network_metadata.persistent_metadata.export_names = entry.export_names;
|
||||||
network_metadata.persistent_metadata.export_descriptions = entry.export_descriptions;
|
network_metadata.persistent_metadata.export_descriptions = entry.export_descriptions;
|
||||||
|
|||||||
+10
@@ -538,6 +538,16 @@ impl NetworkMut<'_> {
|
|||||||
changed
|
changed
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// How many pixels make an inch in the document, or `None` for the default.
|
||||||
|
pub(crate) fn set_pixels_per_inch(&mut self, pixels_per_inch: Option<f64>) -> bool {
|
||||||
|
let changed = self.metadata.pixels_per_inch != pixels_per_inch;
|
||||||
|
self.metadata.pixels_per_inch = pixels_per_inch;
|
||||||
|
if changed {
|
||||||
|
self.emit(NetworkMetadataChange::PixelsPerInch(pixels_per_inch));
|
||||||
|
}
|
||||||
|
changed
|
||||||
|
}
|
||||||
|
|
||||||
/// The display order of pinned nodes in the Inspector.
|
/// The display order of pinned nodes in the Inspector.
|
||||||
pub(crate) fn set_pinned_order(&mut self, pinned_node_order: Vec<NodeId>) -> bool {
|
pub(crate) fn set_pinned_order(&mut self, pinned_node_order: Vec<NodeId>) -> bool {
|
||||||
let changed = self.metadata.pinned_node_order != pinned_node_order;
|
let changed = self.metadata.pinned_node_order != pinned_node_order;
|
||||||
|
|||||||
@@ -511,6 +511,7 @@ impl NodeNetworkInterface {
|
|||||||
.into_iter()
|
.into_iter()
|
||||||
.chain([
|
.chain([
|
||||||
NetworkMetadataChange::PinnedOrder(persistent_metadata.pinned_node_order.clone()),
|
NetworkMetadataChange::PinnedOrder(persistent_metadata.pinned_node_order.clone()),
|
||||||
|
NetworkMetadataChange::PixelsPerInch(persistent_metadata.pixels_per_inch),
|
||||||
NetworkMetadataChange::ImportMetadata(persistent_metadata.import_metadata.clone()),
|
NetworkMetadataChange::ImportMetadata(persistent_metadata.import_metadata.clone()),
|
||||||
NetworkMetadataChange::ExportNames(persistent_metadata.export_names.clone()),
|
NetworkMetadataChange::ExportNames(persistent_metadata.export_names.clone()),
|
||||||
NetworkMetadataChange::ExportDescriptions(persistent_metadata.export_descriptions.clone()),
|
NetworkMetadataChange::ExportDescriptions(persistent_metadata.export_descriptions.clone()),
|
||||||
|
|||||||
@@ -38,14 +38,6 @@ pub struct NodeTemplate {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl NodeTemplate {
|
impl NodeTemplate {
|
||||||
/// A new subgraph with nothing in it, which names no definition since it becomes its own entry in the document's definitions table.
|
|
||||||
pub fn empty_subgraph() -> Self {
|
|
||||||
Self {
|
|
||||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate::default()),
|
|
||||||
..Default::default()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The input slot named by the given parameter symbol, mirroring [`DocumentNode::input`].
|
/// The input slot named by the given parameter symbol, mirroring [`DocumentNode::input`].
|
||||||
pub fn input<P: graphene_std::NodeParameter>(&self, _parameter: P) -> Option<&NodeInput> {
|
pub fn input<P: graphene_std::NodeParameter>(&self, _parameter: P) -> Option<&NodeInput> {
|
||||||
self.inputs.get(P::INDEX)
|
self.inputs.get(P::INDEX)
|
||||||
@@ -299,6 +291,7 @@ impl NodeTemplateImplementation {
|
|||||||
reference,
|
reference,
|
||||||
node_metadata,
|
node_metadata,
|
||||||
pinned_node_order,
|
pinned_node_order,
|
||||||
|
pixels_per_inch: None,
|
||||||
previewing,
|
previewing,
|
||||||
navigation_metadata,
|
navigation_metadata,
|
||||||
selection_undo_history: Default::default(),
|
selection_undo_history: Default::default(),
|
||||||
|
|||||||
Loaded 100 of 210 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user