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
-10
@@ -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",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -3039,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",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -3074,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"
|
||||||
@@ -3427,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"
|
||||||
@@ -3799,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"
|
||||||
@@ -5032,7 +5112,7 @@ dependencies = [
|
|||||||
"parlance",
|
"parlance",
|
||||||
"parley_data",
|
"parley_data",
|
||||||
"parley_emoji",
|
"parley_emoji",
|
||||||
"skrifa",
|
"skrifa 0.44.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -5063,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"
|
||||||
@@ -5865,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"
|
||||||
@@ -5872,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",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -6018,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",
|
||||||
@@ -6602,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"
|
||||||
@@ -6963,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"
|
||||||
@@ -6970,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]]
|
||||||
@@ -7149,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"
|
||||||
@@ -7331,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",
|
||||||
@@ -7931,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",
|
||||||
@@ -9281,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"
|
||||||
@@ -9421,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"
|
||||||
|
|||||||
@@ -223,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
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ use graph_craft::document::value::*;
|
|||||||
use graph_craft::document::*;
|
use graph_craft::document::*;
|
||||||
use graph_craft::{concrete, list};
|
use graph_craft::{concrete, list};
|
||||||
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType};
|
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType};
|
||||||
|
use graphene_std::units::TypedLengthVec2;
|
||||||
use graphene_std::vector::Vector;
|
use graphene_std::vector::Vector;
|
||||||
use graphene_std::*;
|
use graphene_std::*;
|
||||||
use std::collections::{HashMap, VecDeque};
|
use std::collections::{HashMap, VecDeque};
|
||||||
@@ -242,8 +243,8 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
|||||||
inputs: vec![
|
inputs: vec![
|
||||||
NodeInput::type_default(list!(Artboard), true),
|
NodeInput::type_default(list!(Artboard), true),
|
||||||
NodeInput::type_default(list!(Graphic), true),
|
NodeInput::type_default(list!(Graphic), true),
|
||||||
NodeInput::value(TaggedValue::DVec2(DVec2::ZERO), false),
|
NodeInput::value(TaggedValue::LengthVec2(TypedLengthVec2::pixels(DVec2::ZERO)), false),
|
||||||
NodeInput::value(TaggedValue::DVec2(DVec2::new(1920., 1080.)), false),
|
NodeInput::value(TaggedValue::LengthVec2(TypedLengthVec2::pixels(DVec2::new(1920., 1080.))), false),
|
||||||
NodeInput::value(TaggedValue::Color(Color::WHITE), false),
|
NodeInput::value(TaggedValue::Color(Color::WHITE), false),
|
||||||
NodeInput::value(TaggedValue::Bool(true), false),
|
NodeInput::value(TaggedValue::Bool(true), false),
|
||||||
],
|
],
|
||||||
@@ -709,6 +710,41 @@ type InputInspector = HashMap<String, Box<dyn Fn(NodeId, usize, &mut NodeInspect
|
|||||||
// TODO: Replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) or similar
|
// TODO: Replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) or similar
|
||||||
static INPUT_OVERRIDES: once_cell::sync::Lazy<InputInspector> = once_cell::sync::Lazy::new(static_input_inspector);
|
static INPUT_OVERRIDES: once_cell::sync::Lazy<InputInspector> = once_cell::sync::Lazy::new(static_input_inspector);
|
||||||
|
|
||||||
|
/// A number field set up from the proto node parameter's metadata, which only proto nodes have.
|
||||||
|
fn proto_parameter_number_input(node_id: NodeId, index: usize, context: &mut NodeInspectorContext) -> NumberInput {
|
||||||
|
let mut number_input = NumberInput::default();
|
||||||
|
// The field is cloned so the lock is released before the caller builds the row, which locks the node metadata again
|
||||||
|
if let Some(field) = context
|
||||||
|
.network_interface
|
||||||
|
.implementation(&node_id, context.selection_network_path)
|
||||||
|
.and_then(|implementation| if let DocumentNodeImplementation::ProtoNode(id) = implementation { Some(id) } else { None })
|
||||||
|
.and_then(|proto_node_identifier| registry::NODE_METADATA.lock().unwrap().get(proto_node_identifier)?.fields.get(index).cloned())
|
||||||
|
{
|
||||||
|
if let Some(unit) = field.unit {
|
||||||
|
number_input = number_input.unit(unit);
|
||||||
|
}
|
||||||
|
// Typing is clamped only by the hard bounds; the slider extent prefers the soft bounds (see `inspector_row_from_type`)
|
||||||
|
if let Some(hard_min) = field.number_hard_min {
|
||||||
|
number_input = number_input.min(hard_min);
|
||||||
|
}
|
||||||
|
if let Some(hard_max) = field.number_hard_max {
|
||||||
|
number_input = number_input.max(hard_max);
|
||||||
|
}
|
||||||
|
if field.number_mode_range {
|
||||||
|
number_input = number_input
|
||||||
|
.mode_range()
|
||||||
|
.range_min(field.number_soft_min.or(field.number_hard_min))
|
||||||
|
.range_max(field.number_soft_max.or(field.number_hard_max));
|
||||||
|
}
|
||||||
|
number_input = number_input.is_integer(false);
|
||||||
|
if let Some(number_step) = field.number_step {
|
||||||
|
number_input = number_input.step(number_step);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
number_input
|
||||||
|
}
|
||||||
|
|
||||||
/// Defines the logic for inputs to display a custom Inspector widget.
|
/// Defines the logic for inputs to display a custom Inspector widget.
|
||||||
fn static_input_inspector() -> InputInspector {
|
fn static_input_inspector() -> InputInspector {
|
||||||
let mut map: InputInspector = HashMap::new();
|
let mut map: InputInspector = HashMap::new();
|
||||||
@@ -812,50 +848,21 @@ fn static_input_inspector() -> InputInspector {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
map.insert(
|
map.insert(
|
||||||
// The custom number input settings are only available on proto nodes
|
// A length row gated by the bool input before it. Its field keeps any length unit typed into it and gives its bounds in pixels.
|
||||||
"optional_f64".to_string(),
|
"optional_length".to_string(),
|
||||||
Box::new(|node_id, index, context| {
|
Box::new(|node_id, index, context| {
|
||||||
let mut number_input = NumberInput::default();
|
let number_input = proto_parameter_number_input(node_id, index, context);
|
||||||
// The field is cloned so the lock is released before building the row below, which locks the node metadata again
|
// NOTE: The bool input MUST be at the input index directly before the length input!
|
||||||
if let Some(field) = context
|
Ok(vec![LayoutGroup::row(node_inspector::optional_length_widget(
|
||||||
.network_interface
|
|
||||||
.implementation(&node_id, context.selection_network_path)
|
|
||||||
.and_then(|implementation| if let DocumentNodeImplementation::ProtoNode(id) = implementation { Some(id) } else { None })
|
|
||||||
.and_then(|proto_node_identifier| registry::NODE_METADATA.lock().unwrap().get(proto_node_identifier)?.fields.get(index).cloned())
|
|
||||||
{
|
|
||||||
if let Some(unit) = field.unit {
|
|
||||||
number_input = number_input.unit(unit);
|
|
||||||
}
|
|
||||||
// Typing is clamped only by the hard bounds; the slider extent prefers the soft bounds (see `inspector_row_from_type`)
|
|
||||||
if let Some(hard_min) = field.number_hard_min {
|
|
||||||
number_input = number_input.min(hard_min);
|
|
||||||
}
|
|
||||||
if let Some(hard_max) = field.number_hard_max {
|
|
||||||
number_input = number_input.max(hard_max);
|
|
||||||
}
|
|
||||||
if field.number_mode_range {
|
|
||||||
number_input = number_input
|
|
||||||
.mode_range()
|
|
||||||
.range_min(field.number_soft_min.or(field.number_hard_min))
|
|
||||||
.range_max(field.number_soft_max.or(field.number_hard_max));
|
|
||||||
}
|
|
||||||
number_input = number_input.is_integer(false);
|
|
||||||
if let Some(number_step) = field.number_step {
|
|
||||||
number_input = number_input.step(number_step);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
// NOTE: The bool input MUST be at the input index directly before the f64 input!
|
|
||||||
Ok(vec![LayoutGroup::row(node_inspector::optional_f64_widget(
|
|
||||||
ParameterWidgetsInfo::at_index(node_id, index, false, context),
|
ParameterWidgetsInfo::at_index(node_id, index, false, context),
|
||||||
index - 1,
|
index - 1,
|
||||||
number_input,
|
number_input,
|
||||||
None,
|
|
||||||
))])
|
))])
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
map.insert(
|
map.insert(
|
||||||
// Like `optional_f64`, but with a 0-100% range slider beside the number input, double-click restoring the full 100%.
|
// A number row gated by the bool input before it, with a 0-100% range slider beside the number input, double-click restoring the full 100%.
|
||||||
// As with `optional_f64`, the bool input must be at the input index directly before the f64 input.
|
// The bool input must be at the input index directly before the f64 input.
|
||||||
"optional_percentage".to_string(),
|
"optional_percentage".to_string(),
|
||||||
Box::new(|node_id, index, context| {
|
Box::new(|node_id, index, context| {
|
||||||
let number_input = NumberInput::default().mode_increment().unit("%").min(0.).max(100.);
|
let number_input = NumberInput::default().mode_increment().unit("%").min(0.).max(100.);
|
||||||
@@ -957,15 +964,15 @@ fn static_input_inspector() -> InputInspector {
|
|||||||
.and_then(|value| value.as_bool())
|
.and_then(|value| value.as_bool())
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
|
|
||||||
Ok(vec![node_inspector::vec2_widget(
|
let info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||||
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
|
||||||
&x,
|
// A pair measured in pixels is a pair of lengths, which keeps any length unit typed into it
|
||||||
&y,
|
if unit.trim() == "px" {
|
||||||
&unit,
|
let number_props = NumberInput::default().min(min.unwrap_or(f64::NEG_INFINITY)).is_integer(is_integer);
|
||||||
min,
|
return Ok(vec![node_inspector::length_vec2_widget(info, &x, &y, number_props)]);
|
||||||
is_integer,
|
}
|
||||||
false,
|
|
||||||
)])
|
Ok(vec![node_inspector::vec2_widget(info, &x, &y, &unit, min, is_integer, false)])
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
map.insert(
|
map.insert(
|
||||||
@@ -1225,46 +1232,16 @@ fn static_input_inspector() -> InputInspector {
|
|||||||
map.insert(
|
map.insert(
|
||||||
"transform_rotation".to_string(),
|
"transform_rotation".to_string(),
|
||||||
Box::new(|node_id, index, context| {
|
Box::new(|node_id, index, context| {
|
||||||
let mut widgets = node_inspector::start_widgets(&ParameterWidgetsInfo::at_index(node_id, index, true, context));
|
let info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||||
|
let number_props = NumberInput::default().mode(NumberInputMode::Range).range_min(Some(-180.)).range_max(Some(180.));
|
||||||
let document_node = node_inspector::get_document_node(node_id, context)?;
|
Ok(vec![LayoutGroup::row(node_inspector::angle_widget(info, number_props))])
|
||||||
let Some(input) = document_node.inputs.get(index) else {
|
|
||||||
return Err("Input not found in transform rotation input override".to_string());
|
|
||||||
};
|
|
||||||
if let Some(&TaggedValue::Number(val)) = input.as_non_exposed_value() {
|
|
||||||
widgets.extend_from_slice(&[
|
|
||||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
|
||||||
NumberInput::new(Some(val))
|
|
||||||
.unit("°")
|
|
||||||
.mode(NumberInputMode::Range)
|
|
||||||
.range_min(Some(-180.))
|
|
||||||
.range_max(Some(180.))
|
|
||||||
.on_update(node_inspector::update_value_at_index(
|
|
||||||
|number_input: &NumberInput| TaggedValue::Number(number_input.value.unwrap()),
|
|
||||||
node_id,
|
|
||||||
index,
|
|
||||||
))
|
|
||||||
.on_commit(node_inspector::commit_value)
|
|
||||||
.widget_instance(),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(vec![LayoutGroup::row(widgets)])
|
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
// Translation uses a Vec2 widget with X/Y labels and a "px" unit suffix
|
|
||||||
map.insert(
|
map.insert(
|
||||||
"transform_translation".to_string(),
|
"transform_translation".to_string(),
|
||||||
Box::new(|node_id, index, context| {
|
Box::new(|node_id, index, context| {
|
||||||
Ok(vec![node_inspector::vec2_widget(
|
let info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||||
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
Ok(vec![node_inspector::length_vec2_widget(info, "X", "Y", NumberInput::default())])
|
||||||
"X",
|
|
||||||
"Y",
|
|
||||||
" px",
|
|
||||||
None,
|
|
||||||
false,
|
|
||||||
false,
|
|
||||||
)])
|
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
// Scale uses a Vec2 widget with W/H labels and an "x" unit suffix
|
// Scale uses a Vec2 widget with W/H labels and an "x" unit suffix
|
||||||
@@ -1282,48 +1259,11 @@ fn static_input_inspector() -> InputInspector {
|
|||||||
)])
|
)])
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
// Skew has a custom override that maps to degrees
|
|
||||||
map.insert(
|
map.insert(
|
||||||
"transform_skew".to_string(),
|
"transform_skew".to_string(),
|
||||||
Box::new(|node_id, index, context| {
|
Box::new(|node_id, index, context| {
|
||||||
let mut widgets = node_inspector::start_widgets(&ParameterWidgetsInfo::at_index(node_id, index, true, context));
|
let info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||||
|
Ok(vec![node_inspector::angle_vec2_widget(info, "X", "Y", NumberInput::default().min(-89.9).max(89.9))])
|
||||||
let document_node = node_inspector::get_document_node(node_id, context)?;
|
|
||||||
let Some(input) = document_node.inputs.get(index) else {
|
|
||||||
return Err("Input not found in transform skew input override".to_string());
|
|
||||||
};
|
|
||||||
if let Some(&TaggedValue::DVec2(val)) = input.as_non_exposed_value() {
|
|
||||||
widgets.extend_from_slice(&[
|
|
||||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
|
||||||
NumberInput::new(Some(val.x))
|
|
||||||
.label("X")
|
|
||||||
.unit("°")
|
|
||||||
.min(-89.9)
|
|
||||||
.max(89.9)
|
|
||||||
.on_update(node_inspector::update_value_at_index(
|
|
||||||
move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), val.y)),
|
|
||||||
node_id,
|
|
||||||
index,
|
|
||||||
))
|
|
||||||
.on_commit(node_inspector::commit_value)
|
|
||||||
.widget_instance(),
|
|
||||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
|
||||||
NumberInput::new(Some(val.y))
|
|
||||||
.label("Y")
|
|
||||||
.unit("°")
|
|
||||||
.min(-89.9)
|
|
||||||
.max(89.9)
|
|
||||||
.on_update(node_inspector::update_value_at_index(
|
|
||||||
move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(val.x, input.value.unwrap())),
|
|
||||||
node_id,
|
|
||||||
index,
|
|
||||||
))
|
|
||||||
.on_commit(node_inspector::commit_value)
|
|
||||||
.widget_instance(),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(vec![LayoutGroup::row(widgets)])
|
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
map.insert(
|
map.insert(
|
||||||
@@ -1717,9 +1657,9 @@ mod test {
|
|||||||
editor.handle_message(NodeGraphMessage::MoveNodeToChainStart { node_id, parent: layer }).await;
|
editor.handle_message(NodeGraphMessage::MoveNodeToChainStart { node_id, parent: layer }).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Guards the `optional_f64` widget override against holding the node metadata lock while building rows that lock it again
|
// Guards the `optional_length` widget override against holding the node metadata lock while building rows that lock it again
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn optional_f64_inspector_row_builds() {
|
async fn optional_length_inspector_row_builds() {
|
||||||
let mut editor = EditorTestUtils::create();
|
let mut editor = EditorTestUtils::create();
|
||||||
editor.new_document().await;
|
editor.new_document().await;
|
||||||
|
|
||||||
|
|||||||
@@ -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,
|
||||||
@@ -278,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
|
||||||
@@ -287,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,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -305,7 +313,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
|||||||
step,
|
step,
|
||||||
} = options;
|
} = options;
|
||||||
|
|
||||||
let mut number_input = NumberInput::default();
|
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();
|
||||||
}
|
}
|
||||||
@@ -337,16 +345,17 @@ 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, true, context);
|
let default_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||||
|
|
||||||
@@ -387,12 +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) => vec2_widget(default_info, "X", "Y", unit.unwrap_or(""), None, false, false),
|
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", unit.unwrap_or(""), None, false, false),
|
||||||
|
Some(x) if id_is::<LengthVec2>(x) => length_vec2_widget(default_info, "X", "Y", bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)),
|
||||||
|
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)),
|
||||||
@@ -896,6 +909,7 @@ 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>, 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.");
|
||||||
@@ -912,6 +926,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
|||||||
.max((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(),
|
||||||
@@ -923,6 +938,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
|||||||
.max((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(),
|
||||||
@@ -938,6 +954,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
|||||||
.max((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(),
|
||||||
@@ -949,6 +966,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
|||||||
.max((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(),
|
||||||
@@ -1201,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
|
||||||
@@ -1211,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));
|
||||||
@@ -1311,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);
|
||||||
@@ -1412,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)],
|
||||||
@@ -2784,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, 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.), 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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2806,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)];
|
||||||
|
|
||||||
@@ -2825,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));
|
||||||
|
|
||||||
@@ -2884,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![
|
||||||
@@ -3213,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());
|
||||||
@@ -3287,6 +3667,10 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
|
|||||||
default_type = field.default_type.clone();
|
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 {
|
if let Some(default) = default_type {
|
||||||
break 'early_return default;
|
break 'early_return default;
|
||||||
}
|
}
|
||||||
@@ -3715,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();
|
||||||
@@ -3724,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,
|
||||||
@@ -3744,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();
|
||||||
|
|
||||||
@@ -4031,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))
|
||||||
}
|
}
|
||||||
@@ -4056,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;
|
||||||
|
|||||||
@@ -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()),
|
||||||
|
|||||||
+1
-1
@@ -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,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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");
|
||||||
|
|||||||
@@ -128,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))
|
||||||
|
|||||||
@@ -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()),
|
||||||
|
|||||||
@@ -291,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(),
|
||||||
|
|||||||
@@ -674,6 +674,9 @@ pub struct NodeNetworkPersistentMetadata {
|
|||||||
/// The display order of pinned nodes in the Inspector (shown when nothing is selected in this network), keyed by node ID.
|
/// The display order of pinned nodes in the Inspector (shown when nothing is selected in this network), keyed by node ID.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub pinned_node_order: Vec<NodeId>,
|
pub pinned_node_order: Vec<NodeId>,
|
||||||
|
/// How many pixels make an inch, which sizes lengths typed in a physical unit, or `None` for the default of 96. Only the root network's applies.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub pixels_per_inch: Option<f64>,
|
||||||
/// Cached metadata for each node, which is calculated when adding a node to node_metadata
|
/// Cached metadata for each node, which is calculated when adding a node to node_metadata
|
||||||
/// Indicates whether the network is currently rendered with a particular node that is previewed, and if so, which connection should be restored when the preview ends.
|
/// Indicates whether the network is currently rendered with a particular node that is previewed, and if so, which connection should be restored when the preview ends.
|
||||||
pub previewing: Previewing,
|
pub previewing: Previewing,
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ impl OriginalTransforms {
|
|||||||
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 document_node = network_interface.document_network().nodes.get(&transform_node_id)?;
|
let document_node = network_interface.document_network().nodes.get(&transform_node_id)?;
|
||||||
Some(transform_utils::get_current_transform(&document_node.inputs))
|
Some(transform_utils::get_current_transform(&document_node.inputs, network_interface.pixels_per_inch()))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn update<'a>(&mut self, selected: &'a [LayerNodeIdentifier], network_interface: &NodeNetworkInterface, shape_editor: Option<&'a ShapeState>) {
|
pub fn update<'a>(&mut self, selected: &'a [LayerNodeIdentifier], network_interface: &NodeNetworkInterface, shape_editor: Option<&'a ShapeState>) {
|
||||||
|
|||||||
@@ -1468,7 +1468,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
|||||||
|
|
||||||
// Lex a static expression once, learning both whether it lexes at all and whether it references `B`
|
// Lex a static expression once, learning both whether it lexes at all and whether it references `B`
|
||||||
let static_expression = match expression.as_value() {
|
let static_expression = match expression.as_value() {
|
||||||
Some(TaggedValue::String(expression)) => Some(expression.clone()),
|
Some(TaggedValue::String(expression)) => Some(read_old_inverse_functions_as_radians(expression)),
|
||||||
_ => None,
|
_ => None,
|
||||||
};
|
};
|
||||||
let mut references_b = false;
|
let mut references_b = false;
|
||||||
@@ -3536,9 +3536,11 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
|||||||
// Preserve primary input connection
|
// Preserve primary input connection
|
||||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
|
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||||
// Set arrow_to = end - start
|
// Set arrow_to = end - start
|
||||||
document
|
document.network_interface.set_input(
|
||||||
.network_interface
|
&InputConnector::node_at_index(*node_id, 1),
|
||||||
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::DVec2(end - start), false), network_path);
|
NodeInput::value(TaggedValue::LengthVec2(graphene_std::units::TypedLengthVec2::pixels(end - start)), false),
|
||||||
|
network_path,
|
||||||
|
);
|
||||||
// Preserve shaft_width, head_width, head_length (shifted from indices 3,4,5 to 2,3,4)
|
// Preserve shaft_width, head_width, head_length (shifted from indices 3,4,5 to 2,3,4)
|
||||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 2), old_inputs[3].clone(), network_path);
|
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 2), old_inputs[3].clone(), network_path);
|
||||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 3), old_inputs[4].clone(), network_path);
|
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 3), old_inputs[4].clone(), network_path);
|
||||||
@@ -3558,7 +3560,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
|||||||
return None;
|
return None;
|
||||||
};
|
};
|
||||||
let mut transform_template = transform_node_type.default_node_template();
|
let mut transform_template = transform_node_type.default_node_template();
|
||||||
transform_template.inputs[1] = NodeInput::value(TaggedValue::DVec2(start), false);
|
transform_template.inputs[1] = NodeInput::value(TaggedValue::LengthVec2(graphene_std::units::TypedLengthVec2::pixels(start)), false);
|
||||||
|
|
||||||
let transform_id = NodeId::new();
|
let transform_id = NodeId::new();
|
||||||
|
|
||||||
@@ -3601,9 +3603,11 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
|||||||
// Preserve primary input connection
|
// Preserve primary input connection
|
||||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
|
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||||
// Set line_to = end - start
|
// Set line_to = end - start
|
||||||
document
|
document.network_interface.set_input(
|
||||||
.network_interface
|
&InputConnector::node_at_index(*node_id, 1),
|
||||||
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::DVec2(end - start), false), network_path);
|
NodeInput::value(TaggedValue::LengthVec2(graphene_std::units::TypedLengthVec2::pixels(end - start)), false),
|
||||||
|
network_path,
|
||||||
|
);
|
||||||
|
|
||||||
// Find downstream connection to insert Transform node
|
// Find downstream connection to insert Transform node
|
||||||
let downstream = document
|
let downstream = document
|
||||||
@@ -3619,7 +3623,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
|||||||
return None;
|
return None;
|
||||||
};
|
};
|
||||||
let mut transform_template = transform_node_type.default_node_template();
|
let mut transform_template = transform_node_type.default_node_template();
|
||||||
transform_template.inputs[1] = NodeInput::value(TaggedValue::DVec2(start), false);
|
transform_template.inputs[1] = NodeInput::value(TaggedValue::LengthVec2(graphene_std::units::TypedLengthVec2::pixels(start)), false);
|
||||||
|
|
||||||
let transform_id = NodeId::new();
|
let transform_id = NodeId::new();
|
||||||
|
|
||||||
@@ -4045,6 +4049,88 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
|
|||||||
Some(())
|
Some(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The old "Math" node's inverse trigonometric functions, each with the builtin that replaced it.
|
||||||
|
const OLD_INVERSE_FUNCTIONS: [(&str, &str); 6] = [("invsin", "asin"), ("invcos", "acos"), ("invtan", "atan"), ("invcsc", "acsc"), ("invsec", "asec"), ("invcot", "acot")];
|
||||||
|
|
||||||
|
/// The old "Math" node's expression with each inverse trigonometric call, like `invsin(A)`, spelled as the builtin that replaced it
|
||||||
|
/// and divided by `rad` as `(asin(A)/rad)`, since the builtin gives an angle where the old function gave plain radians.
|
||||||
|
fn read_old_inverse_functions_as_radians(expression: &str) -> String {
|
||||||
|
rewrite_old_inverse_calls(expression, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rewrites the calls in `source`, read by the old grammar's ASCII names and numbers, nested `depth` calls deep.
|
||||||
|
fn rewrite_old_inverse_calls(source: &str, depth: usize) -> String {
|
||||||
|
// Beyond the nesting an expression may have, the rest stays as written
|
||||||
|
const MAX_DEPTH: usize = 32;
|
||||||
|
|
||||||
|
let mut result = String::with_capacity(source.len());
|
||||||
|
let mut position = 0;
|
||||||
|
while let Some(character) = source[position..].chars().next() {
|
||||||
|
let start = position;
|
||||||
|
|
||||||
|
// A number ends before a name juxtaposed after it, as in `2invsin(A)`, though an exponent like `2e3` is part of it
|
||||||
|
if character.is_ascii_digit() || character == '.' {
|
||||||
|
let bytes = &source.as_bytes()[start..];
|
||||||
|
let mut length = bytes.iter().take_while(|byte| byte.is_ascii_digit() || **byte == b'.').count();
|
||||||
|
if matches!(bytes.get(length), Some(b'e' | b'E')) {
|
||||||
|
let sign = usize::from(matches!(bytes.get(length + 1), Some(b'+' | b'-')));
|
||||||
|
let digits = bytes.iter().skip(length + 1 + sign).take_while(|byte| byte.is_ascii_digit()).count();
|
||||||
|
if digits > 0 {
|
||||||
|
length += 1 + sign + digits;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
position += length;
|
||||||
|
result.push_str(&source[start..position]);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if !(character.is_ascii_alphabetic() || character == '_') {
|
||||||
|
position += character.len_utf8();
|
||||||
|
result.push(character);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let name_length = source[start..]
|
||||||
|
.find(|character: char| !(character.is_ascii_alphanumeric() || character == '_'))
|
||||||
|
.unwrap_or(source.len() - start);
|
||||||
|
position = start + name_length;
|
||||||
|
let name = &source[start..position];
|
||||||
|
|
||||||
|
// The call's arguments run to the parenthesis closing the one after its name, and may hold more calls
|
||||||
|
let after_name = &source[position..];
|
||||||
|
let open = position + after_name.len() - after_name.trim_start().len();
|
||||||
|
if let Some((_, builtin)) = OLD_INVERSE_FUNCTIONS.iter().find(|(old, _)| *old == name)
|
||||||
|
&& depth < MAX_DEPTH
|
||||||
|
&& let Some(close) = closing_parenthesis(&source[open..])
|
||||||
|
{
|
||||||
|
result.push_str(&format!("({builtin}({})/rad)", rewrite_old_inverse_calls(&source[open + 1..open + close], depth + 1)));
|
||||||
|
position = open + close + 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
result.push_str(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The byte offset of the parenthesis closing the one `text` begins with, or `None` where it begins otherwise or never closes.
|
||||||
|
fn closing_parenthesis(text: &str) -> Option<usize> {
|
||||||
|
if !text.starts_with('(') {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut depth = 0;
|
||||||
|
for (index, character) in text.char_indices() {
|
||||||
|
match character {
|
||||||
|
'(' => depth += 1,
|
||||||
|
')' if depth == 1 => return Some(index),
|
||||||
|
')' => depth -= 1,
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
/// Splits each removed Math f(…) node by the kind of string it held, into Math Aggregate or Math Formula.
|
/// Splits each removed Math f(…) node by the kind of string it held, into Math Aggregate or Math Formula.
|
||||||
fn migrate_math_f_nodes(document: &mut DocumentMessageHandler) {
|
fn migrate_math_f_nodes(document: &mut DocumentMessageHandler) {
|
||||||
let math_f_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
let math_f_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||||
@@ -4853,10 +4939,11 @@ mod tests {
|
|||||||
// The old inputs stay in place and the witness defaults to Number, the output type every such node had
|
// The old inputs stay in place and the witness defaults to Number, the output type every such node had
|
||||||
let node = &document.network_interface.document_network().nodes[&node_id];
|
let node = &document.network_interface.document_network().nodes[&node_id];
|
||||||
let value_at = |index: usize| node.inputs.get(index).and_then(|input| input.as_value()).cloned();
|
let value_at = |index: usize| node.inputs.get(index).and_then(|input| input.as_value()).cloned();
|
||||||
assert_eq!(node.inputs.len(), 3);
|
assert_eq!(node.inputs.len(), 4);
|
||||||
assert_eq!(value_at(0), Some(TaggedValue::Number(4.)));
|
assert_eq!(value_at(0), Some(TaggedValue::Number(4.)));
|
||||||
assert_eq!(value_at(1), Some(TaggedValue::String("x^2".into())));
|
assert_eq!(value_at(1), Some(TaggedValue::String("x^2".into())));
|
||||||
assert_eq!(value_at(2), Some(TaggedValue::Number(0.)));
|
assert_eq!(value_at(2), Some(TaggedValue::Number(0.)));
|
||||||
|
assert_eq!(node.inputs.get(3), Some(&NodeInput::scope(graphene_std::units::PIXELS_PER_INCH_SCOPE)));
|
||||||
}
|
}
|
||||||
|
|
||||||
// The same upgrade on a node whose value comes from upstream, where restoring the inputs has to preserve the wire
|
// The same upgrade on a node whose value comes from upstream, where restoring the inputs has to preserve the wire
|
||||||
@@ -4888,7 +4975,7 @@ mod tests {
|
|||||||
migrate(&mut document);
|
migrate(&mut document);
|
||||||
|
|
||||||
let node = &document.network_interface.document_network().nodes[&node_id];
|
let node = &document.network_interface.document_network().nodes[&node_id];
|
||||||
assert_eq!(node.inputs.len(), 3);
|
assert_eq!(node.inputs.len(), 4);
|
||||||
assert!(
|
assert!(
|
||||||
matches!(node.inputs.first(), Some(NodeInput::Node { node_id: upstream, .. }) if *upstream == source_id),
|
matches!(node.inputs.first(), Some(NodeInput::Node { node_id: upstream, .. }) if *upstream == source_id),
|
||||||
"the upstream wire was dropped by the upgrade, leaving {:?}",
|
"the upstream wire was dropped by the upgrade, leaving {:?}",
|
||||||
@@ -4921,11 +5008,18 @@ mod tests {
|
|||||||
migrate(&mut document);
|
migrate(&mut document);
|
||||||
|
|
||||||
let node = &document.network_interface.document_network().nodes[&node_id];
|
let node = &document.network_interface.document_network().nodes[&node_id];
|
||||||
assert_eq!(node.inputs.len(), 3, "the output type is kept, or added to a node from before it");
|
let identifier = match &node.implementation {
|
||||||
match &node.implementation {
|
|
||||||
DocumentNodeImplementation::ProtoNode(identifier) => identifier.clone(),
|
DocumentNodeImplementation::ProtoNode(identifier) => identifier.clone(),
|
||||||
other => panic!("expected a proto node implementation, got {other:?}"),
|
other => panic!("expected a proto node implementation, got {other:?}"),
|
||||||
|
};
|
||||||
|
|
||||||
|
// The output type is kept, or added to a node from before it, and Math Formula reads the resolution after it
|
||||||
|
let expected_inputs = if identifier == math_formula::IDENTIFIER { 4 } else { 3 };
|
||||||
|
assert_eq!(node.inputs.len(), expected_inputs);
|
||||||
|
if identifier == math_formula::IDENTIFIER {
|
||||||
|
assert_eq!(node.inputs.get(3), Some(&NodeInput::scope(graphene_std::units::PIXELS_PER_INCH_SCOPE)));
|
||||||
}
|
}
|
||||||
|
identifier
|
||||||
};
|
};
|
||||||
let items = || NodeInput::value(TaggedValue::None, false);
|
let items = || NodeInput::value(TaggedValue::None, false);
|
||||||
let expression = |text: &str| NodeInput::value(TaggedValue::String(text.into()), false);
|
let expression = |text: &str| NodeInput::value(TaggedValue::String(text.into()), false);
|
||||||
@@ -4936,6 +5030,48 @@ mod tests {
|
|||||||
assert_eq!(migrated_implementation(vec![items(), expression("a * b + c"), output_type()]), math_formula::IDENTIFIER);
|
assert_eq!(migrated_implementation(vec![items(), expression("a * b + c"), output_type()]), math_formula::IDENTIFIER);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn old_inverse_functions_read_as_the_plain_radians_they_gave() {
|
||||||
|
let read = read_old_inverse_functions_as_radians;
|
||||||
|
assert_eq!(read("invsin(A) + 1"), "(asin(A)/rad) + 1");
|
||||||
|
assert_eq!(read("2invcos (B)^2"), "2(acos(B)/rad)^2");
|
||||||
|
assert_eq!(read("invtan(invsin(A) * 2)"), "(atan((asin(A)/rad) * 2)/rad)");
|
||||||
|
assert_eq!(read("sin(invcot(A))"), "sin((acot(A)/rad))");
|
||||||
|
assert_eq!(read("2e3invsec(A)"), "2e3(asec(A)/rad)");
|
||||||
|
for unchanged in ["invsinh(A)", "B_invsin(A)", "invsin", "invsin(A", "sin(A) + π", ""] {
|
||||||
|
assert_eq!(read(unchanged), unchanged);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The rewritten expression gives the number the old one did
|
||||||
|
let result = math_parser::evaluate(&read("invtan(1) + 1")).unwrap().unwrap();
|
||||||
|
assert!((result.as_real().unwrap() - (std::f64::consts::FRAC_PI_4 + 1.)).abs() < 1e-12);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_old_math_node_keeps_the_plain_radians_its_inverse_functions_gave() {
|
||||||
|
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
|
||||||
|
|
||||||
|
let math_id = NodeId(1);
|
||||||
|
let mut document = DocumentMessageHandler::default();
|
||||||
|
document.network_interface.insert_node(
|
||||||
|
math_id,
|
||||||
|
NodeTemplate {
|
||||||
|
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("math_nodes::MathNode")),
|
||||||
|
inputs: vec![
|
||||||
|
NodeInput::value(TaggedValue::Number(1.), false),
|
||||||
|
NodeInput::value(TaggedValue::String("invtan(A) + 1".into()), false),
|
||||||
|
NodeInput::value(TaggedValue::Number(0.), false),
|
||||||
|
],
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
&[],
|
||||||
|
);
|
||||||
|
migrate(&mut document);
|
||||||
|
|
||||||
|
let node = &document.network_interface.document_network().nodes[&math_id];
|
||||||
|
assert_eq!(node.inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::String("(atan(x)/rad) + 1".into())));
|
||||||
|
}
|
||||||
|
|
||||||
// The old Math node's expression decides its replacement: a static string that never reads `B` becomes "Math Function",
|
// The old Math node's expression decides its replacement: a static string that never reads `B` becomes "Math Function",
|
||||||
// while a wired `B` or an uninspectable expression becomes "Extend" feeding "Math Formula"
|
// while a wired `B` or an uninspectable expression becomes "Extend" feeding "Math Formula"
|
||||||
#[test]
|
#[test]
|
||||||
@@ -5002,8 +5138,8 @@ mod tests {
|
|||||||
let node = &document.network_interface.document_network().nodes[&math_id];
|
let node = &document.network_interface.document_network().nodes[&math_id];
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
node.inputs.len(),
|
node.inputs.len(),
|
||||||
3,
|
4,
|
||||||
"the old `B` input should be dropped, leaving the value, the expression, and the output-type witness"
|
"the old `B` input should be dropped, leaving the value, the expression, the output-type witness, and the resolution"
|
||||||
);
|
);
|
||||||
assert_eq!(node.inputs.first(), Some(&NodeInput::node(source_a_id, 0)));
|
assert_eq!(node.inputs.first(), Some(&NodeInput::node(source_a_id, 0)));
|
||||||
assert_eq!(node.inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::String("2 - 0.2x".into())));
|
assert_eq!(node.inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::String("2 - 0.2x".into())));
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ pub use crate::messages::clipboard::{ClipboardMessage, ClipboardMessageContext,
|
|||||||
pub use crate::messages::color_picker::{ColorPickerMessage, ColorPickerMessageDiscriminant, ColorPickerMessageHandler};
|
pub use crate::messages::color_picker::{ColorPickerMessage, ColorPickerMessageDiscriminant, ColorPickerMessageHandler};
|
||||||
pub use crate::messages::debug::{DebugMessage, DebugMessageDiscriminant, DebugMessageHandler};
|
pub use crate::messages::debug::{DebugMessage, DebugMessageDiscriminant, DebugMessageHandler};
|
||||||
pub use crate::messages::defer::{DeferMessage, DeferMessageDiscriminant, DeferMessageHandler};
|
pub use crate::messages::defer::{DeferMessage, DeferMessageDiscriminant, DeferMessageHandler};
|
||||||
|
pub use crate::messages::dialog::document_setup_dialog::{DocumentSetupDialogMessage, DocumentSetupDialogMessageDiscriminant, DocumentSetupDialogMessageHandler};
|
||||||
pub use crate::messages::dialog::export_dialog::{ExportDialogMessage, ExportDialogMessageContext, ExportDialogMessageDiscriminant, ExportDialogMessageHandler};
|
pub use crate::messages::dialog::export_dialog::{ExportDialogMessage, ExportDialogMessageContext, ExportDialogMessageDiscriminant, ExportDialogMessageHandler};
|
||||||
pub use crate::messages::dialog::new_document_dialog::{NewDocumentDialogMessage, NewDocumentDialogMessageDiscriminant, NewDocumentDialogMessageHandler};
|
pub use crate::messages::dialog::new_document_dialog::{NewDocumentDialogMessage, NewDocumentDialogMessageDiscriminant, NewDocumentDialogMessageHandler};
|
||||||
pub use crate::messages::dialog::preferences_dialog::{PreferencesDialogMessage, PreferencesDialogMessageContext, PreferencesDialogMessageDiscriminant, PreferencesDialogMessageHandler};
|
pub use crate::messages::dialog::preferences_dialog::{PreferencesDialogMessage, PreferencesDialogMessageContext, PreferencesDialogMessageDiscriminant, PreferencesDialogMessageHandler};
|
||||||
|
|||||||
Loaded 100 of 189 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user