Compare commits

..
Author SHA1 Message Date
Dennis Kobert 23d9192693 Exclude executor teardown from the measured bench regions 2026-08-27 10:09:19 +00:00
Timon eb50be844b Remove now obsolete disable-registration special case from node macro (#4375) 2026-07-25 13:54:46 +00:00
Dennis Kobert 0f0f62c2e9 Enforce unwind safety on all public executor entry points (#4356) 2026-07-24 09:34:40 +00:00
Timon f5b1fee85f Fix node insertion crash caused by mismatched DefinitionIdentifier serialization (#4353) 2026-07-22 09:38:07 +00:00
Timon 6f8c4b2adb Desktop: Stop compiling the editor into the wasm wrapper (#4348)
* Make wasm wrapper not depend on editor on native

* Introduce pkg-native

* Fix tests

* Fix fmt

* Correct span and make cargo fmt work inside editor_commands block

* Review

* Fix lint
2026-07-18 10:33:38 +00:00
174 changed files with 6817 additions and 13325 deletions

No files matched your search

Generated
+5 -22
View File
@@ -1141,15 +1141,6 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"
[[package]]
name = "delaunator"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e1ee323c1275374f7e612d3724d12707079fb6a2117349fe144def656f5a880"
dependencies = [
"robust",
]
[[package]]
name = "deranged"
version = "0.4.0"
@@ -2047,7 +2038,6 @@ dependencies = [
"core-types",
"dyn-any",
"glam",
"graphene-hash",
"graphene-resource",
"log",
"raster-types",
@@ -2190,7 +2180,6 @@ dependencies = [
"glam",
"graphic-types",
"node-macro",
"rand",
"raster-types",
"serde",
"vector-types",
@@ -2323,9 +2312,9 @@ dependencies = [
"graph-craft",
"graphene-std",
"graphite-editor",
"graphite-wasm-wrapper",
"image",
"keyboard-types",
"ron",
"serde",
"serde_json",
"thiserror 2.0.18",
@@ -2385,6 +2374,7 @@ dependencies = [
name = "graphite-proc-macros"
version = "0.0.0"
dependencies = [
"convert_case",
"graphite-editor",
"proc-macro2",
"quote",
@@ -2396,17 +2386,17 @@ dependencies = [
name = "graphite-wasm-wrapper"
version = "0.0.0"
dependencies = [
"bytemuck",
"graph-craft",
"graphene-std",
"graphite-editor",
"graphite-proc-macros",
"js-sys",
"log",
"node-macro",
"ron",
"serde",
"serde-wasm-bindgen",
"serde_bytes",
"serde_json",
"tsify",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
@@ -5002,12 +4992,6 @@ dependencies = [
"serde",
]
[[package]]
name = "robust"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e27ee8bb91ca0adcf0ecb116293afa12d393f9c2b9b9cd54d33e8078fe19839"
[[package]]
name = "ron"
version = "0.12.0"
@@ -6591,7 +6575,6 @@ name = "vector-nodes"
version = "0.1.0"
dependencies = [
"core-types",
"delaunator",
"dyn-any",
"futures",
"glam",
-1
View File
@@ -209,7 +209,6 @@ syn = { version = "2.0", default-features = false, features = [
"proc-macro",
] }
lyon_geom = "1.0"
delaunator = "1.0"
petgraph = { version = "0.7", default-features = false, features = ["graphmap"] }
half = { version = "2.4", default-features = false, features = ["bytemuck"] }
tinyvec = { version = "1", features = ["std"] }
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"viLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"contextLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183952488591282082,{"inputs":[{"Node":{"node_id":17965270694495451178,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,-6.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exportsLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183952488591282082,{"inputs":[{"Node":{"node_id":17965270694495451178,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,-6.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exportsLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5],"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"U32":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"CellularDistanceFunction":"Hybrid"},"exposed":false}},{"Value":{"tagged_valLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5],"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"U32":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"CellularDistanceFunction":"Hybrid"},"exposed":false}},{"Value":{"tagged_valLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::artboard::Artboard"}}}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":4}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementatiLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::artboard::Artboard>"}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":4}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphiLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"BoxCorners":[0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[1.0,0.0,0.0,1.0,0.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2288754089236120499,{"inputs":[{"Node":{"Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":null},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"output_index":0}}],"call_argument":{"Concrete":Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":6559102076450693000,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":[[1,[0.0,Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":6559102076450693000,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[31.556350940025634,-2.7755575615628914e-17,2.7755575615628914e-17,31.556350940025634,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0]]},"regions":{"add":[0],"remove":[],"segment_range":[[0,{"start":1,"end":5}]],"fill":[[0,0]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"List":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0]]},"regions":{"add":[0],"remove":[],"segment_range":[[0,{"start":1,"end":5}]],"fill":[[0,0]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Concrete":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"StrinLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scLine truncated
+1 -2
View File
@@ -14,13 +14,12 @@ use winit::event::{ButtonSource, ElementState, MouseButton, StartCause, WindowEv
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
use winit::window::WindowId;
use graphite_desktop_ui::{UiCommand, UiInstance};
use crate::dirs;
use crate::event::{AppEvent, AppEventScheduler};
use crate::persist;
use crate::preferences;
use crate::render::{RenderError, RenderState};
use crate::ui::{UiCommand, UiInstance};
use crate::window::Window;
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, InputMessage, MouseKeys, MouseState, Preferences};
use crate::wrapper::{DesktopWrapper, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
+2 -1
View File
@@ -1,9 +1,10 @@
use crate::ui::Cursor;
use crate::wrapper::NodeGraphExecutionResult;
use crate::wrapper::messages::DesktopWrapperMessage;
pub(crate) enum AppEvent {
UiUpdate(wgpu::Texture),
CursorChange(graphite_desktop_ui::Cursor),
CursorChange(Cursor),
WebCommunicationInitialized,
DesktopWrapperMessage(DesktopWrapperMessage),
NodeGraphExecutionResult(NodeGraphExecutionResult),
+3 -2
View File
@@ -3,12 +3,13 @@ use crate::cli::Cli;
use crate::consts::APP_LOCK_FILE_NAME;
use crate::event::{AppEvent, CreateAppEventSchedulerEventLoopExt};
use clap::Parser;
use graphite_desktop_ui::{Acceleration, UiConfig, UiContext, UiEvent, UiSetupResult};
use std::io::Write;
use std::process::ExitCode;
use tracing_subscriber::EnvFilter;
use ui::{Acceleration, UiConfig, UiContext, UiEvent, UiSetupResult};
use winit::event_loop::EventLoop;
pub(crate) use graphite_desktop_ui as ui;
pub(crate) use graphite_desktop_wrapper as wrapper;
mod app;
@@ -69,7 +70,7 @@ pub fn start() -> ExitCode {
}
};
dirs::clear_dir(&graphite_desktop_ui::temp_dir_root());
dirs::clear_dir(&ui::temp_dir_root());
// TODO: Eventually remove this cleanup code for the old "browser" CEF directory
dirs::delete_old_cef_browser_directory();
+1 -1
View File
@@ -1,8 +1,8 @@
use crate::consts::APP_NAME;
use crate::event::AppEventScheduler;
use crate::ui::Cursor;
use crate::wrapper::messages::MenuItem;
use crate::wrapper::{WgpuInstance, WgpuSurface};
use graphite_desktop_ui::Cursor;
use std::collections::HashMap;
use std::sync::Arc;
use winit::cursor::{CustomCursor, CustomCursorSource};
+1 -1
View File
@@ -14,6 +14,7 @@ gpu = ["graphite-editor/gpu", "graphene-std/shader-nodes"]
[dependencies]
# Local dependencies
graphite-editor = { workspace = true }
graphite-wasm-wrapper = { path = "../../frontend/wrapper", default-features = false, features = ["editor"] }
graphene-std = { workspace = true }
graph-craft = { workspace = true }
wgpu-executor = { workspace = true }
@@ -22,7 +23,6 @@ wgpu = { workspace = true }
thiserror = { workspace = true }
tracing = { workspace = true }
dirs = { workspace = true }
ron = { workspace = true}
vello = { workspace = true }
image = { workspace = true }
serde = { workspace = true }
+6 -15
View File
@@ -1,7 +1,9 @@
use graph_craft::application_io::PlatformApplicationIo;
use graph_craft::application_io::resource::ResourceStorage;
use graphite_editor::application::{Editor, Environment, Host, Platform};
use graphite_editor::messages::prelude::{FrontendMessage, Message, Wake};
use graphite_editor::messages::frontend::FrontendMessage;
use graphite_editor::messages::prelude::Wake;
use message_dispatcher::DesktopWrapperMessageDispatcher;
use messages::{DesktopFrontendMessage, DesktopWrapperMessage};
use std::sync::Arc;
@@ -65,21 +67,10 @@ pub enum NodeGraphExecutionResult {
}
pub fn deserialize_editor_message(data: &[u8]) -> Option<DesktopWrapperMessage> {
if let Ok(string) = std::str::from_utf8(data) {
if let Ok(message) = ron::de::from_str::<Message>(string) {
Some(DesktopWrapperMessage::FromWeb(message.into()))
} else {
None
}
} else {
None
}
let message = graphite_wasm_wrapper::native_communication::decode_editor_command(data)?;
Some(DesktopWrapperMessage::FromWeb(message.into()))
}
pub fn serialize_frontend_messages(messages: Vec<FrontendMessage>) -> Option<Vec<u8>> {
if let Ok(serialized) = ron::ser::to_string(&messages) {
Some(serialized.into_bytes())
} else {
None
}
graphite_wasm_wrapper::native_communication::encode_frontend_messages(messages)
}
+1 -1
View File
@@ -45,7 +45,7 @@ impl<'de> Deserialize<'de> for ResourceEntry {
}
let Raw { mut sources, hash, hash_timestamp } = Raw::deserialize(deserializer)?;
sources.sort_by(|(a, _), (b, _)| a.cmp(b));
sources.sort_by_key(|(a, _)| *a);
sources.dedup_by(|(later_key, later_value), (kept_key, kept_value)| {
// `dedup_by` keeps the first of each run; sorting is stable, so resolve duplicates by LWW.
if later_key != kept_key {
-17
View File
@@ -183,23 +183,6 @@ pub const DEFAULT_DOCUMENT_NAME: &str = "Untitled Document";
pub const MAX_UNDO_HISTORY_LEN: usize = 100; // TODO: Add this to user preferences
pub const AUTO_SAVE_TIMEOUT_SECONDS: u64 = 1;
// PLOTTER
/// Address of the pen plotter print server, hard-coded for the conference booth LAN where it won't change.
pub const PLOTTER_SERVER_ADDRESS: &str = "http://192.168.77.10:4747";
/// Drawable area of letter paper in the plotter, in inches (portrait). The artwork's bounding box (the artboard is
/// dropped) is scaled to fit, rotated to landscape when wider than tall.
pub const PLOTTER_PAPER_SIZE_INCHES: (f64, f64) = (7.5, 10.);
/// Fixed per-job overhead in seconds before the pen starts moving. Derived directly from timed plots: two versions of
/// the same artwork plotted separately (3:24 + 12:17) minus both overlaid in a single job (15:23) leaves the setup
/// time counted one extra time, giving 18 seconds.
pub const PLOTTER_SETUP_SECONDS: f64 = 18.;
/// Pen-down drawing speed in inches per second. Fitted (with the pen lift time below) to timed plots of the same
/// artwork with solid strokes (349 in, 20 lifts, 3:24) and dash-baked strokes (176 in, 818 lifts, 12:17).
pub const PLOTTER_PEN_SPEED_INCHES_PER_SECOND: f64 = 2.047;
/// Seconds per pen lift/reposition/lower cycle, once per subpath. This also covers pen-up travel, which is not
/// modeled by distance because the print server reorders paths to minimize it. Fitted alongside the pen speed above.
pub const PLOTTER_PEN_LIFT_SECONDS: f64 = 0.774;
// INPUT
pub const DOUBLE_CLICK_MILLISECONDS: u64 = 500;
@@ -252,20 +252,9 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
let mut vectors = Vec::new();
let mut resources = Vec::new();
for item in items {
// Pasted templates skip document migration, so stored types normalize here
match item {
ClipboardItem::Layer(mut entry) => {
for (_, template) in &mut entry.nodes {
template.document_node.normalize_stored_types();
}
layers.push(entry);
}
ClipboardItem::Nodes(mut nodes) => {
for (_, template) in &mut nodes {
template.document_node.normalize_stored_types();
}
node_groups.push(nodes);
}
ClipboardItem::Layer(entry) => layers.push(entry),
ClipboardItem::Nodes(nodes) => node_groups.push(nodes),
ClipboardItem::Vector(vector) => vectors.push(vector),
ClipboardItem::Resource(resource) => resources.push(resource),
}
@@ -5,7 +5,7 @@ use crate::messages::prelude::*;
use graphene_std::Color;
use graphene_std::color::SRGBA8;
use graphene_std::core_types::misc::parse_css_color;
use graphene_std::vector::style::{FillChoice, FillChoiceUI, Gradient, GradientUI};
use graphene_std::vector::style::{FillChoice, FillChoiceUI, GradientStops, GradientStopsUI};
/// Bounds for a midpoint position (relative to the interval between two adjacent gradient stops).
const MIN_MIDPOINT: f64 = 0.01;
@@ -28,7 +28,7 @@ pub struct ColorPickerMessageHandler {
old_is_none: bool,
// When set, the picker is editing a gradient: the visual pickers and inputs target the active stop's color.
gradient: Option<Gradient>,
gradient: Option<GradientStops>,
active_marker_index: Option<u32>,
active_marker_is_midpoint: bool,
@@ -430,7 +430,7 @@ impl ColorPickerMessageHandler {
// For gradient editing, the markers' handle colors mirror their gradient stop colors
let markers = gradient.iter().map(|stop| SpectrumMarker::new(stop.position, stop.midpoint, stop.color)).collect();
let mut row_widgets = vec![
SpectrumInput::new(GradientUI::from(gradient))
SpectrumInput::new(GradientStopsUI::from(gradient))
.markers(markers)
.active_marker_index(self.active_marker_index)
.active_marker_is_midpoint(self.active_marker_is_midpoint)
@@ -10,8 +10,6 @@ pub enum DialogMessage {
NewDocumentDialog(NewDocumentDialogMessage),
#[child]
PreferencesDialog(PreferencesDialogMessage),
#[child]
SendToPlotterDialog(SendToPlotterDialogMessage),
// Messages
Dismiss,
@@ -24,9 +22,6 @@ pub enum DialogMessage {
title: String,
description: String,
},
DisplaySendToPlotterSuccess {
job_name: String,
},
RequestAboutGraphiteDialog,
RequestAboutGraphiteDialogWithLocalizedCommitDate {
localized_commit_date: String,
@@ -42,7 +37,6 @@ pub enum DialogMessage {
},
RequestNewDocumentDialog,
RequestPreferencesDialog,
RequestSendToPlotterDialog,
RequestConfirmRestartDialog {
preferences_requiring_restart: Vec<String>,
},
@@ -4,7 +4,6 @@ use crate::messages::dialog::simple_dialogs::{ConfirmRestartDialog, LicensesThir
use crate::messages::frontend::utility_types::ExportBounds;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*;
use graphene_std::vector::style::RenderMode;
#[derive(ExtractField)]
pub struct DialogMessageContext<'a> {
@@ -19,7 +18,6 @@ pub struct DialogMessageHandler {
export_dialog: ExportDialogMessageHandler,
new_document_dialog: NewDocumentDialogMessageHandler,
preferences_dialog: PreferencesDialogMessageHandler,
send_to_plotter_dialog: SendToPlotterDialogMessageHandler,
}
#[message_handler_data]
@@ -31,7 +29,6 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
DialogMessage::ExportDialog(message) => self.export_dialog.process_message(message, responses, ExportDialogMessageContext { portfolio }),
DialogMessage::NewDocumentDialog(message) => self.new_document_dialog.process_message(message, responses, ()),
DialogMessage::PreferencesDialog(message) => self.preferences_dialog.process_message(message, responses, PreferencesDialogMessageContext { preferences }),
DialogMessage::SendToPlotterDialog(message) => self.send_to_plotter_dialog.process_message(message, responses, SendToPlotterDialogMessageContext { portfolio }),
DialogMessage::Dismiss => {
if let Some(message) = self.on_dismiss.take() {
@@ -63,11 +60,6 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
let dialog = simple_dialogs::ErrorDialog { title, description };
dialog.send_dialog_to_frontend(responses);
}
DialogMessage::DisplaySendToPlotterSuccess { job_name } => {
self.on_dismiss = None;
let dialog = simple_dialogs::SendToPlotterSuccessDialog { job_name };
dialog.send_dialog_to_frontend(responses);
}
DialogMessage::RequestAboutGraphiteDialog => {
self.on_dismiss = Some(DialogMessage::Close.into());
responses.add(FrontendMessage::TriggerAboutGraphiteLocalizedCommitDate {
@@ -144,23 +136,6 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
self.on_dismiss = Some(PreferencesDialogMessage::Confirm.into());
self.preferences_dialog.send_dialog_to_frontend(responses, preferences);
}
DialogMessage::RequestSendToPlotterDialog => {
self.on_dismiss = Some(DialogMessage::Close.into());
if let Some(document) = portfolio.active_document() {
// Switch the viewport to outline mode so the artwork previews as the pen plotter will draw it
responses.add(DocumentMessage::SetRenderMode { render_mode: RenderMode::Outline });
// Kick off a render of the plotter SVG purely to measure it for the time estimate shown in the dialog
responses.add(PortfolioMessage::SubmitPlotterExport {
job_name: document.name.clone(),
estimate_only: true,
});
self.send_to_plotter_dialog.job_name = document.name.clone();
self.send_to_plotter_dialog.estimate = crate::messages::dialog::send_to_plotter_dialog::PlotTimeEstimate::Pending;
self.send_to_plotter_dialog.send_dialog_to_frontend(responses);
}
}
DialogMessage::RequestConfirmRestartDialog { preferences_requiring_restart } => {
self.on_dismiss = Some(DialogMessage::Close.into());
let dialog = ConfirmRestartDialog { preferences_requiring_restart };
@@ -174,6 +149,5 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
RequestExportDialog,
RequestNewDocumentDialog,
RequestPreferencesDialog,
RequestSendToPlotterDialog,
);
}
-1
View File
@@ -11,7 +11,6 @@ mod dialog_message_handler;
pub mod export_dialog;
pub mod new_document_dialog;
pub mod preferences_dialog;
pub mod send_to_plotter_dialog;
pub mod simple_dialogs;
#[doc(inline)]
@@ -1,7 +0,0 @@
mod send_to_plotter_dialog_message;
mod send_to_plotter_dialog_message_handler;
#[doc(inline)]
pub use send_to_plotter_dialog_message::{SendToPlotterDialogMessage, SendToPlotterDialogMessageDiscriminant};
#[doc(inline)]
pub use send_to_plotter_dialog_message_handler::{PlotTimeEstimate, SendToPlotterDialogMessageContext, SendToPlotterDialogMessageHandler, estimated_plot_seconds};
@@ -1,10 +0,0 @@
use crate::messages::prelude::*;
#[impl_message(Message, DialogMessage, SendToPlotterDialog)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum SendToPlotterDialogMessage {
JobName { name: String },
UpdateTimeEstimate { seconds: Option<f64> },
Submit,
}
@@ -1,153 +0,0 @@
use crate::consts::{PLOTTER_PAPER_SIZE_INCHES, PLOTTER_PEN_LIFT_SECONDS, PLOTTER_PEN_SPEED_INCHES_PER_SECOND, PLOTTER_SETUP_SECONDS};
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*;
use graphene_std::renderer::plot_statistics::PlotStatistics;
#[derive(ExtractField)]
pub struct SendToPlotterDialogMessageContext<'a> {
pub portfolio: &'a PortfolioMessageHandler,
}
/// How long the plotter is expected to take on the current document, shown in the dialog.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub enum PlotTimeEstimate {
/// The estimate render is still in flight.
#[default]
Pending,
/// The estimate could not be computed.
Unavailable,
/// Estimated plot duration in seconds.
Seconds(f64),
}
/// A dialog to send the current document to the pen plotter print server as an SVG.
#[derive(Debug, Clone, Default, ExtractField)]
pub struct SendToPlotterDialogMessageHandler {
pub job_name: String,
pub estimate: PlotTimeEstimate,
}
#[message_handler_data]
impl MessageHandler<SendToPlotterDialogMessage, SendToPlotterDialogMessageContext<'_>> for SendToPlotterDialogMessageHandler {
fn process_message(&mut self, message: SendToPlotterDialogMessage, responses: &mut VecDeque<Message>, context: SendToPlotterDialogMessageContext) {
let SendToPlotterDialogMessageContext { portfolio } = context;
match message {
SendToPlotterDialogMessage::JobName { name } => self.job_name = name,
SendToPlotterDialogMessage::UpdateTimeEstimate { seconds } => {
self.estimate = match seconds {
Some(seconds) => PlotTimeEstimate::Seconds(seconds),
None => PlotTimeEstimate::Unavailable,
};
// Refresh only the dialog content, since re-displaying the whole dialog would reopen it if the user has already closed it
self.send_layout(responses, LayoutTarget::DialogColumn1);
return;
}
SendToPlotterDialogMessage::Submit => {
// Fall back to the document name so the attendant can still tell jobs apart if the field was cleared
let job_name = if self.job_name.trim().is_empty() {
portfolio.active_document().map(|document| document.name.clone()).unwrap_or_default()
} else {
self.job_name.clone()
};
responses.add_front(PortfolioMessage::SubmitPlotterExport { job_name, estimate_only: false });
}
}
self.send_dialog_to_frontend(responses);
}
advertise_actions!(SendToPlotterDialogUpdate;
);
}
impl DialogLayoutHolder for SendToPlotterDialogMessageHandler {
const ICON: &'static str = "File";
const TITLE: &'static str = "Send to Plotter";
fn layout_buttons(&self) -> Layout {
let widgets = vec![
TextButton::new("Send")
.emphasized(true)
.on_update(|_| {
DialogMessage::CloseAndThen {
followups: vec![SendToPlotterDialogMessage::Submit.into()],
}
.into()
})
.widget_instance(),
TextButton::new("Cancel").on_update(|_| FrontendMessage::DialogClose.into()).widget_instance(),
];
Layout(vec![LayoutGroup::row(widgets)])
}
}
impl LayoutHolder for SendToPlotterDialogMessageHandler {
fn layout(&self) -> Layout {
let job_name = vec![
TextLabel::new("Job Name").table_align(true).min_width(100).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextInput::new(&self.job_name)
.on_update(|text_input: &TextInput| SendToPlotterDialogMessage::JobName { name: text_input.value.clone() }.into())
.min_width(200)
.widget_instance(),
];
let estimate_text = match self.estimate {
PlotTimeEstimate::Pending => "Estimating…".to_string(),
PlotTimeEstimate::Unavailable => "Unknown".to_string(),
PlotTimeEstimate::Seconds(seconds) => format_plot_duration(seconds),
};
let estimated_time = vec![
TextLabel::new("Estimated Time").table_align(true).min_width(100).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextLabel::new(estimate_text).widget_instance(),
];
Layout(vec![LayoutGroup::row(job_name), LayoutGroup::row(estimated_time)])
}
}
/// Estimates how long the plotter will take to draw the given SVG, in seconds.
///
/// The artwork's bounding box is scaled to fit the paper (rotated to landscape when wider than tall), then timed as a
/// fixed setup cost, pen-down drawing at a constant speed, and a fixed cost per pen lift (which also covers pen-up
/// travel, since the print server reorders paths to minimize it). The pen draws every path as its outline, so total
/// path length approximates the pen-down distance regardless of fills. Intricate fine detail like text tends to run
/// over this estimate because the machine cannot reach full speed on tiny curves.
pub fn estimated_plot_seconds(statistics: &PlotStatistics) -> f64 {
let (paper_width, paper_height) = if statistics.width > statistics.height {
(PLOTTER_PAPER_SIZE_INCHES.1, PLOTTER_PAPER_SIZE_INCHES.0)
} else {
PLOTTER_PAPER_SIZE_INCHES
};
let scale = if statistics.width > 0. && statistics.height > 0. {
(paper_width / statistics.width).min(paper_height / statistics.height)
} else {
0.
};
let pen_down_inches = statistics.pen_down_distance * scale;
PLOTTER_SETUP_SECONDS + pen_down_inches / PLOTTER_PEN_SPEED_INCHES_PER_SECOND + statistics.pen_lift_count as f64 * PLOTTER_PEN_LIFT_SECONDS
}
/// Formats an estimated duration like "About 3 min 20 sec", rounded to the nearest 5 seconds.
fn format_plot_duration(seconds: f64) -> String {
let total = (((seconds / 5.).round() * 5.).max(5.)) as u64;
let minutes = total / 60;
let seconds = total % 60;
if minutes == 0 {
format!("About {seconds} sec")
} else if seconds == 0 {
format!("About {minutes} min")
} else {
format!("About {minutes} min {seconds} sec")
}
}
@@ -8,7 +8,6 @@ mod failed_to_load_documents_dialog;
mod failed_to_open_document_dialog;
mod licenses_dialog;
mod licenses_third_party_dialog;
mod send_to_plotter_success_dialog;
pub use about_graphite_dialog::AboutGraphiteDialog;
pub use close_all_documents_dialog::CloseAllDocumentsDialog;
@@ -21,4 +20,3 @@ pub use failed_to_load_documents_dialog::FailedToLoadDocumentsDialog;
pub use failed_to_open_document_dialog::FailedToOpenDocumentDialog;
pub use licenses_dialog::LicensesDialog;
pub use licenses_third_party_dialog::LicensesThirdPartyDialog;
pub use send_to_plotter_success_dialog::SendToPlotterSuccessDialog;
@@ -1,34 +0,0 @@
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*;
/// A dialog to confirm that a job was successfully queued on the pen plotter print server.
pub struct SendToPlotterSuccessDialog {
pub job_name: String,
}
impl DialogLayoutHolder for SendToPlotterSuccessDialog {
const ICON: &'static str = "CheckboxChecked";
const TITLE: &'static str = "Send to Plotter";
fn layout_buttons(&self) -> Layout {
let widgets = vec![TextButton::new("OK").emphasized(true).on_update(|_| FrontendMessage::DialogClose.into()).widget_instance()];
Layout(vec![LayoutGroup::row(widgets)])
}
}
impl LayoutHolder for SendToPlotterSuccessDialog {
fn layout(&self) -> Layout {
Layout(vec![
LayoutGroup::row(vec![TextLabel::new("Sent to the plotter queue").bold(true).widget_instance()]),
LayoutGroup::row(vec![
TextLabel::new(format!(
"The job \"{}\" was added to the queue.\nA booth attendant will start the plot from the dashboard.",
self.job_name
))
.multiline(true)
.widget_instance(),
]),
])
}
}
@@ -1,7 +1,7 @@
use super::IconName;
use super::utility_types::{MouseCursorIcon, PersistedState};
use crate::messages::app_window::app_window_message_handler::AppWindowPlatform;
use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewImage};
use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewImage, RasterizedImage};
use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::utility_types::{
@@ -14,7 +14,6 @@ use crate::messages::prelude::*;
use crate::messages::tool::tool_messages::eyedropper_tool::PrimarySecondary;
use graph_craft::document::NodeId;
use graphene_std::color::SRGBA8;
use graphene_std::raster::Image;
use graphene_std::vector::style::FillChoiceUI;
use std::path::PathBuf;
@@ -106,11 +105,6 @@ pub enum FrontendMessage {
mime: String,
size: (f64, f64),
},
TriggerSendToPlotter {
name: String,
svg: String,
address: String,
},
TriggerFetchAndOpenDocument {
name: String,
filename: String,
@@ -240,7 +234,7 @@ pub enum FrontendMessage {
svg: String,
},
UpdateImageData {
image_data: Vec<(u64, Image<SRGBA8>)>,
image_data: Vec<RasterizedImage>,
},
UpdateDocumentLayerDetails {
data: LayerPanelEntry,
@@ -82,3 +82,12 @@ pub struct EyedropperPreviewImage {
pub width: u32,
pub height: u32,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
#[derive(Clone, Debug, Default, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
pub struct RasterizedImage {
pub id: u64,
pub width: u32,
pub height: u32,
pub pixels: serde_bytes::ByteBuf,
}
@@ -453,7 +453,6 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
// DialogMessage
entry!(KeyDown(KeyE); modifiers=[Accel], action_dispatch=DialogMessage::RequestExportDialog),
entry!(KeyDown(KeyN); modifiers=[Accel], action_dispatch=DialogMessage::RequestNewDocumentDialog),
entry!(KeyDown(KeyP); modifiers=[Accel], action_dispatch=DialogMessage::RequestSendToPlotterDialog),
entry!(KeyDown(Comma); modifiers=[Accel], action_dispatch=DialogMessage::RequestPreferencesDialog),
//
// DebugMessage
@@ -1,5 +1,6 @@
use crate::messages::input_mapper::utility_types::input_keyboard::KeysGroup;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::prelude::*;
use graphene_std::color::SRGBA8;
use graphene_std::vector::style::FillChoiceUI;
@@ -291,7 +292,11 @@ impl LayoutMessageHandler {
responses.add(callback_message);
}
WidgetValueAction::Update => {
let callback_message = (node_type_input.on_update.callback)(&value.into());
let Value::String(ref node_type) = value else {
error!("NodeCatalog update was not of type: String, found {value:?}");
return;
};
let callback_message = (node_type_input.on_update.callback)(&DefinitionIdentifier::from_serialized(node_type));
responses.add(callback_message);
}
},
@@ -6,7 +6,7 @@ use derivative::*;
use graphene_std::Color;
use graphene_std::color::SRGBA8;
use graphene_std::transform::ReferencePoint;
use graphene_std::vector::style::{FillChoiceUI, GradientUI};
use graphene_std::vector::style::{FillChoiceUI, GradientStopsUI};
use graphite_proc_macros::WidgetBuilder;
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
@@ -531,7 +531,7 @@ pub struct SpectrumInput {
// Content
/// The colored gradient drawn behind the markers (display-only, caller-owned).
#[widget_builder(constructor)]
pub track: GradientUI,
pub track: GradientStopsUI,
/// CSS `linear-gradient(...)` string for the track strip's `background-image`. Auto-populated from `track` at layout-send time.
#[serde(rename = "trackCSS")]
#[widget_builder(skip)]
@@ -172,12 +172,6 @@ impl LayoutHolder for MenuBarMessageHandler {
.tooltip_shortcut(action_shortcut!(DialogMessageDiscriminant::RequestExportDialog))
.on_commit(|_| DialogMessage::RequestExportDialog.into())
.disabled(no_active_document),
MenuListEntry::new("Send to Plotter…")
.label("Send to Plotter…")
.icon("FileExport")
.tooltip_shortcut(action_shortcut!(DialogMessageDiscriminant::RequestSendToPlotterDialog))
.on_commit(|_| DialogMessage::RequestSendToPlotterDialog.into())
.disabled(no_active_document),
],
#[cfg(not(target_os = "macos"))]
vec![preferences],
@@ -6,25 +6,14 @@ use crate::messages::prelude::*;
use crate::messages::tool::tool_messages::tool_prelude::*;
use glam::{Affine2, DAffine2, Vec2};
use graph_craft::document::NodeId;
use graphene_std::animation::RealTimeMode;
use graphene_std::blending::BlendMode;
use graphene_std::color::SRGBA8;
use graphene_std::extract_xy::XY;
use graphene_std::gradient::Gradient;
use graphene_std::list::{Item, List, NodeIdPath};
use graphene_std::gradient::GradientStops;
use graphene_std::list::List;
use graphene_std::memo::IORecord;
use graphene_std::raster::{
CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, LuminanceCalculation, NoiseType, RedGreenBlue, RedGreenBlueAlpha, RelativeAbsolute, SelectiveColorChoice,
};
use graphene_std::raster_types::{CPU, GPU, Raster};
use graphene_std::text::TextAlign;
use graphene_std::text_nodes::StringCapitalization;
use graphene_std::transform::{ReferencePoint, ScaleType};
use graphene_std::vector::misc::{
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, SpiralType,
};
use graphene_std::vector::style::{DashPattern, FillChoice, FillChoiceUI, GradientSpreadMethod, GradientType, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector};
use graphene_std::vector::Vector;
use graphene_std::vector::style::{FillChoice, FillChoiceUI, GradientSpreadMethod, GradientType};
use graphene_std::{Artboard, Color, Context, Graphic};
use std::any::Any;
use std::sync::Arc;
@@ -187,10 +176,10 @@ macro_rules! generate_layout_downcast {
}
// TODO: We simply try all these types sequentially. Find a better strategy.
fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'static>, data: &mut LayoutData) -> Option<Vec<LayoutGroup>> {
// `Item<NodeIdPath>` is interpreted as a path (e.g. the value produced by `path_of_subgraph`), shown as a
// `List<NodeId>` is interpreted as a path (e.g. the value produced by `path_of_subgraph`), shown as a
// `List` where each item's NodeId resolves against the prefix made up of the items above it.
if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, Item<NodeIdPath>>>() {
return Some(table_node_id_path_layout_with_breadcrumb(&io.output.element().0, data));
if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<NodeId>>>() {
return Some(table_node_id_path_layout_with_breadcrumb(&io.output, data));
}
generate_layout_downcast!(introspected_data, data, [
List<Artboard>,
@@ -199,106 +188,27 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
List<Raster<CPU>>,
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<GradientStops>,
List<String>,
List<f64>,
List<f32>,
List<u32>,
List<u64>,
List<i32>,
List<i64>,
List<u8>,
List<bool>,
List<DVec2>,
List<DAffine2>,
List<BlendMode>,
List<GradientType>,
List<GradientSpreadMethod>,
List<DashPattern>,
List<BoxCorners>,
List<StrokeJoin>,
List<StrokeAlign>,
List<StrokeCap>,
List<PaintOrder>,
List<MergeByDistanceAlgorithm>,
List<ExtrudeJoiningAlgorithm>,
List<PointSpacingType>,
List<StringCapitalization>,
List<LuminanceCalculation>,
List<RedGreenBlue>,
List<RedGreenBlueAlpha>,
List<RelativeAbsolute>,
List<SelectiveColorChoice>,
List<XY>,
List<ScaleType>,
List<ReferencePoint>,
List<CentroidType>,
List<BooleanOperation>,
List<NoiseType>,
List<FractalType>,
List<CellularDistanceFunction>,
List<CellularReturnType>,
List<DomainWarpType>,
List<RealTimeMode>,
List<GridType>,
List<ArcType>,
List<SpiralType>,
List<TextAlign>,
List<QRCodeErrorCorrectionLevel>,
List<InterpolationDistribution>,
List<RowsOrColumns>,
Item<Artboard>,
Item<Graphic>,
Item<Vector>,
Item<Raster<CPU>>,
Item<Raster<GPU>>,
Item<Color>,
Item<Gradient>,
Item<String>,
Item<f64>,
Item<f32>,
Item<u32>,
Item<u64>,
Item<i32>,
Item<i64>,
Item<bool>,
Item<DVec2>,
Item<DAffine2>,
Item<BlendMode>,
Item<GradientType>,
Item<GradientSpreadMethod>,
Item<DashPattern>,
Item<BoxCorners>,
Item<StrokeJoin>,
Item<StrokeAlign>,
Item<StrokeCap>,
Item<PaintOrder>,
Item<MergeByDistanceAlgorithm>,
Item<ExtrudeJoiningAlgorithm>,
Item<PointSpacingType>,
Item<StringCapitalization>,
Item<LuminanceCalculation>,
Item<RedGreenBlue>,
Item<RedGreenBlueAlpha>,
Item<RelativeAbsolute>,
Item<SelectiveColorChoice>,
Item<XY>,
Item<ScaleType>,
Item<ReferencePoint>,
Item<CentroidType>,
Item<BooleanOperation>,
Item<NoiseType>,
Item<FractalType>,
Item<CellularDistanceFunction>,
Item<CellularReturnType>,
Item<DomainWarpType>,
Item<RealTimeMode>,
Item<GridType>,
Item<ArcType>,
Item<SpiralType>,
Item<TextAlign>,
Item<QRCodeErrorCorrectionLevel>,
Item<InterpolationDistribution>,
Item<RowsOrColumns>,
GradientStops,
f64,
u32,
u64,
bool,
String,
Option<f64>,
DVec2,
DAffine2,
BlendMode,
GradientType,
GradientSpreadMethod,
])
}
@@ -336,57 +246,6 @@ trait TableItemLayout {
}
}
impl<T: TableItemLayout> TableItemLayout for Item<T> {
fn type_name() -> &'static str {
T::type_name()
}
fn identifier(&self) -> String {
self.element().identifier()
}
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
if let Some(step) = data.desired_path.get(data.current_depth).cloned() {
match step {
PathStep::Element(_) => {
data.current_depth += 1;
let result = self.element().layout_with_breadcrumb(data);
data.current_depth -= 1;
return result;
}
PathStep::Attribute { key, .. } => {
if let Some(any) = self.attributes().get_any(&key) {
data.current_depth += 1;
if let Some(result) = drilldown_attribute_layout(any, data) {
data.current_depth -= 1;
return result;
}
data.current_depth -= 1;
warn!("Drilldown unsupported for attribute {key:?}");
}
data.desired_path.truncate(data.current_depth);
}
}
}
let attribute_keys: Vec<String> = self.attributes().keys().map(str::to_string).collect();
// A single element, so no leading ID column, unlike the `List` table
let mut values = vec![self.element().value_widget(PathStep::Element(0), data)];
for key in &attribute_keys {
let target = PathStep::Attribute { row: 0, key: key.clone() };
let widget = self.attributes().get_any(key).and_then(|any| dispatch_value_widget(any, target, data)).unwrap_or_else(|| {
let text = self.attributes().display_value(key, display_value_override).unwrap_or_else(|| "-".to_string());
TextLabel::new(text).narrow(true).widget_instance()
});
values.push(widget);
}
let mut column_names = vec!["element"];
column_names.extend(attribute_keys.iter().map(|s| s.as_str()));
vec![LayoutGroup::table(vec![column_headings(&column_names), values], false)]
}
}
impl<T: TableItemLayout> TableItemLayout for List<T> {
fn type_name() -> &'static str {
"List"
@@ -465,53 +324,12 @@ impl TableItemLayout for Artboard {
}
}
impl TableItemLayout for DashPattern {
fn type_name() -> &'static str {
"DashPattern"
}
fn identifier(&self) -> String {
"DashPattern".to_string()
}
// The wrapping `Item` already contributes the breadcrumb; the inner list supplies the next level
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
self.value_page(data)
}
// Label the spreadsheet's element button with the inner list's identifier, like Artboard
fn value_widget(&self, target: PathStep, data: &LayoutData) -> WidgetInstance {
self.0.value_widget(target, data)
}
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
self.0.layout_with_breadcrumb(data)
}
}
impl TableItemLayout for BoxCorners {
fn type_name() -> &'static str {
"BoxCorners"
}
fn identifier(&self) -> String {
"BoxCorners".to_string()
}
// The wrapping `Item` already contributes the breadcrumb; the inner list supplies the next level
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
self.value_page(data)
}
// Label the spreadsheet's element button with the inner list's identifier, like Artboard
fn value_widget(&self, target: PathStep, data: &LayoutData) -> WidgetInstance {
self.0.value_widget(target, data)
}
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
self.0.layout_with_breadcrumb(data)
}
}
impl TableItemLayout for Graphic {
fn type_name() -> &'static str {
"Graphic"
}
fn identifier(&self) -> String {
match self {
Self::None => "None".to_string(),
Self::Graphic(list) => list.identifier(),
Self::Vector(list) => list.identifier(),
Self::RasterCPU(list) => list.identifier(),
@@ -527,7 +345,6 @@ impl TableItemLayout for Graphic {
}
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
match self {
Self::None => label("None"),
Self::Graphic(list) => list.layout_with_breadcrumb(data),
Self::Vector(list) => list.layout_with_breadcrumb(data),
Self::RasterCPU(list) => list.layout_with_breadcrumb(data),
@@ -695,7 +512,7 @@ impl TableItemLayout for Raster<GPU> {
format!("Raster ({} x {})", self.data().width(), self.data().height())
}
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
let widgets = vec![TextLabel::new("This raster data is a texture on the GPU. It currently cannot be displayed here.").widget_instance()];
let widgets = vec![TextLabel::new("Raster is a texture on the GPU and cannot currently be displayed here").widget_instance()];
vec![LayoutGroup::row(widgets)]
}
}
@@ -720,7 +537,7 @@ impl TableItemLayout for Color {
}
}
impl TableItemLayout for Gradient {
impl TableItemLayout for GradientStops {
fn type_name() -> &'static str {
"Gradient"
}
@@ -768,21 +585,6 @@ impl TableItemLayout for u8 {
}
}
impl TableItemLayout for f32 {
fn type_name() -> &'static str {
"Number (f32)"
}
fn identifier(&self) -> String {
format!("{self}")
}
// Values fall back to the default drill-in button (labeled via `identifier`); the value page shows the rich `NumberInput`.
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
vec![LayoutGroup::row(vec![
NumberInput::new(Some(*self as f64)).disabled(true).max_width(220).display_decimal_places(20).widget_instance(),
])]
}
}
impl TableItemLayout for u32 {
fn type_name() -> &'static str {
"Number (u32)"
@@ -798,37 +600,6 @@ impl TableItemLayout for u32 {
}
}
impl TableItemLayout for i32 {
fn type_name() -> &'static str {
"Number (i32)"
}
fn identifier(&self) -> String {
format!("{self}")
}
// Values fall back to the default drill-in button (labeled via `identifier`); the value page shows the rich `NumberInput`.
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
vec![LayoutGroup::row(vec![
NumberInput::new(Some(*self as f64)).disabled(true).max_width(220).display_decimal_places(20).widget_instance(),
])]
}
}
impl TableItemLayout for i64 {
fn type_name() -> &'static str {
"Number (i64)"
}
fn identifier(&self) -> String {
format!("{self}")
}
// Values fall back to the default drill-in button (labeled via `identifier`); the value page shows the rich `NumberInput`.
// TODO: Make this robust for large i64 values that don't fit in f64 (beyond roughly 2^53), as with u64.
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
vec![LayoutGroup::row(vec![
NumberInput::new(Some(*self as f64)).disabled(true).max_width(220).display_decimal_places(20).widget_instance(),
])]
}
}
impl TableItemLayout for u64 {
fn type_name() -> &'static str {
"Number (u64)"
@@ -955,73 +726,45 @@ impl TableItemLayout for Affine2 {
}
}
// Choice enums all display as their variant's label, shown inline as a plain text widget
macro_rules! impl_table_item_layout_for_choice_enum {
($($ty:ty),* $(,)?) => {
$(
impl TableItemLayout for $ty {
fn type_name() -> &'static str {
stringify!($ty)
}
fn identifier(&self) -> String {
self.to_string()
}
fn value_widget(&self, _target: PathStep, _data: &LayoutData) -> WidgetInstance {
TextLabel::new(self.to_string()).narrow(true).widget_instance()
}
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
vec![LayoutGroup::row(vec![self.value_widget(PathStep::Element(0), _data)])]
}
}
)*
}
}
impl_table_item_layout_for_choice_enum!(
BlendMode,
GradientType,
GradientSpreadMethod,
StrokeJoin,
StrokeAlign,
StrokeCap,
PaintOrder,
MergeByDistanceAlgorithm,
ExtrudeJoiningAlgorithm,
PointSpacingType,
StringCapitalization,
LuminanceCalculation,
RedGreenBlue,
RedGreenBlueAlpha,
RelativeAbsolute,
SelectiveColorChoice,
XY,
ScaleType,
CentroidType,
BooleanOperation,
NoiseType,
FractalType,
CellularDistanceFunction,
CellularReturnType,
DomainWarpType,
RealTimeMode,
GridType,
ArcType,
SpiralType,
TextAlign,
QRCodeErrorCorrectionLevel,
InterpolationDistribution,
RowsOrColumns,
);
// ReferencePoint is not a choice enum with display labels, so its variant name serves as the label
impl TableItemLayout for ReferencePoint {
impl TableItemLayout for BlendMode {
fn type_name() -> &'static str {
"ReferencePoint"
"BlendMode"
}
fn identifier(&self) -> String {
format!("{self:?}")
self.to_string()
}
fn value_widget(&self, _target: PathStep, _data: &LayoutData) -> WidgetInstance {
TextLabel::new(self.identifier()).narrow(true).widget_instance()
TextLabel::new(self.to_string()).narrow(true).widget_instance()
}
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
vec![LayoutGroup::row(vec![self.value_widget(PathStep::Element(0), _data)])]
}
}
impl TableItemLayout for GradientType {
fn type_name() -> &'static str {
"GradientType"
}
fn identifier(&self) -> String {
self.to_string()
}
fn value_widget(&self, _target: PathStep, _data: &LayoutData) -> WidgetInstance {
TextLabel::new(self.to_string()).narrow(true).widget_instance()
}
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
vec![LayoutGroup::row(vec![self.value_widget(PathStep::Element(0), _data)])]
}
}
impl TableItemLayout for GradientSpreadMethod {
fn type_name() -> &'static str {
"GradientSpreadMethod"
}
fn identifier(&self) -> String {
self.to_string()
}
fn value_widget(&self, _target: PathStep, _data: &LayoutData) -> WidgetInstance {
TextLabel::new(self.to_string()).narrow(true).widget_instance()
}
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
vec![LayoutGroup::row(vec![self.value_widget(PathStep::Element(0), _data)])]
@@ -1162,10 +905,12 @@ macro_rules! known_item_types {
List<Raster<CPU>>,
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<GradientStops>,
List<String>,
List<NodeId>,
List<f64>,
Gradient,
List<u8>,
GradientStops,
Color,
NodeId,
DAffine2,
@@ -1174,12 +919,9 @@ macro_rules! known_item_types {
Vec2,
Option<f64>,
f64,
f32,
u8,
u32,
u64,
i32,
i64,
bool,
String,
Vector,
@@ -1187,42 +929,6 @@ macro_rules! known_item_types {
Raster<GPU>,
Graphic,
Artboard,
DashPattern,
BoxCorners,
BlendMode,
GradientType,
GradientSpreadMethod,
StrokeJoin,
StrokeAlign,
StrokeCap,
PaintOrder,
MergeByDistanceAlgorithm,
ExtrudeJoiningAlgorithm,
PointSpacingType,
StringCapitalization,
LuminanceCalculation,
RedGreenBlue,
RedGreenBlueAlpha,
RelativeAbsolute,
SelectiveColorChoice,
XY,
ScaleType,
ReferencePoint,
CentroidType,
BooleanOperation,
NoiseType,
FractalType,
CellularDistanceFunction,
CellularReturnType,
DomainWarpType,
RealTimeMode,
GridType,
ArcType,
SpiralType,
TextAlign,
QRCodeErrorCorrectionLevel,
InterpolationDistribution,
RowsOrColumns,
);
};
}
@@ -1243,10 +949,6 @@ fn display_value_override(any: &dyn Any) -> Option<String> {
/// element-column rendering and attribute-column rendering. Returns `None` for unrecognized
/// types so the caller can fall back to a debug-formatted [`TextLabel`].
fn dispatch_value_widget(any: &dyn Any, target: PathStep, data: &LayoutData) -> Option<WidgetInstance> {
// `NodeIdPath` (e.g. the `editor:layer_path` attribute) drills into its inner path list, matching `drilldown_attribute_layout`.
if let Some(path) = any.downcast_ref::<NodeIdPath>() {
return Some(path.0.value_widget(target, data));
}
macro_rules! check {
( $($ty:ty),* $(,)? ) => {
$(
@@ -1303,10 +1005,10 @@ fn table_node_id_path_layout_with_breadcrumb(path: &List<NodeId>, data: &mut Lay
/// Mirrors [`dispatch_value_widget`] but routes to [`TableItemLayout::layout_with_breadcrumb`].
/// Returns `None` for unrecognized types.
fn drilldown_attribute_layout(any: &dyn Any, data: &mut LayoutData) -> Option<Vec<LayoutGroup>> {
// `NodeIdPath` is interpreted as a path (e.g. the `editor:layer_path` attribute), so each item's NodeId value
// resolves against the prefix made up of preceding items. Handled before the generic blanket impl.
if let Some(path) = any.downcast_ref::<NodeIdPath>() {
return Some(table_node_id_path_layout_with_breadcrumb(&path.0, data));
// `List<NodeId>` is interpreted as a path (e.g. the `editor:layer_path` attribute), so each item's NodeId value
// resolves against the prefix made up of preceding items. Handled before the generic `List<T>` blanket impl.
if let Some(path) = any.downcast_ref::<List<NodeId>>() {
return Some(table_node_id_path_layout_with_breadcrumb(path, data));
}
macro_rules! check {
( $($ty:ty),* $(,)? ) => {
@@ -34,9 +34,9 @@ use crate::node_graph_executor::NodeGraphExecutor;
use glam::{DAffine2, DVec2};
use graph_craft::application_io::resource::ResourceId;
use graph_craft::application_io::wgpu_available;
use graph_craft::descriptor;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput, NodeNetwork, OldNodeNetwork};
use graph_craft::list;
use graphene_std::graphic::is_paint_present;
use graphene_std::math::quad::Quad;
use graphene_std::path_bool_nodes::boolean_intersect;
@@ -125,7 +125,7 @@ pub struct DocumentMessageHandler {
/// network path, the node itself, and its original relative gradient. The deferred migration removes each entry as its bake lands.
/// Transient migration state, but persisted in the saved document so unfinished bakes retry on the next open instead of losing placement.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(crate) pending_gradient_bbox_bake: Vec<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::LegacyGradient)>,
pub(crate) pending_gradient_bbox_bake: Vec<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::Gradient)>,
// =============================================
// Fields omitted from the saved document format
@@ -1323,8 +1323,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
DocumentMessage::SetRenderMode { render_mode } => {
self.render_mode = render_mode;
responses.add_front(NodeGraphMessage::RunDocumentGraph);
// Keep the document bar's render mode radio buttons in sync when the mode is set programmatically
responses.add(PortfolioMessage::UpdateDocumentWidgets);
}
DocumentMessage::AddTransaction => {
// Reverse order since they are added to the front
@@ -2750,7 +2748,7 @@ impl DocumentMessageHandler {
}
/// For each selected layer, splits its fill and stroke into two stacked layers connected
/// to a shared `Solidify Stroke` node via two `Item at Index` nodes (indices 0 and 1).
/// to a shared `Solidify Stroke` node via two `Index Elements` nodes (indices 0 and 1).
/// Layers with only a stroke get just a `Solidify Stroke` added.
/// Layers with only a fill, or neither, are left untouched.
fn handle_expand_fill_stroke_on_selected_layers(&mut self, responses: &mut VecDeque<Message>) {
@@ -2760,7 +2758,7 @@ impl DocumentMessageHandler {
}
let solidify_stroke_definition = document_node_definitions::resolve_proto_node_type(graphene_std::vector::solidify_stroke::IDENTIFIER).expect("Solidify Stroke node should exist");
let item_at_index_definition = document_node_definitions::resolve_proto_node_type(graphene_std::graphic::item_at_index::IDENTIFIER).expect("Item at Index node should exist");
let index_elements_definition = document_node_definitions::resolve_proto_node_type(graphene_std::graphic::index_elements::IDENTIFIER).expect("Index Elements node should exist");
let mut resulting_layers: Vec<NodeId> = Vec::new();
@@ -2793,7 +2791,7 @@ impl DocumentMessageHandler {
if has_fill && has_stroke {
let (existing_index, new_index) = (0_f64, 1_f64);
let existing_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(existing_index), false))]);
let existing_index_template = index_elements_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(existing_index), false))]);
let existing_index_id = NodeId::new();
self.network_interface.insert_node(existing_index_id, existing_index_template, &[]);
self.network_interface.move_node_to_chain_start(&existing_index_id, layer, &[], false);
@@ -2815,7 +2813,7 @@ impl DocumentMessageHandler {
self.network_interface.set_display_name(&new_layer_id, original_name, &[]);
}
let new_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(new_index), false))]);
let new_index_template = index_elements_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(new_index), false))]);
let new_index_id = NodeId::new();
self.network_interface.insert_node(new_index_id, new_index_template, &[]);
self.network_interface.move_node_to_chain_start(&new_index_id, new_layer, &[], false);
@@ -3791,7 +3789,7 @@ impl DocumentMessageHandler {
/// Create a network interface with a single export
fn default_document_network_interface() -> NodeNetworkInterface {
let mut network_interface = NodeNetworkInterface::default();
network_interface.add_export(TaggedValue::TypeDefault(list!(graphene_std::Artboard)), -1, "", &[]);
network_interface.add_export(TaggedValue::TypeDefault(descriptor!(graphene_std::list::List<graphene_std::Artboard>)), -1, "", &[]);
network_interface
}
@@ -4009,7 +4007,7 @@ mod document_message_handler_tests {
#[test]
fn pending_gradient_bakes_round_trip_through_serialization() {
let document = DocumentMessageHandler {
pending_gradient_bbox_bake: vec![(vec![NodeId(7)], NodeId(42), graphic_types::migrations::legacy::LegacyGradient::default())],
pending_gradient_bbox_bake: vec![(vec![NodeId(7)], NodeId(42), graphic_types::migrations::legacy::Gradient::default())],
..Default::default()
};
@@ -4320,35 +4318,4 @@ mod document_message_handler_tests {
Dist: {distance} (should be < 1)"
);
}
// Grouping choreography transiently disconnects the stack wire, and the stored default for that connector
// must stay an empty list rather than any value which materializes as a one-element phantom in the stack
#[tokio::test]
async fn grouping_adds_no_phantom_element_to_the_stack() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await;
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: GroupFolderType::Layer,
})
.await;
let instrumented = editor.eval_graph().await.unwrap();
let base_lengths: Vec<usize> = instrumented
.grab_all_input::<graphene_std::graphic::extend::BaseInput<graphene_std::Graphic>>(&editor.runtime)
.map(|base| base.len())
.collect();
assert!(base_lengths.iter().all(|&len| len == 0), "Every stack base should be empty, found lengths {base_lengths:?}");
let news: Vec<graphene_std::list::List<graphene_std::Graphic>> = instrumented.grab_all_input::<graphene_std::graphic::extend::NewInput<graphene_std::Graphic>>(&editor.runtime).collect();
let phantom_count = news
.iter()
.flat_map(|new| new.iter_element_values())
.filter(|graphic| matches!(graphic, graphene_std::Graphic::None))
.count();
assert_eq!(phantom_count, 0, "No stacked element should be a phantom None graphic");
}
}
@@ -11,7 +11,7 @@ use graphene_std::raster_types::Image;
use graphene_std::subpath::Subpath;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::style::{GradientSpreadMethod, GradientType, Stroke};
use graphene_std::vector::{Gradient, PointId, VectorModificationType};
use graphene_std::vector::{GradientStops, PointId, VectorModificationType};
#[impl_message(Message, DocumentMessage, GraphOperation)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
@@ -22,7 +22,7 @@ pub enum GraphOperationMessage {
},
FillGradientSet {
layer: LayerNodeIdentifier,
gradient: Gradient,
gradient: GradientStops,
gradient_type: GradientType,
spread_method: GradientSpreadMethod,
transform: DAffine2,
@@ -33,7 +33,7 @@ pub enum GraphOperationMessage {
},
GradientStopsSet {
layer: LayerNodeIdentifier,
stops: Gradient,
stops: GradientStops,
},
GradientTransformSet {
layer: LayerNodeIdentifier,
@@ -8,11 +8,12 @@ use crate::messages::portfolio::document::utility_types::nodes::CollapsedLayers;
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils::get_clip_mode;
use glam::{DAffine2, DVec2, IVec2};
use graph_craft::descriptor;
use graph_craft::document::{NodeId, NodeInput};
use graph_craft::list;
use graphene_std::list::List;
use graphene_std::renderer::convert_usvg_path::convert_usvg_path;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::style::{Gradient, GradientSpreadMethod, GradientStop, GradientType, PaintOrder, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::vector::style::{GradientSpreadMethod, GradientStop, GradientStops, GradientType, PaintOrder, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::{Artboard, Color};
#[derive(ExtractField)]
@@ -179,7 +180,7 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
}
// Set the bottom input of the artboard back to artboard
let bottom_input = NodeInput::type_default(list!(Artboard), true);
let bottom_input = NodeInput::type_default(descriptor!(List<Artboard>), true);
network_interface.set_input(&InputConnector::node(artboard_layer.to_node(), 0), bottom_input, &[]);
} else {
// We have some non layers (e.g. just a rectangle node). We disconnect the bottom input and connect it to the left input.
@@ -187,7 +188,7 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
network_interface.set_input(&InputConnector::node(artboard_layer.to_node(), 1), primary_input, &[]);
// Set the bottom input of the artboard back to artboard
let bottom_input = NodeInput::type_default(list!(Artboard), true);
let bottom_input = NodeInput::type_default(descriptor!(List<Artboard>), true);
network_interface.set_input(&InputConnector::node(artboard_layer.to_node(), 0), bottom_input, &[]);
}
}
@@ -507,8 +508,8 @@ const GRAPHITE_NAMESPACE: &str = "https://graphite.art";
/// Pre-parses the raw SVG XML to extract gradient stops that have `graphite:midpoint` attributes.
/// Graphite exports gradients with midpoint curve data by writing interpolated approximation stops
/// alongside the real stops. Real stops are tagged with `graphite:midpoint` attributes.
/// Returns a map from gradient element `id` to `Gradient` containing only the real stops.
fn extract_graphite_gradient_stops(svg: &str) -> HashMap<String, Gradient> {
/// Returns a map from gradient element `id` to `GradientStops` containing only the real stops.
fn extract_graphite_gradient_stops(svg: &str) -> HashMap<String, GradientStops> {
let mut result = HashMap::new();
// Quick check: if the SVG doesn't reference `graphite:midpoint` at all, skip parsing
@@ -554,7 +555,7 @@ fn extract_graphite_gradient_stops(svg: &str) -> HashMap<String, Gradient> {
}
if has_any_midpoint && !real_stops.is_empty() {
result.insert(gradient_id, Gradient::new(real_stops));
result.insert(gradient_id, GradientStops::new(real_stops));
}
}
@@ -578,7 +579,14 @@ fn parse_hex_stop_color(hex: &str, opacity: f32) -> Option<Color> {
/// interact with any existing layers in the parent stack. All descendant layers use a lightweight
/// O(n) import path that skips collision detection and instead calculates positions directly from
/// the known tree structure.
fn import_usvg_node(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node, id: NodeId, parent: LayerNodeIdentifier, insert_index: usize, graphite_gradient_stops: &HashMap<String, Gradient>) {
fn import_usvg_node(
modify_inputs: &mut ModifyInputsContext,
node: &usvg::Node,
id: NodeId,
parent: LayerNodeIdentifier,
insert_index: usize,
graphite_gradient_stops: &HashMap<String, GradientStops>,
) {
let layer = modify_inputs.create_layer(id);
modify_inputs.network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
@@ -641,7 +649,7 @@ fn import_usvg_node_inner(
id: NodeId,
parent: LayerNodeIdentifier,
insert_index: usize,
graphite_gradient_stops: &HashMap<String, Gradient>,
graphite_gradient_stops: &HashMap<String, GradientStops>,
group_extents_map: &mut HashMap<LayerNodeIdentifier, Vec<u32>>,
) -> u32 {
let layer = modify_inputs.create_layer(id);
@@ -684,7 +692,7 @@ fn import_usvg_node_inner(
}
/// Helper to apply path data (vector geometry, fill, stroke, transform) to a layer.
fn import_usvg_path(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node, path: &usvg::Path, layer: LayerNodeIdentifier, graphite_gradient_stops: &HashMap<String, Gradient>) {
fn import_usvg_path(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node, path: &usvg::Path, layer: LayerNodeIdentifier, graphite_gradient_stops: &HashMap<String, GradientStops>) {
let subpaths = convert_usvg_path(path);
// Skip creating a Transform node entirely when the SVG-native transform is identity.
@@ -799,7 +807,7 @@ fn convert_spread_method(spread_method: usvg::SpreadMethod) -> GradientSpreadMet
}
}
fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, graphite_gradient_stops: &HashMap<String, Gradient>) {
fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, graphite_gradient_stops: &HashMap<String, GradientStops>) {
match &fill.paint() {
usvg::Paint::Color(color) => modify_inputs.fill_color_set(Some(usvg_color(*color, fill.opacity().get()))),
usvg::Paint::LinearGradient(linear) => {
@@ -819,7 +827,7 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, g
midpoint: 0.5,
color: usvg_color(stop.color(), stop.opacity().get()),
});
Gradient::new(stops)
GradientStops::new(stops)
}
};
let spread_method = convert_spread_method(linear.spread_method());
@@ -843,7 +851,7 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, g
midpoint: 0.5,
color: usvg_color(stop.color(), stop.opacity().get()),
});
Gradient::new(stops)
GradientStops::new(stops)
}
};
let spread_method = convert_spread_method(radial.spread_method());
@@ -8,7 +8,7 @@ use glam::{DAffine2, DVec2, IVec2};
use graph_craft::application_io::resource::ResourceId;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput};
use graph_craft::{ProtoNodeIdentifier, list};
use graph_craft::{ProtoNodeIdentifier, concrete, descriptor};
use graphene_std::brush::brush_stroke::BrushStroke;
use graphene_std::list::List;
use graphene_std::raster::BlendMode;
@@ -16,7 +16,7 @@ use graphene_std::raster_types::Image;
use graphene_std::subpath::Subpath;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::style::{GradientSpreadMethod, GradientType, Stroke};
use graphene_std::vector::{Gradient, PointId, Vector, VectorModification, VectorModificationType};
use graphene_std::vector::{GradientStops, PointId, Vector, VectorModification, VectorModificationType};
use graphene_std::{Artboard, Color, Graphic, NodeInputDecleration};
#[derive(PartialEq, Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
@@ -134,11 +134,11 @@ impl<'a> ModifyInputsContext<'a> {
/// 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 {
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!(Graphic), true)),
Some(NodeInput::type_default(descriptor!(List<Artboard>), true)),
Some(NodeInput::type_default(descriptor!(List<Graphic>), true)),
Some(NodeInput::value(TaggedValue::DVec2(location), false)),
Some(NodeInput::value(TaggedValue::DVec2(dimensions), false)),
Some(NodeInput::value(TaggedValue::Color(background), false)),
Some(NodeInput::value(TaggedValue::Color(Some(background)), false)),
Some(NodeInput::value(TaggedValue::Bool(clip), false)),
]);
self.network_interface.insert_node(new_id, artboard_node_template, &[]);
@@ -149,7 +149,7 @@ impl<'a> ModifyInputsContext<'a> {
let boolean = resolve_proto_node_type(graphene_std::path_bool_nodes::boolean_operation::IDENTIFIER)
.expect("Boolean node does not exist")
.node_template_input_override([
Some(NodeInput::type_default(list!(Graphic), true)),
Some(NodeInput::type_default(descriptor!(List<Graphic>), true)),
Some(NodeInput::value(TaggedValue::BooleanOperation(operation), false)),
]);
@@ -161,7 +161,7 @@ impl<'a> ModifyInputsContext<'a> {
pub fn insert_blend_data(&mut self, layer: LayerNodeIdentifier, count: f64) -> NodeId {
let blend = resolve_network_node_type("Blend")
.expect("Blend node does not exist")
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::F64(count), false))]);
.node_template_input_override([Some(NodeInput::type_default(descriptor!(List<Graphic>), true)), Some(NodeInput::value(TaggedValue::F64(count), false))]);
let blend_id = NodeId::new();
self.network_interface.insert_node(blend_id, blend, &[]);
@@ -173,7 +173,7 @@ impl<'a> ModifyInputsContext<'a> {
pub fn insert_morph_data(&mut self, layer: LayerNodeIdentifier) -> NodeId {
let morph = resolve_proto_node_type(graphene_std::vector::morph::IDENTIFIER)
.expect("Morph node does not exist")
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::F64(0.5), false))]);
.node_template_input_override([Some(NodeInput::type_default(descriptor!(List<Graphic>), true)), Some(NodeInput::value(TaggedValue::F64(0.5), false))]);
let morph_id = NodeId::new();
self.network_interface.insert_node(morph_id, morph, &[]);
@@ -300,7 +300,7 @@ impl<'a> ModifyInputsContext<'a> {
pub fn insert_color_value(&mut self, color: Color, layer: LayerNodeIdentifier) {
let color_value = resolve_proto_node_type(graphene_std::math_nodes::color_value::IDENTIFIER)
.expect("Color Value node does not exist")
.node_template_input_override([Some(NodeInput::value(TaggedValue::None, false)), Some(NodeInput::value(TaggedValue::Color(color), false))]);
.node_template_input_override([Some(NodeInput::value(TaggedValue::None, false)), Some(NodeInput::value(TaggedValue::Color(Some(color)), false))]);
let color_value_id = NodeId::new();
self.network_interface.insert_node(color_value_id, color_value, &[]);
@@ -433,17 +433,17 @@ impl<'a> ModifyInputsContext<'a> {
return None;
};
// If inserting a 'Path' node, insert a 'Combine Paths' node if the type is `Graphic`.
// If inserting a 'Path' node, insert a 'Flatten Path' node if the type is `Graphic`.
// TODO: Allow the 'Path' node to operate on `List` data by utilizing the reference (index or ID?) for each item.
if node_definition.identifier == "Path" {
let layer_input_type = self.network_interface.input_type(&InputConnector::node(output_layer.to_node(), 1), &[]);
if layer_input_type.compiled_element_name().as_deref() == Some("Graphic") {
let Some(combine_paths_definition) = resolve_proto_node_type(graphene_std::vector_nodes::combine_paths::IDENTIFIER) else {
log::error!("Combine Paths does not exist in ModifyInputsContext::existing_node_id");
if layer_input_type.compiled_nested_type() == Some(&concrete!(List<Graphic>)) {
let Some(flatten_path_definition) = resolve_proto_node_type(graphene_std::vector_nodes::flatten_path::IDENTIFIER) else {
log::error!("Flatten Path does not exist in ModifyInputsContext::existing_node_id");
return None;
};
let node_id = NodeId::new();
self.network_interface.insert_node(node_id, combine_paths_definition.default_node_template(), &[]);
self.network_interface.insert_node(node_id, flatten_path_definition.default_node_template(), &[]);
self.network_interface.move_node_to_chain_start(&node_id, output_layer, &[], self.import);
}
}
@@ -460,15 +460,11 @@ impl<'a> ModifyInputsContext<'a> {
let input_connector = InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX);
let backup_input_connector = InputConnector::node(fill_node_id, graphene_std::vector::fill::BackupColorInput::INDEX);
// The backup remembers the last solid color, so the red-slash "none" choice leaves it untouched
if let Some(color) = color {
self.set_input_with_refresh(backup_input_connector, NodeInput::value(TaggedValue::Color(color), false), true);
}
let fill_value = color.map_or_else(TaggedValue::no_paint, TaggedValue::Color);
self.set_input_with_refresh(input_connector, NodeInput::value(fill_value, false), false);
self.set_input_with_refresh(backup_input_connector, NodeInput::value(TaggedValue::Color(color), false), true);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(color), false), false);
}
pub fn fill_gradient_set(&mut self, gradient: Gradient, gradient_type: GradientType, spread_method: GradientSpreadMethod, transform: DAffine2) {
pub fn fill_gradient_set(&mut self, gradient: GradientStops, gradient_type: GradientType, spread_method: GradientSpreadMethod, transform: DAffine2) {
let Some(fill_node_id) = self.existing_proto_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true) else {
return;
};
@@ -492,14 +488,9 @@ impl<'a> ModifyInputsContext<'a> {
.and_then(|node| node.inputs.get(graphene_std::vector::fill::TransformInput::INDEX))
.is_some_and(|input| input.as_value().is_some());
if transform_is_value {
self.set_input_with_refresh(
InputConnector::node(fill_node_id, graphene_std::vector::fill::HasTransformInput::INDEX),
NodeInput::value(TaggedValue::Bool(true), false),
true,
);
self.set_input_with_refresh(
InputConnector::node(fill_node_id, graphene_std::vector::fill::TransformInput::INDEX),
NodeInput::value(TaggedValue::DAffine2(transform), false),
NodeInput::value(TaggedValue::OptionalDAffine2(Some(transform)), false),
true,
);
}
@@ -572,7 +563,7 @@ impl<'a> ModifyInputsContext<'a> {
}
/// Write the gradient stops to the 'Gradient Value' node feeding the layer.
pub fn gradient_stops_set(&mut self, stops: Gradient) {
pub fn gradient_stops_set(&mut self, stops: GradientStops) {
let Some(output_layer) = self.get_output_layer() else { return };
let gradient_value_id = match get_upstream_gradient_value_node_id(output_layer, self.network_interface) {
@@ -725,7 +716,7 @@ impl<'a> ModifyInputsContext<'a> {
};
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintInput::<List<Graphic>>::INDEX);
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(TaggedValue::Color(color), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::WeightInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.weight), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::AlignInput::INDEX);
@@ -738,8 +729,8 @@ impl<'a> ModifyInputsContext<'a> {
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.join_miter_limit), false), false);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintOrderInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::PaintOrder(stroke.paint_order), false), false);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashPatternInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::DashPattern(stroke.dash_lengths.into()), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashLengthsInput::<graphene_std::list::List<f64>>::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64Array(stroke.dash_lengths), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.dash_offset), false), true);
}
@@ -14,15 +14,15 @@ use glam::DVec2;
use graph_craft::ProtoNodeIdentifier;
use graph_craft::document::value::*;
use graph_craft::document::*;
use graph_craft::{concrete, list};
use graph_craft::{concrete, descriptor};
use graphene_std::extract_xy::XY;
use graphene_std::list::List;
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType, RedGreenBlueAlpha};
use graphene_std::raster_types::{CPU, Raster};
#[allow(unused_imports)]
use graphene_std::transform::Footprint;
use graphene_std::vector::Vector;
use graphene_std::*;
use serde_json::Value;
use std::collections::{HashMap, VecDeque};
pub struct NodePropertiesContext<'a> {
@@ -88,12 +88,8 @@ impl DefinitionIdentifier {
DefinitionIdentifier::Network(data) => format!("NETWORK:{}", data),
}
}
}
impl From<Value> for DefinitionIdentifier {
fn from(value: Value) -> Self {
let s = value.as_str().expect("DefinitionIdentifier value must be a string");
pub fn from_serialized(s: &str) -> Self {
match s.split_once(':') {
Some(("PROTONODE", data)) => DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::with_owned_string(data.to_string())),
Some(("NETWORK", data)) => DefinitionIdentifier::Network(data.to_string()),
@@ -206,7 +202,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
.collect(),
..Default::default()
}),
inputs: vec![NodeInput::type_default(list!(Graphic), true), NodeInput::type_default(list!(Graphic), true)],
inputs: vec![NodeInput::type_default(descriptor!(List<Graphic>), true), NodeInput::type_default(descriptor!(List<Graphic>), true)],
..Default::default()
},
persistent_node_metadata: DocumentNodePersistentMetadata {
@@ -291,11 +287,11 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
call_argument: generic!(T),
implementation: DocumentNodeImplementation::ProtoNode(artboard::create_artboard::IDENTIFIER),
inputs: vec![
NodeInput::import(Type::Fn(concrete!(Context).into(), generic!(T).into()), 1),
NodeInput::import(item!(TaggedValue), 2),
NodeInput::import(item!(TaggedValue), 3),
NodeInput::import(item!(TaggedValue), 4),
NodeInput::import(item!(TaggedValue), 5),
NodeInput::import(concrete!(TaggedValue), 1),
NodeInput::import(concrete!(TaggedValue), 2),
NodeInput::import(concrete!(TaggedValue), 3),
NodeInput::import(concrete!(TaggedValue), 4),
NodeInput::import(concrete!(TaggedValue), 5),
],
..Default::default()
},
@@ -326,7 +322,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
DocumentNode {
inputs: vec![
NodeInput::import(graphene_std::Type::Fn(Box::new(concrete!(Context)), Box::new(list!(Artboard))), 0),
NodeInput::import(graphene_std::Type::Fn(Box::new(concrete!(Context)), Box::new(concrete!(List<Artboard>))), 0),
NodeInput::node(NodeId(3), 0),
],
implementation: DocumentNodeImplementation::ProtoNode(graphic::extend::IDENTIFIER),
@@ -340,11 +336,11 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
..Default::default()
}),
inputs: vec![
NodeInput::type_default(list!(Artboard), true),
NodeInput::type_default(list!(Graphic), true),
NodeInput::type_default(descriptor!(List<Artboard>), true),
NodeInput::type_default(descriptor!(List<Graphic>), true),
NodeInput::value(TaggedValue::DVec2(DVec2::ZERO), false),
NodeInput::value(TaggedValue::DVec2(DVec2::new(1920., 1080.)), false),
NodeInput::value(TaggedValue::Color(Color::WHITE), false),
NodeInput::value(TaggedValue::Color(Some(Color::WHITE)), false),
NodeInput::value(TaggedValue::Bool(true), false),
],
..Default::default()
@@ -452,9 +448,9 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
inputs: vec![NodeInput::import(generic!(T), 4)],
..Default::default()
},
// 1: List Length (number of subpaths)
// 1: Count Elements (number of subpaths)
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(vector::list_length::IDENTIFIER),
implementation: DocumentNodeImplementation::ProtoNode(vector::count_elements::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(0), 0)],
..Default::default()
},
@@ -467,7 +463,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
// 3: Floor (integer count per subpath)
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(math_nodes::floor::IDENTIFIER),
inputs: vec![NodeInput::import(item!(f64), 1)],
inputs: vec![NodeInput::import(concrete!(f64), 1)],
..Default::default()
},
// 4: Multiply (total_instances = count × subpath_count)
@@ -543,8 +539,8 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
NodeInput::import(generic!(T), 0),
NodeInput::node(NodeId(14), 0),
NodeInput::value(TaggedValue::Bool(false), false),
NodeInput::import(item!(vector::misc::InterpolationDistribution), 3),
NodeInput::import(item!(Vector), 4),
NodeInput::import(concrete!(vector::misc::InterpolationDistribution), 3),
NodeInput::import(generic!(T), 4),
],
..Default::default()
},
@@ -574,11 +570,11 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
..Default::default()
}),
inputs: vec![
NodeInput::type_default(list!(Vector), true),
NodeInput::type_default(descriptor!(List<Vector>), true),
NodeInput::value(TaggedValue::F64(10.), false),
NodeInput::value(TaggedValue::Bool(Default::default()), false),
NodeInput::value(TaggedValue::InterpolationDistribution(Default::default()), false),
NodeInput::type_default(list!(Vector), false),
NodeInput::type_default(descriptor!(List<Vector>), false),
],
..Default::default()
},
@@ -603,7 +599,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
..Default::default()
},
// 1: List Length
// 1: Count Elements
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 2)),
@@ -806,9 +802,9 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
inputs: vec![NodeInput::node(NodeId(4), 0), NodeInput::node(NodeId(3), 0)],
..Default::default()
},
// 6: Combine Paths
// 6: Flatten Path
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(vector::combine_paths::IDENTIFIER),
implementation: DocumentNodeImplementation::ProtoNode(vector::flatten_path::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(5), 0)],
..Default::default()
},
@@ -825,7 +821,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
.collect(),
..Default::default()
}),
inputs: vec![NodeInput::type_default(list!(Vector), true)],
inputs: vec![NodeInput::type_default(descriptor!(List<Vector>), true)],
..Default::default()
},
persistent_node_metadata: DocumentNodePersistentMetadata {
@@ -883,7 +879,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
..Default::default()
},
// 6: Combine Paths
// 6: Flatten Path
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(35, 0)),
@@ -923,7 +919,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
exports: vec![NodeInput::node(NodeId(1), 0)],
nodes: [
DocumentNode {
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::import(item!(String), 1)],
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::import(concrete!(String), 1)],
implementation: DocumentNodeImplementation::ProtoNode(platform_application_io::load_resource::IDENTIFIER),
..Default::default()
},
@@ -998,7 +994,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
..Default::default()
},
DocumentNode {
inputs: vec![NodeInput::import(generic!(T), 0), NodeInput::import(item!(Footprint), 1), NodeInput::node(NodeId(1), 0)],
inputs: vec![NodeInput::import(generic!(T), 0), NodeInput::import(concrete!(Footprint), 1), NodeInput::node(NodeId(1), 0)],
implementation: DocumentNodeImplementation::ProtoNode(platform_application_io::rasterize::IDENTIFIER),
..Default::default()
},
@@ -1010,7 +1006,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
..Default::default()
}),
inputs: vec![
NodeInput::type_default(list!(Vector), true),
NodeInput::type_default(descriptor!(List<Vector>), true),
NodeInput::value(
TaggedValue::Footprint(Footprint {
transform: DAffine2::from_scale_angle_translation(DVec2::new(1000., 1000.), 0., DVec2::new(0., 0.)),
@@ -1080,7 +1076,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
nodes: [
DocumentNode {
inputs: vec![
NodeInput::import(list!(Raster<CPU>), 0),
NodeInput::import(concrete!(List<Raster<CPU>>), 0),
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Red), false),
],
implementation: DocumentNodeImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
@@ -1089,7 +1085,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
DocumentNode {
inputs: vec![
NodeInput::import(list!(Raster<CPU>), 0),
NodeInput::import(concrete!(List<Raster<CPU>>), 0),
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Green), false),
],
implementation: DocumentNodeImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
@@ -1098,7 +1094,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
DocumentNode {
inputs: vec![
NodeInput::import(list!(Raster<CPU>), 0),
NodeInput::import(concrete!(List<Raster<CPU>>), 0),
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Blue), false),
],
implementation: DocumentNodeImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
@@ -1107,7 +1103,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
DocumentNode {
inputs: vec![
NodeInput::import(list!(Raster<CPU>), 0),
NodeInput::import(concrete!(List<Raster<CPU>>), 0),
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Alpha), false),
],
implementation: DocumentNodeImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
@@ -1121,7 +1117,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
.collect(),
..Default::default()
}),
inputs: vec![NodeInput::type_default(list!(Raster<CPU>), true)],
inputs: vec![NodeInput::type_default(descriptor!(List<Raster<CPU>>), true)],
..Default::default()
},
persistent_node_metadata: DocumentNodePersistentMetadata {
@@ -1182,13 +1178,13 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
exports: vec![NodeInput::value(TaggedValue::None, false), NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(1), 0)],
nodes: [
DocumentNode {
inputs: vec![NodeInput::import(item!(DVec2), 0), NodeInput::value(TaggedValue::XY(XY::X), false)],
inputs: vec![NodeInput::import(concrete!(DVec2), 0), NodeInput::value(TaggedValue::XY(XY::X), false)],
implementation: DocumentNodeImplementation::ProtoNode(extract_xy::extract_xy::IDENTIFIER),
call_argument: generic!(T),
..Default::default()
},
DocumentNode {
inputs: vec![NodeInput::import(item!(DVec2), 0), NodeInput::value(TaggedValue::XY(XY::Y), false)],
inputs: vec![NodeInput::import(concrete!(DVec2), 0), NodeInput::value(TaggedValue::XY(XY::Y), false)],
implementation: DocumentNodeImplementation::ProtoNode(extract_xy::extract_xy::IDENTIFIER),
call_argument: generic!(T),
..Default::default()
@@ -1239,17 +1235,89 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
description: Cow::Borrowed(
"Decomposes the X and Y components of a vec2.\n\
\n\
The inverse of this node is **Combine Vec2**, which composes a vec2 from its X and Y components.",
The inverse of this node is \"Vec2 Value\", which can have either or both its X and Y parameters exposed as graph inputs.",
),
properties: None,
},
#[cfg(feature = "gpu")]
DocumentNodeDefinition {
identifier: "Upload Texture",
category: "Debug",
node_template: NodeTemplate {
document_node: DocumentNode {
implementation: DocumentNodeImplementation::Network(NodeNetwork {
exports: vec![NodeInput::node(NodeId(1), 0)],
nodes: [
DocumentNode {
inputs: vec![NodeInput::import(concrete!(List<Raster<CPU>>), 0), NodeInput::scope(platform_application_io::wgpu_executor::IDENTIFIER)],
call_argument: generic!(T),
implementation: DocumentNodeImplementation::ProtoNode(wgpu_executor::texture_conversion::upload_texture::IDENTIFIER),
..Default::default()
},
DocumentNode {
call_argument: generic!(T),
inputs: vec![NodeInput::node(NodeId(0), 0)],
implementation: DocumentNodeImplementation::ProtoNode(memo::memoize::IDENTIFIER),
..Default::default()
},
]
.into_iter()
.enumerate()
.map(|(id, node)| (NodeId(id as u64), node))
.collect(),
..Default::default()
}),
inputs: vec![NodeInput::type_default(descriptor!(List<Raster<CPU>>), true)],
..Default::default()
},
persistent_node_metadata: DocumentNodePersistentMetadata {
output_names: vec!["Texture".to_string()],
network_metadata: Some(NodeNetworkMetadata {
persistent_metadata: NodeNetworkPersistentMetadata {
node_metadata: [
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, 0)),
..Default::default()
},
..Default::default()
},
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
..Default::default()
},
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 0)),
..Default::default()
},
..Default::default()
},
]
.into_iter()
.enumerate()
.map(|(id, node)| (NodeId(id as u64), node))
.collect(),
..Default::default()
},
..Default::default()
}),
..Default::default()
},
},
description: Cow::Borrowed("TODO"),
properties: None,
},
DocumentNodeDefinition {
identifier: "Extract",
category: "",
node_template: NodeTemplate {
document_node: DocumentNode {
implementation: DocumentNodeImplementation::Extract,
inputs: vec![NodeInput::type_default(concrete!(DocumentNode), true)],
inputs: vec![NodeInput::type_default(descriptor!(DocumentNode), true)],
..Default::default()
},
persistent_node_metadata: DocumentNodePersistentMetadata {
@@ -1277,25 +1345,25 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
// Node 0: regex_find proto node — returns List<String> of [whole_match, ...capture_groups]
DocumentNode {
inputs: vec![
NodeInput::import(item!(String), 0),
NodeInput::import(item!(String), 1),
NodeInput::import(item!(f64), 2),
NodeInput::import(item!(bool), 3),
NodeInput::import(item!(bool), 4),
NodeInput::import(concrete!(String), 0),
NodeInput::import(concrete!(String), 1),
NodeInput::import(concrete!(f64), 2),
NodeInput::import(concrete!(bool), 3),
NodeInput::import(concrete!(bool), 4),
],
implementation: DocumentNodeImplementation::ProtoNode(text_nodes::regex::regex_find::IDENTIFIER),
..Default::default()
},
// Node 1: item_at_index at index 0, extracts the whole match as a bare String (drops the item's start/end/name attributes since the unwrapped String can't carry them)
// Node 1: extract_element at index 0, extracts the whole match as a bare String (drops the item's start/end/name attributes since the unwrapped String can't carry them)
DocumentNode {
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::F64(0.), false)],
implementation: DocumentNodeImplementation::ProtoNode(graphic::item_at_index::IDENTIFIER),
implementation: DocumentNodeImplementation::ProtoNode(graphic::extract_element::IDENTIFIER),
..Default::default()
},
// Node 2: remove_at_index at index 0, returns the capture group items as a List<String>, preserving each item's start/end/name attributes
// Node 2: omit_element at index 0, returns the capture group items as a List<String>, preserving each item's start/end/name attributes
DocumentNode {
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::F64(0.), false)],
implementation: DocumentNodeImplementation::ProtoNode(graphic::remove_at_index::IDENTIFIER),
implementation: DocumentNodeImplementation::ProtoNode(graphic::omit_element::IDENTIFIER),
..Default::default()
},
]
@@ -1377,7 +1445,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
exports: vec![NodeInput::node(NodeId(1), 0)],
nodes: vec![
DocumentNode {
inputs: vec![NodeInput::import(generic!(T), 0)],
inputs: vec![NodeInput::import(concrete!(List<Vector>), 0)],
implementation: DocumentNodeImplementation::ProtoNode(memo::monitor::IDENTIFIER),
call_argument: generic!(T),
skip_deduplication: true,
@@ -1401,7 +1469,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
..Default::default()
}),
inputs: vec![
NodeInput::type_default(item!(Vector), true),
NodeInput::type_default(descriptor!(List<Vector>), true),
NodeInput::value(TaggedValue::VectorModification(Default::default()), false),
],
..Default::default()
@@ -2134,33 +2202,3 @@ impl DocumentNodeDefinition {
self.node_template_input_override(self.node_template.document_node.inputs.clone().into_iter().map(Some))
}
}
#[cfg(test)]
mod test {
use super::resolve_network_node_type;
use crate::test_utils::test_prelude::*;
use graph_craft::document::NodeId;
// Guards the embedded Map body chain (Read Vector -> Extract Transform -> Decompose Translation -> As Vector) against registry drift
#[tokio::test]
async fn origins_to_polyline_resolves_and_evaluates() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 10., 10.).await;
let layer = editor.active_document().metadata().all_layers().next().expect("drawing a rectangle should create a layer");
let node_id = NodeId::new();
let node_template = resolve_network_node_type("Origins to Polyline")
.expect("the Origins to Polyline definition should exist")
.default_node_template();
editor
.handle_message(NodeGraphMessage::InsertNode {
node_id,
node_template: Box::new(node_template),
})
.await;
editor.handle_message(NodeGraphMessage::MoveNodeToChainStart { node_id, parent: layer }).await;
editor.eval_graph().await.expect("the Origins to Polyline chain should type-resolve and evaluate");
}
}
@@ -1179,8 +1179,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
data_type: self.wire_in_progress_type,
thick: false,
dashed: false,
is_list: false,
center_path_string: String::new(),
};
responses.add(FrontendMessage::UpdateWirePathInProgress { wire_path: Some(wire_path) });
}
@@ -1433,7 +1431,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
return None;
}
let (wire, _center_line, is_stack) = network_interface.vector_wire_from_input(&input, preferences.graph_wire_style, selection_network_path)?;
let (wire, is_stack) = network_interface.vector_wire_from_input(&input, preferences.graph_wire_style, selection_network_path)?;
let node_bbox = kurbo::Rect::new(node_bbox[0].x, node_bbox[0].y, node_bbox[1].x, node_bbox[1].y).to_path(DEFAULT_ACCURACY);
let inside = bezpath_is_inside_bezpath(&wire, &node_bbox, None, None);
@@ -1728,13 +1726,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
continue;
};
// Expand the cull box by a grid cell so a node stays rendered until its connectors, which reach beyond its bounding box, also leave the viewport
let cull_margin = 24.;
if node_bbox[1].x + cull_margin >= document_bbox[0].x
&& node_bbox[0].x - cull_margin <= document_bbox[1].x
&& node_bbox[1].y + cull_margin >= document_bbox[0].y
&& node_bbox[0].y - cull_margin <= document_bbox[1].y
{
if node_bbox[1].x >= document_bbox[0].x && node_bbox[0].x <= document_bbox[1].x && node_bbox[1].y >= document_bbox[0].y && node_bbox[0].y <= document_bbox[1].y {
nodes.push(*node_id);
}
for error in &network_interface.resolved_types.node_graph_errors {
@@ -2175,37 +2167,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
responses.add(NodeGraphMessage::SendGraph);
}
NodeGraphMessage::UpdateTypes { resolved_types, node_graph_errors } => {
// Hidden passthrough nodes let a wire borrow its color and rank from an upstream node, so any type change can restyle wires whose own node is unchanged.
// Compare each displayed wire's style (color, rank) across the update and unload only those that changed, so value-only recompiles keep their built wire paths.
let types_changed = !resolved_types.add.is_empty() || !resolved_types.remove.is_empty();
let wire_style = |network_interface: &mut NodeNetworkInterface, input: &InputConnector| {
network_interface.upstream_output_connector(input, breadcrumb_network_path).map(|output| {
let output_type = network_interface.output_type(&output, breadcrumb_network_path);
(output_type.displayed_type(), output_type.is_list())
})
};
let styles_before = types_changed.then(|| {
network_interface
.node_graph_input_connectors(breadcrumb_network_path)
.into_iter()
.map(|input| {
let style = wire_style(network_interface, &input);
(input, style)
})
.collect::<Vec<_>>()
});
network_interface.resolved_types.update(resolved_types, node_graph_errors);
if let Some(styles_before) = styles_before {
for (input, style_before) in styles_before {
if wire_style(network_interface, &input) != style_before {
network_interface.unload_wire(&input, breadcrumb_network_path);
}
}
}
responses.add(NodeGraphMessage::SendGraph);
}
NodeGraphMessage::UpdateActionButtons => {
if selection_network_path == breadcrumb_network_path {
@@ -19,7 +19,7 @@ use graph_craft::{Type, concrete};
use graphene_std::Graphic;
use graphene_std::NodeInputDecleration;
use graphene_std::animation::RealTimeMode;
use graphene_std::brush::brush_stroke::BrushTrace;
use graphene_std::brush::brush_stroke::BrushStroke;
use graphene_std::color::SRGBA8;
use graphene_std::extract_xy::XY;
use graphene_std::list::List;
@@ -32,11 +32,9 @@ use graphene_std::text::{Font, TextAlign};
use graphene_std::text_nodes::StringCapitalization;
use graphene_std::transform::{Footprint, ReferencePoint, ScaleType, Transform};
use graphene_std::vector::misc::BooleanOperation;
use graphene_std::vector::misc::{
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, SpiralType,
};
use graphene_std::vector::misc::{ArcType, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, SpiralType};
use graphene_std::vector::style::{
DashPattern, FillChoiceUI, Gradient, GradientSpreadMethod, GradientType, GradientUI, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, build_transform_with_y_preservation,
FillChoice, FillChoiceUI, GradientSpreadMethod, GradientStops, GradientStopsUI, GradientType, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, build_transform_with_y_preservation,
};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
@@ -215,24 +213,6 @@ pub(crate) fn property_from_type(
let default_info = ParameterWidgetsInfo::new(node_id, index, true, context);
// A type with no widget can only be supplied through the graph, labeled with a placeholder row
let unsupported_widgets = |default_info: ParameterWidgetsInfo, type_label: String| {
let is_exposed = default_info.is_exposed();
let mut widgets = start_widgets(default_info);
if !is_exposed {
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextLabel::new("-")
.tooltip_label(type_label)
.tooltip_description("This data can only be supplied through the node graph because no widget exists for its type.")
.widget_instance(),
]);
}
vec![LayoutGroup::from(widgets)]
};
let mut extra_widgets = vec![];
let widgets = match ty {
Type::Concrete(concrete_type) => {
@@ -254,84 +234,92 @@ pub(crate) fn property_from_type(
// For all other types, use TypeId-based matching
_ => {
use std::any::TypeId;
// The compiler peels a rank-0 `Item` cell to its element before this arm runs, so widgets dispatch on the bare element `T`
fn id_is<T: 'static>(id: TypeId) -> bool {
id == TypeId::of::<T>()
}
match concrete_type.id {
// ===============
// PRIMITIVE TYPES
// ===============
Some(x) if id_is::<f64>(x) || id_is::<f32>(x) => number_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)).into(),
Some(x) if id_is::<u32>(x) => number_widget(default_info, bounded(number_input.int(), 0., f64::from(u32::MAX))).into(),
Some(x) if id_is::<u64>(x) => number_widget(default_info, bounded(number_input.int(), 0., f64::INFINITY)).into(),
Some(x) if id_is::<bool>(x) => bool_widget(default_info, CheckboxInput::default()).into(),
Some(x) if id_is::<String>(x) => text_widget(default_info).into(),
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", "", None, false),
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::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
Some(x) if id_is::<BrushTrace>(x) => brush_strokes_widget(default_info).into(),
Some(x) if x == TypeId::of::<f64>() || x == TypeId::of::<f32>() => number_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)).into(),
Some(x) if x == TypeId::of::<u32>() => number_widget(default_info, bounded(number_input.int(), 0., f64::from(u32::MAX))).into(),
Some(x) if x == TypeId::of::<u64>() => number_widget(default_info, bounded(number_input.int(), 0., f64::INFINITY)).into(),
Some(x) if x == TypeId::of::<bool>() => bool_widget(default_info, CheckboxInput::default()).into(),
Some(x) if x == TypeId::of::<String>() => text_widget(default_info).into(),
Some(x) if x == TypeId::of::<DVec2>() => vec2_widget(default_info, "X", "Y", "", None, false),
Some(x) if x == TypeId::of::<DAffine2>() => transform_widget(default_info, &mut extra_widgets),
// ==========
// LIST TYPES
// ==========
Some(x) if x == TypeId::of::<List<f64>>() => array_of_number_widget(default_info, TextInput::default()).into(),
Some(x) if x == TypeId::of::<List<Color>>() => color_widget(default_info, ColorInput::default().allow_none(true)),
Some(x) if x == TypeId::of::<List<GradientStops>>() => color_widget(default_info, ColorInput::default().allow_none(false)),
Some(x) if x == TypeId::of::<List<BrushStroke>>() => brush_strokes_widget(default_info).into(),
// ============
// STRUCT TYPES
// ============
Some(x) if id_is::<Font>(x) => font_widget(default_info),
Some(x) if id_is::<Footprint>(x) => footprint_widget(default_info, &mut extra_widgets),
Some(x) if id_is::<Box<VectorModification>>(x) => vector_modification_widget(default_info).into(),
Some(x) if id_is::<Image<Color>>(x) => image_data_widget(default_info).into(),
Some(x) if x == TypeId::of::<Font>() => font_widget(default_info),
Some(x) if x == TypeId::of::<Footprint>() => footprint_widget(default_info, &mut extra_widgets),
Some(x) if x == TypeId::of::<Box<VectorModification>>() => vector_modification_widget(default_info).into(),
Some(x) if x == TypeId::of::<Image<Color>>() => image_data_widget(default_info).into(),
// ===============================
// MANUALLY IMPLEMENTED ENUM TYPES
// ===============================
Some(x) if id_is::<ReferencePoint>(x) => reference_point_widget(default_info, false).into(),
Some(x) if id_is::<BlendMode>(x) => blend_mode_widget(default_info),
Some(x) if x == TypeId::of::<ReferencePoint>() => reference_point_widget(default_info, false).into(),
Some(x) if x == TypeId::of::<BlendMode>() => blend_mode_widget(default_info),
// =========================
// AUTO-GENERATED ENUM TYPES
// =========================
Some(x) if id_is::<GradientType>(x) => enum_choice::<GradientType>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientSpreadMethod>(x) => enum_choice::<GradientSpreadMethod>().for_socket(default_info).property_row(),
Some(x) if id_is::<RealTimeMode>(x) => enum_choice::<RealTimeMode>().for_socket(default_info).property_row(),
Some(x) if id_is::<RedGreenBlue>(x) => enum_choice::<RedGreenBlue>().for_socket(default_info).property_row(),
Some(x) if id_is::<RedGreenBlueAlpha>(x) => enum_choice::<RedGreenBlueAlpha>().for_socket(default_info).property_row(),
Some(x) if id_is::<XY>(x) => enum_choice::<XY>().for_socket(default_info).property_row(),
Some(x) if id_is::<StringCapitalization>(x) => enum_choice::<StringCapitalization>().for_socket(default_info).property_row(),
Some(x) if id_is::<NoiseType>(x) => enum_choice::<NoiseType>().for_socket(default_info).property_row(),
Some(x) if id_is::<FractalType>(x) => enum_choice::<FractalType>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<CellularDistanceFunction>(x) => enum_choice::<CellularDistanceFunction>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<CellularReturnType>(x) => enum_choice::<CellularReturnType>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<DomainWarpType>(x) => enum_choice::<DomainWarpType>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<RelativeAbsolute>(x) => enum_choice::<RelativeAbsolute>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<GridType>(x) => enum_choice::<GridType>().for_socket(default_info).property_row(),
Some(x) if id_is::<StrokeCap>(x) => enum_choice::<StrokeCap>().for_socket(default_info).property_row(),
Some(x) if id_is::<StrokeJoin>(x) => enum_choice::<StrokeJoin>().for_socket(default_info).property_row(),
Some(x) if id_is::<StrokeAlign>(x) => enum_choice::<StrokeAlign>().for_socket(default_info).property_row(),
Some(x) if id_is::<PaintOrder>(x) => enum_choice::<PaintOrder>().for_socket(default_info).property_row(),
Some(x) if id_is::<ArcType>(x) => enum_choice::<ArcType>().for_socket(default_info).property_row(),
Some(x) if id_is::<RowsOrColumns>(x) => enum_choice::<RowsOrColumns>().for_socket(default_info).property_row(),
Some(x) if id_is::<TextAlign>(x) => enum_choice::<TextAlign>().for_socket(default_info).property_row(),
Some(x) if id_is::<MergeByDistanceAlgorithm>(x) => enum_choice::<MergeByDistanceAlgorithm>().for_socket(default_info).property_row(),
Some(x) if id_is::<ExtrudeJoiningAlgorithm>(x) => enum_choice::<ExtrudeJoiningAlgorithm>().for_socket(default_info).property_row(),
Some(x) if id_is::<PointSpacingType>(x) => enum_choice::<PointSpacingType>().for_socket(default_info).property_row(),
Some(x) if id_is::<BooleanOperation>(x) => enum_choice::<BooleanOperation>().for_socket(default_info).property_row(),
Some(x) if id_is::<CentroidType>(x) => enum_choice::<CentroidType>().for_socket(default_info).property_row(),
Some(x) if id_is::<LuminanceCalculation>(x) => enum_choice::<LuminanceCalculation>().for_socket(default_info).property_row(),
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).property_row(),
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).property_row(),
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).property_row(),
Some(x) if x == TypeId::of::<GradientType>() => enum_choice::<GradientType>().for_socket(default_info).property_row(),
Some(x) if x == TypeId::of::<GradientSpreadMethod>() => enum_choice::<GradientSpreadMethod>().for_socket(default_info).property_row(),
Some(x) if x == TypeId::of::<RealTimeMode>() => enum_choice::<RealTimeMode>().for_socket(default_info).property_row(),
Some(x) if x == TypeId::of::<RedGreenBlue>() => enum_choice::<RedGreenBlue>().for_socket(default_info).property_row(),
Some(x) if x == TypeId::of::<RedGreenBlueAlpha>() => enum_choice::<RedGreenBlueAlpha>().for_socket(default_info).property_row(),
Some(x) if x == TypeId::of::<XY>() => enum_choice::<XY>().for_socket(default_info).property_row(),
Some(x) if x == TypeId::of::<StringCapitalization>() => enum_choice::<StringCapitalization>().for_socket(default_info).property_row(),
Some(x) if x == TypeId::of::<NoiseType>() => enum_choice::<NoiseType>().for_socket(default_info).property_row(),
Some(x) if x == TypeId::of::<FractalType>() => enum_choice::<FractalType>().for_socket(default_info).disabled(false).property_row(),
Some(x) if x == TypeId::of::<CellularDistanceFunction>() => enum_choice::<CellularDistanceFunction>().for_socket(default_info).disabled(false).property_row(),
Some(x) if x == TypeId::of::<CellularReturnType>() => enum_choice::<CellularReturnType>().for_socket(default_info).disabled(false).property_row(),
Some(x) if x == TypeId::of::<DomainWarpType>() => enum_choice::<DomainWarpType>().for_socket(default_info).disabled(false).property_row(),
Some(x) if x == TypeId::of::<RelativeAbsolute>() => enum_choice::<RelativeAbsolute>().for_socket(default_info).disabled(false).property_row(),
Some(x) if x == TypeId::of::<GridType>() => enum_choice::<GridType>().for_socket(default_info).property_row(),
Some(x) if x == TypeId::of::<StrokeCap>() => enum_choice::<StrokeCap>().for_socket(default_info).property_row(),
Some(x) if x == TypeId::of::<StrokeJoin>() => enum_choice::<StrokeJoin>().for_socket(default_info).property_row(),
Some(x) if x == TypeId::of::<StrokeAlign>() => enum_choice::<StrokeAlign>().for_socket(default_info).property_row(),
Some(x) if x == TypeId::of::<PaintOrder>() => enum_choice::<PaintOrder>().for_socket(default_info).property_row(),
Some(x) if x == TypeId::of::<ArcType>() => enum_choice::<ArcType>().for_socket(default_info).property_row(),
Some(x) if x == TypeId::of::<RowsOrColumns>() => enum_choice::<RowsOrColumns>().for_socket(default_info).property_row(),
Some(x) if x == TypeId::of::<TextAlign>() => enum_choice::<TextAlign>().for_socket(default_info).property_row(),
Some(x) if x == TypeId::of::<MergeByDistanceAlgorithm>() => enum_choice::<MergeByDistanceAlgorithm>().for_socket(default_info).property_row(),
Some(x) if x == TypeId::of::<ExtrudeJoiningAlgorithm>() => enum_choice::<ExtrudeJoiningAlgorithm>().for_socket(default_info).property_row(),
Some(x) if x == TypeId::of::<PointSpacingType>() => enum_choice::<PointSpacingType>().for_socket(default_info).property_row(),
Some(x) if x == TypeId::of::<BooleanOperation>() => enum_choice::<BooleanOperation>().for_socket(default_info).property_row(),
Some(x) if x == TypeId::of::<CentroidType>() => enum_choice::<CentroidType>().for_socket(default_info).property_row(),
Some(x) if x == TypeId::of::<LuminanceCalculation>() => enum_choice::<LuminanceCalculation>().for_socket(default_info).property_row(),
Some(x) if x == TypeId::of::<QRCodeErrorCorrectionLevel>() => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).property_row(),
Some(x) if x == TypeId::of::<ScaleType>() => enum_choice::<ScaleType>().for_socket(default_info).property_row(),
Some(x) if x == TypeId::of::<InterpolationDistribution>() => enum_choice::<InterpolationDistribution>().for_socket(default_info).property_row(),
// =====
// OTHER
// =====
_ => return Err(unsupported_widgets(default_info, concrete_type.to_string())),
_ => {
let is_exposed = default_info.is_exposed();
let mut widgets = start_widgets(default_info);
if !is_exposed {
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextLabel::new("-")
.tooltip_label(concrete_type.to_string())
.tooltip_description("This data can only be supplied through the node graph because no widget exists for its type.")
.widget_instance(),
]);
}
return Err(vec![widgets.into()]);
}
}
}
}
}
Type::Item(element) => return property_from_type(node_id, index, element, number_options, unit, display_decimal_places, step, context),
Type::List(element) => match element.as_ref() {
Type::Concrete(element_type) if element_type.name == std::any::type_name::<f64>() => array_of_number_widget(default_info, TextInput::default()).into(),
_ => return Err(unsupported_widgets(default_info, ty.to_string())),
},
Type::Generic(_) => vec![TextLabel::new("Generic Type (Not Supported)").widget_instance()].into(),
Type::Fn(_, out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context),
Type::Future(out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context),
@@ -866,32 +854,6 @@ pub fn array_of_number_widget(parameter_widgets_info: ParameterWidgetsInfo, text
widgets
}
pub fn dash_pattern_widget(parameter_widgets_info: ParameterWidgetsInfo, text_input: TextInput) -> Vec<WidgetInstance> {
let ParameterWidgetsInfo { document_node, node_id, index, .. } = parameter_widgets_info;
let mut widgets = start_widgets(parameter_widgets_info);
let Some(document_node) = document_node else { return Vec::new() };
let Some(input) = document_node.inputs.get(index) else {
log::warn!("A widget failed to be built because its node's input index is invalid.");
return vec![];
};
if let Some(TaggedValue::DashPattern(pattern)) = &input.as_non_exposed_value() {
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
text_input
.value(pattern.0.iter_element_values().map(|length| length.to_string()).collect::<Vec<_>>().join(", "))
.on_update(optionally_update_value(
move |input: &TextInput| Some(TaggedValue::DashPattern(DashPattern::from(input.value.as_str()))),
node_id,
index,
))
.widget_instance(),
])
}
widgets
}
pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetInstance>, Option<Vec<WidgetInstance>>) {
pub fn assign_font_message(node_id: NodeId, font: Font) -> Message {
let resource_id = ResourceId::new();
@@ -1204,37 +1166,30 @@ pub fn color_widget(parameter_widgets_info: ParameterWidgetsInfo, color_button:
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
// Add the color input
let widget_value = match &**tagged_value {
TaggedValue::Color(color) => FillChoiceUI::Solid(SRGBA8::from(*color)),
TaggedValue::Gradient(stops) => FillChoiceUI::Gradient(GradientUI::from(stops)),
value if value.is_no_paint() => FillChoiceUI::None,
x => {
warn!("Color {x:?}");
return LayoutGroup::row(widgets);
}
};
// A paint input (`allow_none`) stores the pick as a plain color, gradient, or no-paint type default,
// while a plain color or gradient input always keeps its own value type
let on_update: fn(&ColorInput) -> TaggedValue = if color_button.allow_none {
|input| match &input.value {
FillChoiceUI::None => TaggedValue::no_paint(),
FillChoiceUI::Solid(srgba) => TaggedValue::Color(Color::from(*srgba)),
FillChoiceUI::Gradient(gradient_ui) => TaggedValue::Gradient(Gradient::from(gradient_ui)),
}
} else if matches!(&**tagged_value, TaggedValue::Gradient(_)) {
|input| TaggedValue::Gradient(input.value.as_gradient().map(Gradient::from).unwrap_or_default())
} else {
|input| TaggedValue::Color(input.value.as_solid().map(Color::from).unwrap_or(Color::TRANSPARENT))
};
widgets.push(
color_button
.value(widget_value)
.on_update(update_value(on_update, node_id, index))
.on_commit(commit_value)
.widget_instance(),
);
match &**tagged_value {
TaggedValue::Color(color) => widgets.push(
color_button
.value(FillChoiceUI::from(&match color {
Some(color) => FillChoice::Solid(*color),
None => FillChoice::None,
}))
.on_update(update_value(|input: &ColorInput| TaggedValue::Color(input.value.as_solid().map(Color::from)), node_id, index))
.on_commit(commit_value)
.widget_instance(),
),
TaggedValue::Gradient(stops) => widgets.push(
color_button
.value(FillChoiceUI::from(&FillChoice::Gradient(stops.clone())))
.on_update(update_value(
|input: &ColorInput| TaggedValue::Gradient(input.value.as_gradient().map(GradientStops::from).unwrap_or_default()),
node_id,
index,
))
.on_commit(commit_value)
.widget_instance(),
),
x => warn!("Color {x:?}"),
}
LayoutGroup::row(widgets)
}
@@ -1303,8 +1258,8 @@ pub fn query_assign_colors_randomize(node_id: NodeId, context: &NodePropertiesCo
}
/// 2-stop black-to-white gradient track for spectrum sliders that map a value to a grayscale axis.
fn bw_track() -> Gradient {
Gradient {
fn bw_track() -> GradientStops {
GradientStops {
position: vec![0., 1.],
midpoint: vec![0.5, 0.5],
color: vec![Color::BLACK, Color::WHITE],
@@ -1312,8 +1267,8 @@ fn bw_track() -> Gradient {
}
/// 3-stop black-to-color-to-white gradient track for spectrum sliders that map a value to a hue's full luminance range.
fn color_track(color: Color) -> Gradient {
Gradient {
fn color_track(color: Color) -> GradientStops {
GradientStops {
position: vec![0., 0.5, 1.],
midpoint: vec![0.5; 3],
color: vec![Color::BLACK, color, Color::WHITE],
@@ -1348,7 +1303,7 @@ pub(crate) fn brightness_contrast_properties(node_id: NodeId, context: &mut Node
let contrast_min = if use_classic_value { -100. } else { -50. };
let zero_position = -contrast_min / (100. - contrast_min);
let contrast_track = Gradient {
let contrast_track = GradientStops {
position: vec![0., zero_position, 1.],
midpoint: vec![0.5; 3],
color: vec![Color::from_rgbf32_unchecked(0.5, 0.5, 0.5), Color::BLACK, Color::from_rgbf32_unchecked(0.5, 0.5, 0.5)],
@@ -1445,7 +1400,7 @@ fn build_shared_spectrum_section(node_id: NodeId, context: &mut NodePropertiesCo
// Build the shared spectrum widget (placed on the first non-exposed row)
let spectrum_widget = (!spectrum_markers.is_empty()).then(|| {
SpectrumInput::new(GradientUI::from(&bw_track()))
SpectrumInput::new(GradientStopsUI::from(&bw_track()))
.markers(spectrum_markers)
.show_midpoints(false)
.allow_insert(false)
@@ -1538,13 +1493,13 @@ pub(crate) fn hue_saturation_properties(node_id: NodeId, context: &mut NodePrope
let saturated_current_hue = Color::from_hsva(marker_hue, 1., 1., 1.);
// Hue: cyclic rainbow
let hue_track = Gradient {
let hue_track = GradientStops {
position: vec![0., 1. / 6., 2. / 6., 3. / 6., 4. / 6., 5. / 6., 1.],
midpoint: vec![0.5; 7],
color: vec![Color::RED, Color::YELLOW, Color::GREEN, Color::CYAN, Color::BLUE, Color::MAGENTA, Color::RED],
};
// Saturation: gray to the fully saturated current hue
let saturation_track = Gradient {
let saturation_track = GradientStops {
position: vec![0., 1.],
midpoint: vec![0.5, 0.5],
color: vec![Color::from_rgbf32_unchecked(0.5, 0.5, 0.5), saturated_current_hue],
@@ -1594,7 +1549,7 @@ fn spectrum_slider_row(
node_id: NodeId,
context: &mut NodePropertiesContext,
input_index: usize,
track: Gradient,
track: GradientStops,
handle_color: Color,
value_min: f64,
value_max: f64,
@@ -1619,7 +1574,7 @@ fn spectrum_slider_row(
let position_to_value = move |position: f64| value_min + position * value_range;
row.push(
SpectrumInput::new(GradientUI::from(&track))
SpectrumInput::new(GradientStopsUI::from(&track))
.markers(vec![SpectrumMarker::new(position, 0.5, handle_color)])
.show_midpoints(false)
.allow_insert(false)
@@ -1679,7 +1634,7 @@ pub(crate) fn threshold_properties(node_id: NodeId, context: &mut NodeProperties
pub(crate) fn vibrance_properties(node_id: NodeId, context: &mut NodePropertiesContext) -> Vec<LayoutGroup> {
use graphene_std::raster::vibrance::*;
let track = Gradient {
let track = GradientStops {
position: vec![0., 1.],
midpoint: vec![0.5, 0.5],
color: vec![Color::from_rgbf32_unchecked(0.5, 0.5, 0.5), Color::RED],
@@ -2212,7 +2167,7 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
use graphene_std::vector::generator_nodes::rectangle::*;
// Corner Radius
let mut corner_radius_row_1 = start_widgets(ParameterWidgetsInfo::new(node_id, CornerRadiusInput::INDEX, true, context));
let mut corner_radius_row_1 = start_widgets(ParameterWidgetsInfo::new(node_id, CornerRadiusInput::<f64>::INDEX, true, context));
corner_radius_row_1.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
let mut corner_radius_row_2 = vec![Separator::new(SeparatorStyle::Unrelated).widget_instance()];
@@ -2232,15 +2187,20 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
};
if let Some(&TaggedValue::Bool(is_individual)) = input.as_non_exposed_value() {
// Values
let Some(input) = document_node.inputs.get(CornerRadiusInput::INDEX) else {
let Some(input) = document_node.inputs.get(CornerRadiusInput::<f64>::INDEX) else {
log::warn!("A widget failed to be built because its node's input index is invalid.");
return vec![];
};
let corner_values = match input.as_non_exposed_value() {
Some(TaggedValue::BoxCorners(corners)) => corners.to_corner_values(),
_ => [0.; 4],
let uniform_val = match input.as_non_exposed_value() {
Some(TaggedValue::F64(x)) => *x,
Some(TaggedValue::F64Array(values)) => values.first().copied().unwrap_or(0.),
_ => 0.,
};
let individual_val = match input.as_non_exposed_value() {
Some(&TaggedValue::F64(x)) => vec![x; 4],
Some(TaggedValue::F64Array(values)) => values.clone(),
_ => vec![0.; 4],
};
let uniform_val = corner_values[0];
// Uniform/individual radio input widget
let uniform = RadioEntryData::new("Uniform")
@@ -2255,13 +2215,14 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: CornerRadiusInput::INDEX,
value: TaggedValue::BoxCorners(BoxCorners::from(uniform_val)),
input_index: CornerRadiusInput::<f64>::INDEX,
value: TaggedValue::F64(uniform_val),
}
.into(),
]),
})
.on_commit(commit_value);
let individual_val_for_switch = individual_val.clone();
let individual = RadioEntryData::new("Individual")
.label("Individual")
.on_update(move |_| Message::Batched {
@@ -2274,8 +2235,8 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: CornerRadiusInput::INDEX,
value: TaggedValue::BoxCorners(BoxCorners::from(corner_values.to_vec())),
input_index: CornerRadiusInput::<f64>::INDEX,
value: TaggedValue::F64Array(individual_val_for_switch.clone()),
}
.into(),
]),
@@ -2286,23 +2247,24 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
// Radius value input widget
let input_widget = if is_individual {
let from_string = |string: &str| {
string
.split(&[',', ' '])
.filter(|x| !x.is_empty())
.map(str::parse::<f64>)
.collect::<Result<Vec<f64>, _>>()
.ok()
.map(|values| TaggedValue::F64Array(values.into_iter().take(4).collect()))
};
TextInput::default()
.value(corner_values.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(", "))
.on_update(optionally_update_value(
move |x: &TextInput| Some(TaggedValue::BoxCorners(BoxCorners::from(x.value.as_str()))),
node_id,
CornerRadiusInput::INDEX,
))
.value(individual_val.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(", "))
.on_update(optionally_update_value(move |x: &TextInput| from_string(&x.value), node_id, CornerRadiusInput::<f64>::INDEX))
.widget_instance()
} else {
NumberInput::default()
.value(Some(uniform_val))
.unit(" px")
.on_update(update_value(
move |x: &NumberInput| TaggedValue::BoxCorners(BoxCorners::from(x.value.unwrap())),
node_id,
CornerRadiusInput::INDEX,
))
.on_update(update_value(move |x: &NumberInput| TaggedValue::F64(x.value.unwrap()), node_id, CornerRadiusInput::<f64>::INDEX))
.on_commit(commit_value)
.widget_instance()
};
@@ -2371,14 +2333,10 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
let mut unit_suffix = None;
let input_type = match implementation {
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => 'early_return: {
// Clone to end the `network_interface` borrow held via `implementation`, freeing the mutable borrow `input_type` needs below
let proto_node_identifier = proto_node_identifier.clone();
let mut default_type = None;
if let Some(field) = graphene_std::registry::NODE_METADATA
.lock()
.unwrap()
.get(&proto_node_identifier)
.get(proto_node_identifier)
.and_then(|metadata| metadata.fields.get(input_index))
{
number_options = NumberOptions {
@@ -2391,14 +2349,12 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
display_decimal_places = field.number_display_decimal_places;
unit_suffix = field.unit;
step = field.number_step;
default_type = field.default_type.clone();
if let Some(ref default) = field.default_type {
break 'early_return default.clone();
}
}
if let Some(default) = default_type {
break 'early_return default;
}
let Some(implementations) = &interpreted_executor::node_registry::NODE_REGISTRY.get(&proto_node_identifier) else {
let Some(implementations) = &interpreted_executor::node_registry::NODE_REGISTRY.get(proto_node_identifier) else {
log::error!("Could not get implementation for protonode {proto_node_identifier:?}");
return Vec::new();
};
@@ -2486,7 +2442,7 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
enum ResolvedFill {
Solid(Option<Color>),
Gradient {
gradient: Gradient,
gradient: GradientStops,
gradient_type: GradientType,
spread_method: GradientSpreadMethod,
transform: DAffine2,
@@ -2496,6 +2452,9 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
Other,
}
let connector = InputConnector::node(node_id, FillInput::<List<Graphic>>::INDEX);
let input_type = context.network_interface.input_type(&connector, context.selection_network_path);
// Pass blank_assist=false because the assist slot is filled below ("Reverse Stops" button when in gradient mode)
let mut widgets_first_row = start_widgets(ParameterWidgetsInfo::new(node_id, FillInput::<List<Graphic>>::INDEX, false, context));
@@ -2507,42 +2466,51 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
// bounding-box default transform needs the layer, and it falls back to a unit box when there isn't one.
let layer = root_layer_for_chain_node(node_id, context);
let fill = match get_document_node(node_id, context) {
Ok(document_node) => match document_node.inputs[FillInput::<List<Graphic>>::INDEX].as_value() {
Some(TaggedValue::Color(color)) => ResolvedFill::Solid(Some(*color)),
Some(value) if value.is_no_paint() => ResolvedFill::Solid(None),
Some(TaggedValue::Gradient(_)) => {
match graph_modification_utils::read_fill_node_gradient(document_node, || {
let fill = match input_type.compiled_nested_type() {
Some(ty) if ty == &concrete!(List<Color>) => {
if let Ok(document_node) = get_document_node(node_id, context) {
let color = match document_node.inputs[FillInput::<List<Graphic>>::INDEX].as_value() {
Some(&TaggedValue::Color(c)) => c,
_ => None,
};
ResolvedFill::Solid(color)
} else {
ResolvedFill::Other
}
}
Some(ty) if ty == &concrete!(List<GradientStops>) => {
// Read this node's own inputs rather than the layer's nearest Fill, which may be a different node when Fills are chained
if let Ok(document_node) = get_document_node(node_id, context)
&& let Some(gradient) = graph_modification_utils::read_fill_node_gradient(document_node, || {
layer.map_or([DVec2::ZERO, DVec2::ONE], |layer| context.network_interface.document_metadata().nonzero_bounding_box(layer))
}) {
Some(gradient) => ResolvedFill::Gradient {
gradient: gradient.stops,
gradient_type: gradient.gradient_type,
spread_method: gradient.spread_method,
transform: gradient.transform,
transform_is_value: gradient.transform_is_value,
},
None => ResolvedFill::Other,
ResolvedFill::Gradient {
gradient: gradient.stops,
gradient_type: gradient.gradient_type,
spread_method: gradient.spread_method,
transform: gradient.transform,
transform_is_value: gradient.transform_is_value,
}
} else {
ResolvedFill::Other
}
_ => ResolvedFill::Other,
},
Err(_) => ResolvedFill::Other,
}
_ => ResolvedFill::Other,
};
let (backup_color, backup_gradient) = match get_document_node(node_id, context) {
Ok(document_node) => {
let backup_color = match document_node.inputs[BackupColorInput::INDEX].as_value() {
Some(&TaggedValue::Color(color)) => Some(color),
Some(&TaggedValue::Color(color)) => color,
_ => None,
};
let backup_stops = match document_node.inputs[BackupGradientInput::INDEX].as_value() {
Some(TaggedValue::Gradient(stops)) => stops.clone(),
_ => Gradient::default(),
_ => GradientStops::default(),
};
(backup_color, backup_stops)
}
Err(_) => (None, Gradient::default()),
Err(_) => (None, GradientStops::default()),
};
match &fill {
@@ -2568,33 +2536,28 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
FillChoiceUI::None
}
}
ResolvedFill::Gradient { gradient: stops, .. } => FillChoiceUI::Gradient(GradientUI::from(stops)),
ResolvedFill::Gradient { gradient: stops, .. } => FillChoiceUI::Gradient(GradientStopsUI::from(stops)),
ResolvedFill::Other => FillChoiceUI::None,
};
let solid_set_messages = move |color: Option<Color>| {
let mut messages = vec![
let solid_set_messages = move |color: Option<Color>| Message::Batched {
messages: Box::new([
NodeGraphMessage::SetInputValue {
node_id,
input_index: FillInput::<List<Graphic>>::INDEX,
value: color.map_or_else(TaggedValue::no_paint, TaggedValue::Color),
value: TaggedValue::Color(color),
}
.into(),
];
if let Some(color) = color {
messages.push(
NodeGraphMessage::SetInputValue {
node_id,
input_index: BackupColorInput::INDEX,
value: TaggedValue::Color(color),
}
.into(),
);
}
Message::Batched { messages: messages.into() }
NodeGraphMessage::SetInputValue {
node_id,
input_index: BackupColorInput::INDEX,
value: TaggedValue::Color(color),
}
.into(),
]),
};
let gradient_set_messages = move |gradient: Gradient| Message::Batched {
let gradient_set_messages = move |gradient: GradientStops| Message::Batched {
messages: Box::new([
NodeGraphMessage::SetInputValue {
node_id,
@@ -2622,7 +2585,7 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
solid_set_messages(color)
}
FillChoiceUI::Gradient(gradient_stops_ui) => {
let gradient = Gradient::from(gradient_stops_ui);
let gradient = GradientStops::from(gradient_stops_ui);
gradient_set_messages(gradient)
}
})
@@ -2639,11 +2602,7 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
let entries = vec![
RadioEntryData::new("solid")
.label("Solid")
.on_update(update_value(
move |_| backup_color.map_or_else(TaggedValue::no_paint, TaggedValue::Color),
node_id,
FillInput::<List<Graphic>>::INDEX,
))
.on_update(update_value(move |_| TaggedValue::Color(backup_color), node_id, FillInput::<List<Graphic>>::INDEX))
.on_commit(commit_value),
RadioEntryData::new("gradient")
.label("Gradient")
@@ -2709,22 +2668,7 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
} else {
"Swap the start and end points of the gradient line."
})
.on_update(move |_| Message::Batched {
messages: Box::new([
NodeGraphMessage::SetInputValue {
node_id,
input_index: HasTransformInput::INDEX,
value: TaggedValue::Bool(true),
}
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: TransformInput::INDEX,
value: TaggedValue::DAffine2(new_transform),
}
.into(),
]),
})
.on_update(update_value(move |_| TaggedValue::OptionalDAffine2(Some(new_transform)), node_id, TransformInput::INDEX))
.widget_instance();
spread_methods_row.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
spread_methods_row.push(reverse_direction_button);
@@ -2768,8 +2712,8 @@ pub fn stroke_properties(node_id: NodeId, context: &mut NodePropertiesContext) -
_ => &StrokeJoin::Miter,
};
let has_dash_lengths = match &document_node.inputs[DashPatternInput::INDEX].as_value() {
Some(TaggedValue::DashPattern(pattern)) => pattern.0.is_empty(),
let has_dash_lengths = match &document_node.inputs[DashLengthsInput::<List<f64>>::INDEX].as_value() {
Some(TaggedValue::F64Array(values)) => values.is_empty(),
_ => true,
};
let miter_limit_disabled = join_value != &StrokeJoin::Miter;
@@ -2795,7 +2739,10 @@ pub fn stroke_properties(node_id: NodeId, context: &mut NodePropertiesContext) -
.for_socket(ParameterWidgetsInfo::new(node_id, PaintOrderInput::INDEX, true, context))
.property_row();
let disabled_number_input = NumberInput::default().unit(" px").disabled(has_dash_lengths);
let dash_lengths = dash_pattern_widget(ParameterWidgetsInfo::new(node_id, DashPatternInput::INDEX, true, context), TextInput::default().centered(true));
let dash_lengths = array_of_number_widget(
ParameterWidgetsInfo::new(node_id, DashLengthsInput::<List<f64>>::INDEX, true, context),
TextInput::default().centered(true),
);
let number_input = disabled_number_input;
let dash_offset = number_widget(ParameterWidgetsInfo::new(node_id, DashOffsetInput::INDEX, true, context), number_input);
@@ -1,5 +1,10 @@
use graph_craft::document::NodeId;
use graphene_std::{Type, simplify_identifier_name};
use graph_craft::document::value::TaggedValue;
use graphene_std::Type;
use graphene_std::list::List;
use graphene_std::raster_types::{CPU, Raster};
use graphene_std::vector::Vector;
use graphene_std::{Artboard, Graphic};
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
@@ -19,22 +24,20 @@ pub enum FrontendGraphDataType {
impl FrontendGraphDataType {
pub fn from_type(input: &Type) -> Self {
// Color a wire by its element type, peeling a rank-0 `Item` or rank-1 `List` wrapper (and a whole-list `Bundle` cell) so all ranks share the element's color
let nested_type = input.nested_type();
let element = match nested_type.bundle_element_name() {
Some(bundle_element) => simplify_identifier_name(bundle_element),
None => nested_type.list_element().unwrap_or(nested_type).identifier_name(),
};
match element.as_str() {
"Vector" => Self::Vector,
"Graphic" => Self::Graphic,
"Artboard" => Self::Artboard,
"Color" => Self::Color,
"Gradient" => Self::Gradient,
"String" => Self::Typography,
"f64" | "f32" | "u32" | "u64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
raster if raster.starts_with("Raster") => Self::Raster,
match TaggedValue::from_type_or_none(input) {
TaggedValue::U32(_) | TaggedValue::U64(_) | TaggedValue::F32(_) | TaggedValue::F64(_) | TaggedValue::DVec2(_) | TaggedValue::F64Array(_) | TaggedValue::DAffine2(_) => Self::Number,
TaggedValue::Color(_) => Self::Color,
TaggedValue::LegacyGradient(_) | TaggedValue::Gradient(_) => Self::Gradient,
TaggedValue::String(_) => Self::Typography,
// Types whose `TaggedValue` variant has been removed are routed through `TypeDefault` and identified by the descriptor's type name.
TaggedValue::TypeDefault(td) => match td.name.as_ref() {
n if n == std::any::type_name::<List<Graphic>>() => Self::Graphic,
n if n == std::any::type_name::<List<Artboard>>() => Self::Artboard,
n if n == std::any::type_name::<List<Raster<CPU>>>() => Self::Raster,
n if n == std::any::type_name::<List<Vector>>() => Self::Vector,
n if n == std::any::type_name::<List<String>>() => Self::Typography,
_ => Self::General,
},
_ => Self::General,
}
}
@@ -708,103 +708,3 @@ async fn demo_artwork_edit_autosaves_and_round_trips() {
// Autosaving the undone state still round-trips cleanly (no drift panic).
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
}
/// The document's single Fill node, as `(network_path, node_id)`.
fn find_fill_node(document: &DocumentMessageHandler) -> (Vec<graph_craft::document::NodeId>, graph_craft::document::NodeId) {
node_paths(&document.network_interface)
.into_iter()
.find(|(network_path, node_id)| {
let Some(network) = document.network_interface.nested_network(network_path) else { return false };
network.nodes[node_id].implementation == graph_craft::document::DocumentNodeImplementation::ProtoNode(graphene_std::vector_nodes::fill::IDENTIFIER)
})
.expect("the document should contain a Fill node")
}
/// The stored paint value of the document's single Fill node.
fn fill_paint_value(document: &DocumentMessageHandler) -> graph_craft::document::value::TaggedValue {
use graphene_std::NodeInputDecleration as _;
let (network_path, node_id) = find_fill_node(document);
let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve");
let input = network.nodes[&node_id]
.inputs
.get(graphene_std::vector::fill::FillInput::<graphene_std::list::List<graphene_std::Graphic>>::INDEX)
.expect("Fill should have a paint input");
input.as_value().expect("the paint input should hold a value").clone()
}
#[tokio::test]
async fn none_fill_survives_document_reopen() {
use graphene_std::NodeInputDecleration as _;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await;
// Pick the red-slash "none" paint, stored the same way as the Fill widget's None choice
let (_, fill_node_id) = find_fill_node(editor.active_document());
editor
.handle_message(NodeGraphMessage::SetInputValue {
node_id: fill_node_id,
input_index: graphene_std::vector::fill::FillInput::<graphene_std::list::List<graphene_std::Graphic>>::INDEX,
value: graph_craft::document::value::TaggedValue::no_paint(),
})
.await;
assert!(fill_paint_value(editor.active_document()).is_no_paint(), "the None pick should store as no_paint");
// Reopen through the editor's real open path, which runs the document migrations
let serialized = editor.active_document().serialize_document();
editor
.handle_message(PortfolioMessage::OpenDocumentFile {
document_name: None,
document_path: None,
document_serialized_content: serialized,
})
.await;
let reopened_paint = fill_paint_value(editor.active_document());
assert!(reopened_paint.is_no_paint(), "a none fill should survive reopening, but the stored paint became {reopened_paint:?}");
}
#[tokio::test]
async fn legacy_four_input_fill_migrates_to_the_split_transform_shape() {
use graph_craft::document::value::TaggedValue;
use graphene_std::NodeInputDecleration as _;
// A minimal master-era document: a 4-input Fill (content, fill: wired, backup color, backup gradient) fed by another node
const LEGACY_DOCUMENT: &str = r#"{"network_interface":{"network":{"exports":[{"Node":{"node_id":1,"output_index":0,"lambda":false}}],"nodes":[[1,{"inputs":[{"Value":{"tagged_value":{"GraphicGroup":{"instance":[],"transform":[],"alpha_blending":[],"source_node_id":[]}},"exposed":true}},{"Node":{"node_id":2,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"OptionalColor":null},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"stops":[[0.0,{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0}],[1.0,{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0}]],"gradient_type":"Linear","start":[0.0,0.5],"end":[1.0,0.5],"transform":[1.0,0.0,0.0,1.0,0.0,0.0]}},"exposed":false}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"GradientStops":[[0.0,{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0}],[1.0,{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0}]]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::ops::SampleGradientNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]},"network_metadata":{"persistent_metadata":{"node_metadata":[[1,{"persistent_metadata":{"reference":"Fill","display_name":"","input_properties":[{"input_data":{"input_name":"Vector Data"},"widget_override":null},{"input_data":{"input_name":"Fill"},"widget_override":null},{"input_data":{"input_name":"Backup Color"},"widget_override":null},{"input_data":{"input_name":"Backup Gradient"},"widget_override":null}],"output_names":["Future<Instances<VectorData>>"],"has_primary_output":true,"locked":false,"pinned":false,"node_type_metadata":{"Node":{"position":{"Absolute":[0,0]}}},"network_metadata":null}}],[2,{"persistent_metadata":{"reference":"Sample Gradient","display_name":"","input_properties":[{"input_data":{"input_name":"Primary"},"widget_override":null},{"input_data":{"input_name":"Gradient"},"widget_override":null},{"input_data":{"input_name":"Position"},"widget_override":null}],"output_names":["Future<Color>"],"has_primary_output":true,"locked":false,"pinned":false,"node_type_metadata":{"Node":{"position":{"Absolute":[-20,0]}}},"network_metadata":null}}]],"previewing":"No","navigation_metadata":{"node_graph_ptz":{"pan":[0.0,0.0],"tilt":0.0,"zoom":1.0,"flip":false},"node_graph_to_viewport":[1.0,0.0,0.0,1.0,0.0,0.0],"node_graph_top_right":[0.0,0.0]},"selection_undo_history":[],"selection_redo_history":[]}}},"collapsed":[],"name":"legacy_fill.graphite","commit_hash":"0000000000000000000000000000000000000000","document_ptz":{"pan":[0.0,0.0],"tilt":0.0,"zoom":1.0,"flip":false},"document_mode":"DesignMode","view_mode":"Normal","overlays_visibility_settings":{"all":true,"artboard_name":true,"compass_rose":true,"quick_measurement":true,"transform_measurement":true,"transform_cage":true,"hover_outline":true,"selection_outline":true,"pivot":true,"path":true,"anchors":true,"handles":true},"rulers_visible":true,"snapping_state":{"snapping_enabled":true,"grid_snapping":false,"artboards":true,"tolerance":8.0,"bounding_box":{"center_point":true,"corner_point":true,"edge_midpoint":true,"align_with_edges":true,"distribute_evenly":true},"path":{"anchor_point":true,"line_midpoint":true,"along_path":true,"normal_to_path":true,"tangent_to_path":true,"path_intersection_point":true,"align_with_anchor_point":true,"perpendicular_from_endpoint":true},"grid":{"origin":[0.0,0.0],"grid_type":{"Rectangular":{"spacing":[1.0,1.0]}},"grid_color":{"red":0.6,"green":0.6,"blue":0.6,"alpha":1.0},"dot_display":false}},"graph_view_overlay_open":false,"graph_fade_artwork_percentage":80.0}"#;
// Deserializing alone must succeed, so a failure below is attributable to the migrations
DocumentMessageHandler::deserialize_document(LEGACY_DOCUMENT).expect("the legacy document should deserialize");
let mut editor = EditorTestUtils::create();
editor
.handle_message(PortfolioMessage::OpenDocumentFile {
document_name: None,
document_path: None,
document_serialized_content: LEGACY_DOCUMENT.to_string(),
})
.await;
let document = editor.active_document();
let (network_path, node_id) = find_fill_node(document);
let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve");
let inputs = &network.nodes[&node_id].inputs;
assert_eq!(inputs.len(), 8, "the legacy Fill should upgrade to the 8-input shape");
let paint = &inputs[graphene_std::vector::fill::FillInput::<graphene_std::list::List<graphene_std::Graphic>>::INDEX];
assert!(
matches!(paint, graph_craft::document::NodeInput::Node { .. }),
"the wired legacy fill should keep its connection, but became {paint:?}"
);
let has_transform = inputs[graphene_std::vector::fill::HasTransformInput::INDEX].as_value();
assert!(
matches!(has_transform, Some(TaggedValue::Bool(_))),
"the has-transform input should hold a bool, but became {has_transform:?}"
);
let transform = inputs[graphene_std::vector::fill::TransformInput::INDEX].as_value();
assert!(
matches!(transform, Some(TaggedValue::DAffine2(_))),
"the transform input should hold a matrix, but became {transform:?}"
);
}
@@ -15,7 +15,7 @@ use crate::messages::portfolio::document::node_graph::document_node_definitions:
use crate::messages::portfolio::document::node_graph::utility_types::{Direction, FrontendClickTargets, FrontendGraphDataType, FrontendGraphInput, FrontendGraphOutput};
use crate::messages::portfolio::document::overlays::utility_functions::text_width;
use crate::messages::portfolio::document::utility_types::network_interface::resolved_types::ResolvedDocumentNodeTypes;
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_thick_wire_center_line, build_vector_wire};
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_vector_wire};
use crate::messages::tool::common_functionality::graph_modification_utils;
use crate::messages::tool::tool_messages::tool_prelude::NumberInputMode;
use deserialization::deserialize_node_persistent_metadata;
@@ -2499,20 +2499,14 @@ impl NodeNetworkInterface {
let vertical_start: bool = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path));
let thick = vertical_end && vertical_start;
let vector_wire = build_vector_wire(output_position, input_position, vertical_start, vertical_end, graph_wire_style);
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end);
let path_string = vector_wire.to_svg();
let center_path_string = center_line.to_svg();
let input_type = self.input_type(&input, network_path);
let data_type = input_type.displayed_type();
let is_list = input_type.is_list();
let data_type = self.input_type(&input, network_path).displayed_type();
let wire_path_update = Some(WirePath {
path_string,
data_type,
thick,
dashed: false,
is_list,
center_path_string,
});
Some(WirePathUpdate {
@@ -2522,15 +2516,15 @@ impl NodeNetworkInterface {
})
}
/// Returns the wire subpath, its thick center-line subpath, and whether the wire should be thick.
pub fn vector_wire_from_input(&mut self, input: &InputConnector, wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option<(BezPath, BezPath, bool)> {
/// Returns the vector subpath and a boolean of whether the wire should be thick.
pub fn vector_wire_from_input(&mut self, input: &InputConnector, wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option<(BezPath, bool)> {
let Some(input_position) = self.get_input_center(input, network_path) else {
log::error!("Could not get dom rect for wire end: {input:?}");
return None;
};
// An upstream output could not be found, so the wire does not exist, but it should still be loaded as as empty vector
let Some(upstream_output) = self.upstream_output_connector(input, network_path) else {
return Some((BezPath::new(), BezPath::new(), false));
return Some((BezPath::new(), false));
};
let Some(output_position) = self.get_output_center(&upstream_output, network_path) else {
log::error!("Could not get output port for wire start: {:?}", upstream_output);
@@ -2539,29 +2533,21 @@ impl NodeNetworkInterface {
let vertical_end = input.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path) && input.input_index() == 0);
let vertical_start = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path));
let thick = vertical_end && vertical_start;
let vector_wire = build_vector_wire(output_position, input_position, vertical_start, vertical_end, wire_style);
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end);
Some((vector_wire, center_line, thick))
Some((build_vector_wire(output_position, input_position, vertical_start, vertical_end, wire_style), thick))
}
pub fn wire_path_from_input(&mut self, input: &InputConnector, graph_wire_style: GraphWireStyle, dashed: bool, network_path: &[NodeId]) -> Option<WirePath> {
let (vector_wire, center_line, thick) = self.vector_wire_from_input(input, graph_wire_style, network_path)?;
let (vector_wire, thick) = self.vector_wire_from_input(input, graph_wire_style, network_path)?;
let path_string = vector_wire.to_svg();
let center_path_string = center_line.to_svg();
let (data_type, is_list) = self
let data_type = self
.upstream_output_connector(input, network_path)
.map(|output| {
let output_type = self.output_type(&output, network_path);
(output_type.displayed_type(), output_type.is_list())
})
.unwrap_or((FrontendGraphDataType::General, false));
.map(|output| self.output_type(&output, network_path).displayed_type())
.unwrap_or(FrontendGraphDataType::General);
Some(WirePath {
path_string,
data_type,
thick,
dashed,
is_list,
center_path_string,
})
}
@@ -6119,19 +6105,6 @@ impl NodeNetworkInterface {
// Chain is empty: wire the node as the first (and only) entry in the chain
if matches!(current_input, NodeInput::Value { .. }) {
// A node whose exposed primary defaults to no value inherits the layer's content value, so the chain keeps producing the layer's content type
let node_primary = InputConnector::node(*node_id, 0);
let default_is_valueless = self
.input_from_connector(&node_primary, network_path)
.is_some_and(|input| matches!(input, NodeInput::Value { tagged_value, exposed: true } if matches!(**tagged_value, TaggedValue::None)));
if default_is_valueless {
if import {
self.set_input_for_import(&node_primary, current_input.clone(), network_path);
} else {
self.set_input(&node_primary, current_input.clone(), network_path);
}
}
// Wire: [parent] -> [new node]
if import {
self.set_input_for_import(&parent_input, NodeInput::node(*node_id, 0), network_path);
@@ -4,7 +4,11 @@ use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNodeImplementation, InlineRust, NodeInput};
use graph_craft::proto::{GraphErrorType, GraphErrors};
use graph_craft::{Type, concrete};
use graphene_std::list::List;
use graphene_std::raster_types::{CPU, Raster};
use graphene_std::uuid::NodeId;
use graphene_std::vector::Vector;
use graphene_std::{Artboard, Graphic};
use interpreted_executor::dynamic_executor::{NodeTypes, ResolvedDocumentNodeTypesDelta};
use interpreted_executor::node_registry::NODE_REGISTRY;
@@ -52,28 +56,28 @@ impl TypeSource {
return FrontendGraphDataType::Invalid;
};
match self.compiled_nested_type() {
Some(nested_type) => FrontendGraphDataType::from_type(nested_type),
Some(nested_type) => match TaggedValue::from_type_or_none(nested_type) {
TaggedValue::U32(_) | TaggedValue::U64(_) | TaggedValue::F32(_) | TaggedValue::F64(_) | TaggedValue::DVec2(_) | TaggedValue::F64Array(_) | TaggedValue::DAffine2(_) => {
FrontendGraphDataType::Number
}
TaggedValue::Color(_) => FrontendGraphDataType::Color,
TaggedValue::LegacyGradient(_) | TaggedValue::Gradient(_) => FrontendGraphDataType::Gradient,
TaggedValue::String(_) => FrontendGraphDataType::Typography,
// Types whose `TaggedValue` variant has been removed are routed through `TypeDefault` and identified by the descriptor's type name.
TaggedValue::TypeDefault(td) => match td.name.as_ref() {
n if n == std::any::type_name::<List<Graphic>>() => FrontendGraphDataType::Graphic,
n if n == std::any::type_name::<List<Artboard>>() => FrontendGraphDataType::Artboard,
n if n == std::any::type_name::<List<Raster<CPU>>>() => FrontendGraphDataType::Raster,
n if n == std::any::type_name::<List<Vector>>() => FrontendGraphDataType::Vector,
n if n == std::any::type_name::<List<String>>() => FrontendGraphDataType::Typography,
_ => FrontendGraphDataType::General,
},
_ => FrontendGraphDataType::General,
},
None => FrontendGraphDataType::General,
}
}
/// Whether the compiled type is a rank-1 `List<T>`, as opposed to a rank-0 `Item<T>` or a bare value.
/// A bundled cell carrying a whole list displays as the list it carries.
pub fn is_list(&self) -> bool {
self.compiled_nested_type().is_some_and(|ty| matches!(ty, Type::List(_)) || ty.bundle_element_name().is_some())
}
/// The element type's identifier name with any rank-0 `Item` or rank-1 `List` wrapper peeled, so semantic type checks can be rank-agnostic.
pub fn compiled_element_name(&self) -> Option<String> {
let nested_type = self.compiled_nested_type()?;
// A rank-0 `Item` or rank-1 `List` peels to its element; a bare value reports itself
let element = match nested_type {
Type::Item(element) | Type::List(element) => element.as_ref(),
other => other,
};
Some(element.identifier_name())
}
pub fn compiled_nested_type(&self) -> Option<&Type> {
match self {
TypeSource::Compiled(compiled_type) => Some(compiled_type.nested_type()),
@@ -202,19 +206,6 @@ impl NodeNetworkInterface {
concrete!(())
}
};
// A List-typed default drops to its Item counterpart (when that has a default value and the connector accepts rank 0),
// since a stored Item default can promote back onto a List connector but a stored List default can never return to rank 0
if let Some(element) = guaranteed_type.nested_type().list_element()
&& let Some(item_type) = self
.potential_valid_input_types(input_connector, network_path)
.into_iter()
.find(|ty| matches!(ty.nested_type(), Type::Item(item_element) if item_element.as_ref() == element))
&& let Some(item_default) = TaggedValue::from_type(&item_type)
{
return item_default;
}
TaggedValue::from_type_or_none(&guaranteed_type)
}
@@ -342,19 +333,12 @@ impl NodeNetworkInterface {
pub fn output_type(&mut self, output_connector: &OutputConnector, network_path: &[NodeId]) -> TypeSource {
match output_connector {
OutputConnector::Node { node_id, output_index } => {
// A hidden node is replaced by a passthrough during flattening, so its output carries its primary input's type
if *output_index == 0 && !self.is_visible(node_id, network_path) {
return self.input_type(&InputConnector::node(*node_id, 0), network_path);
}
// First try iterating upstream to the first protonode and try get its compiled type
let Some(implementation) = self.implementation(node_id, network_path) else {
return TypeSource::Error("Could not get implementation");
};
match implementation {
DocumentNodeImplementation::Network(_) => self.input_type(&InputConnector::Export(*output_index), &[network_path, &[*node_id]].concat()),
// The compiler removes passthrough nodes so they resolve no type of their own, but their output carries their primary input's type
DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::ops::passthrough::IDENTIFIER => self.input_type(&InputConnector::node(*node_id, 0), network_path),
DocumentNodeImplementation::ProtoNode(_) => match self.resolved_types.types.get(&[network_path, &[*node_id]].concat()) {
Some(resolved_type) => TypeSource::Compiled(resolved_type.output.clone()),
None => TypeSource::Unknown,
@@ -12,12 +12,6 @@ pub struct WirePath {
pub data_type: FrontendGraphDataType,
pub thick: bool,
pub dashed: bool,
// A rank-1 `List<T>` wire renders as a doubled-up pair of parallel lines to distinguish it from a rank-0 `Item<T>` wire
#[serde(rename = "isList")]
pub is_list: bool,
// A thick wire's center line reaches past the wire into the cleaved connector slots, so it needs its own longer path; empty otherwise
#[serde(rename = "centerPathString")]
pub center_path_string: String,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
@@ -63,19 +57,6 @@ impl GraphWireStyle {
pub fn build_vector_wire(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool, graph_wire_style: GraphWireStyle) -> BezPath {
let grid_spacing = 24.;
// A thick layer-stack wire (vertical at both ends) is skipped across a single straight grid cell where its connectors
// already meet, and otherwise trimmed 3px inward at each end since it overshoots the connectors.
let (output_position, input_position) = if vertical_out && vertical_in {
if thick_wire_spans_single_cell(output_position, input_position) {
return BezPath::new();
}
let trim = 3. * (input_position.y - output_position.y).signum();
(output_position + DVec2::new(0., trim), input_position - DVec2::new(0., trim))
} else {
(output_position, input_position)
};
match graph_wire_style {
GraphWireStyle::Direct => {
let horizontal_gap = (output_position.x - input_position.x).abs();
@@ -120,31 +101,6 @@ pub fn build_vector_wire(output_position: DVec2, input_position: DVec2, vertical
}
}
fn thick_wire_spans_single_cell(output_position: DVec2, input_position: DVec2) -> bool {
let grid_spacing = 24.;
(output_position.x - input_position.x).abs() < 1. && (output_position.y - input_position.y).abs() <= grid_spacing
}
/// The center line that cleaves a thick layer-stack wire. Its ends reach past the wire (1.5px toward the output
/// connector and 2px toward the input) so the color runs through the full cleaved connector slots. Empty for other wires.
pub fn build_thick_wire_center_line(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool) -> BezPath {
if !(vertical_out && vertical_in) || thick_wire_spans_single_cell(output_position, input_position) {
return BezPath::new();
}
// The 8px wire trims 3px at each end; the center line trims less so it reaches further into the cleaved slots
let sign = (input_position.y - output_position.y).signum();
let output_trim = 1.5;
let input_trim = 1.;
let start = output_position + DVec2::new(0., output_trim * sign);
let end = input_position - DVec2::new(0., input_trim * sign);
let mut center_line = BezPath::new();
center_line.move_to(dvec2_to_point(start));
center_line.line_to(dvec2_to_point(end));
center_line
}
fn straight_wire_path(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool) -> Vec<IVec2> {
let grid_spacing = 24;
let line_width = 2;
@@ -7,18 +7,15 @@ use crate::messages::portfolio::document::utility_types::network_interface::{Inp
use crate::messages::prelude::DocumentMessageHandler;
use glam::{DVec2, IVec2};
use graph_craft::application_io::resource::{DataSource, Resource, ResourceHash, ResourceId};
use graph_craft::descriptor;
use graph_craft::document::DocumentNode;
use graph_craft::document::{DocumentNodeImplementation, NodeInput, value::TaggedValue};
use graph_craft::{Type, item};
use graphene_std::Color;
use graphene_std::NodeInputDecleration;
use graphene_std::ProtoNodeIdentifier;
use graphene_std::text::{TextAlign, TypesettingConfig};
use graphene_std::transform::ScaleType;
use graphene_std::uuid::NodeId;
use graphene_std::vector::graphic_types;
use graphene_std::vector::misc::BoxCorners;
use graphene_std::vector::style::{DashPattern, PaintOrder, StrokeAlign};
use graphene_std::vector::style::{PaintOrder, StrokeAlign};
use std::collections::HashMap;
use std::f64::consts::PI;
use std::ops::Range;
@@ -35,9 +32,6 @@ const TEXT_REPLACEMENTS: &[(&str, &str)] = &[
("\"OptionalF64\":", "\"F64\":"),
("\"path_bool_nodes::BooleanOperation\"", "\"vector_types::vector::misc::BooleanOperation\""),
("\"core_types::table::Table<", "\"core_types::list::List<"),
// The `GradientStops` type was renamed to `Gradient`; stale stored output names are cleared so the display falls back to the live type name
("\"output_names\":[\"GradientStops\"]", "\"output_names\":[\"\"]"),
("vector_types::gradient::GradientStops", "vector_types::gradient::Gradient"),
];
pub struct NodeReplacement<'a> {
@@ -93,6 +87,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::animation::animation_time::IDENTIFIER,
aliases: &["graphene_core::animation::AnimationTimeNode"],
},
NodeReplacement {
node: graphene_std::debug::clone::IDENTIFIER,
aliases: &["graphene_core::ops::CloneNode"],
},
NodeReplacement {
node: graphene_std::extract_xy::extract_xy::IDENTIFIER,
aliases: &["graphene_core::ops::ExtractXyNode"],
@@ -108,14 +106,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphene_core::transform_nodes::FreezeRealTimeNode",
"graphene_core::vector::SubpathSegmentLengthsNode",
"core_types::vector::SubpathSegmentLengthsNode",
// The deleted debug Option trio degrades to a passthrough of its single input
"graphene_core::ops::SizeOfNode",
"graphene_core::debug::SizeOfNode",
"graphene_core::ops::SomeNode",
"graphene_core::debug::SomeNode",
"graphene_core::ops::UnwrapNode",
"graphene_core::debug::UnwrapNode",
"graphene_core::debug::UnwrapOptionNode",
],
},
NodeReplacement {
@@ -130,6 +120,18 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::animation::real_time::IDENTIFIER,
aliases: &["graphene_core::animation::RealTimeNode"],
},
NodeReplacement {
node: graphene_std::debug::size_of::IDENTIFIER,
aliases: &["graphene_core::ops::SizeOfNode"],
},
NodeReplacement {
node: graphene_std::debug::some::IDENTIFIER,
aliases: &["graphene_core::ops::SomeNode"],
},
NodeReplacement {
node: graphene_std::debug::unwrap_option::IDENTIFIER,
aliases: &["graphene_core::ops::UnwrapNode", "graphene_core::debug::UnwrapNode"],
},
// ================================
// graphic
// ================================
@@ -159,19 +161,13 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
aliases: &["graphene_core::graphic::FlattenVectorNode", "graphene_core::graphic_element::FlattenVectorNode"],
},
NodeReplacement {
node: graphene_std::graphic::item_at_index::IDENTIFIER,
node: graphene_std::graphic::index_elements::IDENTIFIER,
aliases: &[
"graphene_core::graphic_element::IndexNode",
"graphene_core::graphic::IndexNode",
"graphene_core::graphic::IndexElementsNode",
"graphic_nodes::graphic::IndexElementsNode",
"graphic_nodes::graphic::ExtractElementNode",
],
},
NodeReplacement {
node: graphene_std::graphic::remove_at_index::IDENTIFIER,
aliases: &["graphic_nodes::graphic::OmitElementNode"],
},
NodeReplacement {
node: graphene_std::graphic::legacy_layer_extend::IDENTIFIER,
aliases: &[
@@ -294,8 +290,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
],
},
NodeReplacement {
node: graphene_std::math_nodes::magnitude::IDENTIFIER,
aliases: &["math_nodes::LengthNode", "graphene_math_nodes::LengthNode", "graphene_core::ops::LenghtNode"],
node: graphene_std::math_nodes::length::IDENTIFIER,
aliases: &["graphene_math_nodes::LengthNode", "graphene_core::ops::LenghtNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::less_than::IDENTIFIER,
@@ -420,8 +416,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::math_nodes::as_u_64::IDENTIFIER,
aliases: &["graphene_math_nodes::ToU64Node", "graphene_core::ops::ToU64Node", "math_nodes::ToU64Node"],
},
// The old 'Vec2 Value' node took separate X and Y inputs, a role now filled by 'Combine Vec2', while the new 'Vec2 Value' node takes a single vec2 input.
// Old references (including these older aliases) are remapped here to `vec_2_value::IDENTIFIER` so the per-node migration in `migrate_node` can detect the leftover 3-input shape and convert it into a 'Combine Vec2' node.
NodeReplacement {
node: graphene_std::math_nodes::vec_2_value::IDENTIFIER,
aliases: &[
@@ -741,12 +735,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
// vector
// ================================
NodeReplacement {
node: graphene_std::vector::bake_transform::IDENTIFIER,
aliases: &[
"graphene_core::vector::ApplyTransformNode",
"graphene_core::vector::vector_modification::ApplyTransformNode",
"vector_nodes::vector_modification_nodes::ApplyTransformNode",
],
node: graphene_std::vector::apply_transform::IDENTIFIER,
aliases: &["graphene_core::vector::ApplyTransformNode", "graphene_core::vector::vector_modification::ApplyTransformNode"],
},
NodeReplacement {
node: graphene_std::vector::area::IDENTIFIER,
@@ -781,7 +771,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
aliases: &["graphene_core::vector::ClosePathNode"],
},
NodeReplacement {
node: graphene_std::vector::list_length::IDENTIFIER,
node: graphene_std::vector::count_elements::IDENTIFIER,
aliases: &["graphene_core::vector::CountElementsNode"],
},
NodeReplacement {
@@ -805,7 +795,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
aliases: &["graphene_core::vector::vector_nodes::FillNode", "graphene_core::vector::FillNode"],
},
NodeReplacement {
node: graphene_std::vector::combine_paths::IDENTIFIER,
node: graphene_std::vector::flatten_path::IDENTIFIER,
aliases: &[
"graphene_core::vector::vector_nodes::FlattenPathNode",
"graphene_core::vector::FlattenVectorElementsNode",
@@ -1131,7 +1121,6 @@ pub fn document_migration_replace_resources_referenced_by_hash(document_serializ
pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_node_definitions_on_open: bool) {
document.network_interface.migrate_path_modify_node();
document.network_interface.document_network_mut().normalize_stored_types();
let network = document.network_interface.document_network().clone();
@@ -1296,9 +1285,9 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
migrate_node(node_id, node, network_path, document, reset_node_definitions_on_open);
}
// The old geometry-producing "Text" node was split into the current "Text" (`String[]`) -> converter pair, which reuses the same proto
// identifier. Runs after `migrate_node` normalizes old text nodes to the legacy 13-input layout, distinguished from the current 12-input
// node by the trailing `separate_glyphs` input (index 12): forward inputs 0..=11 onto the new node and splice the matching converter after it.
// The old geometry-producing "Text" node was split into the current "Text" (`String[]`) -> "Text to Vector" pair, which reuses the same
// proto identifier. Runs after `migrate_node` normalizes old text nodes to the legacy 13-input layout, distinguished from the current
// 12-input node by the trailing `separate_glyphs` input (index 12): forward inputs 0..=11 onto the new node and move it onto `text_to_vector`.
let old_text_nodes: Vec<(NodeId, Vec<NodeId>)> = document
.network_interface
.document_network()
@@ -1332,8 +1321,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
document.network_interface.set_input(&InputConnector::node(*node_id, new_index), input.clone(), network_path);
}
}
// A `true` toggle at index 12 chose per-glyph geometry, which is now the dedicated "Text to Vector Glyphs" node
let separate_glyphs = matches!(old_inputs.get(12).and_then(|input| input.as_value()), Some(TaggedValue::Bool(true)));
let separate_glyphs = old_inputs.get(12).cloned();
// Collect the inputs reading the old text node's output before any rewiring so the new node can be spliced onto those wires.
let downstream_consumers: Vec<InputConnector> = document
@@ -1345,62 +1333,44 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
let text_was_in_chain = text_nodes_in_chain.contains(node_id);
// Insert the converter that turns the `text` `String[]` output back into vector geometry: "Text to Vector Glyphs" for the per-glyph case, otherwise "Text to Vector".
let converter_identifier = if separate_glyphs {
graphene_std::text::text_to_vector_glyphs::IDENTIFIER
} else {
graphene_std::text::text_to_vector::IDENTIFIER
};
let Some(converter_definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(converter_identifier)) else {
// Insert the `text_to_vector` node that converts the `text` `String[]` output back into vector geometry.
let Some(text_to_vector_definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::text::text_to_vector::IDENTIFIER)) else {
continue;
};
let converter_id = NodeId::new();
document.network_interface.insert_node(converter_id, converter_definition.default_node_template(), network_path);
let text_to_vector_id = NodeId::new();
document
.network_interface
.insert_node(text_to_vector_id, text_to_vector_definition.default_node_template(), network_path);
// Splice the converter onto the wire(s) leaving `text` (`insert_node_between` is the pure wire-splice the editor uses for dropping a node on a wire).
// Splice `text_to_vector` onto the wire(s) leaving `text` (`insert_node_between` is the pure wire-splice the editor uses for
// dropping a node on a wire), then carry the old `separate_glyphs` value onto its second input.
if let Some((first_consumer, remaining_consumers)) = downstream_consumers.split_first() {
document.network_interface.insert_node_between(&converter_id, first_consumer, 0, network_path);
document.network_interface.insert_node_between(&text_to_vector_id, first_consumer, 0, network_path);
for consumer in remaining_consumers {
document.network_interface.set_input(consumer, NodeInput::node(converter_id, 0), network_path);
document.network_interface.set_input(consumer, NodeInput::node(text_to_vector_id, 0), network_path);
}
} else {
document.network_interface.set_input(&InputConnector::node(converter_id, 0), NodeInput::node(*node_id, 0), network_path);
document
.network_interface
.set_input(&InputConnector::node(text_to_vector_id, 0), NodeInput::node(*node_id, 0), network_path);
}
if let Some(separate_glyphs) = separate_glyphs {
document.network_interface.set_input(&InputConnector::node(text_to_vector_id, 1), separate_glyphs, network_path);
}
// If `text` was in a layer chain, re-chain the converter and its upstream so both lay out by distance from the layer (the splice
// broke the chain, like `move_node_to_chain_start`). Otherwise `text` is absolute, so place the converter beside it instead of
// If `text` was in a layer chain, re-chain `text_to_vector` and its upstream so both lay out by distance from the layer (the splice
// broke the chain, like `move_node_to_chain_start`). Otherwise `text` is absolute, so place `text_to_vector` beside it instead of
// leaving it at the origin.
if text_was_in_chain {
document.network_interface.force_set_upstream_to_chain(&converter_id, network_path);
document.network_interface.force_set_upstream_to_chain(&text_to_vector_id, network_path);
} else if let Some(text_position) = document.network_interface.position(node_id, network_path) {
document.network_interface.shift_absolute_node_position(&converter_id, text_position + IVec2::new(7, 0), network_path);
document
.network_interface
.shift_absolute_node_position(&text_to_vector_id, text_position + IVec2::new(7, 0), network_path);
}
}
}
/// Converts a legacy stroke dash input (a `List<f64>`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type.
fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> {
let NodeInput::Value { tagged_value, exposed } = input else { return None };
let pattern = match &*tagged_value.clone().into_inner() {
TaggedValue::F64Array(lengths) => DashPattern::from(lengths.clone()),
TaggedValue::F64(length) => DashPattern::from(*length),
TaggedValue::String(text) => DashPattern::from(text.as_str()),
_ => return None,
};
Some(NodeInput::value(TaggedValue::DashPattern(pattern), *exposed))
}
/// Converts a legacy rectangle corner radius input (a single `f64` or a `List<f64>` of up to four values) to the `BoxCorners` value type.
fn migrate_corner_radius_input(input: &NodeInput) -> Option<NodeInput> {
let NodeInput::Value { tagged_value, exposed } = input else { return None };
let corners = match &*tagged_value.clone().into_inner() {
TaggedValue::F64Array(values) => BoxCorners::from(values.clone()),
TaggedValue::F64(value) => BoxCorners::from(*value),
_ => return None,
};
Some(NodeInput::value(TaggedValue::BoxCorners(corners), *exposed))
}
fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId], document: &mut DocumentMessageHandler, reset_node_definitions_on_open: bool) -> Option<()> {
// Must run before the reset block below: a node referencing a removed catalog entry would otherwise abort
// `migrate_node` via the `?` on `resolve_document_node_type`, preventing subsequent migration blocks from running.
@@ -1602,8 +1572,8 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
inputs_count = 5;
}
// Upgrade the legacy 4-input Fill node (content, fill: Fill, _backup_color, _backup_gradient: Gradient) to the value-model
// 8-input shape (content, fill: generic paint list, _backup_color, _backup_gradient, _gradient_type, _spread_method, _has_transform, _transform).
// Upgrade the legacy 4-input Fill node (content, fill: Fill, _backup_color, _backup_gradient: Gradient) to the
// value-model 7-input shape (content, fill: generic paint list, _backup_color, _backup_gradient, _gradient_type, _spread_method, _transform).
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::fill::IDENTIFIER) && inputs_count == 4 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
@@ -1612,21 +1582,21 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
// Content: no change
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
// Fill: a literal Fill value is decomposed, and a wired input (`List<Gradient> / List<Color>`) is kept as-is
// Fill: a literal Fill value is decomposed, and a wired input (`List<GradientStops> / List<Color>`) is kept as-is
match old_inputs[1].as_value() {
Some(TaggedValue::LegacyFill(old_fill)) => {
let exposed = old_inputs[1].is_exposed();
let fill_value = match old_fill {
graphic_types::migrations::legacy::LegacyFill::None => TaggedValue::no_paint(),
graphic_types::migrations::legacy::LegacyFill::Solid(color) => TaggedValue::Color(*color),
graphic_types::migrations::legacy::LegacyFill::Gradient(gradient) => TaggedValue::Gradient(gradient.stops.clone()),
graphic_types::migrations::legacy::Fill::None => TaggedValue::Color(None),
graphic_types::migrations::legacy::Fill::Solid(color) => TaggedValue::Color(Some(*color)),
graphic_types::migrations::legacy::Fill::Gradient(gradient) => TaggedValue::Gradient(gradient.stops.clone()),
};
document
.network_interface
.set_input(&InputConnector::node(*node_id, 1), NodeInput::value(fill_value, exposed), network_path);
// Gradient metadata (4, 5, 6, 7): applies only to a literal gradient, solids/none keep the template defaults
if let graphic_types::migrations::legacy::LegacyFill::Gradient(gradient) = old_fill {
// Gradient metadata (4, 5, 6): applies only to a literal gradient, solids/none keep the template defaults
if let graphic_types::migrations::legacy::Fill::Gradient(gradient) = old_fill {
document.network_interface.set_input(
&InputConnector::node(*node_id, 4),
NodeInput::value(TaggedValue::GradientType(gradient.gradient_type), false),
@@ -1638,23 +1608,20 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
network_path,
);
if gradient.absolute {
let transform = gradient.transform * gradient.to_transform();
document
.network_interface
.set_input(&InputConnector::node(*node_id, 6), NodeInput::value(TaggedValue::Bool(true), false), network_path);
document
.network_interface
.set_input(&InputConnector::node(*node_id, 7), NodeInput::value(TaggedValue::DAffine2(transform), false), network_path);
let transform = if gradient.absolute {
Some(gradient.transform * gradient.to_transform())
} else {
// Baking a legacy bounding-box-relative gradient is deferred until the measurement pre-pass can supply the paint
// target's bounds, so the template's unbaked `_has_transform = false` stands until the bake lands
// Baking a legacy bounding-box-relative gradient is deferred until the measurement pre-pass can supply the paint target's bounds
document.pending_gradient_bbox_bake.push((network_path.to_vec(), *node_id, gradient.clone()));
}
None
};
document
.network_interface
.set_input(&InputConnector::node(*node_id, 6), NodeInput::value(TaggedValue::OptionalDAffine2(transform), false), network_path);
}
}
// Wired/exposed fill keeps the connection.
// The generic paint connector accepts the existing `List<Color>`/`List<Gradient>` paint sources directly.
// The generic paint connector accepts the existing `List<Color>`/`List<GradientStops>` paint sources directly.
_ => {
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
}
@@ -1673,7 +1640,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
if matches!(
old_inputs[1].as_value(),
Some(TaggedValue::LegacyFill(
graphic_types::migrations::legacy::LegacyFill::None | graphic_types::migrations::legacy::LegacyFill::Solid(_)
graphic_types::migrations::legacy::Fill::None | graphic_types::migrations::legacy::Fill::Solid(_)
))
) {
document
@@ -1685,54 +1652,19 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
network_path,
);
if g.absolute {
let transform = g.transform * g.to_transform();
document
.network_interface
.set_input(&InputConnector::node(*node_id, 6), NodeInput::value(TaggedValue::Bool(true), false), network_path);
document
.network_interface
.set_input(&InputConnector::node(*node_id, 7), NodeInput::value(TaggedValue::DAffine2(transform), false), network_path);
let transform = if g.absolute {
Some(g.transform * g.to_transform())
} else {
document.pending_gradient_bbox_bake.push((network_path.to_vec(), *node_id, g.clone()));
}
None
};
document
.network_interface
.set_input(&InputConnector::node(*node_id, 6), NodeInput::value(TaggedValue::OptionalDAffine2(transform), false), network_path);
}
}
inputs_count = 8;
}
// Fill split its `Option<DAffine2>` placement into a `_has_transform` bool immediately before the `_transform` matrix
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER) && inputs_count == 7 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
for (index, input) in old_inputs.iter().enumerate().take(6) {
document.network_interface.set_input(&InputConnector::node(*node_id, index), input.clone(), network_path);
}
match old_inputs.get(6).and_then(|input| input.as_value()) {
Some(TaggedValue::LegacyOptionalDAffine2(value)) => {
let has_transform = value.is_some();
let transform = value.unwrap_or(glam::DAffine2::IDENTITY);
document
.network_interface
.set_input(&InputConnector::node(*node_id, 6), NodeInput::value(TaggedValue::Bool(has_transform), false), network_path);
document
.network_interface
.set_input(&InputConnector::node(*node_id, 7), NodeInput::value(TaggedValue::DAffine2(transform), false), network_path);
}
// A wired (or otherwise non-value) transform keeps its connection and is treated as present
_ => {
document
.network_interface
.set_input(&InputConnector::node(*node_id, 6), NodeInput::value(TaggedValue::Bool(true), false), network_path);
let transform_input = old_inputs.get(6).cloned().unwrap_or_else(|| NodeInput::value(TaggedValue::DAffine2(glam::DAffine2::IDENTITY), false));
document.network_interface.set_input(&InputConnector::node(*node_id, 7), transform_input, network_path);
}
}
inputs_count = 8;
inputs_count = 7;
}
// Upgrade Stroke node to reorder parameters and add "Align" and "Paint Order" (#2644)
@@ -1751,111 +1683,10 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
document.network_interface.set_input(&InputConnector::node(*node_id, 5), old_inputs[6].clone(), network_path);
document.network_interface.set_input(&InputConnector::node(*node_id, 6), old_inputs[7].clone(), network_path);
document.network_interface.set_input(&InputConnector::node(*node_id, 7), paint_order_input, network_path);
let dash_input = migrate_dash_input(&old_inputs[3]).unwrap_or_else(|| old_inputs[3].clone());
document.network_interface.set_input(&InputConnector::node(*node_id, 8), dash_input, network_path);
document.network_interface.set_input(&InputConnector::node(*node_id, 8), old_inputs[3].clone(), network_path);
document.network_interface.set_input(&InputConnector::node(*node_id, 9), old_inputs[4].clone(), network_path);
}
// TODO: Eventually remove this migration document upgrade code
// A legacy "no color" on a plain color connector (`TaggedValue::no_paint()` restored by the deserializer) becomes a color,
// since only paint connectors keep the no-paint choice
{
let migrate_color_input = |input: &NodeInput, fallback: Color| -> Option<NodeInput> {
let NodeInput::Value { tagged_value, exposed } = input else { return None };
if !tagged_value.is_no_paint() {
return None;
}
Some(NodeInput::value(TaggedValue::Color(fallback), *exposed))
};
let conversions: &[(ProtoNodeIdentifier, usize, Color)] = &[
(graphene_std::vector::fill::IDENTIFIER, graphene_std::vector::fill::BackupColorInput::INDEX, Color::BLACK),
(
graphene_std::artboard::create_artboard::IDENTIFIER,
graphene_std::artboard::create_artboard::BackgroundInput::INDEX,
Color::WHITE,
),
(
graphene_std::math_nodes::color_value::IDENTIFIER,
graphene_std::math_nodes::color_value::ColorInput::INDEX,
Color::TRANSPARENT,
),
(
graphene_std::raster_nodes::adjustments::black_and_white::IDENTIFIER,
graphene_std::raster_nodes::adjustments::black_and_white::TintInput::INDEX,
Color::BLACK,
),
(
graphene_std::raster_nodes::blending_nodes::color_overlay::IDENTIFIER,
graphene_std::raster_nodes::blending_nodes::color_overlay::ColorInput::INDEX,
Color::BLACK,
),
(
graphene_std::raster_nodes::std_nodes::empty_image::IDENTIFIER,
graphene_std::raster_nodes::std_nodes::empty_image::ColorInput::INDEX,
Color::WHITE,
),
];
for &(ref identifier, index, fallback) in conversions {
if reference != DefinitionIdentifier::ProtoNode(identifier.clone()) {
continue;
}
let Some(input) = node.inputs.get(index) else { continue };
if let Some(migrated) = migrate_color_input(input, fallback) {
document.network_interface.set_input(&InputConnector::node(*node_id, index), migrated, network_path);
}
}
}
// The stroke dash sequence became the `DashPattern` value type; convert any already-shaped stroke that still stores a legacy dash input
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER)
&& let Some(dash_input) = node.inputs.get(graphene_std::vector::stroke::DashPatternInput::INDEX)
&& let Some(migrated) = migrate_dash_input(dash_input)
{
document
.network_interface
.set_input(&InputConnector::node(*node_id, graphene_std::vector::stroke::DashPatternInput::INDEX), migrated, network_path);
}
// The rectangle's corner radius became the `BoxCorners` value type and its hidden individual-radii toggle moved after the
// user-visible inputs. A legacy rectangle stores that toggle (a plain `bool`) at index 3, where the new shape stores the corner
// radius, so a `bool` value there identifies the old input order: [width, height, individual, corner_radius, clamped].
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER)
&& let Some(toggle_input) = node.inputs.get(3)
&& matches!(toggle_input.as_value(), Some(TaggedValue::Bool(_)))
{
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
let corner_radius = migrate_corner_radius_input(&old_inputs[4]).unwrap_or_else(|| old_inputs[4].clone());
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
document.network_interface.set_input(&InputConnector::node(*node_id, 2), old_inputs[2].clone(), network_path);
document.network_interface.set_input(&InputConnector::node(*node_id, 3), corner_radius, network_path);
document.network_interface.set_input(&InputConnector::node(*node_id, 4), old_inputs[5].clone(), network_path);
document.network_interface.set_input(&InputConnector::node(*node_id, 5), old_inputs[3].clone(), network_path);
}
// The Text to Vector node's runtime `separate_glyphs` toggle became the dedicated "Text to Vector Glyphs" node, leaving Text to Vector as a plain
// string-to-compound-path converter. A 2-input Text to Vector is the old toggled shape: a `true` toggle routes to Text to Vector Glyphs, otherwise
// the node stays Text to Vector; either way the toggle input is dropped and the string wire is preserved.
if reference == DefinitionIdentifier::ProtoNode(graphene_std::text::text_to_vector::IDENTIFIER) && inputs_count == 2 {
let separate_glyphs = matches!(node.inputs.get(1).and_then(|input| input.as_value()), Some(TaggedValue::Bool(true)));
let target = if separate_glyphs {
graphene_std::text::text_to_vector_glyphs::IDENTIFIER
} else {
graphene_std::text::text_to_vector::IDENTIFIER
};
let mut node_template = resolve_proto_node_type(target)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
if let Some(string_input) = node.inputs.first() {
document.network_interface.set_input(&InputConnector::node(*node_id, 0), string_input.clone(), network_path);
}
}
// Upgrade Text node to include line height and character spacing, which were previously hardcoded to 1, from https://github.com/GraphiteEditor/Graphite/pull/2016
if reference == DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::new("graphene_std::text::TextNode")) && inputs_count == 8 {
let mut template: NodeTemplate = legacy_text_node_template()?;
@@ -2023,20 +1854,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
.set_input(&InputConnector::node(*node_id, 2), NodeInput::value(TaggedValue::Bool(false), false), network_path);
}
// Convert the old 'Vec2 Value' node, identified by its leftover 3-input shape with separate X and Y inputs,
// into the 'Combine Vec2' node which now fills that role (the new 'Vec2 Value' node instead takes a single vec2 input)
if reference == DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::vec_2_value::IDENTIFIER) && inputs_count == 3 {
let combine_vec2_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::combine_vec_2::IDENTIFIER);
let mut node_template = resolve_document_node_type(&combine_vec2_reference)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
document.network_interface.set_input(&InputConnector::node(*node_id, 2), old_inputs[2].clone(), network_path);
}
// Upgrade the Mirror node to add the `keep_original` boolean input
if reference == DefinitionIdentifier::ProtoNode(graphene_std::graphic::mirror::IDENTIFIER) && inputs_count == 3 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
@@ -2169,13 +1986,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
}
// A brush node saved before `Item<Raster<CPU>>` had a default stored its unconnected background as the invalid `()`,
// which fails type resolution against the raster primary; adopt the definition's empty-raster default instead.
if reference == DefinitionIdentifier::ProtoNode(graphene_std::brush::brush::brush::IDENTIFIER) && matches!(node.inputs.first().and_then(|input| input.as_value()), Some(TaggedValue::None)) {
let default_background = resolve_document_node_type(&reference)?.node_template.document_node.inputs.first()?.clone();
document.network_interface.set_input(&InputConnector::node(*node_id, 0), default_background, network_path);
}
if reference == DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::new("graphene_core::vector::RemoveHandlesNode")) {
let mut node_template = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::vector::auto_tangents::IDENTIFIER))?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
@@ -2392,7 +2202,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
// Migrate from the v2 "Morph" node (2 inputs: content, progression) to the v3 "Morph" node (5 inputs: content, progression, reverse, distribution, path).
// The old progression used integer part for pair selection (range 0..N-1 where N is the number of content objects).
// The new progression uses fractional 0..1 for euclidean traversal through all objects.
// We insert List Length → Subtract 1 → Divide to remap: new_progression = old_progression / (N - 1).
// We insert Count Elements → Subtract 1 → Divide to remap: new_progression = old_progression / (N - 1).
// For the common 2-object case (N=2), this divides by 1 which is a no-op, preserving identical behavior.
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::morph::IDENTIFIER) && inputs_count == 2 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
@@ -2407,14 +2217,14 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
return None;
};
// Create List Length node: counts content `List` items → N
let Some(list_length_def) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::vector::list_length::IDENTIFIER)) else {
log::error!("Could not get list_length node from definition when upgrading morph");
// Create Count Elements node: counts content `List` items → N
let Some(count_elements_def) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::vector::count_elements::IDENTIFIER)) else {
log::error!("Could not get count_elements node from definition when upgrading morph");
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
return None;
};
let list_length_template = list_length_def.default_node_template();
let list_length_id = NodeId::new();
let count_elements_template = count_elements_def.default_node_template();
let count_elements_id = NodeId::new();
// Create Subtract node: N → N-1
let Some(subtract_def) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::subtract::IDENTIFIER)) else {
@@ -2436,10 +2246,10 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
let divide_id = NodeId::new();
// Insert and position nodes
document.network_interface.insert_node(list_length_id, list_length_template, network_path);
document.network_interface.insert_node(count_elements_id, count_elements_template, network_path);
document
.network_interface
.shift_absolute_node_position(&list_length_id, morph_position + IVec2::new(-21, 2), network_path);
.shift_absolute_node_position(&count_elements_id, morph_position + IVec2::new(-21, 2), network_path);
document.network_interface.insert_node(subtract_id, subtract_template, network_path);
document.network_interface.shift_absolute_node_position(&subtract_id, morph_position + IVec2::new(-14, 2), network_path);
@@ -2447,13 +2257,13 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
document.network_interface.insert_node(divide_id, divide_template, network_path);
document.network_interface.shift_absolute_node_position(&divide_id, morph_position + IVec2::new(-7, 1), network_path);
// Wire: content source → List Length input 0
document.network_interface.set_input(&InputConnector::node(list_length_id, 0), old_inputs[0].clone(), network_path);
// Wire: content source → Count Elements input 0
document.network_interface.set_input(&InputConnector::node(count_elements_id, 0), old_inputs[0].clone(), network_path);
// Wire: List Length output → Subtract input 0 (minuend)
// Wire: Count Elements output → Subtract input 0 (minuend)
document
.network_interface
.set_input(&InputConnector::node(subtract_id, 0), NodeInput::node(list_length_id, 0), network_path);
.set_input(&InputConnector::node(subtract_id, 0), NodeInput::node(count_elements_id, 0), network_path);
// Wire: old progression → Divide input 0 (numerator)
document.network_interface.set_input(&InputConnector::node(divide_id, 0), old_inputs[1].clone(), network_path);
@@ -2634,9 +2444,11 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
let modification = modification.clone();
let was_exposed = *exposed;
document
.network_interface
.set_input(&InputConnector::node(*node_id, 0), NodeInput::type_default(item!(graphene_std::vector::Vector), true), network_path);
document.network_interface.set_input(
&InputConnector::node(*node_id, 0),
NodeInput::type_default(descriptor!(graphene_std::list::List<graphene_std::vector::Vector>), true),
network_path,
);
if !was_exposed {
document
@@ -2668,34 +2480,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
}
}
// A value input stored as a List-form TypeDefault adopts the definition's current default when the connector's declared default has since changed (e.g. the connector was ranked down to Item).
// The red-slash no-paint choice shares that stored form but is a deliberate value, not a stale disconnect default, so it is exempt.
if let Some(definition) = resolve_document_node_type(&reference) {
let definition_inputs = definition.node_template.document_node.inputs.clone();
for (index, definition_input) in definition_inputs.iter().enumerate() {
if !matches!(definition_input, NodeInput::Value { .. }) {
continue;
}
let stale_list_default = document
.network_interface
.input_from_connector(&InputConnector::node(*node_id, index), network_path)
.is_some_and(|stored_input| match stored_input {
NodeInput::Value { tagged_value, .. } => match &**tagged_value {
TaggedValue::TypeDefault(stored_type) if matches!(stored_type, Type::List(_)) && !tagged_value.is_no_paint() => {
!matches!(definition_input, NodeInput::Value { tagged_value, .. } if matches!(&**tagged_value, TaggedValue::TypeDefault(definition_type) if definition_type == stored_type))
}
_ => false,
},
_ => false,
});
if stale_list_default {
document.network_interface.set_input(&InputConnector::node(*node_id, index), definition_input.clone(), network_path);
}
}
}
// ==================================
// PUT ALL MIGRATIONS ABOVE THIS LINE
// ==================================
@@ -2781,31 +2565,6 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
}
}
// The removed Attach Attribute node degrades to a passthrough of its
// content: its eager whole-list source input cannot be mechanically rewired as Write Attribute's lazy per-item value producer.
if let Some(DefinitionIdentifier::ProtoNode(identifier)) = document.network_interface.reference(node_id, network_path)
&& identifier.as_str().ends_with("::AttachAttributeNode")
{
let mut node_template = resolve_proto_node_type(graphene_std::ops::passthrough::IDENTIFIER)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
if let Some(content) = old_inputs.first() {
document.network_interface.set_input(&InputConnector::node(*node_id, 0), content.clone(), network_path);
}
}
// The Upload Texture node's old wrapper-network form maps onto its proto node form, which draws the executor from scope
if let Some(DefinitionIdentifier::Network(name)) = document.network_interface.reference(node_id, network_path)
&& name == "Upload Texture"
{
let mut node_template = resolve_proto_node_type(graphene_std::platform_application_io::upload_texture::IDENTIFIER)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
if let Some(content) = old_inputs.first() {
document.network_interface.set_input(&InputConnector::node(*node_id, 0), content.clone(), network_path);
}
}
Some(())
}
@@ -2813,13 +2572,6 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
mod tests {
use super::*;
// The removed-definition blocks above abort silently via `?` if their swap target ever leaves the catalog
#[test]
fn removed_definition_swap_targets_resolve() {
assert!(resolve_proto_node_type(graphene_std::ops::passthrough::IDENTIFIER).is_some());
assert!(resolve_proto_node_type(graphene_std::platform_application_io::upload_texture::IDENTIFIER).is_some());
}
#[test]
fn test_no_duplicate_node_replacements() {
let mut hashmap = HashMap::<ProtoNodeIdentifier, u32>::new();
@@ -197,10 +197,6 @@ pub enum PortfolioMessage {
artboard_name: Option<String>,
artboard_count: usize,
},
SubmitPlotterExport {
job_name: String,
estimate_only: bool,
},
SubmitActiveGraphRender,
SubmitGraphRender {
document_id: DocumentId,
@@ -5,7 +5,7 @@ use crate::application::{Editor, generate_uuid};
use crate::consts::{DEFAULT_DOCUMENT_NAME, FILE_EXTENSION, GDD_FILE_EXTENSION};
use crate::messages::animation::TimingInformation;
use crate::messages::dialog::simple_dialogs;
use crate::messages::frontend::utility_types::{DocumentInfo, ExportBounds, FileType, PersistedState};
use crate::messages::frontend::utility_types::{DocumentInfo, PersistedState};
use crate::messages::input_mapper::utility_types::input_keyboard::Key;
use crate::messages::input_mapper::utility_types::macros::{action_shortcut, action_shortcut_manual};
use crate::messages::layout::utility_types::widget_prelude::*;
@@ -1461,32 +1461,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
});
}
}
PortfolioMessage::SubmitPlotterExport { job_name, estimate_only } => {
let document_id = self.active_document_id.expect("Tried to render non-existent document");
let document = self.documents.get_mut(&document_id).expect("Tried to render non-existent document");
let export_config = ExportConfig {
name: job_name,
file_type: FileType::Svg,
scale_factor: 1.,
bounds: ExportBounds::AllArtwork,
for_plotter: true,
plotter_estimate_only: estimate_only,
..Default::default()
};
let result = self.executor.submit_document_export(document, document_id, export_config);
if let Err(description) = result {
// A failed estimate render (e.g. an empty document) just marks the estimate as unavailable
if estimate_only {
responses.add(DialogMessage::SendToPlotterDialog(SendToPlotterDialogMessage::UpdateTimeEstimate { seconds: None }));
} else {
responses.add(DialogMessage::DisplayDialogError {
title: "Unable to send to the plotter".to_string(),
description,
});
}
}
}
PortfolioMessage::SubmitActiveGraphRender => {
if let Some(document_id) = self.active_document_id {
responses.add(PortfolioMessage::SubmitGraphRender { document_id, ignore_hash: false });
-1
View File
@@ -14,7 +14,6 @@ pub use crate::messages::defer::{DeferMessage, DeferMessageDiscriminant, DeferMe
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::preferences_dialog::{PreferencesDialogMessage, PreferencesDialogMessageContext, PreferencesDialogMessageDiscriminant, PreferencesDialogMessageHandler};
pub use crate::messages::dialog::send_to_plotter_dialog::{SendToPlotterDialogMessage, SendToPlotterDialogMessageContext, SendToPlotterDialogMessageDiscriminant, SendToPlotterDialogMessageHandler};
pub use crate::messages::dialog::{DialogMessage, DialogMessageContext, DialogMessageDiscriminant, DialogMessageHandler};
pub use crate::messages::frontend::{FrontendMessage, FrontendMessageDiscriminant};
pub use crate::messages::future::{FutureMessage, FutureMessageContext, FutureMessageDiscriminant, FutureMessageHandler, MessageFuture, MessageSpawner, Wake};
@@ -4,18 +4,18 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeNetworkInterface, NodeTemplate};
use crate::messages::prelude::*;
use glam::{DAffine2, DVec2};
use graph_craft::ProtoNodeIdentifier;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, NodeId, NodeInput};
use graph_craft::{ProtoNodeIdentifier, concrete};
use graphene_std::NodeInputDecleration;
use graphene_std::list::List;
use graphene_std::raster::BlendMode;
use graphene_std::raster_types::Image;
use graphene_std::raster_types::{CPU, GPU, Image, Raster};
use graphene_std::subpath::Subpath;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::misc::ManipulatorPointId;
use graphene_std::vector::style::{FillChoice, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, initial_gradient_transform_for_bounding_box};
use graphene_std::vector::{Gradient, GradientSpreadMethod, GradientType, PointId, SegmentId, VectorModificationType};
use graphene_std::vector::{GradientSpreadMethod, GradientStops, GradientType, PointId, SegmentId, VectorModificationType};
use graphene_std::{Color, Graphic};
use std::collections::VecDeque;
@@ -101,21 +101,21 @@ pub fn merge_layers(document: &DocumentMessageHandler, first_layer: LayerNodeIde
delete_children: false,
});
// Add a Combine Paths node after the merge
let combine_paths_node_id = NodeId::new();
let combine_paths_node = document_node_definitions::resolve_proto_node_type(graphene_std::vector::combine_paths::IDENTIFIER)
.expect("Failed to create combine paths node")
// Add a Flatten Path node after the merge
let flatten_node_id = NodeId::new();
let flatten_node = document_node_definitions::resolve_proto_node_type(graphene_std::vector::flatten_path::IDENTIFIER)
.expect("Failed to create flatten node")
.default_node_template();
responses.add(NodeGraphMessage::InsertNode {
node_id: combine_paths_node_id,
node_template: Box::new(combine_paths_node),
node_id: flatten_node_id,
node_template: Box::new(flatten_node),
});
responses.add(NodeGraphMessage::MoveNodeToChainStart {
node_id: combine_paths_node_id,
node_id: flatten_node_id,
parent: first_layer,
});
// Add a path node after the combine paths node
// Add a path node after the flatten node
let path_node_id = NodeId::new();
let path_node = document_node_definitions::resolve_network_node_type("Path")
.expect("Failed to create path node")
@@ -310,7 +310,7 @@ pub fn get_fill_input_node_id(layer: LayerNodeIdentifier, network_interface: &No
}
/// Get the gradient stops of a layer, if any.
pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Gradient> {
pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<GradientStops> {
// Try to find the gradient stops value that is created by a Fill node first
if let Some(fill_node_id) = get_fill_node_id_with_direct_fill_input(layer, network_interface) {
return network_interface
@@ -329,7 +329,7 @@ pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNe
Some(stops.clone())
}
/// Compute the transform from a gradient's local space to viewport space for the given layer. For a `List<Gradient>`
/// Compute the transform from a gradient's local space to viewport space for the given layer. For a `List<GradientStops>`
/// layer this is the layer's incoming footprint transform; for a Fill-owned gradient value it composes the layer's viewport
/// transform with the [0,1]² → bounding-box mapping.
pub fn gradient_space_transform(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> glam::DAffine2 {
@@ -363,10 +363,10 @@ pub fn gradient_orientation_rightward(transform: glam::DAffine2) -> bool {
/// Get the current fill of a layer from the closest "Fill" node.
pub fn get_fill_color(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Color> {
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))?;
let TaggedValue::Color(color) = inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)?.as_value()? else {
let &TaggedValue::Color(color) = inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)?.as_value()? else {
return None;
};
Some(*color)
color
}
/// Get the current blend mode of a layer from the closest upstream "Blend Mode" node.
@@ -570,8 +570,8 @@ pub fn get_stroke_options(layer: LayerNodeIdentifier, network_interface: &NodeNe
Some(TaggedValue::PaintOrder(value)) => *value,
_ => PaintOrder::default(),
};
let dash_lengths = match read(graphene_std::vector::stroke::DashPatternInput::INDEX) {
Some(TaggedValue::DashPattern(value)) => value.0.iter_element_values().copied().collect(),
let dash_lengths = match read(graphene_std::vector::stroke::DashLengthsInput::<List<f64>>::INDEX) {
Some(TaggedValue::F64Array(value)) => value.clone(),
_ => Vec::new(),
};
let dash_offset = match read(graphene_std::vector::stroke::DashOffsetInput::INDEX) {
@@ -626,7 +626,7 @@ pub fn set_stroke_weight_for_selected_layers(weight: f64, document: &DocumentMes
/// A Fill node's decoded gradient inputs, with the transform kept in its raw form (not yet baked into `start`/`end`).
pub struct FillNodeGradient {
pub stops: Gradient,
pub stops: GradientStops,
pub gradient_type: GradientType,
pub spread_method: GradientSpreadMethod,
pub transform: DAffine2,
@@ -649,11 +649,9 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
Some(&TaggedValue::GradientSpreadMethod(value)) => value,
_ => GradientSpreadMethod::default(),
};
let has_transform = matches!(fill_node.inputs.get(fill::HasTransformInput::INDEX).and_then(|input| input.as_value()), Some(&TaggedValue::Bool(true)));
let transform_input = fill_node.inputs.get(fill::TransformInput::INDEX).and_then(|input| input.as_value());
let transform = match (has_transform, transform_input) {
(true, Some(&TaggedValue::DAffine2(value))) => value,
(false, _) => initial_gradient_transform_for_bounding_box(bounding_box()),
let transform = match transform_input {
Some(&TaggedValue::OptionalDAffine2(value)) => value.unwrap_or_else(|| initial_gradient_transform_for_bounding_box(bounding_box())),
_ => DAffine2::IDENTITY,
};
@@ -669,11 +667,7 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
pub fn get_stroke_color(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Option<Color>> {
let color_index = graphene_std::vector::stroke::PaintInput::<List<Graphic>>::INDEX;
let tagged = NodeGraphLayer::new(layer, network_interface).find_input(&DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER), color_index)?;
match tagged {
TaggedValue::Color(color) => Some(Some(*color)),
value if value.is_no_paint() => Some(None),
_ => None,
}
if let TaggedValue::Color(color) = tagged { Some(*color) } else { None }
}
/// Aggregated fill state across all selected non-artboard layers.
@@ -693,7 +687,7 @@ pub struct SelectedStrokeState {
}
/// Reads the fill state across all selected non-artboard layers, including whether their enabled states or colors differ.
/// "Enabled" tracks node attachment: a layer counts as enabled whenever a Fill node is attached, even when that fill's value is the no-paint choice.
/// "Enabled" tracks node attachment: a layer counts as enabled whenever a Fill node is attached, even when that fill's value is [`FillChoice::None`].
/// Unticked means there is no Fill node. Returns `None` only when no layer is selected.
pub fn selected_fill_state(document: &DocumentMessageHandler) -> Option<SelectedFillState> {
let selected_nodes = document.network_interface.selected_nodes();
@@ -706,9 +700,8 @@ pub fn selected_fill_state(document: &DocumentMessageHandler) -> Option<Selected
let fill_node = document.network_interface.document_network().nodes.get(&fill_node_id)?;
match fill_node.inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)?.as_value()? {
TaggedValue::Color(color) => Some(FillChoice::Solid(*color)),
&TaggedValue::Color(color) => Some(color.map_or(FillChoice::None, FillChoice::Solid)),
TaggedValue::Gradient(stops) => Some(FillChoice::Gradient(stops.clone())),
value if value.is_no_paint() => Some(FillChoice::None),
_ => None,
}
})()
@@ -806,10 +799,10 @@ pub fn set_fill_for_selected_layers(fill_choice: FillChoice, document: &Document
Some(TaggedValue::GradientSpreadMethod(value)) => *value,
_ => GradientSpreadMethod::default(),
};
let has_transform = matches!(read(graphene_std::vector::fill::HasTransformInput::INDEX), Some(TaggedValue::Bool(true)));
let transform = match (has_transform, read(graphene_std::vector::fill::TransformInput::INDEX)) {
(true, Some(TaggedValue::DAffine2(value))) => *value,
(false, _) => initial_gradient_transform_for_bounding_box(document.network_interface.document_metadata().nonzero_bounding_box(layer)),
let transform = match read(graphene_std::vector::fill::TransformInput::INDEX) {
Some(TaggedValue::OptionalDAffine2(value)) => {
value.unwrap_or_else(|| initial_gradient_transform_for_bounding_box(document.network_interface.document_metadata().nonzero_bounding_box(layer)))
}
_ => DAffine2::IDENTITY,
};
@@ -833,7 +826,7 @@ pub fn set_stroke_color_for_selected_layers(color: Option<Color>, weight: f64, d
for layer in layers {
if let Some(node_id) = get_stroke_id(layer, &document.network_interface) {
let input_index = graphene_std::vector::stroke::PaintInput::<List<Graphic>>::INDEX;
let value = color.map_or_else(TaggedValue::no_paint, TaggedValue::Color);
let value = TaggedValue::Color(color);
responses.add(NodeGraphMessage::SetInputValue { node_id, input_index, value });
} else {
let stroke = graphene_std::vector::style::Stroke::new(weight);
@@ -984,6 +977,6 @@ impl<'a> NodeGraphLayer<'a> {
pub fn is_raster_layer(layer: LayerNodeIdentifier, network_interface: &mut NodeNetworkInterface) -> bool {
let layer_input_type = network_interface.input_type(&InputConnector::node(layer.to_node(), 1), &[]);
matches!(layer_input_type.compiled_element_name().as_deref(), Some("Raster<CPU>" | "Raster<GPU>"))
layer_input_type.compiled_nested_type() == Some(&concrete!(List<Raster<CPU>>)) || layer_input_type.compiled_nested_type() == Some(&concrete!(List<Raster<GPU>>))
}
}
@@ -421,7 +421,7 @@ impl ShapeState {
(point.as_handle().is_some() && self.ignore_handles) || (point.as_anchor().is_some() && self.ignore_anchors)
}
/// Applies a dummy vector modification to the layer. In the case where a group containing some vector data is selected, this triggers the creation of a Combine Paths node.
/// Applies a dummy vector modification to the layer. In the case where a group containing some vector data is selected, this triggers the creation of a «Flatten Path» node.
fn add_dummy_modification_to_trigger_graph_reorganization(layer: LayerNodeIdentifier, start_point: PointId, _end_point: PointId, responses: &mut VecDeque<Message>) {
// Apply a zero-delta to one of the points to trigger reorganization
let dummy_modification = VectorModificationType::ApplyPointDelta {
@@ -75,8 +75,8 @@ mod test_ellipse {
let node_graph_layer = NodeGraphLayer::new(layer, &document.network_interface);
let ellipse_node = node_graph_layer.upstream_node_id_from_protonode(ellipse::IDENTIFIER)?;
Some(ResolvedEllipse {
radius_x: instrumented.grab_ranked_input::<ellipse::RadiusXInput>(&vec![ellipse_node], &editor.runtime).unwrap(),
radius_y: instrumented.grab_ranked_input::<ellipse::RadiusYInput>(&vec![ellipse_node], &editor.runtime).unwrap(),
radius_x: instrumented.grab_protonode_input::<ellipse::RadiusXInput>(&vec![ellipse_node], &editor.runtime).unwrap(),
radius_y: instrumented.grab_protonode_input::<ellipse::RadiusYInput>(&vec![ellipse_node], &editor.runtime).unwrap(),
transform: document.metadata().transform_to_document(layer),
})
})
@@ -5,6 +5,7 @@ use crate::messages::tool::common_functionality::graph_modification_utils;
use graph_craft::document::value::TaggedValue;
use graphene_std::NodeInputDecleration;
use graphene_std::choice_type::ChoiceTypeStatic;
use graphene_std::list::List;
use graphene_std::vector::style::{PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
/// All non-color stroke-related options surfaced in the control bar popover.
@@ -214,7 +215,7 @@ pub fn apply_paint_order(drawing: &mut DrawingToolState, order: PaintOrder, docu
pub fn apply_dash_lengths(drawing: &mut DrawingToolState, lengths: Vec<f64>, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
drawing.dash_lengths = Some(lengths.clone());
set_stroke_input_for_selected(document, graphene_std::vector::stroke::DashPatternInput::INDEX, TaggedValue::DashPattern(lengths.into()), responses);
set_stroke_input_for_selected(document, graphene_std::vector::stroke::DashLengthsInput::<List<f64>>::INDEX, TaggedValue::F64Array(lengths), responses);
}
pub fn apply_dash_offset(drawing: &mut DrawingToolState, offset: f64, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
@@ -11,7 +11,9 @@ use crate::messages::tool::common_functionality::transformation_cage::SelectedEd
use crate::messages::tool::tool_messages::path_tool::PathOverlayMode;
use crate::messages::tool::utility_types::ToolType;
use glam::{DAffine2, DVec2};
use graph_craft::concrete;
use graph_craft::document::value::TaggedValue;
use graphene_std::list::List;
use graphene_std::renderer::Quad;
use graphene_std::subpath::{Bezier, BezierHandles};
use graphene_std::vector::algorithms::bezpath_algorithms::pathseg_compute_lookup_table;
@@ -566,11 +568,11 @@ pub fn make_path_editable_is_allowed(network_interface: &mut NodeNetworkInterfac
}
for _ in selected_layers {}
// Must be a vector layer, at either rank
// Must be a layer of type List<Vector>
let node_id = NodeGraphLayer::new(first_layer, network_interface).horizontal_layer_flow().nth(1)?;
let output_type = network_interface.output_type(&OutputConnector::node(node_id, 0), &[]);
if output_type.compiled_element_name().as_deref() != Some("Vector") {
if output_type.compiled_nested_type() != Some(&concrete!(List<Vector>)) {
return None;
}
@@ -205,19 +205,17 @@ impl Fsm for FillToolFsmState {
#[cfg(test)]
mod test_fill {
pub use crate::test_utils::test_prelude::*;
use graphene_std::Graphic;
use graphene_std::color::SRGBA8;
use graphene_std::list::{Item, List};
use graphene_std::list::List;
use graphene_std::vector::fill;
// The Fill tool writes solid colors, whose stored values the input monitor records as `Item<Color>` wires
async fn get_fills(editor: &mut EditorTestUtils) -> Vec<Item<Color>> {
async fn get_fills(editor: &mut EditorTestUtils) -> Vec<List<Color>> {
let instrumented = match editor.eval_graph().await {
Ok(instrumented) => instrumented,
Err(e) => panic!("Failed to evaluate graph: {e}"),
};
instrumented.grab_all_input_as::<fill::FillInput<List<Graphic>>, Item<Color>>(&editor.runtime).collect()
instrumented.grab_all_input::<fill::FillInput<List<Color>>>(&editor.runtime).collect()
}
#[tokio::test]
@@ -247,7 +245,7 @@ mod test_fill {
editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::empty()).await;
let fills = get_fills(&mut editor).await;
assert_eq!(fills.len(), 1);
let color = fills.first().unwrap().element();
let color = fills.first().unwrap().element(0).expect("Color is stored in the list");
assert_eq!(SRGBA8::from(*color), SRGBA8::from(Color::GREEN));
}
@@ -260,7 +258,7 @@ mod test_fill {
editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::SHIFT).await;
let fills = get_fills(&mut editor).await;
assert_eq!(fills.len(), 1);
let color = fills.first().unwrap().element();
let color = fills.first().unwrap().element(0).expect("Color is stored in the list");
assert_eq!(SRGBA8::from(*color), SRGBA8::from(Color::YELLOW));
}
}
@@ -16,7 +16,7 @@ use glam::DMat2;
use graph_craft::document::value::TaggedValue;
use graphene_std::color::SRGBA8;
use graphene_std::raster::color::Color;
use graphene_std::vector::style::{FillChoice, FillChoiceUI, Gradient, GradientSpreadMethod, GradientStop, GradientType, GradientUI, build_transform_with_y_preservation};
use graphene_std::vector::style::{FillChoice, FillChoiceUI, GradientSpreadMethod, GradientStop, GradientStops, GradientStopsUI, GradientType, build_transform_with_y_preservation};
#[derive(Default, ExtractField)]
pub struct GradientTool {
@@ -53,7 +53,7 @@ pub enum GradientToolMessage {
CommitTransactionForColorStop,
CloseStopColorPicker,
UpdateStopColor { color: Color },
UpdateStops { stops: GradientUI },
UpdateStops { stops: GradientStopsUI },
UpdateOptions { options: GradientOptionsUpdate },
}
@@ -146,7 +146,7 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Grad
}
}
ToolMessage::Gradient(GradientToolMessage::UpdateStops { stops }) => {
apply_stops_update(&mut self.data, context, responses, Gradient::from(&stops));
apply_stops_update(&mut self.data, context, responses, GradientStops::from(&stops));
}
ToolMessage::Gradient(GradientToolMessage::CloseStopColorPicker) => {
if self.data.color_picker_transaction_open {
@@ -264,7 +264,7 @@ impl LayoutHolder for GradientTool {
.or_else(|| self.data.default_gradient_stops.clone())
.map(FillChoice::Gradient)
.unwrap_or_else(|| {
FillChoice::Gradient(Gradient::new([
FillChoice::Gradient(GradientStops::new([
GradientStop {
position: 0.,
midpoint: 0.5,
@@ -389,7 +389,7 @@ enum GradientSource {
}
/// Get the gradient with appearance information from Fill node values, or the chain connected to Fill node / layer.
fn resolve_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<(Gradient, GradientAppearance, GradientSource)> {
fn resolve_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<(GradientStops, GradientAppearance, GradientSource)> {
if let Some(stops) = get_gradient_stops(layer, network_interface) {
// A Fill node holding a direct gradient value decodes through the shared reader
if let Some(fill_id) = get_fill_node_id_with_direct_fill_input(layer, network_interface) {
@@ -521,15 +521,15 @@ struct SelectedGradient {
dragging: GradientDragTarget,
/// Transform from the geometry's local gradient space to viewport space.
gradient_space_transform: DAffine2,
gradient: Gradient,
gradient: GradientStops,
appearance: GradientAppearance,
initial_gradient: Gradient,
initial_gradient: GradientStops,
/// Transform from unit [0, 1] line to the geometry's local gradient space, the snapshot from `GradientAppearance.transform`.
initial_gradient_transform: DAffine2,
is_gradient_chain: bool,
}
fn calculate_insertion(start: DVec2, end: DVec2, stops: &Gradient, mouse: DVec2) -> Option<f64> {
fn calculate_insertion(start: DVec2, end: DVec2, stops: &GradientStops, mouse: DVec2) -> Option<f64> {
let distance = (end - start).angle_to(mouse - start).sin() * (mouse - start).length();
let projection = ((end - start).angle_to(mouse - start)).cos() * start.distance(mouse) / start.distance(end);
@@ -568,7 +568,7 @@ fn calculate_insertion(start: DVec2, end: DVec2, stops: &Gradient, mouse: DVec2)
}
impl SelectedGradient {
pub fn new(gradient: Gradient, appearance: GradientAppearance, source: GradientSource, layer: LayerNodeIdentifier, document: &DocumentMessageHandler) -> Self {
pub fn new(gradient: GradientStops, appearance: GradientAppearance, source: GradientSource, layer: LayerNodeIdentifier, document: &DocumentMessageHandler) -> Self {
let gradient_space_transform = gradient_space_transform(layer, document);
Self {
layer: Some(layer),
@@ -820,7 +820,7 @@ impl SelectedGradient {
}
/// Send the four per-attribute graph operations that mirror the in-memory `Gradient` onto the chain feeding the layer.
fn dispatch_gradient_chain_writes(layer: LayerNodeIdentifier, gradient: &Gradient, appearance: GradientAppearance, responses: &mut VecDeque<Message>) {
fn dispatch_gradient_chain_writes(layer: LayerNodeIdentifier, gradient: &GradientStops, appearance: GradientAppearance, responses: &mut VecDeque<Message>) {
responses.add(GraphOperationMessage::GradientStopsSet { layer, stops: gradient.clone() });
responses.add(GraphOperationMessage::GradientTransformSet {
layer,
@@ -868,11 +868,11 @@ struct GradientToolData {
has_selected_gradient: bool,
/// Cached stops of the currently selected layer's gradient, mirrored into the control-bar widget.
/// Independent of any in-progress drag (which uses `selected_gradient`) so it stays current after selection changes too.
current_gradient_stops: Option<Gradient>,
current_gradient_stops: Option<GradientStops>,
/// User-customized default gradient stop colors: used when nothing that has a gradient is selected.
/// `None` means to follow the working colors.
/// Cleared on tool deactivation so each fresh activation starts from the working colors again.
default_gradient_stops: Option<Gradient>,
default_gradient_stops: Option<GradientStops>,
/// Cached viewport-space orientation (true = predominantly rightward) of the selected gradient line.
/// Used to refresh the control bar's "Reverse Direction" icon only when the line's apparent direction flips.
gradient_orientation_rightward: bool,
@@ -1496,7 +1496,7 @@ impl Fsm for GradientToolFsmState {
// Generate a new gradient running primary → secondary so the default working colors
// (primary = black, secondary = white) produce the expected black-to-white gradient
None => (
Gradient::new([
GradientStops::new([
GradientStop {
position: 0.,
midpoint: 0.5,
@@ -1738,7 +1738,7 @@ impl Fsm for GradientToolFsmState {
}
}
fn insert_stop_at_point(gradient: &mut Gradient, point: DVec2, unit_to_viewport: DAffine2) -> Option<usize> {
fn insert_stop_at_point(gradient: &mut GradientStops, point: DVec2, unit_to_viewport: DAffine2) -> Option<usize> {
let (start, end) = gradient_handle_positions(unit_to_viewport);
let t = ((end - start).angle_to(point - start)).cos() * start.distance(point) / start.distance(end);
(0. ..=1.).contains(&t).then(|| gradient.insert_stop(t))
@@ -1831,8 +1831,8 @@ fn apply_gradient_update(
data: &mut GradientToolData,
context: &mut ToolActionMessageContext,
responses: &mut VecDeque<Message>,
condition: impl Fn((&Gradient, &GradientAppearance)) -> bool,
update: impl Fn((&mut Gradient, &mut GradientAppearance)),
condition: impl Fn((&GradientStops, &GradientAppearance)) -> bool,
update: impl Fn((&mut GradientStops, &mut GradientAppearance)),
) {
let selected_layers: Vec<_> = context
.document
@@ -1888,7 +1888,7 @@ fn apply_gradient_update(
/// Set new gradient stops on every selected layer's gradient. Unlike `apply_gradient_update`, this doesn't open its own
/// transaction so it can be called repeatedly during a color picker drag and have all the changes coalesced into a
/// single undo entry by the surrounding 'on_commit' callback.
fn apply_stops_update(data: &mut GradientToolData, context: &mut ToolActionMessageContext, responses: &mut VecDeque<Message>, new_gradient: Gradient) {
fn apply_stops_update(data: &mut GradientToolData, context: &mut ToolActionMessageContext, responses: &mut VecDeque<Message>, new_gradient: GradientStops) {
let selected_layers: Vec<_> = context
.document
.network_interface
@@ -1933,7 +1933,7 @@ fn apply_stops_update(data: &mut GradientToolData, context: &mut ToolActionMessa
}
/// Find the first selected visible layer that has a gradient and return both the layer ID and its resolved gradient.
fn current_layer_and_gradient(document: &DocumentMessageHandler) -> (Option<LayerNodeIdentifier>, Option<(Gradient, GradientAppearance)>) {
fn current_layer_and_gradient(document: &DocumentMessageHandler) -> (Option<LayerNodeIdentifier>, Option<(GradientStops, GradientAppearance)>) {
for layer in document.network_interface.selected_nodes().selected_visible_layers(&document.network_interface) {
if let Some((gradient, appearance, _source)) = resolve_gradient(layer, &document.network_interface) {
return (Some(layer), Some((gradient, appearance)));
@@ -1942,7 +1942,7 @@ fn current_layer_and_gradient(document: &DocumentMessageHandler) -> (Option<Laye
(None, None)
}
fn get_gradient_on_selected_layer(document: &DocumentMessageHandler) -> Option<(Gradient, GradientAppearance, GradientSource)> {
fn get_gradient_on_selected_layer(document: &DocumentMessageHandler) -> Option<(GradientStops, GradientAppearance, GradientSource)> {
document
.network_interface
.selected_nodes()
@@ -2015,19 +2015,19 @@ mod test_gradient {
use graphene_std::color::SRGBA8;
use graphene_std::list::List;
use graphene_std::vector::style::{GradientSpreadMethod, build_transform_with_y_preservation};
use graphene_std::vector::{Gradient, GradientStop, fill};
use graphene_std::vector::{GradientStop, GradientStops, fill};
use graphene_std::{Graphic, NodeInputDecleration};
use super::gradient_space_transform;
struct ResolvedGradient {
stops: Gradient,
stops: GradientStops,
spread_method: GradientSpreadMethod,
transform: DAffine2,
}
impl ResolvedGradient {
fn new(stops: Gradient, appearance: super::GradientAppearance) -> Self {
fn new(stops: GradientStops, appearance: super::GradientAppearance) -> Self {
Self {
stops,
spread_method: appearance.spread_method,
@@ -2068,9 +2068,8 @@ mod test_gradient {
_ => GradientSpreadMethod::default(),
};
let has_transform = matches!(fill_node.inputs.get(fill::HasTransformInput::INDEX).and_then(|input| input.as_value()), Some(&TaggedValue::Bool(true)));
let local_transform = match fill_node.inputs.get(fill::TransformInput::INDEX).and_then(|input| input.as_value()) {
Some(&TaggedValue::DAffine2(value)) if has_transform => value,
Some(&TaggedValue::OptionalDAffine2(Some(value))) => value,
_ => DAffine2::IDENTITY,
};
@@ -2148,7 +2147,7 @@ mod test_gradient {
.handle_message(NodeGraphMessage::SetInputValue {
node_id: gradient_node_id,
input_index: 1,
value: TaggedValue::Gradient(Gradient::new([
value: TaggedValue::Gradient(GradientStops::new([
GradientStop {
position: 0.,
midpoint: 0.5,
@@ -2185,7 +2184,7 @@ mod test_gradient {
.handle_message(NodeGraphMessage::SetInputValue {
node_id: gradient_node_id,
input_index: 1,
value: TaggedValue::Gradient(Gradient::new([
value: TaggedValue::Gradient(GradientStops::new([
GradientStop {
position: 0.,
midpoint: 0.5,
@@ -2656,7 +2655,7 @@ mod test_gradient {
// Create original transform for the control geometry and apply it
let initial_start = DVec2::new(10., 50.);
let initial_end = DVec2::new(200., 50.);
let stops = Gradient::new([
let stops = GradientStops::new([
GradientStop {
position: 0.,
midpoint: 0.5,
@@ -2727,7 +2726,7 @@ mod test_gradient {
let layer = create_gradient_list_layer(&mut editor).await;
// Set up a 3-stop gradient with distinct colors
let original_stops = Gradient::new([
let original_stops = GradientStops::new([
GradientStop {
position: 0.,
midpoint: 0.5,
@@ -2828,7 +2827,7 @@ mod test_gradient {
.handle_message(NodeGraphMessage::SetInputValue {
node_id: gradient_value_id,
input_index: 1,
value: TaggedValue::Gradient(Gradient::new([
value: TaggedValue::Gradient(GradientStops::new([
GradientStop {
position: 0.,
midpoint: 0.5,
+30 -109
View File
@@ -1,4 +1,4 @@
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
use crate::messages::frontend::utility_types::{ExportBounds, FileType, RasterizedImage};
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
use crate::messages::prelude::*;
use glam::{DAffine2, DVec2, UVec2};
@@ -82,7 +82,7 @@ struct ExecutionContext {
/// Set when this execution is a gradient-migration measurement run, carrying the "Fill" node (addressed by its enclosing
/// network path) and its original relative gradient. The evaluated geometry is read back from the inspect result to size the
/// gradient; such runs never touch the visible artwork. Carrying the entry keeps a stale re-dispatched response paired with the fill it measured.
measure_fill: Option<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::LegacyGradient)>,
measure_fill: Option<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::Gradient)>,
}
// TODO: Eventually remove this document upgrade code
@@ -92,7 +92,7 @@ struct ExecutionContext {
#[derive(Debug, Clone)]
struct GradientMigration {
document_id: DocumentId,
remaining: VecDeque<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::LegacyGradient)>,
remaining: VecDeque<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::Gradient)>,
resolution: UVec2,
scale: f64,
}
@@ -196,8 +196,6 @@ impl NodeGraphExecutor {
render_mode: document.render_mode,
for_export: false,
for_eyedropper: false,
hide_artboard_background: false,
bake_stroke_dashes: false,
};
// Execute the node graph
@@ -269,8 +267,6 @@ impl NodeGraphExecutor {
render_mode,
for_export: false,
for_eyedropper: true,
hide_artboard_background: false,
bake_stroke_dashes: false,
};
// Execute the node graph
@@ -319,25 +315,15 @@ impl NodeGraphExecutor {
..Default::default()
};
// The plotter flow switches the viewport to Outline mode as a preview, so pin its export to the normal render
// mode for a deterministic serialization regardless of what the viewport is showing
let render_mode = if export_config.for_plotter {
graphene_std::vector::style::RenderMode::Normal
} else {
document.render_mode
};
let render_config = RenderConfig {
viewport,
scale: export_config.scale_factor,
time: Default::default(),
pointer: DVec2::ZERO,
export_format,
render_mode,
render_mode: document.render_mode,
for_export: true,
for_eyedropper: false,
hide_artboard_background: export_config.for_plotter,
bake_stroke_dashes: export_config.for_plotter,
};
export_config.size = resolution;
@@ -464,6 +450,7 @@ impl NodeGraphExecutor {
resolved_types: incomplete_delta,
node_graph_errors,
});
responses.add(NodeGraphMessage::SendGraph);
return Err(format!("Node graph evaluation failed:\n{e}"));
}
@@ -474,6 +461,7 @@ impl NodeGraphExecutor {
resolved_types: type_delta,
node_graph_errors,
});
responses.add(NodeGraphMessage::SendGraph);
}
NodeGraphUpdate::EyedropperPreview(raster) => {
let (data, width, height) = raster.to_flat_u8();
@@ -504,7 +492,7 @@ impl NodeGraphExecutor {
}
// Snapshot the queue but leave `pending_gradient_bbox_bake` populated, so subsequent render requests keep deferring here (and hit the guard above); each entry is removed from the document as its bake lands.
let remaining: VecDeque<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::LegacyGradient)> = document.pending_gradient_bbox_bake.iter().cloned().collect();
let remaining: VecDeque<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::Gradient)> = document.pending_gradient_bbox_bake.iter().cloned().collect();
let Some((first_network_path, first_fill, first_gradient)) = remaining.front().cloned() else {
return false;
};
@@ -531,7 +519,7 @@ impl NodeGraphExecutor {
document_id: DocumentId,
network_path: Vec<NodeId>,
fill_node_id: NodeId,
gradient: graphic_types::migrations::legacy::LegacyGradient,
gradient: graphic_types::migrations::legacy::Gradient,
resolution: UVec2,
scale: f64,
responses: &mut VecDeque<Message>,
@@ -582,8 +570,6 @@ impl NodeGraphExecutor {
render_mode: document.render_mode,
for_export: false,
for_eyedropper: false,
hide_artboard_background: false,
bake_stroke_dashes: false,
};
let execution_id = self.queue_execution(render_config);
self.futures.push_back((
@@ -602,7 +588,7 @@ impl NodeGraphExecutor {
&mut self,
document: &mut DocumentMessageHandler,
document_id: DocumentId,
bake_target: (Vec<NodeId>, NodeId, graphic_types::migrations::legacy::LegacyGradient),
bake_target: (Vec<NodeId>, NodeId, graphic_types::migrations::legacy::Gradient),
inspect_result: Option<InspectResult>,
responses: &mut VecDeque<Message>,
) {
@@ -624,14 +610,10 @@ impl NodeGraphExecutor {
if fill_transform_unbaked(document, &network_path, fill_node_id) {
let absolute_gradient = gradient.to_absolute(bounding_box, item_transform);
let gradient_transform = absolute_gradient.transform * absolute_gradient.to_transform();
let has_transform_input = InputConnector::node(fill_node_id, graphene_std::vector::fill::HasTransformInput::INDEX);
let transform_input = InputConnector::node(fill_node_id, graphene_std::vector::fill::TransformInput::INDEX);
let input = InputConnector::node(fill_node_id, graphene_std::vector::fill::TransformInput::INDEX);
document
.network_interface
.set_input(&has_transform_input, NodeInput::value(TaggedValue::Bool(true), false), &network_path);
document
.network_interface
.set_input(&transform_input, NodeInput::value(TaggedValue::DAffine2(gradient_transform), false), &network_path);
.set_input(&input, NodeInput::value(TaggedValue::OptionalDAffine2(Some(gradient_transform)), false), &network_path);
}
// The transform is settled, so its entry no longer needs to persist for a retry on the next open
@@ -678,19 +660,15 @@ impl NodeGraphExecutor {
match render_output.data {
RenderOutputType::Svg { svg, image_data } => {
// Convert each linear-light `Image<Color>` into the JS-boundary `Image<SRGBA8>` form (gamma byte channels) before dispatching.
// Convert each linear-light `Image<Color>` into gamma sRGB bytes (the DOM boundary form) before dispatching.
let rgba8_bytes = |&color: &_| <[u8; 4]>::from(SRGBA8::from(color));
let image_data = image_data
.into_iter()
.map(|(id, image)| {
(
id,
graphene_std::raster::Image {
width: image.width,
height: image.height,
data: image.data.iter().map(|&c| SRGBA8::from(c)).collect(),
base64_string: image.base64_string,
},
)
.map(|(id, image)| RasterizedImage {
id,
width: image.width,
height: image.height,
pixels: image.data.iter().flat_map(rgba8_bytes).collect::<Vec<u8>>().into(),
})
.collect();
responses.add(FrontendMessage::UpdateImageData { image_data });
@@ -749,8 +727,6 @@ impl NodeGraphExecutor {
size,
artboard_name,
artboard_count,
for_plotter,
plotter_estimate_only,
..
} = export_config;
@@ -771,18 +747,7 @@ impl NodeGraphExecutor {
data: RenderOutputType::Svg { svg, .. },
..
}) => {
if plotter_estimate_only {
// Measure the SVG the plotter would receive and report the time estimate back to the dialog
let seconds =
graphene_std::renderer::plot_statistics::svg_plot_statistics(&svg).map(|statistics| crate::messages::dialog::send_to_plotter_dialog::estimated_plot_seconds(&statistics));
responses.add(DialogMessage::SendToPlotterDialog(SendToPlotterDialogMessage::UpdateTimeEstimate { seconds }));
} else if for_plotter {
responses.add(FrontendMessage::TriggerSendToPlotter {
name: base_name,
svg,
address: crate::consts::PLOTTER_SERVER_ADDRESS.to_string(),
});
} else if file_type == FileType::Svg {
if file_type == FileType::Svg {
responses.add(FrontendMessage::TriggerSaveFile {
name,
folder,
@@ -852,16 +817,16 @@ impl NodeGraphExecutor {
}
// TODO: Eventually remove this document upgrade code
/// Whether the fill node's `_has_transform` is still `false`, meaning its gradient placement has not yet been baked
/// (or set by the user), so a measured bake may safely be written.
/// Whether the fill node's transform input is still the unset `OptionalDAffine2(None)` placeholder that the migration leaves
/// behind, meaning its gradient placement has not yet been baked (or set by the user), so a measured bake may safely be written.
fn fill_transform_unbaked(document: &DocumentMessageHandler, network_path: &[NodeId], fill_node_id: NodeId) -> bool {
let Some(network) = document.network_interface.document_network().nested_network(network_path) else {
return false;
};
let Some(node) = network.nodes.get(&fill_node_id) else { return false };
matches!(
node.inputs.get(graphene_std::vector::fill::HasTransformInput::INDEX).and_then(|input| input.as_value()),
Some(TaggedValue::Bool(false))
node.inputs.get(graphene_std::vector::fill::TransformInput::INDEX).and_then(|input| input.as_value()),
Some(TaggedValue::OptionalDAffine2(None))
)
}
@@ -948,18 +913,9 @@ mod test {
use graph_craft::document::NodeNetwork;
use graphene_std::Context;
use graphene_std::NodeInputDecleration;
use graphene_std::list::Item;
use graphene_std::memo::IORecord;
use test_prelude::LayerNodeIdentifier;
/// A ranked input whose `Item<E>` Result carries an element `E`, recovered by `grab_ranked_input`.
pub trait RankedResult {
type Element: Send + Sync + Clone + 'static;
}
impl<E: Send + Sync + Clone + 'static> RankedResult for Item<E> {
type Element = E;
}
/// Stores all of the monitor nodes that have been attached to a graph
#[derive(Default)]
pub struct Instrumented {
@@ -982,17 +938,11 @@ mod test {
let mut monitor_node_ids = Vec::with_capacity(node.inputs.len());
for input in &mut node.inputs {
let node_id = NodeId::new();
let old_input = std::mem::replace(input, NodeInput::node(node_id, 0));
monitor_nodes.push((old_input, node_id));
path.push(node_id);
monitor_node_ids.push(path.clone());
path.pop();
// A None value is a unit wire with nothing to record and no Monitor row, so its slot stays a dead path that introspects as absent
if matches!(input, NodeInput::Value { tagged_value, .. } if matches!(&**tagged_value, graph_craft::document::value::TaggedValue::None)) {
continue;
}
let old_input = std::mem::replace(input, NodeInput::node(node_id, 0));
monitor_nodes.push((old_input, node_id));
}
if let DocumentNodeImplementation::ProtoNode(identifier) = &mut node.implementation {
path.push(*id);
@@ -1024,21 +974,15 @@ mod test {
where
Input::Result: Send + Sync + Clone + 'static,
{
Self::downcast_record::<Input::Result>(dynamic).or_else(|| {
warn!("cannot downcast type for introspection");
None
})
}
/// Pulls a concrete output type out of a monitor record, tolerating the three context shapes the executor records against.
fn downcast_record<Output: Send + Sync + Clone + 'static>(dynamic: Arc<dyn std::any::Any + Send + Sync>) -> Option<Output> {
if let Some(x) = dynamic.downcast_ref::<IORecord<(), Output>>() {
// This is quite inflexible since it only allows the footprint as inputs.
if let Some(x) = dynamic.downcast_ref::<IORecord<(), Input::Result>>() {
Some(x.output.clone())
} else if let Some(x) = dynamic.downcast_ref::<IORecord<Footprint, Output>>() {
} else if let Some(x) = dynamic.downcast_ref::<IORecord<Footprint, Input::Result>>() {
Some(x.output.clone())
} else if let Some(x) = dynamic.downcast_ref::<IORecord<Context, Output>>() {
} else if let Some(x) = dynamic.downcast_ref::<IORecord<Context, Input::Result>>() {
Some(x.output.clone())
} else {
warn!("cannot downcast type for introspection");
None
}
}
@@ -1057,18 +1001,6 @@ mod test {
.filter_map(Instrumented::downcast::<Input>) // Some might not resolve (e.g. generics that don't work properly)
}
/// Like [`Self::grab_all_input`], but downcasting the recorded values to `Output` instead of the marker's `Result`.
/// Useful when a stored value's wire form (e.g. `Item<Color>`) differs from the declared row types the marker's generic accepts.
pub fn grab_all_input_as<'a, Input: NodeInputDecleration + 'a, Output: Send + Sync + Clone + 'static>(&'a self, runtime: &'a NodeRuntime) -> impl Iterator<Item = Output> + 'a {
self.protonodes_by_name
.get(&Input::identifier())
.map_or([].as_slice(), |x| x.as_slice())
.iter()
.filter_map(|inputs| inputs.get(Input::INDEX))
.filter_map(|input_monitor_node| runtime.executor.introspect(input_monitor_node).ok())
.filter_map(Instrumented::downcast_record::<Output>)
}
pub fn grab_protonode_input<Input: NodeInputDecleration>(&self, path: &Vec<NodeId>, runtime: &NodeRuntime) -> Option<Input::Result>
where
Input::Result: Send + Sync + Clone + 'static,
@@ -1080,17 +1012,6 @@ mod test {
Self::downcast::<Input>(dynamic)
}
/// Grabs a ranked (`Item<E>`) input's recorded value as its bare element `E`.
/// A stored value materializes as an `Item<E>` wire, so the monitor records the whole cell and this unwraps its element.
pub fn grab_ranked_input<Input: NodeInputDecleration>(&self, path: &Vec<NodeId>, runtime: &NodeRuntime) -> Option<<Input::Result as RankedResult>::Element>
where
Input::Result: RankedResult,
{
let input_monitor_node = self.protonodes_by_path.get(path)?.get(Input::INDEX)?;
let dynamic = runtime.executor.introspect(input_monitor_node).ok()?;
Self::downcast_record::<Item<<Input::Result as RankedResult>::Element>>(dynamic).map(|item| item.into_element())
}
pub fn grab_input_from_layer<Input: NodeInputDecleration>(&self, layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface, runtime: &NodeRuntime) -> Option<Input::Result>
where
Input::Result: Send + Sync + Clone + 'static,
+2 -28
View File
@@ -10,7 +10,7 @@ use graph_craft::graphene_compiler::Compiler;
use graph_craft::proto::GraphErrors;
use graphene_std::application_io::{ApplicationIo, ExportFormat, NodeGraphUpdateMessage, NodeGraphUpdateSender, RenderConfig, Texture};
use graphene_std::bounds::RenderBoundingBox;
use graphene_std::list::{Item, List};
use graphene_std::list::List;
use graphene_std::memo::IORecord;
use graphene_std::ops::Convert;
#[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))]
@@ -91,10 +91,6 @@ pub struct ExportConfig {
pub size: UVec2,
pub artboard_name: Option<String>,
pub artboard_count: usize,
/// Send the exported SVG to the pen plotter print server instead of saving it as a file.
pub for_plotter: bool,
/// Only measure the plotter SVG for a time estimate instead of sending it to the print server.
pub plotter_estimate_only: bool,
}
#[derive(Clone)]
@@ -382,7 +378,7 @@ impl NodeRuntime {
use graph_craft::graphene_compiler::Executor;
match self.executor.input_type() {
Some(t) if t == concrete!(Context) => (&self.executor).execute(render_config.into_context()).await.map_err(|e| e.to_string()),
Some(t) if t == concrete!(RenderConfig) => (&self.executor).execute(render_config).await.map_err(|e| e.to_string()),
Some(t) if t == concrete!(()) => (&self.executor).execute(()).await.map_err(|e| e.to_string()),
Some(t) => Err(format!("Invalid input type {t:?}")),
_ => Err(format!("No input type:\n{:?}", self.node_graph_errors)),
@@ -445,28 +441,6 @@ impl NodeRuntime {
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &io.output, bounds, responses)
}
}
// Rank-0 wires record single items; each arm mirrors its list counterpart through a singleton raise
else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, Item<Graphic>>>() {
if update_thumbnails {
let singleton = List::new_from_item(io.output.clone());
let bounds = graphene_std::renderer::graphic_list_bounding_box(&singleton, DAffine2::IDENTITY);
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &singleton, bounds, responses)
}
} else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, Item<Artboard>>>() {
if update_thumbnails {
let singleton = List::new_from_item(io.output.clone());
let bounds = artboard_clip_bounds(&singleton);
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &singleton, bounds, responses)
}
} else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, Item<Vector>>>() {
self.vector_modify.insert(parent_network_node_id, io.output.element().clone());
} else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, Item<String>>>() {
if update_thumbnails {
let singleton = List::new_from_item(io.output.clone());
let bounds = graphene_std::renderer::text_list_bounding_box(&singleton, DAffine2::IDENTITY);
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &singleton, bounds, responses)
}
}
// Other
else {
log::warn!("Failed to downcast monitor node output {parent_network_node_id:?}");
+1
View File
@@ -1,4 +1,5 @@
node_modules/
wrapper/pkg/
wrapper/pkg-native/
public/build/
dist/
+1
View File
@@ -29,6 +29,7 @@ export default defineConfig([
"**/node_modules/",
"**/dist/",
"**/pkg/",
"**/pkg-native/",
"wasm/pkg/",
// Don't ignore JS and TS dotfiles in this folder
"!**/.*.js",
+11 -31
View File
@@ -320,7 +320,7 @@
<div class="wires" style:transform-origin="0 0" style:transform={`translate(${$nodeGraphTransform.x}px, ${$nodeGraphTransform.y}px) scale(${$nodeGraphTransform.scale})`}>
<svg>
{#each $nodeGraphWires.values() as map}
{#each map.values() as { pathString, centerPathString, dataType, thick, dashed }}
{#each map.values() as { pathString, dataType, thick, dashed }}
{#if thick}
<path
d={pathString}
@@ -329,8 +329,6 @@
style:--data-color-dim={`var(--color-data-${dataType.toLowerCase()}-dim)`}
style:--data-dasharray={`3,${dashed ? 2 : 0}`}
/>
<!-- A thin inner line splits the layer-stack wire down the middle reaching past the ends into the cleaved connector slots -->
<path d={centerPathString} style:--data-line-width="2px" style:--data-color="#444444" style:--data-color-dim="#444444" style:--data-dasharray={`3,${dashed ? 2 : 0}`} />
{/if}
{/each}
{/each}
@@ -563,10 +561,7 @@
{#if node.primaryOutput.connectedTo.length > 0}
<path d="M0,6.953l2.521,-1.694a2.649,2.649,0,0,1,2.959,0l2.52,1.694v5.047h-8z" fill="var(--data-color)" />
{#if node.primaryOutputConnectedToLayer}
<path
d="M0,4.5 C0,4.5 0,-3.5 0,-3.5 C0,-3.5 3,-3.5 3,-3.5 C3,-3.5 3,2.565 3,2.565 C2.834,2.632 2.673,2.717 2.52,2.819 C2.52,2.819 0,4.5 0,4.5 ZM5,2.566 C5,2.566 5,-3.5 5,-3.5 C5,-3.5 8,-3.5 8,-3.5 C8,-3.5 8,4.5 8,4.5 C8,4.5 5.479,2.819 5.479,2.819 C5.326,2.717 5.166,2.633 5,2.566 Z"
fill="var(--data-color-dim)"
/>
<path d="M0,-3.5h8v8l-2.521,-1.681a2.666,2.666,0,0,0,-2.959,0l-2.52,1.681z" fill="var(--data-color-dim)" />
{/if}
{:else}
<path d="M0,6.953l2.521,-1.694a2.649,2.649,0,0,1,2.959,0l2.52,1.694v5.047h-8z" fill="var(--data-color-dim)" />
@@ -588,10 +583,7 @@
{#if node.primaryInput?.connectedTo !== "Connected to nothing."}
<path d="M0,0H8V8L5.479,6.319a2.666,2.666,0,0,0-2.959,0L0,8Z" fill="var(--data-color)" />
{#if node.primaryInputConnectedToLayer}
<path
d="M2.512,9.26 C2.673,9.157 2.834,9.072 3,9 C3,9 3,16 3,16 C3,16 0,16 0,16 C0,16 0,10.95 0,10.95 C0,10.95 2.512,9.26 2.512,9.26 ZM5,16 C5,16 5,9 5,9 C5.166,9.073 5.327,9.158 5.48,9.26 C5.48,9.26 8,10.95 8,10.95 C8,10.95 8,16 8,16 C8,16 5,16 5,16 Z"
fill="var(--data-color-dim)"
/>
<path d="M0,10.95l2.52,-1.69c0.89,-0.6,2.06,-0.6,2.96,0l2.52,1.69v5.05h-8v-5.05z" fill="var(--data-color-dim)" />
{/if}
{:else}
<path d="M0,0H8V8L5.479,6.319a2.666,2.666,0,0,0-2.959,0L0,8Z" fill="var(--data-color-dim)" />
@@ -687,27 +679,15 @@
<div class="wires">
<svg>
{#each $nodeGraphWires.values() as map}
{#each map.values() as { pathString, dataType, thick, dashed, isList }}
{#each map.values() as { pathString, dataType, thick, dashed }}
{#if !thick}
{#if isList}
<!-- A rank-1 List wire reads as two parallel lines: a triple-width data line split down the middle by a 1x background-colored overlay -->
<path
d={pathString}
style:--data-line-width="4px"
style:--data-color={`var(--color-data-${dataType.toLowerCase()})`}
style:--data-color-dim={`var(--color-data-${dataType.toLowerCase()}-dim)`}
style:--data-dasharray={`3,${dashed ? 2 : 0}`}
/>
<path d={pathString} style:--data-line-width="2px" style:--data-color="#444444" style:--data-color-dim="#444444" style:--data-dasharray={`3,${dashed ? 2 : 0}`} />
{:else}
<path
d={pathString}
style:--data-line-width="2px"
style:--data-color={`var(--color-data-${dataType.toLowerCase()})`}
style:--data-color-dim={`var(--color-data-${dataType.toLowerCase()}-dim)`}
style:--data-dasharray={`3,${dashed ? 2 : 0}`}
/>
{/if}
<path
d={pathString}
style:--data-line-width="2px"
style:--data-color={`var(--color-data-${dataType.toLowerCase()})`}
style:--data-color-dim={`var(--color-data-${dataType.toLowerCase()}-dim)`}
style:--data-dasharray={`3,${dashed ? 2 : 0}`}
/>
{/if}
{/each}
{/each}
@@ -2,7 +2,7 @@
import { createEventDispatcher } from "svelte";
import ColorPicker from "/src/components/floating-menus/ColorPicker.svelte";
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import { contrastingOutlineFactor, fillChoiceUIColor, fillChoiceUIGradient } from "/src/utility-functions/colors";
import { contrastingOutlineFactor, fillChoiceUIColor, fillChoiceUIGradientStops } from "/src/utility-functions/colors";
import type { FillChoiceUI, MenuDirection, ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
const dispatch = createEventDispatcher<{ value: FillChoiceUI; startHistoryTransaction: undefined }>();
@@ -29,10 +29,10 @@
$: outlineFactor = contrastingOutlineFactor(value, "--color-3-darkgray", 0.01);
$: outlined = outlineFactor > 0.0001;
$: gradient = fillChoiceUIGradient(value);
$: gradientStops = fillChoiceUIGradientStops(value);
$: solidColor = fillChoiceUIColor(value);
$: none = value === "None";
$: transparency = gradient ? gradient.color.some((color) => color.alpha < 255) : solidColor ? solidColor.alpha < 255 : false;
$: transparency = gradientStops ? gradientStops.color.some((color) => color.alpha < 255) : solidColor ? solidColor.alpha < 255 : false;
</script>
<LayoutCol
-32
View File
@@ -29,9 +29,6 @@ const initialState: PortfolioStoreState = {
let subscriptionsRouter: SubscriptionsRouter | undefined = undefined;
// Prevents double-submitting a plotter job while one upload is still in flight
let plotterUploadInFlight = false;
// Store state persisted across HMR to maintain reactive subscriptions in the component tree
const store: Writable<PortfolioStoreState> = import.meta.hot?.data?.store || writable<PortfolioStoreState>(initialState);
if (import.meta.hot) import.meta.hot.data.store = store;
@@ -132,34 +129,6 @@ export function createPortfolioStore(subscriptions: SubscriptionsRouter, editor:
}
});
subscriptions.subscribeFrontendMessage("TriggerSendToPlotter", async (data) => {
const { name, svg, address } = data;
if (plotterUploadInFlight) return;
plotterUploadInFlight = true;
try {
// POST the SVG to the print server's job queue endpoint, with the job name in the query string
const endpoint = `${address}/api/jobs?name=${encodeURIComponent(name)}`;
let response;
try {
response = await fetch(endpoint, { method: "POST", headers: { "content-type": "image/svg+xml" }, body: svg });
} catch {
editor.errorDialog("Send to Plotter failed", `Could not reach the print server. Is it running at ${address} and connected to the same network?`);
return;
}
if (response.status === 201) {
editor.sendToPlotterSuccessDialog(name);
} else {
const serverError = (await response.json().catch(() => undefined))?.error;
editor.errorDialog("Send to Plotter failed", `The print server rejected the job${serverError ? `: ${serverError}` : ` (HTTP ${response.status})`}.`);
}
} finally {
plotterUploadInFlight = false;
}
});
subscriptions.subscribeFrontendMessage("UpdateWorkspacePanelLayout", (data) => {
update((state) => {
state.panelLayout = data.panelLayout;
@@ -227,7 +196,6 @@ export function destroyPortfolioStore() {
subscriptions.unsubscribeFrontendMessage("TriggerSaveDocument");
subscriptions.unsubscribeFrontendMessage("TriggerSaveFile");
subscriptions.unsubscribeFrontendMessage("TriggerExportImage");
subscriptions.unsubscribeFrontendMessage("TriggerSendToPlotter");
subscriptions.unsubscribeFrontendMessage("UpdateWorkspacePanelLayout");
subscriptions.unsubscribeLayoutUpdate("WelcomeScreenButtons");
subscriptions.unsubscribeLayoutUpdate("PropertiesPanel");
+9 -9
View File
@@ -1,4 +1,4 @@
import type { FillChoiceUI, GradientUI, SRGBA8 } from "/wrapper/pkg/graphite_wasm_wrapper";
import type { FillChoiceUI, GradientStopsUI, SRGBA8 } from "/wrapper/pkg/graphite_wasm_wrapper";
// Channels can have any range (0-1, 0-255, 0-100, 0-360) in the context they are being used in, these are just containers for the numbers
export type HSV = { h: number; s: number; v: number };
@@ -167,12 +167,12 @@ export function contrastingOutlineFactor(value: FillChoiceUI, proximityColor: st
return (1 - Math.min(distance / proximityRange, 1)) * (1 - sRgba8ToHSV(color).s);
};
const gradient = fillChoiceUIGradient(value);
if (gradient) {
if (gradient.color.length === 0) return 0;
const gradientStops = fillChoiceUIGradientStops(value);
if (gradientStops) {
if (gradientStops.color.length === 0) return 0;
const first = contrast(gradient.color[0]);
const last = contrast(gradient.color[gradient.color.length - 1]);
const first = contrast(gradientStops.color[0]);
const last = contrast(gradientStops.color[gradientStops.color.length - 1]);
return Math.min(first, last);
}
@@ -182,7 +182,7 @@ export function contrastingOutlineFactor(value: FillChoiceUI, proximityColor: st
// GRADIENT UTILITY FUNCTIONS
export function isGradientUI(value: unknown): value is GradientUI {
export function isGradientStopsUI(value: unknown): value is GradientStopsUI {
return typeof value === "object" && value !== null && "position" in value && "midpoint" in value && "color" in value;
}
@@ -193,7 +193,7 @@ export function fillChoiceUIColor(value: FillChoiceUI): SRGBA8 | undefined {
return undefined;
}
export function fillChoiceUIGradient(value: FillChoiceUI): GradientUI | undefined {
export function fillChoiceUIGradientStops(value: FillChoiceUI): GradientStopsUI | undefined {
if (typeof value === "object" && "Gradient" in value) return value.Gradient;
return undefined;
}
@@ -201,6 +201,6 @@ export function fillChoiceUIGradient(value: FillChoiceUI): GradientUI | undefine
export function parseFillChoiceUI(value: unknown): FillChoiceUI {
if (value === "None" || value === undefined || value === null) return "None";
if (typeof value === "object" && value !== null && "Solid" in value && isSRgba8(value.Solid)) return { Solid: value.Solid };
if (typeof value === "object" && value !== null && "Gradient" in value && isGradientUI(value.Gradient)) return { Gradient: value.Gradient };
if (typeof value === "object" && value !== null && "Gradient" in value && isGradientStopsUI(value.Gradient)) return { Gradient: value.Gradient };
return "None";
}
+4 -1
View File
@@ -23,7 +23,10 @@ export default defineConfig(({ mode }) => {
// Default for builds that exclude the `wasmSplitting` plugin, which overrides this when active
define: { __WASM_PART_COUNT__: "1" },
resolve: {
alias: [{ find: /\/..\/branding\/(.*\.svg)/, replacement: path.resolve(projectRootDir, "../branding", "$1?raw") }],
alias: [
...(mode === "native" ? [{ find: /^\/wrapper\/pkg\//, replacement: "/wrapper/pkg-native/" }] : []),
{ find: /\/..\/branding\/(.*\.svg)/, replacement: path.resolve(projectRootDir, "../branding", "$1?raw") },
],
},
server: {
port: 8080,
+15 -11
View File
@@ -11,33 +11,37 @@ repository = "https://github.com/GraphiteEditor/Graphite"
license = "Apache-2.0"
[features]
default = ["gpu", "shader-nodes"]
gpu = ["editor/gpu"]
shader-nodes = ["graphene-std/shader-nodes", "gpu"]
native = ["node-macro/disable-registration"]
default = ["gpu", "shader-nodes", "web"]
web = ["editor", "editor?/wasm"]
editor = ["dep:editor", "dep:graphene-std", "dep:graph-craft", "dep:wgpu"]
gpu = ["editor?/gpu"]
shader-nodes = ["graphene-std?/shader-nodes", "gpu"]
native = []
[lib]
crate-type = ["cdylib", "rlib"]
[dependencies]
# Local dependencies
editor = { path = "../../editor", package = "graphite-editor", features = ["gpu", "wasm"] }
graphene-std = { workspace = true }
editor = { path = "../../editor", package = "graphite-editor", optional = true }
graphite-proc-macros = { workspace = true }
graphene-std = { workspace = true, optional = true }
# Workspace dependencies
bytemuck = { workspace = true }
graph-craft = { workspace = true }
graph-craft = { workspace = true, optional = true }
log = { workspace = true }
serde = { workspace = true }
wasm-bindgen = { workspace = true }
serde-wasm-bindgen = { workspace = true }
js-sys = { workspace = true }
wasm-bindgen-futures = { workspace = true }
wgpu = { workspace = true }
wgpu = { workspace = true, optional = true }
web-sys = { workspace = true }
ron = { workspace = true }
serde_json = { workspace = true }
node-macro = { workspace = true }
tsify = { workspace = true }
[dev-dependencies]
serde_bytes = { workspace = true }
[lints.rust]
unexpected_cfgs = { level = "warn", check-cfg = [
+690
View File
@@ -0,0 +1,690 @@
//! Commands that JS can call on the editor. Each function maps its arguments to a `Message`. On web the generated
//! stub dispatches it directly, on native the arguments are sent as an `EditorCommand` and the same body runs in
//! the editor process.
#![allow(clippy::too_many_arguments)]
#[cfg(target_family = "wasm")]
use crate::editor_wrapper::EditorWrapper;
use graphite_proc_macros::editor_commands;
use serde::{Deserialize, Serialize};
use tsify::Tsify;
#[cfg(target_family = "wasm")]
use wasm_bindgen::prelude::*;
#[editor_commands]
mod editor_commands {
use crate::helpers::translate_key;
use editor::messages::clipboard::utility_types::ClipboardContentRaw;
use editor::messages::input_mapper::utility_types::input_keyboard::ModifierKeys;
use editor::messages::input_mapper::utility_types::input_mouse::{EditorMouseState, ScrollDelta};
use editor::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use editor::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use editor::messages::portfolio::document::utility_types::network_interface::ImportOrExport;
use editor::messages::portfolio::utility_types::PanelGroupId;
use editor::messages::prelude::*;
use editor::messages::tool::tool_messages::tool_prelude::WidgetId;
use graph_craft::document::NodeId;
use graphene_std::raster::color::Color;
use graphene_std::vector::style::FillChoice;
use std::path::PathBuf;
/// Re-sends all UI layouts to the frontend. Called during HMR re-mounts when the frontend has lost its layout state.
fn resend_all_layouts() -> Message {
LayoutMessage::ResendAllLayouts.into()
}
/// First message of a session, sent once the frontend is ready
fn init_portfolio() -> Message {
PortfolioMessage::Init.into()
}
/// Per-frame tick: advances the animation clock and broadcasts the animation frame event
fn animation_frame(timestamp: u64) -> Message {
Message::Batched {
messages: Box::new([
InputPreprocessorMessage::CurrentTime { timestamp }.into(),
AnimationMessage::IncrementFrameCounter.into(),
// Used by auto-panning, but this could possibly be refactored in the future, see:
// <https://github.com/GraphiteEditor/Graphite/pull/2562#discussion_r2041102786>
BroadcastMessage::TriggerEvent(EventMessage::AnimationFrame).into(),
]),
}
}
fn auto_save_all_documents() -> Message {
PortfolioMessage::AutoSaveAllDocuments.into()
}
fn add_primary_import() -> Message {
Message::Batched {
messages: Box::new([DocumentMessage::AddTransaction.into(), NodeGraphMessage::AddPrimaryImport.into()]),
}
}
fn add_secondary_import() -> Message {
Message::Batched {
messages: Box::new([DocumentMessage::AddTransaction.into(), NodeGraphMessage::AddSecondaryImport.into()]),
}
}
fn add_primary_export() -> Message {
Message::Batched {
messages: Box::new([DocumentMessage::AddTransaction.into(), NodeGraphMessage::AddPrimaryExport.into()]),
}
}
fn add_secondary_export() -> Message {
Message::Batched {
messages: Box::new([DocumentMessage::AddTransaction.into(), NodeGraphMessage::AddSecondaryExport.into()]),
}
}
/// Start Pointer Lock
fn app_window_pointer_lock() -> Message {
AppWindowMessage::PointerLock.into()
}
/// Minimizes the application window to the taskbar or dock
fn app_window_minimize() -> Message {
AppWindowMessage::Minimize.into()
}
/// Toggles minimizing or restoring down the application window
fn app_window_maximize() -> Message {
AppWindowMessage::Maximize.into()
}
fn app_window_fullscreen() -> Message {
AppWindowMessage::Fullscreen.into()
}
/// Closes the application window
fn app_window_close() -> Message {
AppWindowMessage::Close.into()
}
/// Drag the application window
fn app_window_drag() -> Message {
AppWindowMessage::Drag.into()
}
/// Displays a dialog with an error message
fn error_dialog(title: String, description: String) -> Message {
DialogMessage::DisplayDialogError { title, description }.into()
}
/// Update the value of a given UI widget, but don't commit it to the history (unless `commit_layout()` is called, which handles that)
fn widget_value_update(layout_target: LayoutTarget, widget_id: u64, value: Any, resend_widget: bool) -> Message {
let widget_id = WidgetId(widget_id);
let update = LayoutMessage::WidgetValueUpdate {
layout_target,
widget_id,
value: value.cast(),
};
if resend_widget {
Message::Batched {
messages: Box::new([update.into(), LayoutMessage::ResendActiveWidget { layout_target, widget_id }.into()]),
}
} else {
update.into()
}
}
/// Commit the value of a given UI widget to the history
fn widget_value_commit(layout_target: LayoutTarget, widget_id: u64, value: Any) -> Message {
LayoutMessage::WidgetValueCommit {
layout_target,
widget_id: WidgetId(widget_id),
value: value.cast(),
}
.into()
}
/// Update the value of a given UI widget, and commit it to the history
fn widget_value_commit_and_update(layout_target: LayoutTarget, widget_id: u64, value: Any, resend_widget: bool) -> Message {
let widget_id = WidgetId(widget_id);
let mut messages: Vec<Message> = vec![
LayoutMessage::WidgetValueCommit {
layout_target,
widget_id,
value: value.cast(),
}
.into(),
LayoutMessage::WidgetValueUpdate {
layout_target,
widget_id,
value: value.cast(),
}
.into(),
];
if resend_widget {
messages.push(LayoutMessage::ResendActiveWidget { layout_target, widget_id }.into());
}
// Close out a transaction that the widget's `on_commit` opened (if any), so a single click on widgets like the
// NumberInput's increment buttons collapses into one history step instead of leaving the transaction in `Modified`
messages.push(DocumentMessage::EndTransaction.into());
Message::Batched { messages: messages.into() }
}
/// Fire a widget's drag-drop action (e.g. when a draggable item is dropped on a button)
fn widget_value_drag_drop(layout_target: LayoutTarget, widget_id: u64) -> Message {
let widget_id = WidgetId(widget_id);
LayoutMessage::WidgetValueDragDrop { layout_target, widget_id }.into()
}
/// Closes out the current transaction (drag-end / text-commit end), so emits during a slider drag collapse into one history step instead of N
fn end_transaction() -> Message {
DocumentMessage::EndTransaction.into()
}
fn load_preferences(preferences: Option<String>) -> Message {
let Some(preferences) = preferences else { return Message::NoOp };
let Ok(preferences) = serde_json::from_str(&preferences) else {
log::error!("Failed to deserialize preferences");
return Message::NoOp;
};
PreferencesMessage::Load { preferences }.into()
}
fn load_document_content(document_id: u64, document: String) -> Message {
PersistentStateMessage::LoadDocument {
document_id: DocumentId(document_id),
document,
}
.into()
}
fn select_document(document_id: u64) -> Message {
PortfolioMessage::SelectDocument { document_id: DocumentId(document_id) }.into()
}
/// Rename the currently active document.
fn rename_document(new_name: String) -> Message {
PortfolioMessage::RenameDocument { new_name }.into()
}
fn new_document_dialog() -> Message {
DialogMessage::RequestNewDocumentDialog.into()
}
fn open_file(path: String, content: Vec<u8>) -> Message {
PortfolioMessage::OpenFile { path: PathBuf::from(path), content }.into()
}
fn import_file(path: String, content: Vec<u8>) -> Message {
PortfolioMessage::ImportFile { path: PathBuf::from(path), content }.into()
}
fn trigger_auto_save(document_id: u64) -> Message {
PortfolioMessage::AutoSaveDocument { document_id: DocumentId(document_id) }.into()
}
fn reorder_document(document_id: u64, new_index: usize) -> Message {
PortfolioMessage::ReorderDocument {
document_id: DocumentId(document_id),
new_index,
}
.into()
}
fn reorder_panel_group_tab(group: u64, old_index: usize, new_index: usize) -> Message {
PortfolioMessage::ReorderPanelGroupTab {
group: PanelGroupId(group),
old_index,
new_index,
}
.into()
}
fn move_all_panel_tabs(source_group: u64, target_group: u64, insert_index: usize) -> Message {
PortfolioMessage::MoveAllPanelTabs {
source_group: PanelGroupId(source_group),
target_group: PanelGroupId(target_group),
insert_index,
}
.into()
}
fn move_panel_tab(source_group: u64, target_group: u64, insert_index: usize) -> Message {
PortfolioMessage::MovePanelTab {
source_group: PanelGroupId(source_group),
target_group: PanelGroupId(target_group),
insert_index,
}
.into()
}
fn set_panel_group_active_tab(group: u64, tab_index: usize) -> Message {
PortfolioMessage::SetPanelGroupActiveTab {
group: PanelGroupId(group),
tab_index,
}
.into()
}
fn split_panel_group(target_group: u64, direction: DockingSplitDirection, tabs: PanelTypes, active_tab_index: usize) -> Message {
PortfolioMessage::SplitPanelGroup {
target_group: PanelGroupId(target_group),
direction,
tabs,
active_tab_index,
}
.into()
}
fn set_panel_group_sizes(split_path: Vec<u32>, sizes: Vec<f64>) -> Message {
let split_path = split_path.into_iter().map(|i| i as usize).collect();
PortfolioMessage::SetPanelGroupSizes { split_path, sizes }.into()
}
fn close_document_with_confirmation(document_id: u64) -> Message {
PortfolioMessage::CloseDocumentWithConfirmation { document_id: DocumentId(document_id) }.into()
}
fn request_about_graphite_dialog_with_localized_commit_date(localized_commit_date: String, localized_commit_year: String) -> Message {
DialogMessage::RequestAboutGraphiteDialogWithLocalizedCommitDate {
localized_commit_date,
localized_commit_year,
}
.into()
}
fn request_licenses_third_party_dialog_with_license_text(license_text: String) -> Message {
DialogMessage::RequestLicensesThirdPartyDialogWithLicenseText { license_text }.into()
}
/// Send new viewport info to the backend
fn update_viewport(x: f64, y: f64, width: f64, height: f64, scale: f64) -> Message {
ViewportMessage::Update { x, y, width, height, scale }.into()
}
/// Mouse movement within the screenspace bounds of the viewport
fn on_mouse_move(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Message {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
InputPreprocessorMessage::PointerMove { editor_mouse_state, modifier_keys }.into()
}
/// Mouse scrolling within the screenspace bounds of the viewport
fn on_wheel_scroll(x: f64, y: f64, mouse_keys: u8, wheel_delta_x: f64, wheel_delta_y: f64, wheel_delta_z: f64, modifiers: u8) -> Message {
let mut editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
editor_mouse_state.scroll_delta = ScrollDelta::new(wheel_delta_x, wheel_delta_y, wheel_delta_z);
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
InputPreprocessorMessage::WheelScroll { editor_mouse_state, modifier_keys }.into()
}
/// A mouse button depressed within screenspace the bounds of the viewport
fn on_mouse_down(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Message {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys }.into()
}
/// A mouse button released
fn on_mouse_up(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Message {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys }.into()
}
/// Mouse shaken
fn on_mouse_shake(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Message {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
InputPreprocessorMessage::PointerShake { editor_mouse_state, modifier_keys }.into()
}
/// Mouse double clicked
fn on_double_click(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Message {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
InputPreprocessorMessage::DoubleClick { editor_mouse_state, modifier_keys }.into()
}
/// A keyboard button depressed within screenspace the bounds of the viewport
fn on_key_down(name: String, modifiers: u8, key_repeat: bool) -> Message {
let key = translate_key(&name);
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
trace!("Key down {key:?}, name: {name}, modifiers: {modifiers:?}, key repeat: {key_repeat}");
InputPreprocessorMessage::KeyDown { key, key_repeat, modifier_keys }.into()
}
/// A keyboard button released
fn on_key_up(name: String, modifiers: u8, key_repeat: bool) -> Message {
let key = translate_key(&name);
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
trace!("Key up {key:?}, name: {name}, modifiers: {modifier_keys:?}, key repeat: {key_repeat}");
InputPreprocessorMessage::KeyUp { key, key_repeat, modifier_keys }.into()
}
/// A text box was committed
fn on_change_text(new_text: String, is_left_or_right_click: bool) -> Message {
TextToolMessage::TextChange { new_text, is_left_or_right_click }.into()
}
/// Dialog got dismissed
fn on_dialog_dismiss() -> Message {
DialogMessage::Dismiss.into()
}
/// A text box was changed
fn update_bounds(new_text: String) -> Message {
TextToolMessage::UpdateBounds { new_text }.into()
}
/// Update primary color from sRGB bytes (the wire format at the JS boundary).
fn update_primary_color(color: SRGBA8) -> Message {
ToolMessage::SelectWorkingColor {
color: Color::from(color),
primary: true,
}
.into()
}
/// Update secondary color from sRGB bytes (the wire format at the JS boundary).
fn update_secondary_color(color: SRGBA8) -> Message {
ToolMessage::SelectWorkingColor {
color: Color::from(color),
primary: false,
}
.into()
}
/// Initialize the Rust color picker handler with a starting value (used when the frontend `<ColorPicker />` opens).
fn open_color_picker(initial_value: FillChoiceUI, allow_none: bool, disabled: bool) -> Message {
ColorPickerMessage::Open {
initial_value: FillChoice::from(&initial_value),
allow_none,
disabled,
}
.into()
}
/// Tell the Rust color picker handler that the popover is closing.
fn close_color_picker() -> Message {
ColorPickerMessage::Close.into()
}
/// Update the color of the currently-edited gradient stop, from sRGB bytes (the wire format at the JS boundary).
fn update_gradient_stop_color(color: SRGBA8) -> Message {
GradientToolMessage::UpdateStopColor { color: Color::from(color) }.into()
}
/// Start a new undo transaction for gradient stop color editing
fn start_gradient_stop_color_transaction() -> Message {
GradientToolMessage::StartTransactionForColorStop.into()
}
/// Commit the current gradient stop color transaction (called on pointer-up after each drag/click)
fn commit_gradient_stop_color_transaction() -> Message {
GradientToolMessage::CommitTransactionForColorStop.into()
}
/// Close the gradient stop color picker and commit any pending transaction
fn close_gradient_stop_color_picker() -> Message {
GradientToolMessage::CloseStopColorPicker.into()
}
/// Toggle clipping the alpha of a layer to the alpha of the layer below it in the layer stack
fn clip_layer(id: u64) -> Message {
DocumentMessage::ClipLayer { id: NodeId(id) }.into()
}
/// Modify the layer selection based on the layer which is clicked while holding down the <kbd>Ctrl</kbd> and/or <kbd>Shift</kbd> modifier keys used for range selection behavior
fn select_layer(id: u64, ctrl: bool, shift: bool) -> Message {
DocumentMessage::SelectLayer { id: NodeId(id), ctrl, shift }.into()
}
/// Deselect all layers
fn deselect_all_layers() -> Message {
DocumentMessage::DeselectAllLayers.into()
}
/// Move a layer to within a folder and placed down at the given index.
/// If the folder is `None`, it is inserted into the document root.
/// If the insert index is `None`, it is inserted at the start of the folder.
fn move_layer_in_tree(insert_parent_id: Option<u64>, insert_index: Option<usize>) -> Message {
let insert_parent_id = insert_parent_id.map(NodeId);
let parent = insert_parent_id.map(LayerNodeIdentifier::new_unchecked).unwrap_or_default();
DocumentMessage::MoveSelectedLayersTo {
parent,
insert_index: insert_index.unwrap_or_default(),
}
.into()
}
/// Reorder a draggable Properties panel section to the given index among its peers.
fn reorder_properties_section(node_id: u64, insert_index: usize) -> Message {
DocumentMessage::ReorderPropertiesSection {
node_id: NodeId(node_id),
insert_index,
}
.into()
}
/// Duplicate the selected layers, placing the copies within the given folder at the given index.
/// If the folder is `None`, they are inserted into the document root.
/// If the insert index is `None`, they are inserted at the start of the folder.
fn duplicate_layer_in_tree(insert_parent_id: Option<u64>, insert_index: Option<usize>) -> Message {
DocumentMessage::DuplicateSelectedLayersTo {
parent: insert_parent_id.map(NodeId).map(LayerNodeIdentifier::new_unchecked).unwrap_or_default(),
insert_index: insert_index.unwrap_or_default(),
}
.into()
}
/// Set the name for the layer
fn set_layer_name(id: u64, name: String) -> Message {
let layer = LayerNodeIdentifier::new_unchecked(NodeId(id));
NodeGraphMessage::SetDisplayName {
node_id: layer.to_node(),
network_path: Vec::new(),
alias: name,
skip_adding_history_step: false,
}
.into()
}
/// Translates document (in viewport coords)
fn pan_canvas_abort_prepare(x_not_y_axis: bool) -> Message {
NavigationMessage::CanvasPanAbortPrepare { x_not_y_axis }.into()
}
fn pan_canvas_abort(x_not_y_axis: bool) -> Message {
NavigationMessage::CanvasPanAbort { x_not_y_axis }.into()
}
/// Translates document (in viewport coords)
fn pan_canvas(delta_x: f64, delta_y: f64) -> Message {
NavigationMessage::CanvasPan { delta: (delta_x, delta_y).into() }.into()
}
/// Translates document (in viewport coords)
fn pan_canvas_by_fraction(delta_x: f64, delta_y: f64) -> Message {
NavigationMessage::CanvasPanByViewportFraction { delta: (delta_x, delta_y).into() }.into()
}
/// Merge the selected nodes into a subnetwork
fn merge_selected_nodes() -> Message {
NodeGraphMessage::MergeSelectedNodes.into()
}
/// Toggle lock state of all selected layers
fn toggle_selected_locked() -> Message {
NodeGraphMessage::ToggleSelectedLocked.into()
}
/// Creates a new document node in the node graph
fn create_node(node_type: String, x: i32, y: i32) -> Message {
let id = NodeId::new();
NodeGraphMessage::CreateNodeFromContextMenu {
node_id: Some(id),
node_type: DefinitionIdentifier::from_serialized(&node_type),
xy: Some((x / 24, y / 24)),
add_transaction: true,
}
.into()
}
/// Respond to selection read
fn read_selection(content: Option<String>, cut: bool) -> Message {
ClipboardMessage::ReadSelection { content, cut }.into()
}
/// Paste from a serialized JSON representation
fn paste_text(data: String) -> Message {
ClipboardMessage::ReadClipboard {
content: ClipboardContentRaw::Text(data),
}
.into()
}
/// Pastes an image
fn paste_image(
name: Option<String>,
image_data: Vec<u8>,
width: u32,
height: u32,
mouse_x: Option<f64>,
mouse_y: Option<f64>,
insert_parent_id: Option<u64>,
insert_index: Option<usize>,
) -> Message {
let mouse = mouse_x.and_then(|x| mouse_y.map(|y| (x, y)));
let image = graphene_std::raster::Image::from_image_data(&image_data, width, height);
let parent_and_insert_index = if let (Some(insert_parent_id), Some(insert_index)) = (insert_parent_id, insert_index) {
let insert_parent_id = NodeId(insert_parent_id);
let parent = LayerNodeIdentifier::new_unchecked(insert_parent_id);
Some((parent, insert_index))
} else {
None
};
PortfolioMessage::InsertImage {
name,
image,
mouse,
parent_and_insert_index,
}
.into()
}
/// Pastes an SVG given its string representation
fn paste_svg(name: Option<String>, svg: String, mouse_x: Option<f64>, mouse_y: Option<f64>, insert_parent_id: Option<u64>, insert_index: Option<usize>) -> Message {
let mouse = mouse_x.and_then(|x| mouse_y.map(|y| (x, y)));
let parent_and_insert_index = if let (Some(insert_parent_id), Some(insert_index)) = (insert_parent_id, insert_index) {
let insert_parent_id = NodeId(insert_parent_id);
let parent = LayerNodeIdentifier::new_unchecked(insert_parent_id);
Some((parent, insert_index))
} else {
None
};
PortfolioMessage::InsertSvg {
name,
svg,
mouse,
parent_and_insert_index,
}
.into()
}
/// Toggle visibility of a layer or node given its node ID
fn toggle_node_visibility_layer_panel(id: u64) -> Message {
NodeGraphMessage::ToggleVisibility {
node_id: NodeId(id),
network_path: Vec::new(),
}
.into()
}
/// Pin or unpin a node given its node ID
fn set_node_pinned(id: u64, pinned: bool) -> Message {
DocumentMessage::SetNodePinned { node_id: NodeId(id), pinned }.into()
}
/// Collapse or expand a node's section in the Properties panel
fn toggle_node_properties_section_expanded(id: u64) -> Message {
DocumentMessage::ToggleNodePropertiesSectionExpanded { node_id: NodeId(id) }.into()
}
/// Delete a layer or node given its node ID
fn delete_node(id: u64) -> Message {
DocumentMessage::DeleteNode { node_id: NodeId(id) }.into()
}
/// Toggle lock state of a layer from the layer list
fn toggle_layer_lock(node_id: u64) -> Message {
NodeGraphMessage::ToggleLocked {
node_id: NodeId(node_id),
network_path: Vec::new(),
}
.into()
}
/// Toggle expansions state of a layer from the layer list
fn toggle_layer_expansion(tree_path: Vec<u64>, recursive: bool) -> Message {
let tree_path = tree_path.into_iter().map(NodeId).collect();
DocumentMessage::ToggleLayerExpansion { tree_path, recursive }.into()
}
/// Set the active panel to the most recently clicked panel
fn set_active_panel(panel: String) -> Message {
DocumentMessage::SetActivePanel { active_panel: panel.into() }.into()
}
/// Toggle display type for a layer
fn set_to_node_or_layer(id: u64, is_layer: bool) -> Message {
DocumentMessage::SetToNodeOrLayer { node_id: NodeId(id), is_layer }.into()
}
/// Set the name of an import or export
fn set_import_name(index: usize, name: String) -> Message {
NodeGraphMessage::SetImportExportName {
name,
index: ImportOrExport::Import(index),
}
.into()
}
/// Set the name of an export
fn set_export_name(index: usize, name: String) -> Message {
NodeGraphMessage::SetImportExportName {
name,
index: ImportOrExport::Export(index),
}
.into()
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Tsify)]
#[tsify(from_wasm_abi)]
pub struct Any(#[tsify(type = "any")] serde_json::Value);
impl Any {
#[cfg(feature = "editor")]
pub(crate) fn cast<T: for<'de> Deserialize<'de>>(&self) -> T {
serde_json::from_value(self.0.clone()).unwrap()
}
}
macro_rules! editor_proxy_types {
($($name:ident = $real:ty;)*) => {
$(
#[cfg(feature = "editor")]
pub type $name = $real;
#[cfg(not(feature = "editor"))]
pub type $name = Any;
)*
};
}
editor_proxy_types! {
LayoutTarget = editor::messages::layout::utility_types::layout_widget::LayoutTarget;
DockingSplitDirection = editor::messages::portfolio::utility_types::DockingSplitDirection;
PanelTypes = Vec<editor::messages::portfolio::utility_types::PanelType>;
SRGBA8 = graphene_std::color::SRGBA8;
FillChoiceUI = graphene_std::vector::style::FillChoiceUI;
}
+70 -818
View File
@@ -1,44 +1,33 @@
#![allow(clippy::too_many_arguments)]
//
// This file is where functions are defined to be called directly from JS.
// It serves as a thin wrapper over the editor backend API that relies
// on the dispatcher messaging system and more complex Rust data types.
//
//! JS-facing editor handle. Owns the callback that delivers `FrontendMessage`s to JS; on web `dispatch` runs
//! messages through the in-process editor, on native `send` forwards them as `EditorCommand`s.
#[cfg(not(feature = "native"))]
use crate::EDITOR;
#[cfg(not(feature = "native"))]
use crate::helpers::poll_node_graph_evaluation;
use crate::helpers::{auto_save_all_documents, calculate_hash, render_image_data_to_canvases, request_animation_frame, set_timeout, translate_key, wrapper};
use crate::{EDITOR_HAS_CRASHED, Error, FRONTEND_READY, MESSAGE_BUFFER};
use crate::MESSAGE_BUFFER;
#[cfg(all(feature = "native", target_family = "wasm"))]
use crate::editor_commands::EditorCommand;
#[cfg(not(feature = "native"))]
use crate::helpers::poll_node_graph_evaluation;
#[cfg(any(not(feature = "native"), target_family = "wasm"))]
use crate::helpers::wrapper;
#[cfg(feature = "editor")]
use crate::helpers::{calculate_hash, render_image_data_to_canvases};
use crate::helpers::{request_animation_frame, set_timeout};
use crate::{EDITOR_HAS_CRASHED, FRONTEND_READY};
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
use editor::application::{Editor, Environment, Host, Platform};
use editor::consts::{FILE_EXTENSION, GDD_FILE_EXTENSION};
use editor::messages::clipboard::utility_types::ClipboardContentRaw;
use editor::messages::input_mapper::utility_types::input_keyboard::ModifierKeys;
use editor::messages::input_mapper::utility_types::input_mouse::{EditorMouseState, ScrollDelta};
use editor::messages::layout::utility_types::layout_widget::LayoutTarget;
use editor::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use editor::messages::portfolio::document::utility_types::network_interface::ImportOrExport;
use editor::messages::portfolio::utility_types::{DockingSplitDirection, PanelGroupId, PanelType};
#[cfg(feature = "editor")]
use editor::messages::prelude::*;
use editor::messages::tool::tool_messages::tool_prelude::WidgetId;
use graph_craft::document::NodeId;
use graphene_std::color::SRGBA8;
use graphene_std::graphene_hash::CacheHashWrapper;
use graphene_std::raster::color::Color;
use graphene_std::vector::style::{FillChoice, FillChoiceUI};
#[cfg(feature = "editor")]
use serde::Serialize;
use serde_wasm_bindgen::{self, from_value};
use std::cell::RefCell;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use wasm_bindgen::prelude::*;
static IMAGE_DATA_HASH: AtomicU64 = AtomicU64::new(0);
pub(crate) static IMAGE_DATA_HASH: AtomicU64 = AtomicU64::new(0);
/// This struct is, via wasm-bindgen, used by JS to interact with the editor backend. It does this by calling functions, which are `impl`ed
#[wasm_bindgen]
#[derive(Clone)]
pub struct EditorWrapper {
@@ -46,13 +35,7 @@ pub struct EditorWrapper {
frontend_message_handler_callback: js_sys::Function,
}
// Defined separately from the `impl` block below since this `impl` block lacks the `#[wasm_bindgen]` attribute.
// Quirks in wasm-bindgen prevent functions in `#[wasm_bindgen]` `impl` blocks from being made publicly accessible from Rust.
impl EditorWrapper {
pub fn send_frontend_message_to_js_rust_proxy(&self, message: FrontendMessage) {
self.send_frontend_message_to_js(message);
}
#[cfg(any(feature = "native", target_family = "wasm"))]
fn initialize_wrapper(frontend_message_handler_callback: js_sys::Function) -> EditorWrapper {
use crate::{EDITOR_WRAPPER, PANIC_DIALOG_MESSAGE_CALLBACK};
@@ -69,10 +52,6 @@ impl EditorWrapper {
#[wasm_bindgen]
impl EditorWrapper {
// ========================
// Editor wrapper machinery
// ========================
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
pub async fn create(platform: String, uuid_random_seed: u64, frontend_message_handler_callback: js_sys::Function) -> EditorWrapper {
use graph_craft::application_io::PlatformApplicationIo;
@@ -115,7 +94,6 @@ impl EditorWrapper {
#[cfg(not(feature = "native"))]
pub(crate) fn dispatch<T: Into<Message>>(&self, message: T) {
// Process no further messages after a crash to avoid spamming the console
use crate::MESSAGE_BUFFER;
if EDITOR_HAS_CRASHED.load(Ordering::SeqCst) {
return;
}
@@ -137,24 +115,15 @@ impl EditorWrapper {
self.send_frontend_message_to_js(message);
}
}
#[cfg(feature = "native")]
pub(crate) fn dispatch<T: Into<Message>>(&self, message: T) {
let message: Message = message.into();
let Ok(serialized_message) = ron::to_string(&message) else {
log::error!("Failed to serialize message");
return;
};
crate::native_communication::send_message_to_cef(serialized_message)
}
// Sends a FrontendMessage to JavaScript
#[cfg(feature = "editor")]
pub(crate) fn send_frontend_message_to_js(&self, message: FrontendMessage) {
if let FrontendMessage::UpdateImageData { ref image_data } = message {
let new_hash = calculate_hash(&CacheHashWrapper(image_data));
let new_hash = calculate_hash(image_data);
let prev_hash = IMAGE_DATA_HASH.load(Ordering::Relaxed);
if new_hash != prev_hash {
render_image_data_to_canvases(image_data.as_slice());
render_image_data_to_canvases(image_data.iter());
IMAGE_DATA_HASH.store(new_hash, Ordering::Relaxed);
}
return;
@@ -172,16 +141,31 @@ impl EditorWrapper {
}
}
// ================================================
// Functions for calling the editor in Rust from JS
// ================================================
pub(crate) fn forward_serialized_frontend_message_to_js(&self, name: &str, data: crate::wasm_value::WasmValue) {
let js_return_value = self.frontend_message_handler_callback.call2(&JsValue::null(), &JsValue::from(name), &data.into());
/// Re-sends all UI layouts to the frontend. Called during HMR re-mounts when the frontend has lost its layout state.
#[wasm_bindgen(js_name = resendAllLayouts)]
pub fn resend_all_layouts(&self) {
self.dispatch(LayoutMessage::ResendAllLayouts);
if let Err(error) = js_return_value {
error!("While handling FrontendMessage {name:?}, JavaScript threw an error:\n{error:?}")
}
}
#[cfg(all(feature = "native", target_family = "wasm"))]
pub(crate) fn send(&self, command: EditorCommand) {
// Process no further commands after a crash to avoid spamming the console
if EDITOR_HAS_CRASHED.load(Ordering::SeqCst) {
return;
}
let Ok(serialized) = serde_json::to_string(&command) else {
log::error!("Failed to serialize editor command");
return;
};
crate::native_communication::send_message_to_cef(serialized)
}
}
#[wasm_bindgen]
impl EditorWrapper {
#[wasm_bindgen(js_name = initAfterFrontendReady)]
pub fn init_after_frontend_ready(&self) {
// Enforce idempotency, so if this is called again during an HMR re-mount, we don't initialize the editor backend twice
@@ -192,7 +176,8 @@ impl EditorWrapper {
#[cfg(feature = "native")]
crate::native_communication::initialize_native_communication();
self.dispatch(PortfolioMessage::Init);
#[cfg(target_family = "wasm")]
self.init_portfolio();
// Poll node graph evaluation on `requestAnimationFrame`
{
@@ -203,25 +188,19 @@ impl EditorWrapper {
#[cfg(not(feature = "native"))]
wasm_bindgen_futures::spawn_local(poll_node_graph_evaluation());
if !EDITOR_HAS_CRASHED.load(Ordering::SeqCst) {
wrapper(|wrapper| {
// Process all messages that have been queued up
let mut messages = MESSAGE_BUFFER.take();
messages.push(
InputPreprocessorMessage::CurrentTime {
timestamp: js_sys::Date::now() as u64,
}
.into(),
);
messages.push(AnimationMessage::IncrementFrameCounter.into());
// Used by auto-panning, but this could possibly be refactored in the future, see:
// <https://github.com/GraphiteEditor/Graphite/pull/2562#discussion_r2041102786>
messages.push(BroadcastMessage::TriggerEvent(EventMessage::AnimationFrame).into());
wrapper.dispatch(Message::Batched { messages: messages.into() });
});
}
#[cfg(any(not(feature = "native"), target_family = "wasm"))]
wrapper(|wrapper| {
// On web, flush the messages that queued up while the editor was locked before this frame's tick
#[cfg(not(feature = "native"))]
{
let messages = MESSAGE_BUFFER.take();
if !messages.is_empty() {
wrapper.dispatch(Message::Batched { messages: messages.into() });
}
}
#[cfg(target_family = "wasm")]
wrapper.animation_frame(js_sys::Date::now() as u64);
});
// Schedule ourself for another requestAnimationFrame callback
request_animation_frame(f.borrow().as_ref().unwrap());
@@ -230,101 +209,25 @@ impl EditorWrapper {
request_animation_frame(g.borrow().as_ref().unwrap());
}
const AUTO_SAVE_TIMEOUT_SECONDS: u64 = 1;
// Auto save all documents on `setTimeout`
{
let f = std::rc::Rc::new(RefCell::new(None));
let g = f.clone();
*g.borrow_mut() = Some(Closure::new(move || {
auto_save_all_documents();
#[cfg(target_family = "wasm")]
wrapper(|wrapper| wrapper.auto_save_all_documents());
// Schedule ourself for another setTimeout callback
set_timeout(f.borrow().as_ref().unwrap(), Duration::from_secs(editor::consts::AUTO_SAVE_TIMEOUT_SECONDS));
set_timeout(f.borrow().as_ref().unwrap(), Duration::from_secs(AUTO_SAVE_TIMEOUT_SECONDS));
}));
set_timeout(g.borrow().as_ref().unwrap(), Duration::from_secs(editor::consts::AUTO_SAVE_TIMEOUT_SECONDS));
set_timeout(g.borrow().as_ref().unwrap(), Duration::from_secs(AUTO_SAVE_TIMEOUT_SECONDS));
}
}
#[wasm_bindgen(js_name = addPrimaryImport)]
pub fn add_primary_import(&self) {
self.dispatch(DocumentMessage::AddTransaction);
self.dispatch(NodeGraphMessage::AddPrimaryImport);
}
#[wasm_bindgen(js_name = addSecondaryImport)]
pub fn add_secondary_import(&self) {
self.dispatch(DocumentMessage::AddTransaction);
self.dispatch(NodeGraphMessage::AddSecondaryImport);
}
#[wasm_bindgen(js_name = addPrimaryExport)]
pub fn add_primary_export(&self) {
self.dispatch(DocumentMessage::AddTransaction);
self.dispatch(NodeGraphMessage::AddPrimaryExport);
}
#[wasm_bindgen(js_name = addSecondaryExport)]
pub fn add_secondary_export(&self) {
self.dispatch(DocumentMessage::AddTransaction);
self.dispatch(NodeGraphMessage::AddSecondaryExport);
}
/// Start Pointer Lock
#[wasm_bindgen(js_name = appWindowPointerLock)]
pub fn app_window_pointer_lock(&self) {
let message = AppWindowMessage::PointerLock;
self.dispatch(message);
}
/// Minimizes the application window to the taskbar or dock
#[wasm_bindgen(js_name = appWindowMinimize)]
pub fn app_window_minimize(&self) {
let message = AppWindowMessage::Minimize;
self.dispatch(message);
}
/// Toggles minimizing or restoring down the application window
#[wasm_bindgen(js_name = appWindowMaximize)]
pub fn app_window_maximize(&self) {
let message = AppWindowMessage::Maximize;
self.dispatch(message);
}
#[wasm_bindgen(js_name = appWindowFullscreen)]
pub fn app_window_fullscreen(&self) {
let message = AppWindowMessage::Fullscreen;
self.dispatch(message);
}
/// Closes the application window
#[wasm_bindgen(js_name = appWindowClose)]
pub fn app_window_close(&self) {
let message = AppWindowMessage::Close;
self.dispatch(message);
}
/// Drag the application window
#[wasm_bindgen(js_name = appWindowDrag)]
pub fn app_window_start_drag(&self) {
let message = AppWindowMessage::Drag;
self.dispatch(message);
}
/// Displays a dialog with an error message
#[wasm_bindgen(js_name = errorDialog)]
pub fn error_dialog(&self, title: String, description: String) {
let message = DialogMessage::DisplayDialogError { title, description };
self.dispatch(message);
}
/// Displays a dialog confirming that a job was successfully queued on the pen plotter print server
#[wasm_bindgen(js_name = sendToPlotterSuccessDialog)]
pub fn send_to_plotter_success_dialog(&self, job_name: String) {
let message = DialogMessage::DisplaySendToPlotterSuccess { job_name };
self.dispatch(message);
}
/// Answer whether or not the editor has crashed
#[wasm_bindgen(js_name = hasCrashed)]
pub fn has_crashed(&self) -> bool {
@@ -337,676 +240,25 @@ impl EditorWrapper {
cfg!(debug_assertions)
}
/// Get the constant `FILE_EXTENSION`
#[wasm_bindgen(js_name = fileExtension)]
pub fn file_extension(&self) -> String {
FILE_EXTENSION.into()
"graphite".into()
}
/// Get the constant `GDD_FILE_EXTENSION`
#[wasm_bindgen(js_name = gddFileExtension)]
pub fn gdd_file_extension(&self) -> String {
GDD_FILE_EXTENSION.into()
}
/// Update the value of a given UI widget, but don't commit it to the history (unless `commit_layout()` is called, which handles that)
#[wasm_bindgen(js_name = widgetValueUpdate)]
pub fn widget_value_update(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue, resend_widget: bool) -> Result<(), JsValue> {
self.widget_value_update_helper(layout_target, widget_id, value, resend_widget)
}
/// Commit the value of a given UI widget to the history
#[wasm_bindgen(js_name = widgetValueCommit)]
pub fn widget_value_commit(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue) -> Result<(), JsValue> {
self.widget_value_commit_helper(layout_target, widget_id, value)
}
/// Update the value of a given UI widget, and commit it to the history
#[wasm_bindgen(js_name = widgetValueCommitAndUpdate)]
pub fn widget_value_commit_and_update(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue, resend_widget: bool) -> Result<(), JsValue> {
self.widget_value_commit_helper(layout_target, widget_id, value.clone())?;
self.widget_value_update_helper(layout_target, widget_id, value, resend_widget)?;
// Close out a transaction that the widget's `on_commit` opened (if any), so a single click on widgets like the
// NumberInput's increment buttons collapses into one history step instead of leaving the transaction in `Modified`
self.dispatch(DocumentMessage::EndTransaction);
Ok(())
}
/// Fire a widget's drag-drop action (e.g. when a draggable item is dropped on a button)
#[wasm_bindgen(js_name = widgetValueDragDrop)]
pub fn widget_value_drag_drop(&self, layout_target: LayoutTarget, widget_id: u64) {
let widget_id = WidgetId(widget_id);
self.dispatch(LayoutMessage::WidgetValueDragDrop { layout_target, widget_id });
}
/// Closes out the current transaction (drag-end / text-commit end), so emits during a slider drag collapse into one history step instead of N
#[wasm_bindgen(js_name = endTransaction)]
pub fn end_transaction(&self) {
self.dispatch(DocumentMessage::EndTransaction);
}
pub fn widget_value_update_helper(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue, resend_widget: bool) -> Result<(), JsValue> {
let widget_id = WidgetId(widget_id);
let value: serde_json::Value = from_value(value).map_err(|e| Error::new(&format!("Could not update UI: {e}")))?;
let message = LayoutMessage::WidgetValueUpdate { layout_target, widget_id, value };
self.dispatch(message);
if resend_widget {
let resend_message = LayoutMessage::ResendActiveWidget { layout_target, widget_id };
self.dispatch(resend_message);
}
Ok(())
}
pub fn widget_value_commit_helper(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue) -> Result<(), JsValue> {
let widget_id = WidgetId(widget_id);
let value: serde_json::Value = from_value(value).map_err(|e| Error::new(&format!("Could not commit UI: {e}")))?;
let message = LayoutMessage::WidgetValueCommit { layout_target, widget_id, value };
self.dispatch(message);
Ok(())
}
#[wasm_bindgen(js_name = loadPreferences)]
pub fn load_preferences(&self, preferences: Option<String>) {
if let Some(preferences) = preferences {
let Ok(preferences) = serde_json::from_str(&preferences) else {
log::error!("Failed to deserialize preferences");
return;
};
let message = PreferencesMessage::Load { preferences };
self.dispatch(message);
}
"gdd".into()
}
/// Load persisted browser storage state (web only; on desktop, persistence is handled natively and this is never triggered)
#[cfg(all(feature = "web", not(feature = "native")))]
#[wasm_bindgen(js_name = loadPersistedState)]
pub fn load_persisted_state(&self, state: editor::messages::frontend::utility_types::PersistedState) {
self.dispatch(PersistentStateMessage::LoadState { state });
}
#[wasm_bindgen(js_name = loadDocumentContent)]
pub fn load_document_content(&self, document_id: u64, document: String) {
let message = PersistentStateMessage::LoadDocument {
document_id: DocumentId(document_id),
document,
};
self.dispatch(message);
}
#[wasm_bindgen(js_name = selectDocument)]
pub fn select_document(&self, document_id: u64) {
let document_id = DocumentId(document_id);
let message = PortfolioMessage::SelectDocument { document_id };
self.dispatch(message);
}
/// Rename the currently active document.
#[wasm_bindgen(js_name = renameDocument)]
pub fn rename_document(&self, new_name: String) {
let message = PortfolioMessage::RenameDocument { new_name };
self.dispatch(message);
}
#[wasm_bindgen(js_name = newDocumentDialog)]
pub fn new_document_dialog(&self) {
let message = DialogMessage::RequestNewDocumentDialog;
self.dispatch(message);
}
#[wasm_bindgen(js_name = openFile)]
pub fn open_file(&self, path: String, content: Vec<u8>) {
let message = PortfolioMessage::OpenFile { path: PathBuf::from(path), content };
self.dispatch(message);
}
#[wasm_bindgen(js_name = importFile)]
pub fn import_file(&self, path: String, content: Vec<u8>) {
let message = PortfolioMessage::ImportFile { path: PathBuf::from(path), content };
self.dispatch(message);
}
#[wasm_bindgen(js_name = triggerAutoSave)]
pub fn trigger_auto_save(&self, document_id: u64) {
let document_id = DocumentId(document_id);
let message = PortfolioMessage::AutoSaveDocument { document_id };
self.dispatch(message);
}
#[wasm_bindgen(js_name = reorderDocument)]
pub fn reorder_document(&self, document_id: u64, new_index: usize) {
let document_id = DocumentId(document_id);
let message = PortfolioMessage::ReorderDocument { document_id, new_index };
self.dispatch(message);
}
#[wasm_bindgen(js_name = reorderPanelGroupTab)]
pub fn reorder_panel_group_tab(&self, group: u64, old_index: usize, new_index: usize) {
let message = PortfolioMessage::ReorderPanelGroupTab {
group: PanelGroupId(group),
old_index,
new_index,
};
self.dispatch(message);
}
#[wasm_bindgen(js_name = moveAllPanelTabs)]
pub fn move_all_panel_tabs(&self, source_group: u64, target_group: u64, insert_index: usize) {
let message = PortfolioMessage::MoveAllPanelTabs {
source_group: PanelGroupId(source_group),
target_group: PanelGroupId(target_group),
insert_index,
};
self.dispatch(message);
}
#[wasm_bindgen(js_name = movePanelTab)]
pub fn move_panel_tab(&self, source_group: u64, target_group: u64, insert_index: usize) {
let message = PortfolioMessage::MovePanelTab {
source_group: PanelGroupId(source_group),
target_group: PanelGroupId(target_group),
insert_index,
};
self.dispatch(message);
}
#[wasm_bindgen(js_name = setPanelGroupActiveTab)]
pub fn set_panel_group_active_tab(&self, group: u64, tab_index: usize) {
let message = PortfolioMessage::SetPanelGroupActiveTab {
group: PanelGroupId(group),
tab_index,
};
self.dispatch(message);
}
#[wasm_bindgen(js_name = splitPanelGroup)]
pub fn split_panel_group(&self, target_group: u64, direction: DockingSplitDirection, tabs: Vec<PanelType>, active_tab_index: usize) {
let message = PortfolioMessage::SplitPanelGroup {
target_group: PanelGroupId(target_group),
direction,
tabs,
active_tab_index,
};
self.dispatch(message);
}
#[wasm_bindgen(js_name = setPanelGroupSizes)]
pub fn set_panel_group_sizes(&self, split_path: Vec<u32>, sizes: Vec<f64>) {
let split_path = split_path.into_iter().map(|i| i as usize).collect();
let message = PortfolioMessage::SetPanelGroupSizes { split_path, sizes };
self.dispatch(message);
}
#[wasm_bindgen(js_name = closeDocumentWithConfirmation)]
pub fn close_document_with_confirmation(&self, document_id: u64) {
let document_id = DocumentId(document_id);
let message = PortfolioMessage::CloseDocumentWithConfirmation { document_id };
self.dispatch(message);
}
#[wasm_bindgen(js_name = requestAboutGraphiteDialogWithLocalizedCommitDate)]
pub fn request_about_graphite_dialog_with_localized_commit_date(&self, localized_commit_date: String, localized_commit_year: String) {
let message = DialogMessage::RequestAboutGraphiteDialogWithLocalizedCommitDate {
localized_commit_date,
localized_commit_year,
};
self.dispatch(message);
}
#[wasm_bindgen(js_name = requestLicensesThirdPartyDialogWithLicenseText)]
pub fn request_licenses_third_party_dialog_with_license_text(&self, license_text: String) {
let message = DialogMessage::RequestLicensesThirdPartyDialogWithLicenseText { license_text };
self.dispatch(message);
}
/// Send new viewport info to the backend
#[wasm_bindgen(js_name = updateViewport)]
pub fn update_viewport(&self, x: f64, y: f64, width: f64, height: f64, scale: f64) {
let message = ViewportMessage::Update { x, y, width, height, scale };
self.dispatch(message);
}
/// Mouse movement within the screenspace bounds of the viewport
#[wasm_bindgen(js_name = onMouseMove)]
pub fn on_mouse_move(&self, x: f64, y: f64, mouse_keys: u8, modifiers: u8) {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
let message = InputPreprocessorMessage::PointerMove { editor_mouse_state, modifier_keys };
self.dispatch(message);
}
/// Mouse scrolling within the screenspace bounds of the viewport
#[wasm_bindgen(js_name = onWheelScroll)]
pub fn on_wheel_scroll(&self, x: f64, y: f64, mouse_keys: u8, wheel_delta_x: f64, wheel_delta_y: f64, wheel_delta_z: f64, modifiers: u8) {
let mut editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
editor_mouse_state.scroll_delta = ScrollDelta::new(wheel_delta_x, wheel_delta_y, wheel_delta_z);
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
let message = InputPreprocessorMessage::WheelScroll { editor_mouse_state, modifier_keys };
self.dispatch(message);
}
/// A mouse button depressed within screenspace the bounds of the viewport
#[wasm_bindgen(js_name = onMouseDown)]
pub fn on_mouse_down(&self, x: f64, y: f64, mouse_keys: u8, modifiers: u8) {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
let message = InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys };
self.dispatch(message);
}
/// A mouse button released
#[wasm_bindgen(js_name = onMouseUp)]
pub fn on_mouse_up(&self, x: f64, y: f64, mouse_keys: u8, modifiers: u8) {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
let message = InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys };
self.dispatch(message);
}
/// Mouse shaken
#[wasm_bindgen(js_name = onMouseShake)]
pub fn on_mouse_shake(&self, x: f64, y: f64, mouse_keys: u8, modifiers: u8) {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
let message = InputPreprocessorMessage::PointerShake { editor_mouse_state, modifier_keys };
self.dispatch(message);
}
/// Mouse double clicked
#[wasm_bindgen(js_name = onDoubleClick)]
pub fn on_double_click(&self, x: f64, y: f64, mouse_keys: u8, modifiers: u8) {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
let message = InputPreprocessorMessage::DoubleClick { editor_mouse_state, modifier_keys };
self.dispatch(message);
}
/// A keyboard button depressed within screenspace the bounds of the viewport
#[wasm_bindgen(js_name = onKeyDown)]
pub fn on_key_down(&self, name: String, modifiers: u8, key_repeat: bool) {
let key = translate_key(&name);
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
trace!("Key down {key:?}, name: {name}, modifiers: {modifiers:?}, key repeat: {key_repeat}");
let message = InputPreprocessorMessage::KeyDown { key, key_repeat, modifier_keys };
self.dispatch(message);
}
/// A keyboard button released
#[wasm_bindgen(js_name = onKeyUp)]
pub fn on_key_up(&self, name: String, modifiers: u8, key_repeat: bool) {
let key = translate_key(&name);
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
trace!("Key up {key:?}, name: {name}, modifiers: {modifier_keys:?}, key repeat: {key_repeat}");
let message = InputPreprocessorMessage::KeyUp { key, key_repeat, modifier_keys };
self.dispatch(message);
}
/// A text box was committed
#[wasm_bindgen(js_name = onChangeText)]
pub fn on_change_text(&self, new_text: String, is_left_or_right_click: bool) -> Result<(), JsValue> {
let message = TextToolMessage::TextChange { new_text, is_left_or_right_click };
self.dispatch(message);
Ok(())
}
/// Dialog got dismissed
#[wasm_bindgen(js_name = onDialogDismiss)]
pub fn on_dialog_dismiss(&self) {
let message = DialogMessage::Dismiss;
self.dispatch(message);
}
/// A text box was changed
#[wasm_bindgen(js_name = updateBounds)]
pub fn update_bounds(&self, new_text: String) -> Result<(), JsValue> {
let message = TextToolMessage::UpdateBounds { new_text };
self.dispatch(message);
Ok(())
}
/// Update primary color from sRGB bytes (the wire format at the JS boundary).
#[wasm_bindgen(js_name = updatePrimaryColor)]
pub fn update_primary_color(&self, color: SRGBA8) {
self.dispatch(ToolMessage::SelectWorkingColor {
color: Color::from(color),
primary: true,
});
}
/// Update secondary color from sRGB bytes (the wire format at the JS boundary).
#[wasm_bindgen(js_name = updateSecondaryColor)]
pub fn update_secondary_color(&self, color: SRGBA8) {
self.dispatch(ToolMessage::SelectWorkingColor {
color: Color::from(color),
primary: false,
});
}
/// Initialize the Rust color picker handler with a starting value (used when the frontend `<ColorPicker />` opens).
#[wasm_bindgen(js_name = openColorPicker)]
pub fn open_color_picker(&self, initial_value: FillChoiceUI, allow_none: bool, disabled: bool) {
let initial_value = FillChoice::from(&initial_value);
self.dispatch(ColorPickerMessage::Open { initial_value, allow_none, disabled });
}
/// Tell the Rust color picker handler that the popover is closing.
#[wasm_bindgen(js_name = closeColorPicker)]
pub fn close_color_picker(&self) {
self.dispatch(ColorPickerMessage::Close);
}
/// Update the color of the currently-edited gradient stop, from sRGB bytes (the wire format at the JS boundary).
#[wasm_bindgen(js_name = updateGradientStopColor)]
pub fn update_gradient_stop_color(&self, color: SRGBA8) {
self.dispatch(GradientToolMessage::UpdateStopColor { color: Color::from(color) });
}
/// Start a new undo transaction for gradient stop color editing
#[wasm_bindgen(js_name = startGradientStopColorTransaction)]
pub fn start_gradient_stop_color_transaction(&self) {
self.dispatch(GradientToolMessage::StartTransactionForColorStop);
}
/// Commit the current gradient stop color transaction (called on pointer-up after each drag/click)
#[wasm_bindgen(js_name = commitGradientStopColorTransaction)]
pub fn commit_gradient_stop_color_transaction(&self) {
self.dispatch(GradientToolMessage::CommitTransactionForColorStop);
}
/// Close the gradient stop color picker and commit any pending transaction
#[wasm_bindgen(js_name = closeGradientStopColorPicker)]
pub fn close_gradient_stop_color_picker(&self) {
self.dispatch(GradientToolMessage::CloseStopColorPicker);
}
/// Toggle clipping the alpha of a layer to the alpha of the layer below it in the layer stack
#[wasm_bindgen(js_name = clipLayer)]
pub fn clip_layer(&self, id: u64) {
let id = NodeId(id);
let message = DocumentMessage::ClipLayer { id };
self.dispatch(message);
}
/// Modify the layer selection based on the layer which is clicked while holding down the <kbd>Ctrl</kbd> and/or <kbd>Shift</kbd> modifier keys used for range selection behavior
#[wasm_bindgen(js_name = selectLayer)]
pub fn select_layer(&self, id: u64, ctrl: bool, shift: bool) {
let id = NodeId(id);
let message = DocumentMessage::SelectLayer { id, ctrl, shift };
self.dispatch(message);
}
/// Deselect all layers
#[wasm_bindgen(js_name = deselectAllLayers)]
pub fn deselect_all_layers(&self) {
let message = DocumentMessage::DeselectAllLayers;
self.dispatch(message);
}
/// Move a layer to within a folder and placed down at the given index.
/// If the folder is `None`, it is inserted into the document root.
/// If the insert index is `None`, it is inserted at the start of the folder.
#[wasm_bindgen(js_name = moveLayerInTree)]
pub fn move_layer_in_tree(&self, insert_parent_id: Option<u64>, insert_index: Option<usize>) {
let insert_parent_id = insert_parent_id.map(NodeId);
let parent = insert_parent_id.map(LayerNodeIdentifier::new_unchecked).unwrap_or_default();
let message = DocumentMessage::MoveSelectedLayersTo {
parent,
insert_index: insert_index.unwrap_or_default(),
};
self.dispatch(message);
}
/// Reorder a draggable Properties panel section to the given index among its peers.
#[wasm_bindgen(js_name = reorderPropertiesSection)]
pub fn reorder_properties_section(&self, node_id: u64, insert_index: usize) {
self.dispatch(DocumentMessage::ReorderPropertiesSection {
node_id: NodeId(node_id),
insert_index,
});
}
/// Duplicate the selected layers, placing the copies within the given folder at the given index.
/// If the folder is `None`, they are inserted into the document root.
/// If the insert index is `None`, they are inserted at the start of the folder.
#[wasm_bindgen(js_name = duplicateLayerInTree)]
pub fn duplicate_layer_in_tree(&self, insert_parent_id: Option<u64>, insert_index: Option<usize>) {
let message = DocumentMessage::DuplicateSelectedLayersTo {
parent: insert_parent_id.map(NodeId).map(LayerNodeIdentifier::new_unchecked).unwrap_or_default(),
insert_index: insert_index.unwrap_or_default(),
};
self.dispatch(message);
}
/// Set the name for the layer
#[wasm_bindgen(js_name = setLayerName)]
pub fn set_layer_name(&self, id: u64, name: String) {
let layer = LayerNodeIdentifier::new_unchecked(NodeId(id));
let message = NodeGraphMessage::SetDisplayName {
node_id: layer.to_node(),
network_path: Vec::new(),
alias: name,
skip_adding_history_step: false,
};
self.dispatch(message);
}
/// Translates document (in viewport coords)
#[wasm_bindgen(js_name = panCanvasAbortPrepare)]
pub fn pan_canvas_abort_prepare(&self, x_not_y_axis: bool) {
let message = NavigationMessage::CanvasPanAbortPrepare { x_not_y_axis };
self.dispatch(message);
}
#[wasm_bindgen(js_name = panCanvasAbort)]
pub fn pan_canvas_abort(&self, x_not_y_axis: bool) {
let message = NavigationMessage::CanvasPanAbort { x_not_y_axis };
self.dispatch(message);
}
/// Translates document (in viewport coords)
#[wasm_bindgen(js_name = panCanvas)]
pub fn pan_canvas(&self, delta_x: f64, delta_y: f64) {
let message = NavigationMessage::CanvasPan { delta: (delta_x, delta_y).into() };
self.dispatch(message);
}
/// Translates document (in viewport coords)
#[wasm_bindgen(js_name = panCanvasByFraction)]
pub fn pan_canvas_by_fraction(&self, delta_x: f64, delta_y: f64) {
let message = NavigationMessage::CanvasPanByViewportFraction { delta: (delta_x, delta_y).into() };
self.dispatch(message);
}
/// Merge the selected nodes into a subnetwork
#[wasm_bindgen(js_name = mergeSelectedNodes)]
pub fn merge_nodes(&self) {
let message = NodeGraphMessage::MergeSelectedNodes;
self.dispatch(message);
}
/// Toggle lock state of all selected layers
#[wasm_bindgen(js_name = toggleSelectedLocked)]
pub fn toggle_selected_locked(&self) {
let message = NodeGraphMessage::ToggleSelectedLocked;
self.dispatch(message);
}
/// Creates a new document node in the node graph
#[wasm_bindgen(js_name = createNode)]
pub fn create_node(&self, node_type: JsValue, x: i32, y: i32) {
let value: serde_json::Value = serde_wasm_bindgen::from_value(node_type).unwrap();
let id = NodeId::new();
let message = NodeGraphMessage::CreateNodeFromContextMenu {
node_id: Some(id),
node_type: value.into(),
xy: Some((x / 24, y / 24)),
add_transaction: true,
};
self.dispatch(message);
}
/// Respond to selection read
#[wasm_bindgen(js_name = readSelection)]
pub fn read_selection(&self, content: Option<String>, cut: bool) {
let message = ClipboardMessage::ReadSelection { content, cut };
self.dispatch(message);
}
/// Paste from a serialized JSON representation
#[wasm_bindgen(js_name = pasteText)]
pub fn paste_text(&self, data: String) {
let message = ClipboardMessage::ReadClipboard {
content: ClipboardContentRaw::Text(data),
};
self.dispatch(message);
}
/// Pastes an image
#[wasm_bindgen(js_name = pasteImage)]
pub fn paste_image(
&self,
name: Option<String>,
image_data: Vec<u8>,
width: u32,
height: u32,
mouse_x: Option<f64>,
mouse_y: Option<f64>,
insert_parent_id: Option<u64>,
insert_index: Option<usize>,
) {
let mouse = mouse_x.and_then(|x| mouse_y.map(|y| (x, y)));
let image = graphene_std::raster::Image::from_image_data(&image_data, width, height);
let parent_and_insert_index = if let (Some(insert_parent_id), Some(insert_index)) = (insert_parent_id, insert_index) {
let insert_parent_id = NodeId(insert_parent_id);
let parent = LayerNodeIdentifier::new_unchecked(insert_parent_id);
Some((parent, insert_index))
} else {
None
};
let message = PortfolioMessage::InsertImage {
name,
image,
mouse,
parent_and_insert_index,
};
self.dispatch(message);
}
/// Pastes an SVG given its string representation
#[wasm_bindgen(js_name = pasteSvg)]
pub fn paste_svg(&self, name: Option<String>, svg: String, mouse_x: Option<f64>, mouse_y: Option<f64>, insert_parent_id: Option<u64>, insert_index: Option<usize>) {
let mouse = mouse_x.and_then(|x| mouse_y.map(|y| (x, y)));
let parent_and_insert_index = if let (Some(insert_parent_id), Some(insert_index)) = (insert_parent_id, insert_index) {
let insert_parent_id = NodeId(insert_parent_id);
let parent = LayerNodeIdentifier::new_unchecked(insert_parent_id);
Some((parent, insert_index))
} else {
None
};
let message = PortfolioMessage::InsertSvg {
name,
svg,
mouse,
parent_and_insert_index,
};
self.dispatch(message);
}
/// Toggle visibility of a layer or node given its node ID
#[wasm_bindgen(js_name = toggleNodeVisibilityLayerPanel)]
pub fn toggle_node_visibility_layer(&self, id: u64) {
let node_id = NodeId(id);
let message = NodeGraphMessage::ToggleVisibility { node_id, network_path: Vec::new() };
self.dispatch(message);
}
/// Pin or unpin a node given its node ID
#[wasm_bindgen(js_name = setNodePinned)]
pub fn set_node_pinned(&self, id: u64, pinned: bool) {
self.dispatch(DocumentMessage::SetNodePinned { node_id: NodeId(id), pinned });
}
/// Collapse or expand a node's section in the Properties panel
#[wasm_bindgen(js_name = toggleNodePropertiesSectionExpanded)]
pub fn toggle_node_properties_section_expanded(&self, id: u64) {
self.dispatch(DocumentMessage::ToggleNodePropertiesSectionExpanded { node_id: NodeId(id) });
}
/// Delete a layer or node given its node ID
#[wasm_bindgen(js_name = deleteNode)]
pub fn delete_node(&self, id: u64) {
self.dispatch(DocumentMessage::DeleteNode { node_id: NodeId(id) });
}
/// Toggle lock state of a layer from the layer list
#[wasm_bindgen(js_name = toggleLayerLock)]
pub fn toggle_layer_lock(&self, node_id: u64) {
let message = NodeGraphMessage::ToggleLocked {
node_id: NodeId(node_id),
network_path: Vec::new(),
};
self.dispatch(message);
}
/// Toggle expansions state of a layer from the layer list
#[wasm_bindgen(js_name = toggleLayerExpansion)]
pub fn toggle_layer_expansion(&self, tree_path: &[u64], recursive: bool) {
let tree_path = tree_path.iter().map(|&id| NodeId(id)).collect();
let message = DocumentMessage::ToggleLayerExpansion { tree_path, recursive };
self.dispatch(message);
}
/// Set the active panel to the most recently clicked panel
#[wasm_bindgen(js_name = setActivePanel)]
pub fn set_active_panel(&self, panel: String) {
let message = DocumentMessage::SetActivePanel { active_panel: panel.into() };
self.dispatch(message);
}
/// Toggle display type for a layer
#[wasm_bindgen(js_name = setToNodeOrLayer)]
pub fn set_to_node_or_layer(&self, id: u64, is_layer: bool) {
self.dispatch(DocumentMessage::SetToNodeOrLayer { node_id: NodeId(id), is_layer });
}
/// Set the name of an import or export
#[wasm_bindgen(js_name = setImportName)]
pub fn set_import_name(&self, index: usize, name: String) {
let message = NodeGraphMessage::SetImportExportName {
name,
index: ImportOrExport::Import(index),
};
self.dispatch(message);
}
/// Set the name of an export
#[wasm_bindgen(js_name = setExportName)]
pub fn set_export_name(&self, index: usize, name: String) {
let message = NodeGraphMessage::SetImportExportName {
name,
index: ImportOrExport::Export(index),
};
self.dispatch(message);
#[cfg(feature = "native")]
#[wasm_bindgen(js_name = loadPersistedState)]
pub fn load_persisted_state(&self, _state: JsValue) {
log::error!("loadPersistedState is unavailable on desktop; persistence is handled natively");
}
}
+18 -23
View File
@@ -1,14 +1,18 @@
#[cfg(not(feature = "native"))]
use crate::EDITOR;
#[cfg(not(feature = "native"))]
use crate::EDITOR_HAS_CRASHED;
use crate::EDITOR_WRAPPER;
use crate::editor_wrapper::EditorWrapper;
use crate::{EDITOR_HAS_CRASHED, EDITOR_WRAPPER};
use crate::native_communication::RasterizedImage;
#[cfg(not(feature = "native"))]
use editor::application::Editor;
#[cfg(feature = "editor")]
use editor::messages::input_mapper::utility_types::input_keyboard::Key;
#[cfg(not(feature = "native"))]
use editor::messages::prelude::*;
use graphene_std::color::SRGBA8;
use graphene_std::raster::Image;
use js_sys::{Object, Reflect};
#[cfg(not(feature = "native"))]
use std::sync::atomic::Ordering;
use std::time::Duration;
use wasm_bindgen::JsCast;
@@ -119,18 +123,8 @@ pub(crate) fn async_wake_callback() -> Wake {
})
}
pub(crate) fn auto_save_all_documents() {
// Process no further messages after a crash to avoid spamming the console
if EDITOR_HAS_CRASHED.load(Ordering::SeqCst) {
return;
}
wrapper(|wrapper| {
wrapper.dispatch(PortfolioMessage::AutoSaveAllDocuments);
});
}
pub(crate) fn render_image_data_to_canvases(image_data: &[(u64, Image<SRGBA8>)]) {
/// Blits each rasterized image to a canvas registered on `window.imageCanvases`
pub(crate) fn render_image_data_to_canvases<'a>(image_data: impl IntoIterator<Item = &'a RasterizedImage>) {
let window = match window() {
Some(window) => window,
None => {
@@ -155,11 +149,13 @@ pub(crate) fn render_image_data_to_canvases(image_data: &[(u64, Image<SRGBA8>)])
};
let canvases_obj = Object::from(canvases_obj);
for (placeholder_id, image) in image_data.iter() {
for image in image_data {
let (placeholder_id, width, height) = (image.id, image.width, image.height);
let pixels = image.pixels.as_slice();
let canvas_name = placeholder_id.to_string();
let js_key = JsValue::from_str(&canvas_name);
if Reflect::has(&canvases_obj, &js_key).unwrap_or(false) || image.width == 0 || image.height == 0 {
if Reflect::has(&canvases_obj, &js_key).unwrap_or(false) || width == 0 || height == 0 {
continue;
}
@@ -169,8 +165,8 @@ pub(crate) fn render_image_data_to_canvases(image_data: &[(u64, Image<SRGBA8>)])
.dyn_into::<HtmlCanvasElement>()
.expect("Failed to cast element to HtmlCanvasElement");
canvas.set_width(image.width);
canvas.set_height(image.height);
canvas.set_width(width);
canvas.set_height(height);
let context: CanvasRenderingContext2d = canvas
.get_context("2d")
@@ -178,10 +174,8 @@ pub(crate) fn render_image_data_to_canvases(image_data: &[(u64, Image<SRGBA8>)])
.expect("2d context was not found")
.dyn_into::<CanvasRenderingContext2d>()
.expect("Failed to cast context to CanvasRenderingContext2d");
// `SRGBA8` is `#[repr(C)]` of four `u8`s, so the data buffer is already the byte format the canvas expects
let u8_data: &[u8] = bytemuck::cast_slice(&image.data);
let clamped_u8_data = wasm_bindgen::Clamped(u8_data);
match ImageData::new_with_u8_clamped_array_and_sh(clamped_u8_data, image.width, image.height) {
let clamped_pixels = wasm_bindgen::Clamped(pixels);
match ImageData::new_with_u8_clamped_array_and_sh(clamped_pixels, width, height) {
Ok(image_data_obj) => {
if context.put_image_data(&image_data_obj, 0, 0).is_err() {
error!("Failed to put image data on canvas for id: {placeholder_id}");
@@ -209,6 +203,7 @@ pub(crate) fn calculate_hash<T: std::hash::Hash>(t: &T) -> u64 {
}
/// Translate a keyboard key from its JS name to its Rust `Key` enum
#[cfg(feature = "editor")]
pub(crate) fn translate_key(name: &str) -> Key {
use Key::*;
+69 -39
View File
@@ -4,11 +4,18 @@
#[macro_use]
extern crate log;
pub mod editor_commands;
pub mod editor_wrapper;
pub mod helpers;
pub mod native_communication;
mod wasm_value;
#[cfg(any(feature = "native", not(target_family = "wasm")))]
pub use editor_commands::EditorCommand;
#[cfg(feature = "editor")]
use crate::helpers::wrapper;
#[cfg(feature = "editor")]
use editor::messages::prelude::*;
use std::panic;
use std::sync::Mutex;
@@ -24,6 +31,7 @@ pub static LOGGER: WasmLog = WasmLog;
thread_local! {
#[cfg(not(feature = "native"))]
pub static EDITOR: Mutex<Option<editor::application::Editor>> = const { Mutex::new(None) };
#[cfg(not(feature = "native"))]
pub static MESSAGE_BUFFER: std::cell::RefCell<Vec<Message>> = const { std::cell::RefCell::new(Vec::new()) };
pub static EDITOR_WRAPPER: Mutex<Option<editor_wrapper::EditorWrapper>> = const { Mutex::new(None) };
pub static PANIC_DIALOG_MESSAGE_CALLBACK: std::cell::RefCell<Option<js_sys::Function>> = const { std::cell::RefCell::new(None) };
@@ -43,36 +51,41 @@ pub fn init_graphite() {
/// When a panic occurs, notify the user and log the error to the JS console before the backend dies
pub fn panic_hook(info: &panic::PanicHookInfo) {
let info = info.to_string();
let backtrace = Error::new("stack").stack().to_string();
if backtrace.contains("DynAnyNode") {
log::error!("Node graph evaluation panicked {info}");
// When the graph panics, the node runtime lock may not be released properly
if editor::node_graph_executor::NODE_RUNTIME.try_lock().is_none() {
unsafe { editor::node_graph_executor::NODE_RUNTIME.force_unlock() };
// Node graph panics can only originate here when the node graph runs inside this wasm module
#[cfg(feature = "editor")]
{
let backtrace = Error::new("stack").stack().to_string();
if backtrace.contains("DynAnyNode") {
log::error!("Node graph evaluation panicked {info}");
// When the graph panics, the node runtime lock may not be released properly
if editor::node_graph_executor::NODE_RUNTIME.try_lock().is_none() {
unsafe { editor::node_graph_executor::NODE_RUNTIME.force_unlock() };
}
if !NODE_GRAPH_ERROR_DISPLAYED.load(Ordering::SeqCst) {
NODE_GRAPH_ERROR_DISPLAYED.store(true, Ordering::SeqCst);
wrapper(|wrapper| {
let error = r#"
<rect x="50%" y="50%" width="600" height="100" transform="translate(-300 -50)" rx="4" fill="var(--color-error-red)" />
<text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" font-size="18" fill="var(--color-2-mildblack)">
<tspan x="50%" dy="-24" font-weight="bold">The document crashed while being rendered in its current state.</tspan>
<tspan x="50%" dy="24">The editor is now unstable! Undo your last action to restore the artwork,</tspan>
<tspan x="50%" dy="24">then save your document and restart the editor before continuing work.</tspan>
/text>"#
// It's a mystery why the `/text>` tag above needs to be missing its `<`, but when it exists it prints the `<` character in the text. However this works with it removed.
.to_string();
wrapper.send_frontend_message_to_js(FrontendMessage::UpdateDocumentArtwork { svg: error });
});
}
return;
}
if !NODE_GRAPH_ERROR_DISPLAYED.load(Ordering::SeqCst) {
NODE_GRAPH_ERROR_DISPLAYED.store(true, Ordering::SeqCst);
wrapper(|wrapper| {
let error = r#"
<rect x="50%" y="50%" width="600" height="100" transform="translate(-300 -50)" rx="4" fill="var(--color-error-red)" />
<text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" font-size="18" fill="var(--color-2-mildblack)">
<tspan x="50%" dy="-24" font-weight="bold">The document crashed while being rendered in its current state.</tspan>
<tspan x="50%" dy="24">The editor is now unstable! Undo your last action to restore the artwork,</tspan>
<tspan x="50%" dy="24">then save your document and restart the editor before continuing work.</tspan>
/text>"#
// It's a mystery why the `/text>` tag above needs to be missing its `<`, but when it exists it prints the `<` character in the text. However this works with it removed.
.to_string();
wrapper.send_frontend_message_to_js_rust_proxy(FrontendMessage::UpdateDocumentArtwork { svg: error });
});
}
return;
} else {
EDITOR_HAS_CRASHED.store(true, Ordering::SeqCst);
}
EDITOR_HAS_CRASHED.store(true, Ordering::SeqCst);
log::error!("{info}");
// Prefer using the raw JS callback to avoid mutex lock contention inside the panic hook.
@@ -82,30 +95,20 @@ pub fn panic_hook(info: &panic::PanicHookInfo) {
}
fn send_panic_dialog_via_callback(panic_info: String) -> Result<(), String> {
let message = FrontendMessage::DisplayDialogPanic { panic_info };
let message_type = message.to_discriminant().local_name();
let message = PanicDialogMessage::DisplayDialogPanic { panic_info: panic_info.clone() };
let Ok(message_data) = serde_wasm_bindgen::to_value(&message) else {
log::error!("Failed to serialize crash dialog panic message");
let FrontendMessage::DisplayDialogPanic { panic_info } = message else {
unreachable!("Message variant changed unexpectedly")
};
return Err(panic_info);
};
PANIC_DIALOG_MESSAGE_CALLBACK.with(|callback| {
let callback_ref = callback.borrow();
let Some(callback) = callback_ref.as_ref() else {
let FrontendMessage::DisplayDialogPanic { panic_info } = message else {
unreachable!("Message variant changed unexpectedly")
};
return Err(panic_info);
};
if let Err(error) = callback.call2(&JsValue::null(), &JsValue::from(message_type), &message_data) {
log::error!("Failed to send crash dialog panic message to JS: {:?}", error);
let FrontendMessage::DisplayDialogPanic { panic_info } = message else {
unreachable!("Message variant changed unexpectedly")
};
if let Err(error) = callback.call2(&JsValue::null(), &JsValue::from("DisplayDialogPanic"), &message_data) {
log::error!("Failed to send crash dialog panic message to JS: {error:?}");
return Err(panic_info);
}
@@ -201,3 +204,30 @@ impl log::Log for WasmLog {
fn flush(&self) {}
}
#[cfg(feature = "editor")]
use editor::messages::prelude::FrontendMessage as PanicDialogMessage;
#[cfg(not(feature = "editor"))]
use PanicDialogMessageCopy as PanicDialogMessage;
#[cfg(any(not(feature = "editor"), test))]
#[derive(serde::Serialize)]
enum PanicDialogMessageCopy {
DisplayDialogPanic {
#[serde(rename = "panicInfo")]
panic_info: String,
},
}
#[cfg(all(test, feature = "editor"))]
mod tests {
use super::*;
#[test]
fn panic_dialog_copy_matches_editor_shape() {
let copy = serde_json::to_value(PanicDialogMessageCopy::DisplayDialogPanic { panic_info: "info".into() }).unwrap();
let real = serde_json::to_value(FrontendMessage::DisplayDialogPanic { panic_info: "info".into() }).unwrap();
assert_eq!(copy, real);
}
}
+96 -9
View File
@@ -1,25 +1,77 @@
use crate::editor_wrapper::EditorWrapper;
use crate::helpers::wrapper;
use editor::messages::prelude::FrontendMessage;
//! Messaging with the native process. Serialized `FrontendMessage`s come in and are forwarded to JS,
//! `EditorCommand`s go back out. Encoding and decoding both live here so the wire format stays in one place.
use crate::editor_wrapper::{EditorWrapper, IMAGE_DATA_HASH};
use crate::helpers::{calculate_hash, render_image_data_to_canvases, wrapper};
use crate::wasm_value::WasmValue;
use js_sys::{ArrayBuffer, Uint8Array};
use std::sync::atomic::Ordering;
use wasm_bindgen::prelude::*;
#[wasm_bindgen(js_name = "receiveNativeMessage")]
pub fn receive_native_message(buffer: ArrayBuffer) {
let buffer = Uint8Array::new(buffer.as_ref()).to_vec();
match ron::from_str::<Vec<FrontendMessage>>(str::from_utf8(buffer.as_slice()).unwrap()) {
match serde_json::from_slice::<Vec<(String, String)>>(&buffer) {
Ok(messages) => {
let callback = move |wrapper: &mut EditorWrapper| {
for message in messages {
wrapper.send_frontend_message_to_js_rust_proxy(message);
wrapper(move |wrapper: &mut EditorWrapper| {
for (name, data) in messages {
match name.as_str() {
"UpdateImageData" => {
let new_hash = calculate_hash(&data);
if IMAGE_DATA_HASH.swap(new_hash, Ordering::Relaxed) == new_hash {
continue;
}
match serde_json::from_str::<Vec<RasterizedImage>>(&data) {
Ok(image_data) => render_image_data_to_canvases(image_data.iter()),
Err(e) => error!("Failed to deserialize image data: {e:?}"),
}
}
_ => match serde_json::from_str::<WasmValue>(&data) {
Ok(value) => wrapper.forward_serialized_frontend_message_to_js(&name, value),
Err(e) => log::error!("Failed to deserialize frontend message {name}: {e:?}"),
},
}
}
};
wrapper(callback);
});
}
Err(e) => log::error!("Failed to deserialize frontend messages: {e:?}"),
}
}
#[cfg(feature = "editor")]
pub fn encode_frontend_messages(messages: Vec<editor::messages::prelude::FrontendMessage>) -> Option<Vec<u8>> {
use editor::messages::prelude::FrontendMessage;
use editor::utility_traits::{AsMessage, ToDiscriminant};
let messages: Vec<(String, String)> = messages
.into_iter()
.map(|message| {
let name = message.to_discriminant().local_name();
let data = match message {
FrontendMessage::UpdateImageData { image_data } => serde_json::to_string(&image_data).inspect_err(|e| log::error!("Failed to serialize {name} payload: {e}")).ok()?,
message => crate::wasm_value::encode(&message)
.inspect_err(|e| log::error!("Failed to serialize FrontendMessage {name}: {e}"))
.ok()?,
};
Some((name, data))
})
.collect::<Option<_>>()?;
serde_json::to_vec(&messages).ok()
}
#[cfg(all(feature = "editor", any(feature = "native", not(target_family = "wasm"))))]
pub fn decode_editor_command(data: &[u8]) -> Option<editor::messages::prelude::Message> {
match serde_json::from_slice::<crate::EditorCommand>(data) {
Ok(command) => Some(command.into()),
Err(e) => {
log::error!("Failed to deserialize editor command: {e}");
None
}
}
}
pub fn initialize_native_communication() {
let global = js_sys::global();
@@ -44,3 +96,38 @@ pub fn send_message_to_cef(message: String) {
// Call it with argument
func.call1(&JsValue::NULL, &JsValue::from(buffer)).expect("Function call failed");
}
#[cfg(feature = "editor")]
pub(crate) use editor::messages::frontend::utility_types::RasterizedImage;
#[cfg(not(feature = "editor"))]
pub(crate) use RasterizedImageCopy as RasterizedImage;
#[cfg(any(not(feature = "editor"), test))]
#[derive(serde::Deserialize)]
pub(crate) struct RasterizedImageCopy {
pub(crate) id: u64,
pub(crate) width: u32,
pub(crate) height: u32,
pub(crate) pixels: Vec<u8>,
}
#[cfg(all(test, feature = "editor"))]
mod tests {
use super::*;
#[test]
fn rasterized_image_copy_matches_editor_shape() {
let editor_image = RasterizedImage {
id: 7,
width: 2,
height: 1,
pixels: serde_bytes::ByteBuf::from(vec![1, 2, 3, 4, 5, 6, 7, 8]),
};
let json = serde_json::to_string(&vec![editor_image]).unwrap();
let decoded: Vec<RasterizedImageCopy> = serde_json::from_str(&json).unwrap();
assert_eq!(decoded[0].id, 7);
assert_eq!((decoded[0].width, decoded[0].height), (2, 1));
assert_eq!(decoded[0].pixels, [1, 2, 3, 4, 5, 6, 7, 8]);
}
}
+448
View File
@@ -0,0 +1,448 @@
//! Serializable stand-in for `JsValue`, used to send `FrontendMessage`s from the native editor process to JS.
//! Keeps the types JSON can't represent (`BigInt`, `Uint8Array`, `Map`, `undefined`, `NaN`) so the wasm side
//! can reconstruct the same `JsValue`s that `serde_wasm_bindgen` produces on web.
use serde::{Deserialize, Serialize};
#[cfg(feature = "editor")]
use serde_json::Error;
use wasm_bindgen::JsValue;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub(crate) enum WasmValue {
Undefined,
Bool(bool),
Number(f64),
NonFinite(NonFinite),
Int(i64),
UInt(u64),
String(String),
Bytes(Vec<u8>),
Seq(Vec<WasmValue>),
Object(Vec<(String, WasmValue)>),
Map(Vec<(WasmValue, WasmValue)>),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum NonFinite {
Nan,
PositiveInfinity,
NegativeInfinity,
}
impl From<NonFinite> for f64 {
fn from(value: NonFinite) -> Self {
match value {
NonFinite::Nan => f64::NAN,
NonFinite::PositiveInfinity => f64::INFINITY,
NonFinite::NegativeInfinity => f64::NEG_INFINITY,
}
}
}
impl From<WasmValue> for JsValue {
fn from(value: WasmValue) -> Self {
match value {
WasmValue::Undefined => JsValue::UNDEFINED,
WasmValue::Bool(value) => JsValue::from_bool(value),
WasmValue::Number(value) => JsValue::from_f64(value),
WasmValue::NonFinite(value) => JsValue::from_f64(value.into()),
WasmValue::Int(value) => JsValue::from(value),
WasmValue::UInt(value) => JsValue::from(value),
WasmValue::String(value) => JsValue::from_str(&value),
WasmValue::Bytes(bytes) => js_sys::Uint8Array::from(bytes.as_slice()).into(),
WasmValue::Seq(values) => {
let array = js_sys::Array::new();
for value in values {
array.push(&value.into());
}
array.into()
}
WasmValue::Object(fields) => {
let object = js_sys::Object::new();
for (key, value) in fields {
let _ = js_sys::Reflect::set(&object, &JsValue::from_str(&key), &value.into());
}
object.into()
}
WasmValue::Map(entries) => {
let map = js_sys::Map::new();
for (key, value) in entries {
map.set(&key.into(), &value.into());
}
map.into()
}
}
}
}
#[cfg(feature = "editor")]
pub(crate) fn encode<T: Serialize + ?Sized>(value: &T) -> Result<String, serde_json::Error> {
serde_json::to_string(&ser::to_value(value)?)
}
#[cfg(feature = "editor")]
mod ser {
use super::*;
use serde::ser::{self, Error as _};
pub(super) fn to_value<T: Serialize + ?Sized>(value: &T) -> Result<WasmValue, Error> {
value.serialize(ValueSerializer)
}
struct ValueSerializer;
impl ser::Serializer for ValueSerializer {
type Ok = WasmValue;
type Error = Error;
type SerializeSeq = SeqSerializer;
type SerializeTuple = SeqSerializer;
type SerializeTupleStruct = SeqSerializer;
type SerializeTupleVariant = VariantSeqSerializer;
type SerializeMap = MapSerializer;
type SerializeStruct = ObjectSerializer;
type SerializeStructVariant = VariantObjectSerializer;
fn serialize_bool(self, v: bool) -> Result<WasmValue, Error> {
Ok(WasmValue::Bool(v))
}
fn serialize_i8(self, v: i8) -> Result<WasmValue, Error> {
Ok(WasmValue::Number(v as f64))
}
fn serialize_i16(self, v: i16) -> Result<WasmValue, Error> {
Ok(WasmValue::Number(v as f64))
}
fn serialize_i32(self, v: i32) -> Result<WasmValue, Error> {
Ok(WasmValue::Number(v as f64))
}
fn serialize_i64(self, v: i64) -> Result<WasmValue, Error> {
Ok(WasmValue::Int(v))
}
fn serialize_i128(self, v: i128) -> Result<WasmValue, Error> {
if let Ok(v) = i64::try_from(v) {
Ok(WasmValue::Int(v))
} else {
u64::try_from(v)
.map(WasmValue::UInt)
.map_err(|_| Error::custom(format!("i128 value {v} exceeds the wire BigInt range")))
}
}
fn serialize_u8(self, v: u8) -> Result<WasmValue, Error> {
Ok(WasmValue::Number(v as f64))
}
fn serialize_u16(self, v: u16) -> Result<WasmValue, Error> {
Ok(WasmValue::Number(v as f64))
}
fn serialize_u32(self, v: u32) -> Result<WasmValue, Error> {
Ok(WasmValue::Number(v as f64))
}
fn serialize_u64(self, v: u64) -> Result<WasmValue, Error> {
Ok(WasmValue::UInt(v))
}
fn serialize_u128(self, v: u128) -> Result<WasmValue, Error> {
u64::try_from(v)
.map(WasmValue::UInt)
.map_err(|_| Error::custom(format!("u128 value {v} exceeds the wire BigInt range")))
}
fn serialize_f32(self, v: f32) -> Result<WasmValue, Error> {
self.serialize_f64(v as f64)
}
fn serialize_f64(self, v: f64) -> Result<WasmValue, Error> {
Ok(if v.is_finite() {
WasmValue::Number(v)
} else if v.is_nan() {
WasmValue::NonFinite(NonFinite::Nan)
} else if v > 0. {
WasmValue::NonFinite(NonFinite::PositiveInfinity)
} else {
WasmValue::NonFinite(NonFinite::NegativeInfinity)
})
}
fn serialize_char(self, v: char) -> Result<WasmValue, Error> {
Ok(WasmValue::String(v.to_string()))
}
fn serialize_str(self, v: &str) -> Result<WasmValue, Error> {
Ok(WasmValue::String(v.to_string()))
}
fn serialize_bytes(self, v: &[u8]) -> Result<WasmValue, Error> {
Ok(WasmValue::Bytes(v.to_vec()))
}
fn serialize_none(self) -> Result<WasmValue, Error> {
Ok(WasmValue::Undefined)
}
fn serialize_some<T: Serialize + ?Sized>(self, value: &T) -> Result<WasmValue, Error> {
value.serialize(self)
}
fn serialize_unit(self) -> Result<WasmValue, Error> {
Ok(WasmValue::Undefined)
}
fn serialize_unit_struct(self, _name: &'static str) -> Result<WasmValue, Error> {
Ok(WasmValue::Undefined)
}
fn serialize_unit_variant(self, _name: &'static str, _variant_index: u32, variant: &'static str) -> Result<WasmValue, Error> {
Ok(WasmValue::String(variant.to_string()))
}
fn serialize_newtype_struct<T: Serialize + ?Sized>(self, _name: &'static str, value: &T) -> Result<WasmValue, Error> {
value.serialize(self)
}
fn serialize_newtype_variant<T: Serialize + ?Sized>(self, _name: &'static str, _variant_index: u32, variant: &'static str, value: &T) -> Result<WasmValue, Error> {
Ok(WasmValue::Object(vec![(variant.to_string(), value.serialize(ValueSerializer)?)]))
}
fn serialize_seq(self, len: Option<usize>) -> Result<SeqSerializer, Error> {
Ok(SeqSerializer(Vec::with_capacity(len.unwrap_or_default())))
}
fn serialize_tuple(self, len: usize) -> Result<SeqSerializer, Error> {
self.serialize_seq(Some(len))
}
fn serialize_tuple_struct(self, _name: &'static str, len: usize) -> Result<SeqSerializer, Error> {
self.serialize_seq(Some(len))
}
fn serialize_tuple_variant(self, _name: &'static str, _variant_index: u32, variant: &'static str, len: usize) -> Result<VariantSeqSerializer, Error> {
Ok(VariantSeqSerializer {
variant,
elements: Vec::with_capacity(len),
})
}
fn serialize_map(self, len: Option<usize>) -> Result<MapSerializer, Error> {
Ok(MapSerializer {
entries: Vec::with_capacity(len.unwrap_or_default()),
pending_key: None,
})
}
fn serialize_struct(self, _name: &'static str, len: usize) -> Result<ObjectSerializer, Error> {
Ok(ObjectSerializer(Vec::with_capacity(len)))
}
fn serialize_struct_variant(self, _name: &'static str, _variant_index: u32, variant: &'static str, len: usize) -> Result<VariantObjectSerializer, Error> {
Ok(VariantObjectSerializer {
variant,
fields: Vec::with_capacity(len),
})
}
}
struct SeqSerializer(Vec<WasmValue>);
impl ser::SerializeSeq for SeqSerializer {
type Ok = WasmValue;
type Error = Error;
fn serialize_element<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
self.0.push(value.serialize(ValueSerializer)?);
Ok(())
}
fn end(self) -> Result<WasmValue, Error> {
Ok(WasmValue::Seq(self.0))
}
}
impl ser::SerializeTuple for SeqSerializer {
type Ok = WasmValue;
type Error = Error;
fn serialize_element<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
ser::SerializeSeq::serialize_element(self, value)
}
fn end(self) -> Result<WasmValue, Error> {
ser::SerializeSeq::end(self)
}
}
impl ser::SerializeTupleStruct for SeqSerializer {
type Ok = WasmValue;
type Error = Error;
fn serialize_field<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
ser::SerializeSeq::serialize_element(self, value)
}
fn end(self) -> Result<WasmValue, Error> {
ser::SerializeSeq::end(self)
}
}
struct VariantSeqSerializer {
variant: &'static str,
elements: Vec<WasmValue>,
}
impl ser::SerializeTupleVariant for VariantSeqSerializer {
type Ok = WasmValue;
type Error = Error;
fn serialize_field<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
self.elements.push(value.serialize(ValueSerializer)?);
Ok(())
}
fn end(self) -> Result<WasmValue, Error> {
Ok(WasmValue::Object(vec![(self.variant.to_string(), WasmValue::Seq(self.elements))]))
}
}
struct MapSerializer {
entries: Vec<(WasmValue, WasmValue)>,
pending_key: Option<WasmValue>,
}
impl ser::SerializeMap for MapSerializer {
type Ok = WasmValue;
type Error = Error;
fn serialize_key<T: Serialize + ?Sized>(&mut self, key: &T) -> Result<(), Error> {
self.pending_key = Some(key.serialize(ValueSerializer)?);
Ok(())
}
fn serialize_value<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
let key = self.pending_key.take().ok_or_else(|| Error::custom("Map value serialized without a key"))?;
self.entries.push((key, value.serialize(ValueSerializer)?));
Ok(())
}
fn end(self) -> Result<WasmValue, Error> {
Ok(WasmValue::Map(self.entries))
}
}
struct ObjectSerializer(Vec<(String, WasmValue)>);
impl ser::SerializeStruct for ObjectSerializer {
type Ok = WasmValue;
type Error = Error;
fn serialize_field<T: Serialize + ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Error> {
self.0.push((key.to_string(), value.serialize(ValueSerializer)?));
Ok(())
}
fn end(self) -> Result<WasmValue, Error> {
Ok(WasmValue::Object(self.0))
}
}
struct VariantObjectSerializer {
variant: &'static str,
fields: Vec<(String, WasmValue)>,
}
impl ser::SerializeStructVariant for VariantObjectSerializer {
type Ok = WasmValue;
type Error = Error;
fn serialize_field<T: Serialize + ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Error> {
self.fields.push((key.to_string(), value.serialize(ValueSerializer)?));
Ok(())
}
fn end(self) -> Result<WasmValue, Error> {
Ok(WasmValue::Object(vec![(self.variant.to_string(), WasmValue::Object(self.fields))]))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::wasm_value::encode;
use serde::Serialize;
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
enum TestMessage {
UnitVariant,
StructVariant {
#[serde(rename = "nodeId")]
node_id: u64,
width: u32,
scale: f64,
min: f64,
max: f64,
label: Option<String>,
widths: std::collections::BTreeMap<u64, u32>,
flags: Vec<bool>,
bytes: serde_bytes::ByteBuf,
},
}
#[test]
fn mirrors_serde_wasm_bindgen_representations() {
assert_eq!(to_value(&TestMessage::UnitVariant).unwrap(), WasmValue::String("unitVariant".into()));
let message = TestMessage::StructVariant {
node_id: u64::MAX,
width: 8,
scale: f64::NAN,
min: f64::NEG_INFINITY,
max: f64::INFINITY,
label: None,
widths: [(42, 7)].into(),
flags: vec![true, false],
bytes: serde_bytes::ByteBuf::from(vec![0, 255]),
};
let expected = WasmValue::Object(vec![(
"structVariant".into(),
WasmValue::Object(vec![
("nodeId".into(), WasmValue::UInt(u64::MAX)),
("width".into(), WasmValue::Number(8.)),
("scale".into(), WasmValue::NonFinite(NonFinite::Nan)),
("min".into(), WasmValue::NonFinite(NonFinite::NegativeInfinity)),
("max".into(), WasmValue::NonFinite(NonFinite::PositiveInfinity)),
("label".into(), WasmValue::Undefined),
("widths".into(), WasmValue::Map(vec![(WasmValue::UInt(42), WasmValue::Number(7.))])),
("flags".into(), WasmValue::Seq(vec![WasmValue::Bool(true), WasmValue::Bool(false)])),
("bytes".into(), WasmValue::Bytes(vec![0, 255])),
]),
)]);
assert_eq!(to_value(&message).unwrap(), expected);
}
#[test]
fn encode_decode_roundtrip() {
let message = TestMessage::StructVariant {
node_id: 1,
width: 2,
scale: f64::NAN,
min: f64::NEG_INFINITY,
max: 1.5,
label: Some("hi".into()),
widths: [(3, 4)].into(),
flags: vec![true],
bytes: serde_bytes::ByteBuf::from(vec![9]),
};
let json: &str = &encode(&message).unwrap();
let decoded: WasmValue = serde_json::from_str(json).unwrap();
assert_eq!(decoded, to_value(&message).unwrap());
}
}
}
+5 -44
View File
@@ -121,18 +121,6 @@ impl OriginalLocation {
}
}
impl DocumentNode {
/// Normalizes this node's stored types (call argument, `Import` input types, `TypeDefault` value payloads, and any nested network) to their structural form.
/// Applied once at ingestion (document migration and clipboard paste) so no name-encoded ranked type enters a live document.
pub fn normalize_stored_types(&mut self) {
self.call_argument = self.call_argument.clone().normalize_rank();
for input in &mut self.inputs {
normalize_input_stored_type(input);
}
if let Some(network) = self.implementation.get_network_mut() {
network.normalize_stored_types();
}
}
/// Locate the input that is a [`NodeInput::Import`] at index `offset` and replace it with a [`NodeInput::Node`].
pub fn populate_first_network_input(&mut self, node_id: NodeId, output_index: usize, offset: usize, source: impl Iterator<Item = Source>, skip: usize) {
let (index, _) = self
@@ -232,7 +220,7 @@ pub enum DocumentNodeMetadata {
impl DocumentNodeMetadata {
pub fn ty(&self) -> Type {
match self {
DocumentNodeMetadata::DocumentNodePath => item!(core_types::list::NodeIdPath),
DocumentNodeMetadata::DocumentNodePath => concrete!(core_types::list::List<NodeId>),
}
}
}
@@ -247,10 +235,10 @@ impl NodeInput {
Self::Value { tagged_value, exposed }
}
/// Constructs a `NodeInput::Value` whose tagged value is `TaggedValue::TypeDefault(ty)`, recording only the
/// Constructs a `NodeInput::Value` whose tagged value is `TaggedValue::TypeDefault(td)`, recording only the
/// type so the runtime materializes its default rather than baking a placeholder value into the saved document.
pub fn type_default(ty: Type, exposed: bool) -> Self {
Self::value(TaggedValue::TypeDefault(ty.normalize_rank()), exposed)
pub fn type_default(td: core_types::TypeDescriptor, exposed: bool) -> Self {
Self::value(TaggedValue::TypeDefault(td), exposed)
}
pub const fn import(import_type: Type, import_index: usize) -> Self {
@@ -282,7 +270,6 @@ impl NodeInput {
match self {
NodeInput::Node { .. } => unreachable!("ty() called on NodeInput::Node"),
NodeInput::Value { tagged_value, .. } => tagged_value.ty(),
// Stored import types are normalized to their structural form once at document migration
NodeInput::Import { import_type, .. } => import_type.clone(),
NodeInput::Inline(_) => panic!("ty() called on NodeInput::Inline"),
NodeInput::Scope(_) => panic!("ty() called on NodeInput::Scope"),
@@ -736,33 +723,7 @@ impl ScopeChain<'_> {
}
/// Functions for compiling the network
/// Normalizes the ranked types an input can store: an `Import`'s type or a value's `TypeDefault` payload.
fn normalize_input_stored_type(input: &mut NodeInput) {
match input {
NodeInput::Import { import_type, .. } => *import_type = import_type.clone().normalize_rank(),
NodeInput::Value { tagged_value, .. } => {
if let TaggedValue::TypeDefault(ty) = &**tagged_value {
let normalized = ty.clone().normalize_rank();
if normalized != *ty {
*tagged_value = TaggedValue::TypeDefault(normalized).into();
}
}
}
_ => {}
}
}
impl NodeNetwork {
/// Normalizes every stored type in the network (exports and each node's types) to the structural form, recursively.
pub fn normalize_stored_types(&mut self) {
for export in &mut self.exports {
normalize_input_stored_type(export);
}
for node in self.nodes.values_mut() {
node.normalize_stored_types();
}
}
/// Replace all references in the graph of a node ID with a new node ID defined by the function `f`.
pub fn map_ids(&mut self, f: impl Fn(NodeId) -> NodeId + Copy) {
self.exports.iter_mut().for_each(|output| {
@@ -1034,7 +995,7 @@ impl NodeNetwork {
let (tagged_value, exposed) = match previous_export {
NodeInput::Value { tagged_value, exposed } => (tagged_value, exposed),
NodeInput::Reflection(reflect) => match reflect {
DocumentNodeMetadata::DocumentNodePath => (TaggedValue::NodeIdPath(core_types::list::NodeIdPath::from(path.to_vec())).into(), false),
DocumentNodeMetadata::DocumentNodePath => (TaggedValue::NodeIdPath(path.to_vec()).into(), false),
},
previous_export => {
*export = previous_export;
+137 -314
View File
@@ -2,20 +2,18 @@ use super::DocumentNode;
use crate::application_io::PlatformEditorApi;
use crate::application_io::resource::Resource;
use crate::proto::{Any as DAny, FutureAny};
use brush_nodes::brush_stroke::{BrushStroke, BrushTrace};
use brush_nodes::brush_stroke::BrushStroke;
use core_types::color::SRGBA8;
use core_types::list::{Item, List, NodeIdPath};
use core_types::list::List;
use core_types::transform::Footprint;
use core_types::uuid::NodeId;
use core_types::{CacheHash, Color, ContextFeatures, MemoHash, Node, Type, TypeDescriptor};
use dyn_any::DynAny;
pub use dyn_any::StaticType;
pub use glam::{DAffine2, DVec2, IVec2, UVec2};
use graphene_application_io::resource::ResourceHash;
use graphene_application_io::resource::ResourceId;
use graphic_types::raster_types::{CPU, Image, Raster};
use graphic_types::vector_types::vector::misc::BoxCorners;
use graphic_types::vector_types::vector::style::DashPattern;
use graphic_types::vector_types::vector::style::Gradient;
use graphic_types::vector_types::vector::style::GradientStops;
use graphic_types::vector_types::vector::{self, ReferencePoint};
use graphic_types::{Artboard, Graphic, Vector};
use rendering::RenderMetadata;
@@ -30,38 +28,15 @@ use vector::VectorModification;
pub struct TaggedValueTypeError;
/// Item-cell element types routed through [`TaggedValue::TypeDefault`] instead of another dedicated variant, stored as the concrete `Item<T>` wire type.
/// List of types routed through [`TaggedValue::TypeDefault`] instead of another dedicated variant.
/// Consumed by [`TaggedValue::from_type`] (which creates `TypeDefault` values) and [`TaggedValue::to_dynany`]/[`TaggedValue::to_any`] (which unwrap them into real default values).
macro_rules! for_each_item_type_default {
($action:ident) => {
$action!(Vector);
$action!(f64);
$action!(Raster<CPU>);
$action!(Graphic);
$action!(Color);
$action!(Gradient);
$action!(Artboard);
$action!(String);
};
}
/// List element types routed through [`TaggedValue::TypeDefault`], stored as the structural [`Type::List`] form.
/// `List<f64>` is absent because it stores as `TaggedValue::F64Array`.
macro_rules! for_each_list_type_default {
($action:ident) => {
$action!(Graphic);
$action!(Artboard);
$action!(Raster<CPU>);
$action!(Vector);
$action!(String);
$action!(Color);
$action!(Gradient);
};
}
/// Unranked types routed through [`TaggedValue::TypeDefault`], stored as their concrete type.
macro_rules! for_each_bare_type_default {
macro_rules! for_each_type_default {
($action:ident) => {
$action!(List<Graphic>);
$action!(List<Artboard>);
$action!(List<Raster<CPU>>);
$action!(List<Vector>);
$action!(List<String>);
$action!(DocumentNode);
$action!(Resource);
};
@@ -79,24 +54,22 @@ macro_rules! tagged_value {
// ===============
None,
/// Stores a type, from which its `Default::default()` value can be obtained, rather than storing an actual type's value.
/// Example: `TaggedValue::TypeDefault(concrete!(String))` stores the type `String` but no specific string value.
/// (Old documents stored a bare `TypeDescriptor` payload, routed to this shape by `deserialize_tagged_value_with_legacy_migration`.)
TypeDefault(Type),
/// Example: `TaggedValue::TypeDefault(descriptor!(String))` stores the type `String` but no specific string value.
TypeDefault(TypeDescriptor),
/// Stored compactly as a `Vec<f64>`, materializes as `List<f64>` at runtime via `to_dynany`/`to_any`. Aliases recover legacy on-disk shapes.
#[serde(deserialize_with = "core_types::misc::migrate_to_f64_array")] // TODO: Eventually remove this migration document upgrade code
#[serde(alias = "F64Table", alias = "VecF64", alias = "VecF32", alias = "F64Array4")]
F64Array(Vec<f64>),
/// A plain, always-present color. Aliases recover legacy on-disk shapes; a legacy `null` payload (the old "no color")
/// is routed to [`TaggedValue::no_paint`] by `deserialize_tagged_value_with_legacy_migration`.
#[serde(deserialize_with = "core_types::misc::migrate_to_color")] // TODO: Eventually remove this migration document upgrade code
/// Stored compactly as an `Option<Color>`, materializes as `List<Color>` at runtime via `to_dynany`/`to_any`. Aliases recover legacy on-disk shapes.
#[serde(deserialize_with = "core_types::misc::migrate_to_optional_color")] // TODO: Eventually remove this migration document upgrade code
#[serde(alias = "ColorTable", alias = "OptionalColor", alias = "ColorNotInTable")]
Color(Color),
/// Stored compactly as a `Gradient`, materializing as an `Item<Gradient>` at runtime. Aliases recover legacy on-disk shapes.
Color(Option<Color>),
/// Stored compactly as a `GradientStops`, materializes as a single-row `List<GradientStops>` at runtime via `to_dynany`/`to_any`. Aliases recover legacy on-disk shapes.
/// (Old documents that stored a full `Gradient` struct under this same `"Gradient"` tag are routed to `LegacyGradient` by `deserialize_tagged_value_with_legacy_migration`.)
#[serde(deserialize_with = "graphic_types::vector_types::gradient::migrate_to_gradient")] // TODO: Eventually remove this migration document upgrade code
#[serde(deserialize_with = "graphic_types::vector_types::gradient::migrate_to_gradient_stops")] // TODO: Eventually remove this migration document upgrade code
#[serde(alias = "GradientTable", alias = "GradientPositions", alias = "GradientStops")]
Gradient(Gradient),
/// Stored compactly as a `Vec<BrushStroke>`, materializes as the single-value `Item<BrushTrace>` at runtime via `to_dynany`/`to_any`. Aliases recover legacy on-disk shapes.
Gradient(GradientStops),
/// Stored compactly as a `Vec<BrushStroke>`, materializes as `List<BrushStroke>` at runtime via `to_dynany`/`to_any`. Aliases recover legacy on-disk shapes.
#[serde(deserialize_with = "brush_nodes::migrations::migrate_to_brush_strokes")] // TODO: Eventually remove this migration document upgrade code
#[serde(alias = "BrushStrokeTable")]
BrushStrokes(Vec<BrushStroke>),
@@ -109,10 +82,10 @@ macro_rules! tagged_value {
// =======================
#[serde(skip)]
RenderOutput(RenderOutput),
/// Path to the consumer of a `NodeInput::Reflection(DocumentNodePath)`. Materializes an `Item<NodeIdPath>` at runtime via `to_dynany`/`to_any` during graph flattening, matching the ranked connectors it feeds.
/// Path to the consumer of a `NodeInput::Reflection(DocumentNodePath)`. Materializes a `List<NodeId>` at runtime via `to_dynany`/`to_any` during graph flattening.
#[serde(skip)]
NodeIdPath(NodeIdPath),
/// The `DocumentNode` value carried by an `Extract` proto node, populated at flatten time by `resolve_extract_nodes`. The on-disk placeholder uses `TypeDefault(concrete!(DocumentNode))`.
NodeIdPath(Vec<NodeId>),
/// The `DocumentNode` value carried by an `Extract` proto node, populated at flatten time by `resolve_extract_nodes`. The on-disk placeholder uses `TypeDefault(descriptor!(DocumentNode))`.
#[serde(skip)]
DocumentNode(DocumentNode),
/// Carried by context nullification proto nodes constructed at proto node compilation time in `insert_context_nullification_nodes`.
@@ -145,7 +118,7 @@ macro_rules! tagged_value {
// =======================
// NON-SERIALIZED VARIANTS
// =======================
Self::NodeIdPath(path) => path.cache_hash(state),
Self::NodeIdPath(path) => path.hash(state),
Self::DocumentNode(node) => node.cache_hash(state),
Self::ContextFeatures(features) => features.cache_hash(state),
Self::RenderOutput(x) => x.cache_hash(state),
@@ -165,58 +138,46 @@ macro_rules! tagged_value {
Self::None => Box::new(()),
Self::TypeDefault(td) => {
// Construct the actual default for types without a `TaggedValue` variant directly.
// Recursion through `from_type_or_none` below is safe only because the type-default lists
// exhaustively cover every type that `from_type` would route back to `TypeDefault`.
match &td {
Type::List(element) => {
macro_rules! check {
($type_default:ty) => {
if **element == concrete!($type_default) { return Box::new(List::<$type_default>::default()); }
};
}
for_each_list_type_default!(check);
}
Type::Item(element) => {
macro_rules! check {
($type_default:ty) => {
if **element == concrete!($type_default) { return Box::new(Item::<$type_default>::default()); }
};
}
for_each_item_type_default!(check);
}
Type::Concrete(descriptor) => {
let name = descriptor.name.as_ref();
macro_rules! check_bare {
($type_default:ty) => {
if name == std::any::type_name::<$type_default>() { return Box::new(<$type_default>::default()); }
};
}
for_each_bare_type_default!(check_bare);
}
_ => {}
// Recursion through `from_type_or_none` below is safe only because `for_each_type_default!`
// exhaustively handles every type that `from_type` would route back to `TypeDefault`.
let name = td.name.as_ref();
macro_rules! check {
($type_default:ty) => {
if name == std::any::type_name::<$type_default>() { return Box::new(<$type_default>::default()); }
};
}
Self::from_type_or_none(&td).to_dynany()
for_each_type_default!(check);
Self::from_type_or_none(&Type::Concrete(td)).to_dynany()
}
Self::F64Array(values) => {
let list: List<f64> = values.into_iter().map(core_types::list::Item::new_from_element).collect();
Box::new(list)
}
Self::Color(color) => Box::new(Item::new_from_element(color)),
Self::Gradient(stops) => Box::new(Item::new_from_element(stops)),
Self::BrushStrokes(strokes) => Box::new(core_types::list::Item::new_from_element(BrushTrace::from(strokes))),
Self::Color(color) => {
let list: List<Color> = color.into_iter().map(core_types::list::Item::new_from_element).collect();
Box::new(list)
}
Self::Gradient(stops) => Box::new(List::<GradientStops>::new_from_element(stops)),
Self::BrushStrokes(strokes) => {
let list: List<BrushStroke> = strokes.into_iter().map(core_types::list::Item::new_from_element).collect();
Box::new(list)
}
// =======================
// AUTO-GENERATED VARIANTS
// =======================
$( Self::$identifier(x) => Box::new(Item::new_from_element(x)), )*
$( Self::$identifier(x) => Box::new(x), )*
// =======================
// NON-SERIALIZED VARIANTS
// =======================
Self::RenderOutput(x) => Box::new(Item::new_from_element(x)),
Self::NodeIdPath(path) => Box::new(Item::new_from_element(path)),
Self::RenderOutput(x) => Box::new(x),
Self::NodeIdPath(path) => {
let list: List<NodeId> = path.into_iter().map(core_types::list::Item::new_from_element).collect();
Box::new(list)
}
Self::DocumentNode(node) => Box::new(node),
Self::ContextFeatures(features) => Box::new(Item::new_from_element(features)),
Self::ContextFeatures(features) => Box::new(features),
Self::EditorApi(x) => Box::new(x),
Self::ResourceHash(x) => Box::new(Item::new_from_element(x)),
Self::ResourceHash(x) => Box::new(x),
}
}
@@ -229,88 +190,73 @@ macro_rules! tagged_value {
Self::None => Arc::new(()),
Self::TypeDefault(td) => {
// Same direct-construction path as `to_dynany` for the same reason as in `to_dynany`.
match &td {
Type::List(element) => {
macro_rules! check {
($type_default:ty) => {
if **element == concrete!($type_default) { return Arc::new(List::<$type_default>::default()); }
};
}
for_each_list_type_default!(check);
}
Type::Item(element) => {
macro_rules! check {
($type_default:ty) => {
if **element == concrete!($type_default) { return Arc::new(Item::<$type_default>::default()); }
};
}
for_each_item_type_default!(check);
}
Type::Concrete(descriptor) => {
let name = descriptor.name.as_ref();
macro_rules! check_bare {
($type_default:ty) => {
if name == std::any::type_name::<$type_default>() { return Arc::new(<$type_default>::default()); }
};
}
for_each_bare_type_default!(check_bare);
}
_ => {}
let name = td.name.as_ref();
macro_rules! check {
($type_default:ty) => {
if name == std::any::type_name::<$type_default>() { return Arc::new(<$type_default>::default()); }
};
}
Self::from_type_or_none(&td).to_any()
for_each_type_default!(check);
Self::from_type_or_none(&Type::Concrete(td)).to_any()
}
Self::F64Array(values) => {
let list: List<f64> = values.into_iter().map(core_types::list::Item::new_from_element).collect();
Arc::new(list)
}
Self::Color(color) => Arc::new(Item::new_from_element(color)),
Self::Gradient(stops) => Arc::new(Item::new_from_element(stops)),
Self::BrushStrokes(strokes) => Arc::new(core_types::list::Item::new_from_element(BrushTrace::from(strokes))),
Self::Color(color) => {
let list: List<Color> = color.into_iter().map(core_types::list::Item::new_from_element).collect();
Arc::new(list)
}
Self::Gradient(stops) => Arc::new(List::<GradientStops>::new_from_element(stops)),
Self::BrushStrokes(strokes) => {
let list: List<BrushStroke> = strokes.into_iter().map(core_types::list::Item::new_from_element).collect();
Arc::new(list)
}
// =======================
// AUTO-GENERATED VARIANTS
// =======================
$( Self::$identifier(x) => Arc::new(Item::new_from_element(x)), )*
$( Self::$identifier(x) => Arc::new(x), )*
// =======================
// NON-SERIALIZED VARIANTS
// =======================
Self::RenderOutput(x) => Arc::new(Item::new_from_element(x)),
Self::NodeIdPath(path) => Arc::new(Item::new_from_element(path)),
Self::RenderOutput(x) => Arc::new(x),
Self::NodeIdPath(path) => {
let list: List<NodeId> = path.into_iter().map(core_types::list::Item::new_from_element).collect();
Arc::new(list)
}
Self::DocumentNode(node) => Arc::new(node),
Self::ContextFeatures(features) => Arc::new(Item::new_from_element(features)),
Self::ContextFeatures(features) => Arc::new(features),
Self::EditorApi(x) => Arc::new(x),
Self::ResourceHash(x) => Arc::new(Item::new_from_element(x)),
Self::ResourceHash(x) => Arc::new(x),
}
}
/// Creates the wire [`Type`] of the value inside the tagged value, with ranked types in their structural form.
/// Creates a core_types::Type::Concrete(TypeDescriptor { .. }) with the type of the value inside the tagged value
pub fn ty(&self) -> Type {
let ty = match self {
match self {
// ===============
// MANUAL VARIANTS
// ===============
Self::None => concrete!(()),
Self::TypeDefault(td) => td.clone(),
Self::F64Array(_) => list!(f64),
Self::Color(_) => item!(Color),
Self::Gradient(_) => item!(Gradient),
Self::BrushStrokes(_) => item!(BrushTrace),
Self::TypeDefault(td) => Type::Concrete(td.clone()),
Self::F64Array(_) => concrete!(List<f64>),
Self::Color(_) => concrete!(List<Color>),
Self::Gradient(_) => concrete!(List<GradientStops>),
Self::BrushStrokes(_) => concrete!(List<BrushStroke>),
// =======================
// AUTO-GENERATED VARIANTS
// =======================
$( Self::$identifier(_) => item!($ty), )*
$( Self::$identifier(_) => concrete!($ty), )*
// =======================
// NON-SERIALIZED VARIANTS
// =======================
Self::RenderOutput(_) => item!(RenderOutput),
Self::NodeIdPath(_) => item!(NodeIdPath),
Self::RenderOutput(_) => concrete!(RenderOutput),
Self::NodeIdPath(_) => concrete!(List<NodeId>),
Self::DocumentNode(_) => concrete!(DocumentNode),
Self::ContextFeatures(_) => item!(ContextFeatures),
Self::EditorApi(_) => item!(&PlatformEditorApi),
Self::ResourceHash(_) => item!(ResourceHash),
};
// Defensively converges any remaining name-encoded ranked type (e.g. an opaque macro capture) to the structural form
ty.normalize_rank()
Self::ContextFeatures(_) => concrete!(ContextFeatures),
Self::EditorApi(_) => concrete!(&PlatformEditorApi),
Self::ResourceHash(_) => concrete!(ResourceHash),
}
}
/// Attempts to downcast the dynamic type to a tagged value
@@ -327,11 +273,10 @@ macro_rules! tagged_value {
// AUTO-GENERATED VARIANTS
// =======================
$( x if x == TypeId::of::<$ty>() => Ok(TaggedValue::$identifier(*downcast(input).unwrap())), )*
$( x if x == TypeId::of::<Item<$ty>>() => Ok(TaggedValue::$identifier(downcast::<Item<$ty>>(input).unwrap().into_element())), )*
// =======================
// NON-SERIALIZED VARIANTS
// =======================
x if x == TypeId::of::<Item<RenderOutput>>() => Ok(TaggedValue::RenderOutput(downcast::<Item<RenderOutput>>(input).unwrap().into_element())),
x if x == TypeId::of::<RenderOutput>() => Ok(TaggedValue::RenderOutput(*downcast(input).unwrap())),
_ => Err(format!("Cannot convert {:?} to TaggedValue", DynAny::type_name(input.as_ref()))),
}
@@ -350,18 +295,17 @@ macro_rules! tagged_value {
// AUTO-GENERATED VARIANTS
// =======================
$( x if x == TypeId::of::<$ty>() => Ok(TaggedValue::$identifier(<$ty as Clone>::clone(input.downcast_ref().unwrap()))), )*
$( x if x == TypeId::of::<Item<$ty>>() => Ok(TaggedValue::$identifier(Item::<$ty>::clone(input.downcast_ref().unwrap()).into_element())), )*
// =======================
// NON-SERIALIZED VARIANTS
// =======================
x if x == TypeId::of::<Item<RenderOutput>>() => Ok(TaggedValue::RenderOutput(Item::<RenderOutput>::clone(input.downcast_ref().unwrap()).into_element())),
x if x == TypeId::of::<RenderOutput>() => Ok(TaggedValue::RenderOutput(RenderOutput::clone(input.downcast_ref().unwrap()))),
_ => Err(format!("Cannot convert {:?} to TaggedValue", std::any::type_name_of_val(input))),
}
}
/// Returns a TaggedValue from the type, where that value is its type's `Default::default()`.
/// Dispatches by name for concrete types and structurally by element for ranked types, where the name
/// field is what round-trips through serde so it works even for types deserialized from disk.
/// Dispatches by the type's name (the field that round-trips through serde) so it works for both
/// freshly constructed types and types deserialized from disk where the runtime `TypeId` is unavailable.
pub fn from_type(input: &Type) -> Option<Self> {
match input {
Type::Generic(_) => None,
@@ -370,44 +314,23 @@ macro_rules! tagged_value {
// TODO: Add default implementations for types such as TaggedValue::Subpaths, and use the defaults here and in document_node_types
// Tries using the default for the tagged value type. If it not implemented, then uses the default used in document_node_types. If it is not used there, then TaggedValue::None is returned.
if name == std::any::type_name::<()>() { return Some(TaggedValue::None) }
if name == std::any::type_name::<Color>() { return Some(TaggedValue::Color(Color::default())) }
if name == std::any::type_name::<Gradient>() { return Some(TaggedValue::Gradient(Gradient::default())) }
// List-wrapped types need a single-item default with the element's default, not an empty list
if name == std::any::type_name::<List<Color>>() { return Some(TaggedValue::Color(Some(Color::default()))) }
if name == std::any::type_name::<List<GradientStops>>() { return Some(TaggedValue::Gradient(GradientStops::default())) }
$( if name == std::any::type_name::<$ty>() { return Some(TaggedValue::$identifier(Default::default())) } )*
if name == std::any::type_name::<BrushTrace>() { return Some(TaggedValue::BrushStrokes(Vec::new())) }
// Unranked types without a variant route through `TypeDefault`, with `to_dynany`/`to_any` constructing the actual default at execution time
macro_rules! check_bare {
if name == std::any::type_name::<List<f64>>() { return Some(TaggedValue::F64Array(Vec::new())) }
if name == std::any::type_name::<List<BrushStroke>>() { return Some(TaggedValue::BrushStrokes(Vec::new())) }
// Types whose `TaggedValue` variant has been removed. They route through `TypeDefault` instead, with `to_dynany`/`to_any` constructing the actual default at execution time.
macro_rules! check {
($type_default:ty) => {
if name == std::any::type_name::<$type_default>() { return Some(TaggedValue::TypeDefault(input.clone())); }
if name == std::any::type_name::<$type_default>() { return Some(TaggedValue::TypeDefault(concrete_type.clone())); }
};
}
for_each_bare_type_default!(check_bare);
for_each_type_default!(check);
None
}
Type::Fn(_, output) => TaggedValue::from_type(output),
Type::Future(output) => TaggedValue::from_type(output),
// Element types with a dedicated variant use it directly (the variant's value is a rank-0 cell); the rest store the structural type
Type::Item(element) => TaggedValue::from_type(element).or_else(|| {
macro_rules! check {
($type_default:ty) => {
if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); }
};
}
for_each_item_type_default!(check);
None
}),
// Structural lists match by element; `List<f64>` stays the dedicated `F64Array` variant
Type::List(element) => {
if **element == concrete!(f64) {
return Some(TaggedValue::F64Array(Vec::new()));
}
macro_rules! check {
($type_default:ty) => {
if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); }
};
}
for_each_list_type_default!(check);
None
}
}
}
@@ -421,7 +344,7 @@ macro_rules! tagged_value {
// MANUAL VARIANTS
// ===============
Self::None => "()".to_string(),
Self::TypeDefault(td) => format!("TypeDefault({td})"),
Self::TypeDefault(td) => format!("TypeDefault({})", td.name),
Self::F64Array(values) => format!("F64Array({values:?})"),
Self::Color(color) => format!("Color({color:?})"),
Self::Gradient(stops) => format!("Gradient({stops:?})"),
@@ -479,19 +402,19 @@ tagged_value! {
DVec2(DVec2),
#[serde(alias = "Affine2")]
DAffine2(DAffine2),
OptionalDAffine2(Option<DAffine2>),
#[serde(alias = "FillGradient")]
LegacyGradient(graphic_types::migrations::legacy::Gradient),
Font(Font),
Footprint(Footprint),
VectorModification(Box<VectorModification>),
ImageData(Image<Color>),
Resource(ResourceId),
// Legacy
#[serde(alias = "OptionalDAffine2")]
LegacyOptionalDAffine2(Option<DAffine2>),
#[serde(alias = "FillGradient")]
LegacyGradient(graphic_types::migrations::legacy::LegacyGradient),
Resource(graphene_application_io::resource::ResourceId),
// ==========
// ENUM TYPES
// ==========
#[serde(alias = "Fill")]
LegacyFill(graphic_types::migrations::legacy::Fill),
BlendMode(core_types::blending::BlendMode),
LuminanceCalculation(raster_nodes::adjustments::LuminanceCalculation),
QRCodeErrorCorrectionLevel(vector_nodes::generator_nodes::QRCodeErrorCorrectionLevel),
@@ -521,8 +444,6 @@ tagged_value! {
StrokeJoin(vector::style::StrokeJoin),
StrokeAlign(vector::style::StrokeAlign),
PaintOrder(vector::style::PaintOrder),
DashPattern(vector::style::DashPattern),
BoxCorners(vector::misc::BoxCorners),
GradientType(vector::style::GradientType),
GradientSpreadMethod(vector::style::GradientSpreadMethod),
ReferencePoint(vector::ReferencePoint),
@@ -530,9 +451,6 @@ tagged_value! {
BooleanOperation(vector::misc::BooleanOperation),
TextAlign(text_nodes::TextAlign),
ScaleType(core_types::transform::ScaleType),
// Legacy
#[serde(alias = "Fill")]
LegacyFill(graphic_types::migrations::legacy::LegacyFill),
}
impl TaggedValue {
@@ -594,11 +512,11 @@ impl TaggedValue {
None
}
fn to_gradient(input: &str) -> Option<Gradient> {
fn to_gradient(input: &str) -> Option<GradientStops> {
// String syntax: (e.g. "000000ff, ff0000ff")
let stops = input.split(',').filter_map(|s| to_color(s.trim())).collect::<Vec<_>>();
if stops.len() == 1 {
Some(Gradient::new(vec![
Some(GradientStops::new(vec![
GradientStop {
position: 0.,
midpoint: 0.5,
@@ -612,7 +530,7 @@ impl TaggedValue {
]))
} else if stops.len() >= 2 {
let step = 1. / (stops.len() - 1) as f64;
Some(Gradient::new(stops.into_iter().enumerate().map(|(i, color)| GradientStop {
Some(GradientStops::new(stops.into_iter().enumerate().map(|(i, color)| GradientStop {
position: i as f64 * step,
midpoint: 0.5,
color,
@@ -665,21 +583,19 @@ impl TaggedValue {
() if ty == TypeId::of::<u32>() => FromStr::from_str(string).map(TaggedValue::U32).ok()?,
() if ty == TypeId::of::<DVec2>() => to_dvec2(string).map(TaggedValue::DVec2)?,
() if ty == TypeId::of::<bool>() => FromStr::from_str(string).map(TaggedValue::Bool).ok()?,
() if ty == TypeId::of::<Color>() => to_color(string).map(TaggedValue::Color)?,
// The Fill/Stroke paint wires carry `Graphic` or `Gradient` elements, so a paint default parses through the element recursion as a color or gradient literal
() if ty == TypeId::of::<Graphic>() => to_color(string).map(TaggedValue::Color)?,
() if ty == TypeId::of::<Gradient>() => to_gradient(string).map(TaggedValue::Gradient)?,
// `Color` (not in a `List`) is still currently needed by `BlackAndWhiteNode` and `ColorOverlayNode` GPU `shader_node(PerPixelAdjust)` variants
() if ty == TypeId::of::<Color>() => to_color(string).map(|color| TaggedValue::Color(Some(color)))?,
() if ty == TypeId::of::<List<Color>>() => to_color(string).map(|color| TaggedValue::Color(Some(color)))?,
// The Fill and Stroke nodes' paint connectors default to `List<Graphic>`, their first registered implementation row
() if ty == TypeId::of::<List<Graphic>>() => to_color(string).map(|color| TaggedValue::Color(Some(color)))?,
() if ty == TypeId::of::<List<GradientStops>>() => to_gradient(string).map(TaggedValue::Gradient)?,
() if ty == TypeId::of::<ReferencePoint>() => to_reference_point(string).map(TaggedValue::ReferencePoint)?,
() if ty == TypeId::of::<DashPattern>() => TaggedValue::DashPattern(DashPattern::from(string)),
() if ty == TypeId::of::<BoxCorners>() => TaggedValue::BoxCorners(BoxCorners::from(string)),
_ => return None,
};
Some(ty)
}
Type::Fn(_, output) => TaggedValue::from_primitive_string(string, output),
Type::Future(fut) => TaggedValue::from_primitive_string(string, fut),
Type::Item(element) => TaggedValue::from_primitive_string(string, element),
Type::List(element) => TaggedValue::from_primitive_string(string, element),
}
}
@@ -689,16 +605,6 @@ impl TaggedValue {
_ => panic!("Passed value is not of type u32"),
}
}
/// The stored form of a paint input's red-slash "no paint" choice: the `List<Graphic>` type default, materializing as an empty paint list.
pub fn no_paint() -> Self {
TaggedValue::TypeDefault(list!(Graphic))
}
/// Whether this is the `List<Graphic>` type default created by [`Self::no_paint`] (and by disconnecting a paint wire).
pub fn is_no_paint(&self) -> bool {
matches!(self, TaggedValue::TypeDefault(td) if *td == list!(Graphic))
}
}
/// Custom deserializer hooked onto `NodeInput::Value::tagged_value` that intercepts removed-variant tags before delegating to `TaggedValue`'s standard derive.
@@ -706,16 +612,14 @@ impl TaggedValue {
/// Routes legacy variant names into modern variants, in typed Rust. Each legacy name is also matched against the historical `#[serde(alias = "...")]` spellings the deleted variant accepted, so old-shape inner payloads are caught:
///
/// - `BrushCache` → `TaggedValue::None` (purely runtime cache; no payload to preserve)
/// - `Graphic` (or alias `GraphicGroup`/`Group`) → `TaggedValue::TypeDefault(list!(Graphic))`
/// - `Artboard` (or alias `ArtboardGroup`) → `TaggedValue::TypeDefault(list!(Artboard))`
/// - `Graphic` (or alias `GraphicGroup`/`Group`) → `TaggedValue::TypeDefault(descriptor!(List<Graphic>))`
/// - `Artboard` (or alias `ArtboardGroup`) → `TaggedValue::TypeDefault(descriptor!(List<Artboard>))`
/// - `Raster` (or alias `ImageFrame`/`RasterData`/`Image`):
/// - non-empty (the legacy `image` proto's input 1, where the inner `Raster<CPU>` serializes as the embedded `Image<Color>`) → `TaggedValue::ImageData(<inner Image<Color>>)`
/// - empty → `TaggedValue::TypeDefault(list!(Raster<CPU>))`
/// - empty → `TaggedValue::TypeDefault(descriptor!(List<Raster<CPU>>))`
/// - `Vector` (or alias `VectorData`):
/// - non-empty → `TaggedValue::VectorModification(<built from first element>)` (the document_migration's Path pass disambiguates this between SVG-import legacy and a discardable modern baked value via the input's `exposed` flag)
/// - empty → `TaggedValue::TypeDefault(list!(Vector))`
/// - `FillChoice` → `TaggedValue::Color` (solid), `TaggedValue::Gradient` (gradient), or `TaggedValue::no_paint()` (none)
/// - `TypeDefault` with the old bare-`TypeDescriptor` payload → the same variant wrapping a `Type` (name-encoded `List` normalized to structural)
/// - empty → `TaggedValue::TypeDefault(descriptor!(List<Vector>))`
///
/// All other tags (including ones with the modern shape) fall through to the standard derived `Deserialize` for `TaggedValue`.
// TODO: Eventually remove this migration document upgrade code
@@ -730,8 +634,8 @@ pub fn deserialize_tagged_value_with_legacy_migration<'de, D: serde::Deserialize
{
match tag.as_str() {
"BrushCache" => return Ok(MemoHash::new(TaggedValue::None)),
"Graphic" | "GraphicGroup" | "Group" => return Ok(MemoHash::new(TaggedValue::TypeDefault(list!(Graphic)))),
"Artboard" | "ArtboardGroup" => return Ok(MemoHash::new(TaggedValue::TypeDefault(list!(Artboard)))),
"Graphic" | "GraphicGroup" | "Group" => return Ok(MemoHash::new(TaggedValue::TypeDefault(descriptor!(List<Graphic>)))),
"Artboard" | "ArtboardGroup" => return Ok(MemoHash::new(TaggedValue::TypeDefault(descriptor!(List<Artboard>)))),
"Raster" | "ImageFrame" | "RasterData" | "Image" => {
let first_element = content
.as_object()
@@ -742,7 +646,7 @@ pub fn deserialize_tagged_value_with_legacy_migration<'de, D: serde::Deserialize
let image: Image<Color> = serde_json::from_value(image_value.clone()).map_err(serde::de::Error::custom)?;
return Ok(MemoHash::new(TaggedValue::ImageData(image)));
}
return Ok(MemoHash::new(TaggedValue::TypeDefault(list!(Raster<CPU>))));
return Ok(MemoHash::new(TaggedValue::TypeDefault(descriptor!(List<Raster<CPU>>))));
}
"Vector" | "VectorData" => {
let vector = graphic_types::migrations::migrate_to_optional_vector(content.clone()).map_err(serde::de::Error::custom)?;
@@ -750,42 +654,12 @@ pub fn deserialize_tagged_value_with_legacy_migration<'de, D: serde::Deserialize
let modification = Box::new(VectorModification::create_from_vector(&vector));
return Ok(MemoHash::new(TaggedValue::VectorModification(modification)));
}
return Ok(MemoHash::new(TaggedValue::TypeDefault(list!(Vector))));
return Ok(MemoHash::new(TaggedValue::TypeDefault(descriptor!(List<Vector>))));
}
// The `TypeDefault` payload used to be a bare `TypeDescriptor`; it now carries a `Type`
"TypeDefault" if content.as_object().is_some_and(|c| c.contains_key("name")) => {
let descriptor: TypeDescriptor = serde_json::from_value(content.clone()).map_err(serde::de::Error::custom)?;
return Ok(MemoHash::new(TaggedValue::TypeDefault(Type::Concrete(descriptor).normalize_rank())));
}
// The `Color` tag used to carry `Option<Color>`, where a `null` payload (or an empty legacy color table) was the red-slash "no paint" choice
"Color" | "ColorTable" | "OptionalColor" | "ColorNotInTable"
if content.is_null()
|| content
.as_object()
.and_then(|c| c.get("element").or_else(|| c.get("instance")).or_else(|| c.get("instances")))
.and_then(|e| e.as_array())
.is_some_and(|colors| colors.is_empty()) =>
{
return Ok(MemoHash::new(TaggedValue::no_paint()));
}
// The removed `FillChoice` variant decomposes into the plain paint values
"FillChoice" => {
if let Some(payload) = content.as_object() {
if let Some(solid) = payload.get("Solid") {
let color: Color = serde_json::from_value(solid.clone()).map_err(serde::de::Error::custom)?;
return Ok(MemoHash::new(TaggedValue::Color(color)));
}
if let Some(gradient) = payload.get("Gradient") {
let gradient: Gradient = serde_json::from_value(gradient.clone()).map_err(serde::de::Error::custom)?;
return Ok(MemoHash::new(TaggedValue::Gradient(gradient)));
}
}
return Ok(MemoHash::new(TaggedValue::no_paint()));
}
// The `Gradient` tag was reused: it used to carry a full `Gradient` struct (now `LegacyGradient`), and now carries an `Option<Gradient>`.
// Disambiguate by payload shape: a Gradient struct has `start`/`end` keys; a `Gradient` has none of those (it has `position`/`midpoint`/`color`).
// The `Gradient` tag was reused: it used to carry a full `Gradient` struct (now `LegacyGradient`), and now carries an `Option<GradientStops>`.
// Disambiguate by payload shape: a Gradient struct has `start`/`end` keys; a `GradientStops` has none of those (it has `position`/`midpoint`/`color`).
"Gradient" if content.as_object().is_some_and(|c| c.contains_key("start") && c.contains_key("end")) => {
let gradient: graphic_types::migrations::legacy::LegacyGradient = serde_json::from_value(content.clone()).map_err(serde::de::Error::custom)?;
let gradient: graphic_types::migrations::legacy::Gradient = serde_json::from_value(content.clone()).map_err(serde::de::Error::custom)?;
return Ok(MemoHash::new(TaggedValue::LegacyGradient(gradient)));
}
_ => {}
@@ -833,7 +707,7 @@ impl<'i, T: 'i + AsRef<U> + Sync + Send, U: 'i + StaticType + Sync + Send> Node<
type Output = FutureAny<'i>;
#[inline(always)]
fn eval(&'i self, _: DAny<'i>) -> Self::Output {
Box::pin(async move { Box::new(Item::new_from_element(self.0.as_ref())) as DAny<'i> })
Box::pin(async move { Box::new(self.0.as_ref()) as DAny<'i> })
}
}
@@ -904,26 +778,26 @@ impl CacheHash for RenderOutput {
#[cfg(test)]
mod typedefault_dispatch {
use super::*;
use core_types::{concrete, item, list};
use core_types::descriptor;
/// Round-trips every type in the type-default lists through `TaggedValue::TypeDefault → to_dynany / to_any` and asserts the resulting concrete type matches the stored type.
/// Round-trips every type listed in [`for_each_type_default`] through `TaggedValue::TypeDefault → to_dynany / to_any` and asserts the resulting concrete type matches the descriptor.
///
/// This guards against the only way to break the recursion invariant in the unwrap functions: someone hand-rolling a `TypeDefault`-yielding case in `from_type` (or the macro's expansion in one of the unwrap sites silently failing to match a name). If it fails, the message points at the specific type and the structural reason.
#[test]
fn typedefault_dispatch_terminates() {
macro_rules! check {
($type_default:ty, $stored:expr) => {{
let ty: Type = $stored;
($type_default:ty) => {{
let descriptor = descriptor!($type_default);
let expected_type_id = std::any::TypeId::of::<$type_default>();
let dyn_value = TaggedValue::TypeDefault(ty.clone()).to_dynany();
let dyn_value = TaggedValue::TypeDefault(descriptor.clone()).to_dynany();
assert_eq!(
DynAny::type_id(&*dyn_value),
expected_type_id,
"`to_dynany(TypeDefault({0}))` did not produce a `{0}` — the type-default lists cover this type but the unwrap site doesn't handle it. Without a match, `to_dynany` falls back to `from_type_or_none`, which returns `TypeDefault({0})` again and recurses forever.",
"`to_dynany(TypeDefault({0}))` did not produce a `{0}` — `for_each_type_default!` lists this type but the unwrap site doesn't handle it. Without a match, `to_dynany` falls back to `from_type_or_none`, which returns `TypeDefault({0})` again and recurses forever.",
std::any::type_name::<$type_default>(),
);
let arc_value = TaggedValue::TypeDefault(ty).to_any();
let arc_value = TaggedValue::TypeDefault(descriptor).to_any();
assert_eq!(
(*arc_value).type_id(),
expected_type_id,
@@ -932,57 +806,6 @@ mod typedefault_dispatch {
);
}};
}
macro_rules! check_item {
($element:ty) => {
check!(Item<$element>, item!($element));
};
}
macro_rules! check_list {
($element:ty) => {
check!(List<$element>, list!($element));
};
}
macro_rules! check_bare {
($type_default:ty) => {
check!($type_default, concrete!($type_default));
};
}
for_each_item_type_default!(check_item);
for_each_list_type_default!(check_list);
for_each_bare_type_default!(check_bare);
}
}
#[cfg(test)]
mod paint_default_parsing {
use super::*;
use core_types::{item, list};
/// A Fill/Stroke paint wire carries `Graphic` elements, so its `Color::BLACK` default must parse through the
/// element recursion into a `Color` for a fresh Fill node's paint to resolve.
#[test]
fn paint_wire_parses_color_default_through_its_element() {
let black = Some(TaggedValue::Color(Color::BLACK));
assert_eq!(
TaggedValue::from_primitive_string("Color::BLACK", &list!(Graphic)),
black,
"a `List<Graphic>` paint wire should resolve its color default"
);
assert_eq!(
TaggedValue::from_primitive_string("Color::BLACK", &item!(Graphic)),
black,
"an `Item<Graphic>` paint wire should resolve its color default"
);
}
/// Table-era documents stored the red-slash "no paint" fill as an empty color table, which must keep
/// deserializing to [`TaggedValue::no_paint`] rather than collapsing to a transparent color.
#[test]
fn empty_legacy_color_table_deserializes_to_no_paint() {
for payload in [r#"{"ColorTable": {"instances": []}}"#, r#"{"ColorTable": {"element": []}}"#, r#"{"Color": null}"#] {
let mut deserializer = serde_json::Deserializer::from_str(payload);
let value = deserialize_tagged_value_with_legacy_migration(&mut deserializer).expect("The legacy payload should deserialize");
assert!(value.is_no_paint(), "The legacy payload `{payload}` should migrate to the no-paint choice");
}
for_each_type_default!(check);
}
}
+1 -1
View File
@@ -3,7 +3,7 @@ extern crate log;
#[macro_use]
extern crate core_types;
pub use core_types::{ProtoNodeIdentifier, Type, TypeDescriptor, concrete, descriptor, generic, item, list};
pub use core_types::{ProtoNodeIdentifier, Type, TypeDescriptor, concrete, descriptor, generic};
pub mod application_io;
pub mod document;
+1 -109
View File
@@ -397,7 +397,7 @@ impl ProtoNetwork {
let we_introduce_new_deps = !combined_deps.contains(new_deps);
// For diverging branches, we can add a cache node for all branches which don't reqire all dependencies
for (child_node, (deps, new_id)) in inputs.iter_mut().zip(branch_dependencies) {
for (child_node, (deps, new_id)) in inputs.iter_mut().zip(branch_dependencies.into_iter()) {
if let Some(new_id) = new_id {
*child_node = new_id;
} else if we_introduce_new_deps || deps != combined_deps {
@@ -634,31 +634,6 @@ pub struct TypingContext {
lookup: Cow<'static, HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>>>,
inferred: HashMap<NodeId, NodeIOTypes>,
constructor: HashMap<NodeId, NodeConstructor>,
promotions: HashMap<NodeId, Vec<(usize, Promotion)>>,
}
/// A rank adapter which type resolution marks for insertion between a wire and a connector whose ranks differ,
/// carrying the element type the adapter is registered under.
#[derive(Debug, Clone, PartialEq)]
pub enum Promotion {
/// Raises an `Item<X>` wire onto a `List<X>` connector as a one-element list.
ItemToList(Type),
/// Bundles a whole `List<X>` wire into one opaque `Item<Bundle<X>>` cell.
Bundle(Type),
/// Unbundles an `Item<Bundle<X>>` wire back into the whole `List<X>`.
Unbundle(Type),
}
impl Promotion {
/// The registry identifier of the adapter node monomorphized for this promotion's element type.
pub fn adapter_identifier(&self) -> ProtoNodeIdentifier {
let (adapter_name, element) = match self {
Self::ItemToList(element) => ("graphene_core::ops::ItemToListNode", element),
Self::Bundle(element) => ("graphene_core::ops::BundleNode", element),
Self::Unbundle(element) => ("graphene_core::ops::UnbundleNode", element),
};
ProtoNodeIdentifier::with_owned_string(format!("{adapter_name}<{}>", element.identifier_name()))
}
}
impl TypingContext {
@@ -683,20 +658,9 @@ impl TypingContext {
pub fn remove_inference(&mut self, node_id: NodeId) -> Option<NodeIOTypes> {
self.constructor.remove(&node_id);
self.promotions.remove(&node_id);
self.inferred.remove(&node_id)
}
/// Returns the input positions of a node which type resolution marked for rank promotion, with each position's adapter.
pub fn promotions(&self, node_id: NodeId) -> Option<&Vec<(usize, Promotion)>> {
self.promotions.get(&node_id)
}
/// Looks up the sole constructor registered under an adapter identifier, such as an Item -> List promotion adapter.
pub fn adapter_constructor(&self, identifier: &ProtoNodeIdentifier) -> Option<NodeConstructor> {
self.lookup.get(identifier).and_then(|implementations| implementations.values().next().copied())
}
/// Returns the node constructor for a given node id.
pub fn constructor(&self, node_id: NodeId) -> Option<NodeConstructor> {
self.constructor.get(&node_id).copied()
@@ -767,9 +731,6 @@ impl TypingContext {
// Graphite doesn't have subtyping currently, but it used to have it, and may do so again, so we make sure to compare types in this way to make things easier.
// More details explained here: <https://github.com/GraphiteEditor/Graphite/issues/1741>
(Type::Fn(in1, out1), Type::Fn(in2, out2)) => valid_type(out2, out1) && valid_type(in1, in2),
// Ranked wrappers of the same rank are compared element-wise
(Type::Item(element1), Type::Item(element2)) => valid_type(element1, element2),
(Type::List(element1), Type::List(element2)) => valid_type(element1, element2),
// If either the proposed input or the allowed input are generic, we allow the substitution (meaning this is a valid subtype).
// TODO: Add proper generic counting which is not based on the name
(Type::Generic(_), _) | (_, Type::Generic(_)) => true,
@@ -807,75 +768,6 @@ impl TypingContext {
match valid_impls.as_slice() {
[] => {
// Retry allowing a wire whose rank differs from its connector, satisfied at construction time by an inserted promotion adapter.
// Every rank relation is matched structurally; only the `Bundle` layer inside an `Item` cell remains name-encoded.
fn promotable_adapter(from: &Type, to: &Type) -> Option<Promotion> {
fn concrete_name(ty: &Type) -> Option<&str> {
match ty {
Type::Concrete(descriptor) => Some(&descriptor.name),
_ => None,
}
}
let (Type::Fn(from_input, from_output), Type::Fn(to_input, to_output)) = (from, to) else {
return None;
};
if !valid_type(from_input, to_input) {
return None;
}
let from_value = from_output.nested_type();
let to_value = to_output.nested_type();
match (from_value, to_value) {
// An `Item<X>` wire may feed a `List<X>` connector via a singleton raise
(Type::Item(from_element), Type::List(element)) if valid_type(from_element, element) => Some(Promotion::ItemToList((**element).clone())),
// A `List<X>` wire may feed an `Item<Bundle<X>>` connector by bundling the whole list into one opaque cell
(Type::List(element), Type::Item(_)) if to_value.bundle_element_name().is_some_and(|name| Some(name) == concrete_name(element)) => Some(Promotion::Bundle((**element).clone())),
// An `Item<Bundle<X>>` wire may feed a `List<X>` connector by unbundling it back into the whole list
(Type::Item(_), Type::List(element)) if from_value.bundle_element_name().is_some_and(|name| Some(name) == concrete_name(element)) => {
Some(Promotion::Unbundle((**element).clone()))
}
_ => None,
}
}
let mut promotable_matches = impls
.keys()
.filter(|node_io| collect_generics(node_io).is_empty() && valid_type(&node_io.call_argument, call_argument) && inputs.len() == node_io.inputs.len())
.filter_map(|node_io| {
let mut required_promotions = Vec::new();
for (index, (provided, expected)) in inputs.iter().zip(node_io.inputs.iter()).enumerate() {
if valid_type(provided, expected) {
continue;
}
required_promotions.push((index, promotable_adapter(provided, expected)?));
}
Some((node_io, required_promotions))
})
.collect::<Vec<_>>();
// Prefer the variant needing the fewest promotions, so an Item wire resolves the all-Item variant instead of raising every ranked connector to reach the mapped variant; a tie stays ambiguous.
promotable_matches.sort_by_key(|(_, required_promotions)| required_promotions.len());
let minimum_promotions = promotable_matches.first().map(|(_, required_promotions)| required_promotions.len());
let tied_at_minimum = promotable_matches
.iter()
.take_while(|(_, required_promotions)| Some(required_promotions.len()) == minimum_promotions)
.count();
if tied_at_minimum == 1 {
let (node_io, required_promotions) = promotable_matches.remove(0);
let node_io = node_io.clone();
self.inferred.insert(node_id, node_io.clone());
self.constructor.insert(node_id, impls[&node_io]);
self.promotions.insert(node_id, required_promotions);
return Ok(node_io);
}
let convert_node_index_offset = node.original_location.auto_convert_index.unwrap_or(0);
let mut best_errors = usize::MAX;
let mut error_inputs = Vec::new();
+2 -2
View File
@@ -57,7 +57,7 @@ pub async fn export_document(
}
// Execute the graph
let result = executor.execute(render_config.into_context()).await?;
let result = executor.execute(render_config).await?;
// Handle the result based on output type
match result {
@@ -195,7 +195,7 @@ pub async fn export_gif(
}
// Execute the graph for this frame
let result = executor.execute(render_config.into_context()).await?;
let result = executor.execute(render_config).await?;
// Extract RGBA data from result
let (data, img_width, img_height) = match result {
@@ -6,12 +6,11 @@ use graphene_std::application_io::RenderConfig;
fn subsequent_evaluations(c: &mut Criterion) {
let mut group = c.benchmark_group("Subsequent Evaluations");
let context = RenderConfig::default().into_context();
let context = RenderConfig::default();
bench_for_each_demo(&mut group, |name, g| {
let (executor, _) = setup_network(name);
let context = context.clone();
g.bench_function(name, |b| {
b.iter(|| futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(context.clone()))).unwrap())
b.iter(|| futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(context))).unwrap())
});
});
group.finish();
@@ -10,7 +10,7 @@ fn setup_run_cached(name: &str) -> DynamicExecutor {
let (executor, _) = setup_network(name);
// Warm up the cache by running once
let context = RenderConfig::default().into_context();
let context = RenderConfig::default();
let _ = futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), context));
executor
@@ -19,7 +19,7 @@ fn setup_run_cached(name: &str) -> DynamicExecutor {
#[library_benchmark]
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_cached)]
pub fn run_cached(executor: DynamicExecutor) -> DynamicExecutor {
let context = RenderConfig::default().into_context();
let context = RenderConfig::default();
black_box(futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), black_box(context))).unwrap());
// Return the executor so its teardown happens outside the measured section
@@ -6,13 +6,12 @@ use graphene_std::application_io::RenderConfig;
fn run_once(c: &mut Criterion) {
let mut group = c.benchmark_group("Run Once");
let context = RenderConfig::default().into_context();
let context = RenderConfig::default();
bench_for_each_demo(&mut group, |name, g| {
let context = context.clone();
g.bench_function(name, |b| {
b.iter_batched(
b.iter_batched_ref(
|| setup_network(name),
|(executor, _)| futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(context.clone()))).unwrap(),
|(executor, _)| futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(context))).unwrap(),
criterion::BatchSize::SmallInput,
)
});
@@ -14,7 +14,7 @@ fn setup_run_once(name: &str) -> DynamicExecutor {
#[library_benchmark]
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_once)]
pub fn run_once(executor: DynamicExecutor) -> DynamicExecutor {
let context = application_io::RenderConfig::default().into_context();
let context = application_io::RenderConfig::default();
black_box(futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), black_box(context))).unwrap());
// Return the executor so its teardown happens outside the measured section
@@ -9,14 +9,14 @@ fn update_executor(c: &mut Criterion) {
let mut group = c.benchmark_group("Update Executor");
bench_for_each_demo(&mut group, |name, g| {
g.bench_function(name, |b| {
b.iter_batched(
b.iter_batched_ref(
|| {
let (_, proto_network) = setup_network(name);
let empty = ProtoNetwork::default();
let executor = futures::executor::block_on(DynamicExecutor::new(empty)).unwrap();
(executor, proto_network)
},
|(mut executor, network)| futures::executor::block_on(executor.update(std::hint::black_box(network))),
|(executor, network)| futures::executor::block_on(executor.update(std::hint::black_box(std::mem::take(network)))),
criterion::BatchSize::SmallInput,
)
});
@@ -137,7 +137,7 @@ impl DynamicExecutor {
impl<I> Executor<I, TaggedValue> for &DynamicExecutor
where
I: StaticType + 'static + Send + Sync,
I: StaticType + 'static + Send + Sync + std::panic::UnwindSafe,
{
fn execute(&self, input: I) -> LocalFuture<'_, Result<TaggedValue, Box<dyn Error>>> {
Box::pin(async move {
@@ -262,7 +262,7 @@ impl BorrowTree {
/// This ensures that no borrowed data can escape the node graph.
pub async fn eval_tagged_value<I>(&self, id: NodeId, input: I) -> Result<TaggedValue, String>
where
I: StaticType + 'static + Send + Sync,
I: StaticType + 'static + Send + Sync + std::panic::UnwindSafe,
{
let (node, _path) = self.nodes.get(&id).cloned().ok_or("Output node not found in executor")?;
let output = node.eval(Box::new(input));
@@ -413,19 +413,7 @@ impl BorrowTree {
ConstructionArgs::Inline(_) => unimplemented!("Inline nodes are not supported yet"),
ConstructionArgs::Nodes(ids) => {
let ids = ids.to_vec();
let mut construction_nodes = self.node_deps(&ids);
// Wrap arguments the typing pass marked for rank promotion with their adapter node
if let Some(promotions) = typing_context.promotions(id) {
for (argument_index, promotion) in promotions {
let adapter_constructor = typing_context
.adapter_constructor(&promotion.adapter_identifier())
.ok_or_else(|| vec![GraphError::new(&proto_node, GraphErrorType::NoConstructor)])?;
let adapter = adapter_constructor(vec![construction_nodes[*argument_index].clone()]).await;
construction_nodes[*argument_index] = NodeContainer::new(adapter);
}
}
let construction_nodes = self.node_deps(&ids);
let constructor = typing_context.constructor(id).ok_or_else(|| vec![GraphError::new(&proto_node, GraphErrorType::NoConstructor)])?;
let node = constructor(construction_nodes).await;
let node = NodeContainer::new(node);
@@ -442,4 +430,19 @@ impl BorrowTree {
}
#[cfg(test)]
mod test;
mod test {
use super::*;
use graph_craft::document::value::TaggedValue;
#[test]
fn push_node_sync() {
let mut tree = BorrowTree::default();
let val_1_protonode = ProtoNode::value(ConstructionArgs::Value(TaggedValue::U32(2u32).into()), vec![]);
let context = TypingContext::default();
let future = tree.push_node(NodeId(0), val_1_protonode, &context);
futures::executor::block_on(future).unwrap();
let _node = tree.get(NodeId(0)).unwrap();
let result = futures::executor::block_on(tree.eval(NodeId(0), ()));
assert_eq!(result, Some(2u32));
}
}
@@ -1,668 +0,0 @@
use super::*;
use core_types::Context;
use core_types::list::{Item, List};
use core_types::{item, list};
use graph_craft::ProtoNodeIdentifier;
use graph_craft::document::value::TaggedValue;
use graphene_std::vector::Vector;
#[test]
fn push_node_sync() {
let mut tree = BorrowTree::default();
let val_1_protonode = ProtoNode::value(ConstructionArgs::Value(TaggedValue::U32(2u32).into()), vec![]);
let context = TypingContext::default();
let future = tree.push_node(NodeId(0), val_1_protonode, &context);
futures::executor::block_on(future).unwrap();
let _node = tree.get(NodeId(0)).unwrap();
let result: Option<Item<u32>> = futures::executor::block_on(tree.eval(NodeId(0), ()));
assert_eq!(result.map(|item| *item.element()), Some(2_u32));
}
/// Builds a two-node network feeding the given value into Bounding Box, whose primary input registers both `Item<Vector>` and `List<Vector>` wire variants.
fn bounding_box_network(content: TaggedValue) -> ProtoNetwork {
let value_node = ProtoNode::value(ConstructionArgs::Value(content.into()), vec![NodeId(0)]);
let mut bounding_box_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
bounding_box_node.identifier = ProtoNodeIdentifier::new("core_types::vector::BoundingBoxNode");
ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), value_node), (NodeId(1), bounding_box_node)],
}
}
fn compile_bounding_box_network(content: TaggedValue) -> BorrowTree {
let network = bounding_box_network(content);
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("The network should resolve against exactly one registered wire variant");
futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The resolved variant's constructor should instantiate")
}
#[test]
fn item_wire_variant_resolves_and_executes() {
let tree = compile_bounding_box_network(TaggedValue::TypeDefault(item!(Vector)));
let context: Context = None;
let result: Option<Item<Vector>> = futures::executor::block_on(tree.eval(NodeId(1), context.clone()));
assert!(result.is_some(), "The Item wire variant should downcast and execute end-to-end");
let wrong_type: Option<List<Vector>> = futures::executor::block_on(tree.eval(NodeId(1), context));
assert!(wrong_type.is_none(), "An Item wire should not downcast as a List");
}
#[test]
fn item_wire_promotes_to_list_connector() {
let value_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::TypeDefault(item!(f64)).into()), vec![NodeId(0)]);
// Box Corners takes a `List<f64>` primary, so feeding it an `Item<f64>` wire exercises the singleton raise
let mut box_corners_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
box_corners_node.identifier = graphene_std::vector::generator_nodes::box_corners::IDENTIFIER;
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), value_node), (NodeId(1), box_corners_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("An Item wire should resolve a List connector via promotion");
assert!(typing_context.promotions(NodeId(1)).is_some(), "The typing pass should record the promotion");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The promotion adapter should instantiate");
let context: Context = None;
let result: Option<Item<graphene_std::vector::misc::BoxCorners>> = futures::executor::block_on(tree.eval(NodeId(1), context));
assert!(result.is_some(), "The promoted wire should execute end-to-end");
}
// The layer content path: a rank-0 content wire enters Wrap Graphic's `List` connector by singleton raise, and the
// wrapped `Item<Graphic>` raises again at Extend's `List` connector, so layers accept rank-0 chains without new machinery
#[test]
fn rank_0_content_promotes_through_the_layer_coercion_path() {
let content_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::TypeDefault(item!(Vector)).into()), vec![NodeId(0)]);
let mut wrap_graphic_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
wrap_graphic_node.identifier = ProtoNodeIdentifier::new("graphic_nodes::graphic::WrapGraphicNode");
let base_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::TypeDefault(list!(graphene_std::Graphic)).into()), vec![NodeId(2)]);
let mut extend_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(2), NodeId(1)]), vec![NodeId(3)]);
extend_node.identifier = ProtoNodeIdentifier::new("graphic_nodes::graphic::ExtendNode");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(3),
nodes: vec![(NodeId(0), content_node), (NodeId(1), wrap_graphic_node), (NodeId(2), base_node), (NodeId(3), extend_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("A rank-0 content wire should resolve the layer coercion path via promotion");
assert!(typing_context.promotions(NodeId(1)).is_some(), "The rank-0 content should be raised at Wrap Graphic's List connector");
assert!(typing_context.promotions(NodeId(3)).is_some(), "The wrapped Item<Graphic> should be raised at Extend's List connector");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The promotion adapters should instantiate");
let context: Context = None;
let result: Option<List<graphene_std::Graphic>> = futures::executor::block_on(tree.eval(NodeId(3), context));
let stack = result.expect("The layer coercion path should execute end-to-end");
assert_eq!(stack.len(), 1, "The rank-0 content should contribute exactly one graphic to the stack");
}
/// Builds a network feeding the given content plus an f64 distance value into Offset Points, whose distance input is ranked `Item<f64>`.
fn offset_points_network(content: TaggedValue) -> ProtoNetwork {
let content_node = ProtoNode::value(ConstructionArgs::Value(content.into()), vec![NodeId(0)]);
let distance_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(10.).into()), vec![NodeId(1)]);
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(1)]), vec![NodeId(2)]);
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<f64>");
let mut offset_points_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0), NodeId(2)]), vec![NodeId(3)]);
offset_points_node.identifier = ProtoNodeIdentifier::new("core_types::vector::OffsetPointsNode");
ProtoNetwork {
inputs: vec![],
output: NodeId(3),
nodes: vec![(NodeId(0), content_node), (NodeId(1), distance_node), (NodeId(2), input_adapter_node), (NodeId(3), offset_points_node)],
}
}
#[test]
fn mixed_rank_connectors_resolve_via_promotion() {
let network = offset_points_network(TaggedValue::TypeDefault(list!(Vector)));
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context
.update(&network)
.expect("A List primary with an Item parameter should resolve the mapped variant via promotion");
assert!(typing_context.promotions(NodeId(3)).is_some(), "The Item distance should be marked for promotion");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("Construction should wrap the promoted argument");
let context: Context = None;
let result: Option<List<Vector>> = futures::executor::block_on(tree.eval(NodeId(3), context));
assert!(result.is_some(), "The zipped mapped variant should execute end-to-end");
}
#[test]
fn all_item_connectors_resolve_without_promotion() {
let network = offset_points_network(TaggedValue::TypeDefault(item!(Vector)));
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("All-Item connectors should resolve the rank-0 variant exactly");
assert!(typing_context.promotions(NodeId(3)).is_none(), "No promotion should be needed at rank 0");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The rank-0 variant should instantiate");
let context: Context = None;
let result: Option<Item<Vector>> = futures::executor::block_on(tree.eval(NodeId(3), context));
assert!(result.is_some(), "The rank-0 variant should execute and stay rank 0");
}
/// Builds a Transform network: content (node 0) plus four parameter values, each promoted onto Item wires as the preprocessor would.
fn transform_network(content: TaggedValue, rotation: TaggedValue) -> ProtoNetwork {
let mut nodes = vec![(NodeId(0), ProtoNode::value(ConstructionArgs::Value(content.into()), vec![NodeId(0)]))];
let parameters = [
(TaggedValue::DVec2(glam::DVec2::new(5., 0.)), "DVec2"),
(rotation, "f64"),
(TaggedValue::DVec2(glam::DVec2::ONE), "DVec2"),
(TaggedValue::DVec2(glam::DVec2::ZERO), "DVec2"),
];
let mut transform_inputs = vec![NodeId(0)];
let mut next_id = 1;
for (value, element) in parameters {
let value_id = NodeId(next_id);
let input_adapter_id = NodeId(next_id + 1);
next_id += 2;
nodes.push((value_id, ProtoNode::value(ConstructionArgs::Value(value.into()), vec![value_id])));
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![value_id]), vec![input_adapter_id]);
input_adapter_node.identifier = ProtoNodeIdentifier::with_owned_string(format!("input_adapter<{element}>"));
nodes.push((input_adapter_id, input_adapter_node));
transform_inputs.push(input_adapter_id);
}
let output = NodeId(next_id);
let mut transform_node = ProtoNode::value(ConstructionArgs::Nodes(transform_inputs), vec![output]);
transform_node.identifier = graphene_std::transform_nodes::transform::IDENTIFIER;
nodes.push((output, transform_node));
ProtoNetwork { inputs: vec![], output, nodes }
}
#[test]
fn transform_composes_onto_item_wire() {
use glam::{DAffine2, DVec2};
let network = transform_network(TaggedValue::TypeDefault(item!(Vector)), TaggedValue::F64(0.));
let output = network.output;
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("Transform should resolve its rank-0 variant");
assert!(typing_context.promotions(output).is_none(), "All-Item connectors should need no promotion");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("Transform's rank-0 variant should instantiate");
let context: Context = None;
let result: Option<Item<Vector>> = futures::executor::block_on(tree.eval(output, context));
let item = result.expect("A rank-0 chain through Transform should stay rank 0");
let transform = item.attribute_cloned_or_default::<DAffine2>(core_types::ATTR_TRANSFORM);
assert_eq!(transform.translation, DVec2::new(5., 0.), "The translation should compose onto the item's transform attribute");
}
#[test]
fn transform_broadcasts_item_content_across_a_framed_parameter() {
use glam::DAffine2;
let network = transform_network(TaggedValue::TypeDefault(item!(Vector)), TaggedValue::F64Array(vec![0., 90.]));
let output = network.output;
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context
.update(&network)
.expect("A framed rotation should resolve the mapped variant via promotion of the other connectors");
assert!(typing_context.promotions(output).is_some(), "The Item-typed connectors should be raised into the frame");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The mapped variant should instantiate");
let context: Context = None;
let result: Option<List<Vector>> = futures::executor::block_on(tree.eval(output, context));
let list = result.expect("The broadcast should produce a List");
assert_eq!(list.len(), 2, "One output item per frame slot");
let first: DAffine2 = list.attribute_cloned_or_default(core_types::ATTR_TRANSFORM, 0);
let second: DAffine2 = list.attribute_cloned_or_default(core_types::ATTR_TRANSFORM, 1);
assert!((first.matrix2.col(0).y - 0.).abs() < 1e-10, "Slot 0 should be unrotated");
assert!((second.matrix2.col(0).y - 1.).abs() < 1e-10, "Slot 1 should be rotated 90 degrees");
}
#[test]
fn generator_frames_over_a_list_parameter() {
// A `()` generator (Circle) fed a `List<f64>` radius should frame into one circle per slot
let primary = ProtoNode::value(ConstructionArgs::Value(TaggedValue::None.into()), vec![NodeId(0)]);
let radii = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![10., 20., 30.]).into()), vec![NodeId(1)]);
let mut radius_adapter = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(1)]), vec![NodeId(2)]);
radius_adapter.identifier = ProtoNodeIdentifier::new("input_adapter<f64>");
let mut circle_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0), NodeId(2)]), vec![NodeId(3)]);
circle_node.identifier = graphene_std::vector_nodes::circle::IDENTIFIER;
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(3),
nodes: vec![(NodeId(0), primary), (NodeId(1), radii), (NodeId(2), radius_adapter), (NodeId(3), circle_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("A List<f64> radius should resolve Circle's mapped generator variant");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The mapped generator variant should instantiate");
let context: Context = None;
let result: Option<List<Vector>> = futures::executor::block_on(tree.eval(NodeId(3), context));
let list = result.expect("The generator frame should produce a List<Vector>");
assert_eq!(list.len(), 3, "One circle per radius slot");
}
/// Builds the compiler's cache chain (child, then Memoize, then Context Modification) around a value, as `insert_context_nullification_node` does.
fn nullification_chain_network(value: TaggedValue) -> ProtoNetwork {
let value_node = ProtoNode::value(ConstructionArgs::Value(value.into()), vec![NodeId(0)]);
let mut memoize_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
memoize_node.identifier = graphene_core::memo::memoize::IDENTIFIER;
let features_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::ContextFeatures(Default::default()).into()), vec![NodeId(2)]);
let mut nullification_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(1), NodeId(2)]), vec![NodeId(3)]);
nullification_node.identifier = graphene_core::context_modification::context_modification::IDENTIFIER;
ProtoNetwork {
inputs: vec![],
output: NodeId(3),
nodes: vec![(NodeId(0), value_node), (NodeId(1), memoize_node), (NodeId(2), features_node), (NodeId(3), nullification_node)],
}
}
#[test]
fn the_nullification_chain_resolves_for_ranked_enum_wires() {
use graphene_std::vector::style::StrokeAlign;
// The Item form, as a wrapped input adapter's output presents to the chain
let network = nullification_chain_network(TaggedValue::TypeDefault(item!(StrokeAlign)));
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("An Item<StrokeAlign> wire should resolve through the compiler's cache chain");
// The List form, as a whole-list enum wire presents to the chain
let network = nullification_chain_network(TaggedValue::TypeDefault(list!(StrokeAlign)));
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("A List<StrokeAlign> wire should resolve through the compiler's cache chain");
}
#[test]
fn value_wires_materialize_as_items_at_resolution() {
use glam::{DAffine2, DVec2};
let values = [
TaggedValue::DAffine2(DAffine2::IDENTITY),
TaggedValue::DVec2(DVec2::new(7., 0.)),
TaggedValue::F64(0.),
TaggedValue::DVec2(DVec2::ONE),
TaggedValue::DVec2(DVec2::ZERO),
];
let mut nodes: Vec<_> = values
.into_iter()
.enumerate()
.map(|(index, value)| (NodeId(index as u64), ProtoNode::value(ConstructionArgs::Value(value.into()), vec![NodeId(index as u64)])))
.collect();
let mut transform_node = ProtoNode::value(ConstructionArgs::Nodes((0..5).map(NodeId).collect()), vec![NodeId(5)]);
transform_node.identifier = graphene_std::transform_nodes::transform::IDENTIFIER;
nodes.push((NodeId(5), transform_node));
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(5),
nodes,
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("Value wires should materialize as Items and resolve the all-Item variant");
assert!(typing_context.promotions(NodeId(5)).is_none(), "Already-Item value wires should need no promotion");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The all-Item variant should instantiate");
let context: Context = None;
let result: Option<Item<DAffine2>> = futures::executor::block_on(tree.eval(NodeId(5), context));
let item = result.expect("A value matrix should flow through Transform as an Item");
let transform = item.attribute_cloned_or_default::<DAffine2>(core_types::ATTR_TRANSFORM);
assert_eq!(transform.translation, DVec2::new(7., 0.), "The translation should compose onto the gained transform attribute");
}
// A position's Item wire converts through the vector input adapter into a single-anchor path, which the ItemToList promotion can then raise at a List connector
#[test]
fn position_value_converts_through_the_vector_input_adapter() {
let position_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::DVec2(glam::DVec2::new(3., 4.)).into()), vec![NodeId(0)]);
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<Vector>");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), position_node), (NodeId(1), input_adapter_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("An Item<DVec2> wire should resolve the adapter's element conversion row");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The conversion constructor should instantiate");
let context: Context = None;
let result: Option<Item<Vector>> = futures::executor::block_on(tree.eval(NodeId(1), context));
assert!(result.is_some(), "The position should arrive as an Item<Vector> single-anchor path");
}
// A scalar wire feeding a `DVec2` connector splats into both axes through the input adapter's `Convert` row
#[test]
fn number_value_splats_through_the_vec2_input_adapter() {
let number_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(-60.).into()), vec![NodeId(0)]);
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<DVec2>");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), number_node), (NodeId(1), input_adapter_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("An f64 wire should resolve the adapter's splat conversion row");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The splat constructor should instantiate");
let context: Context = None;
let result: Option<Item<glam::DVec2>> = futures::executor::block_on(tree.eval(NodeId(1), context));
assert_eq!(result.map(|item| *item.element()), Some(glam::DVec2::splat(-60.)), "The scalar should splat into both axes");
}
// A scalar wire feeding a `String` connector formats as text through the input adapter's `Convert` row
#[test]
fn number_value_formats_through_the_string_input_adapter() {
let number_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(42.).into()), vec![NodeId(0)]);
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<String>");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), number_node), (NodeId(1), input_adapter_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("An f64 wire should resolve the adapter's formatting conversion row");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The formatting constructor should instantiate");
let context: Context = None;
let result: Option<Item<String>> = futures::executor::block_on(tree.eval(NodeId(1), context));
assert_eq!(result.map(|item| item.element().clone()), Some("42".to_string()), "The number should format as its text representation");
}
// A `List` wire feeding a `ListDyn` connector erases its element type through the input adapter's `Into` row
#[test]
fn list_wire_erases_through_the_list_dyn_input_adapter() {
use core_types::list::ListDyn;
let list_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![1., 2., 3.]).into()), vec![NodeId(0)]);
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<ListDyn>");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), list_node), (NodeId(1), input_adapter_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("A List<f64> wire should resolve the ListDyn erasure row");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The erasure constructor should instantiate");
let context: Context = None;
let result: Option<ListDyn> = futures::executor::block_on(tree.eval(NodeId(1), context));
let erased = result.expect("The erased list should arrive as a ListDyn");
assert_eq!(erased.len(), 3, "The erased list should keep its row count");
}
#[test]
fn value_wire_passes_through_the_input_adapter_as_item() {
let value_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(3.).into()), vec![NodeId(0)]);
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<f64>");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), value_node), (NodeId(1), input_adapter_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("An f64 value's Item wire should resolve the adapter's passthrough row");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The passthrough constructor should instantiate");
let context: Context = None;
let result: Option<Item<f64>> = futures::executor::block_on(tree.eval(NodeId(1), context));
assert_eq!(result.map(|item| *item.element()), Some(3.), "The value should arrive as an Item");
}
// Path Modify's ranked modification parameter: a `Box<VectorModification>` value rides the `Item` wire through its input adapter,
// exercising the nested-generic identifier round-trip between the registered `stringify!` name and the preprocessor's simplified name
#[test]
fn modification_value_rides_the_item_wire_through_its_input_adapter() {
use graphene_std::vector::VectorModification;
let modification = TaggedValue::VectorModification(Default::default());
let value_node = ProtoNode::value(ConstructionArgs::Value(modification.into()), vec![NodeId(0)]);
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<Box<VectorModification>>");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), value_node), (NodeId(1), input_adapter_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("A modification value's Item wire should resolve the adapter's passthrough row");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The passthrough constructor should instantiate");
let context: Context = None;
let result: Option<Item<Box<VectorModification>>> = futures::executor::block_on(tree.eval(NodeId(1), context));
assert!(result.is_some(), "The modification should arrive as an Item");
}
// The Write Attribute value input: a value's Item wire boxes its element into a type-erased attribute value through the input adapter
#[test]
fn item_wire_boxes_into_the_attribute_value_connector() {
use graphene_std::list::AttributeValueDyn;
let value_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(3.).into()), vec![NodeId(0)]);
let mut attribute_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
attribute_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<AttributeValueDyn>");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), value_node), (NodeId(1), attribute_adapter_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("An Item<f64> wire should resolve the attribute value boxing row");
assert!(typing_context.promotions(NodeId(1)).is_none(), "The already-Item value wire should need no promotion");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The boxing constructor should instantiate");
let context: Context = None;
let result: Option<Item<AttributeValueDyn>> = futures::executor::block_on(tree.eval(NodeId(1), context));
let boxed = result.expect("The boxed attribute value should arrive as an Item");
assert_eq!(
boxed.element().0.as_any().downcast_ref::<f64>(),
Some(&3.),
"The stored value should be the bare element, not the whole Item"
);
}
#[test]
fn list_wire_variant_resolves_and_executes() {
let tree = compile_bounding_box_network(TaggedValue::TypeDefault(list!(Vector)));
let context: Context = None;
let result: Option<List<Vector>> = futures::executor::block_on(tree.eval(NodeId(1), context.clone()));
assert!(result.is_some(), "The mapped List wire variant should downcast and execute end-to-end");
let wrong_type: Option<Item<Vector>> = futures::executor::block_on(tree.eval(NodeId(1), context));
assert!(wrong_type.is_none(), "A List wire should not downcast as an Item");
}
#[test]
fn expander_flattens_under_the_frame() {
// A string value's Item wire feeds String Split's expander primary; its parameters ride Item wires through their input adapters
let string_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::String("a,b".into()).into()), vec![NodeId(0)]);
let delimiter_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::String(",".into()).into()), vec![NodeId(1)]);
let mut delimiter_input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(1)]), vec![NodeId(2)]);
delimiter_input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<String>");
let escaping_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Bool(false).into()), vec![NodeId(3)]);
let mut escaping_input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(3)]), vec![NodeId(4)]);
escaping_input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<bool>");
let output = NodeId(5);
let mut string_split_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0), NodeId(2), NodeId(4)]), vec![output]);
string_split_node.identifier = graphene_std::text_nodes::string_split::IDENTIFIER;
let network = ProtoNetwork {
inputs: vec![],
output,
nodes: vec![
(NodeId(0), string_node),
(NodeId(1), delimiter_node),
(NodeId(2), delimiter_input_adapter_node),
(NodeId(3), escaping_node),
(NodeId(4), escaping_input_adapter_node),
(output, string_split_node),
],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context
.update(&network)
.expect("All-Item connectors should resolve the expander's direct `Item -> List` variant");
assert!(typing_context.promotions(output).is_none(), "No promotion should be needed when every connector is already an Item");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The expander variant should instantiate");
let context: Context = None;
let result: Option<List<String>> = futures::executor::block_on(tree.eval(output, context));
let list = result.expect("An Item-wired expander should produce a List");
assert_eq!(list.len(), 2, "Splitting \"a,b\" on the comma should expand into two rows");
let substrings: Vec<_> = list.iter_element_values().map(|s| s.as_str()).collect();
assert_eq!(substrings, ["a", "b"], "The rows should hold the split substrings");
}
#[test]
fn whole_list_switches_as_one_bundle() {
// One bool selecting between two whole `List<f64>` stacks: each branch bundles into a rank-0 cell, and the result unbundles back to the flat stack
let condition_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Bool(true).into()), vec![NodeId(0)]);
let if_true_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![1., 2., 3.]).into()), vec![NodeId(1)]);
let if_false_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![4., 5.]).into()), vec![NodeId(2)]);
let mut switch_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0), NodeId(1), NodeId(2)]), vec![NodeId(3)]);
switch_node.identifier = ProtoNodeIdentifier::new("math_nodes::SwitchNode");
let mut unbundle_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(3)]), vec![NodeId(4)]);
unbundle_node.identifier = ProtoNodeIdentifier::new("graphene_core::ops::UnbundleNode<f64>");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(4),
nodes: vec![
(NodeId(0), condition_node),
(NodeId(1), if_true_node),
(NodeId(2), if_false_node),
(NodeId(3), switch_node),
(NodeId(4), unbundle_node),
],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context
.update(&network)
.expect("A List<f64> branch should resolve the Item<Bundle<f64>> row via the bundle wrap");
let promotions = typing_context.promotions(NodeId(3)).expect("The condition wrap and both branch bundles should be recorded");
let branch_bundles = promotions
.iter()
.filter(|(index, adapter)| *index != 0 && matches!(adapter, graph_craft::proto::Promotion::Bundle(_)))
.count();
assert_eq!(branch_bundles, 2, "Both branches should bundle their whole list into one opaque cell");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The bundle, wrap, and unbundle adapters should instantiate");
let context: Context = None;
let result: Option<List<f64>> = futures::executor::block_on(tree.eval(NodeId(4), context));
let list = result.expect("The whole stack should round-trip through the bundle switch back to a flat List<f64>");
let values: Vec<f64> = list.iter_element_values().copied().collect();
assert_eq!(values, [1., 2., 3.], "The taken branch's whole list should come through unchanged");
}
#[test]
fn a_bundle_unbundles_into_a_list_connector() {
// A bundled wire (sourced here from a BundleNode, as a Switch branch produces one) feeding Extend's whole-`List` base connector
let stack_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::TypeDefault(list!(graphene_std::Graphic)).into()), vec![NodeId(0)]);
let mut bundle_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
bundle_node.identifier = ProtoNodeIdentifier::new("graphene_core::ops::BundleNode<Graphic>");
let new_layers_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::TypeDefault(list!(graphene_std::Graphic)).into()), vec![NodeId(2)]);
let mut extend_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(1), NodeId(2)]), vec![NodeId(3)]);
extend_node.identifier = ProtoNodeIdentifier::new("graphic_nodes::graphic::ExtendNode");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(3),
nodes: vec![(NodeId(0), stack_node), (NodeId(1), bundle_node), (NodeId(2), new_layers_node), (NodeId(3), extend_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("A bundled wire should feed Extend's List<Graphic> connector via the unbundle");
let promotions = typing_context.promotions(NodeId(3)).expect("Extend's bundled base should be marked for unbundling");
assert!(
promotions.iter().any(|(index, adapter)| *index == 0 && matches!(adapter, graph_craft::proto::Promotion::Unbundle(_))),
"The base connector should unbundle the whole list"
);
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The unbundle adapter should instantiate");
let context: Context = None;
let result: Option<List<graphene_std::Graphic>> = futures::executor::block_on(tree.eval(NodeId(3), context));
assert!(result.is_some(), "The unbundled stack should flow into Extend as a List<Graphic>");
}
#[test]
fn a_whole_list_of_scalars_switches_as_one_bundle() {
// A single bool selecting between two whole `List<f64>` values, covering a primitive element type and confirming the selected list survives intact
let condition_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Bool(true).into()), vec![NodeId(0)]);
let if_true_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![1., 2.]).into()), vec![NodeId(1)]);
let if_false_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![3., 4., 5.]).into()), vec![NodeId(2)]);
let mut switch_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0), NodeId(1), NodeId(2)]), vec![NodeId(3)]);
switch_node.identifier = ProtoNodeIdentifier::new("math_nodes::SwitchNode");
let mut unbundle_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(3)]), vec![NodeId(4)]);
unbundle_node.identifier = ProtoNodeIdentifier::new("graphene_core::ops::UnbundleNode<f64>");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(4),
nodes: vec![
(NodeId(0), condition_node),
(NodeId(1), if_true_node),
(NodeId(2), if_false_node),
(NodeId(3), switch_node),
(NodeId(4), unbundle_node),
],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context
.update(&network)
.expect("A List<f64> branch should resolve the Item<Bundle<f64>> row via the bundle wrap");
let promotions = typing_context.promotions(NodeId(3)).expect("The condition wrap and both branch bundles should be recorded");
let branch_bundles = promotions
.iter()
.filter(|(index, adapter)| *index != 0 && matches!(adapter, graph_craft::proto::Promotion::Bundle(_)))
.count();
assert_eq!(branch_bundles, 2, "Both scalar-list branches should bundle into one opaque cell");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The bundle, wrap, and unbundle adapters should instantiate");
let context: Context = None;
let result: Option<List<f64>> = futures::executor::block_on(tree.eval(NodeId(4), context));
let list = result.expect("The whole scalar list should round-trip through the bundle switch");
assert_eq!(list.len(), 2, "The true branch's whole list should be selected and preserved intact");
}
@@ -1,15 +1,14 @@
use dyn_any::StaticType;
use glam::{DAffine2, DVec2};
use glam::{DAffine2, DVec2, IVec2};
use graph_craft::application_io::PlatformEditorApi;
use graph_craft::application_io::resource::Resource;
use graph_craft::document::DocumentNode;
use graph_craft::document::value::RenderOutput;
use graph_craft::proto::{NodeConstructor, TypeErasedBox};
use graphene_std::animation::RealTimeMode;
use graphene_std::any::DynAnyNode;
use graphene_std::brush::brush_stroke::BrushTrace;
use graphene_std::extract_xy::XY;
use graphene_std::gradient::Gradient;
use graphene_std::list::{AttributeValueDyn, Bundle, Item, List, ListDyn, NodeIdPath};
use graphene_std::application_io::Texture;
use graphene_std::brush::brush_stroke::BrushStroke;
use graphene_std::gradient::GradientStops;
use graphene_std::list::{AttributeDyn, AttributeValueDyn, List, ListDyn};
#[cfg(target_family = "wasm")]
use graphene_std::platform_application_io::canvas_utils::CanvasHandle;
#[cfg(feature = "gpu")]
@@ -18,24 +17,103 @@ use graphene_std::raster::color::Color;
use graphene_std::raster::*;
use graphene_std::raster::{CPU, Raster};
use graphene_std::render_node::RenderIntermediate;
use graphene_std::text::{Font, TextAlign};
use graphene_std::text_nodes::StringCapitalization;
use graphene_std::transform::{Footprint, ReferencePoint, ScaleType};
use graphene_std::vector::misc::{
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, SpiralType,
};
use graphene_std::vector::style::{DashPattern, GradientSpreadMethod, GradientType, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification};
use graphene_std::transform::Footprint;
use graphene_std::uuid::NodeId;
use graphene_std::vector::Vector;
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type_fut, future};
use node_registry_macros::async_node;
use node_registry_macros::{async_node, convert_node, into_node};
use std::collections::HashMap;
#[cfg(feature = "gpu")]
use wgpu_executor::WgpuExecutor;
// TODO: turn into hashmap
fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>> {
let mut node_types: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
// ==========
// INTO NODES
// ==========
into_node!(from: List<Graphic>, to: List<Graphic>),
into_node!(from: List<Raster<CPU>>, to: List<Raster<CPU>>),
#[cfg(feature = "gpu")]
into_node!(from: List<Raster<GPU>>, to: List<Raster<GPU>>),
convert_node!(from: List<Vector>, to: List<Graphic>),
convert_node!(from: List<Raster<CPU>>, to: List<Graphic>),
#[cfg(feature = "gpu")]
convert_node!(from: List<Raster<GPU>>, to: List<Graphic>),
// Type-erased attribute conversions for the `Attach Attribute` node, so it monomorphizes only over the destination `List` type.
convert_node!(from: List<Artboard>, to: AttributeDyn),
convert_node!(from: List<Graphic>, to: AttributeDyn),
convert_node!(from: List<Vector>, to: AttributeDyn),
convert_node!(from: List<Raster<CPU>>, to: AttributeDyn),
convert_node!(from: List<Color>, to: AttributeDyn),
convert_node!(from: List<GradientStops>, to: AttributeDyn),
convert_node!(from: List<f64>, to: AttributeDyn),
convert_node!(from: List<bool>, to: AttributeDyn),
convert_node!(from: List<String>, to: AttributeDyn),
convert_node!(from: List<DAffine2>, to: AttributeDyn),
convert_node!(from: List<BlendMode>, to: AttributeDyn),
convert_node!(from: List<graphene_std::vector::style::GradientType>, to: AttributeDyn),
convert_node!(from: List<graphene_std::vector::style::GradientSpreadMethod>, to: AttributeDyn),
convert_node!(from: List<Artboard>, to: ListDyn),
convert_node!(from: List<Graphic>, to: ListDyn),
convert_node!(from: List<Vector>, to: ListDyn),
convert_node!(from: List<Raster<CPU>>, to: ListDyn),
#[cfg(feature = "gpu")]
convert_node!(from: List<Raster<GPU>>, to: ListDyn),
convert_node!(from: List<Color>, to: ListDyn),
convert_node!(from: List<GradientStops>, to: ListDyn),
convert_node!(from: List<f64>, to: ListDyn),
convert_node!(from: List<bool>, to: ListDyn),
convert_node!(from: List<String>, to: ListDyn),
convert_node!(from: List<u8>, to: ListDyn),
convert_node!(from: List<NodeId>, to: ListDyn),
convert_node!(from: List<DAffine2>, to: ListDyn),
convert_node!(from: List<BlendMode>, to: ListDyn),
convert_node!(from: List<graphene_std::vector::style::GradientType>, to: ListDyn),
convert_node!(from: List<graphene_std::vector::style::GradientSpreadMethod>, to: ListDyn),
// Type-erased attribute value conversions for the `Write Attribute` node, so it monomorphizes only over the destination `List` type.
convert_node!(from: f64, to: AttributeValueDyn),
convert_node!(from: u32, to: AttributeValueDyn),
convert_node!(from: u64, to: AttributeValueDyn),
convert_node!(from: bool, to: AttributeValueDyn),
convert_node!(from: String, to: AttributeValueDyn),
convert_node!(from: DVec2, to: AttributeValueDyn),
convert_node!(from: DAffine2, to: AttributeValueDyn),
convert_node!(from: Color, to: AttributeValueDyn),
convert_node!(from: BlendMode, to: AttributeValueDyn),
convert_node!(from: graphene_std::vector::style::GradientType, to: AttributeValueDyn),
convert_node!(from: graphene_std::vector::style::GradientSpreadMethod, to: AttributeValueDyn),
convert_node!(from: List<String>, to: AttributeValueDyn),
convert_node!(from: List<NodeId>, to: AttributeValueDyn),
convert_node!(from: List<Color>, to: AttributeValueDyn),
convert_node!(from: List<GradientStops>, to: AttributeValueDyn),
convert_node!(from: List<Vector>, to: AttributeValueDyn),
convert_node!(from: List<Raster<CPU>>, to: AttributeValueDyn),
convert_node!(from: List<Raster<GPU>>, to: AttributeValueDyn),
convert_node!(from: List<Graphic>, to: AttributeValueDyn),
// into_node!(from: List<Raster<CPU>>, to: List<Raster<SRGBA8>>),
#[cfg(feature = "gpu")]
into_node!(from: &PlatformEditorApi, to: &WgpuExecutor),
convert_node!(from: DVec2, to: DVec2),
convert_node!(from: List<Vector>, to: List<Vector>),
convert_node!(from: DVec2, to: List<Vector>),
convert_node!(from: String, to: String),
convert_node!(from: bool, to: String),
convert_node!(from: DVec2, to: String),
convert_node!(from: IVec2, to: String),
convert_node!(from: DAffine2, to: String),
#[cfg(feature = "gpu")]
convert_node!(from: List<Raster<CPU>>, to: List<Raster<CPU>>, converter: &WgpuExecutor),
#[cfg(feature = "gpu")]
convert_node!(from: List<Raster<CPU>>, to: List<Raster<GPU>>, converter: &WgpuExecutor),
#[cfg(feature = "gpu")]
convert_node!(from: List<Raster<GPU>>, to: List<Raster<GPU>>, converter: &WgpuExecutor),
#[cfg(feature = "gpu")]
convert_node!(from: List<Raster<GPU>>, to: List<Raster<CPU>>, converter: &WgpuExecutor),
// =============
// MONITOR NODES
// =============
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => ()]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Artboard>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Graphic>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Vector>]),
@@ -43,540 +121,207 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
#[cfg(feature = "gpu")]
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Raster<GPU>>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Color>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Gradient>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Artboard>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Graphic>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Vector>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Raster<CPU>>]),
#[cfg(feature = "gpu")]
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Raster<GPU>>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Color>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Gradient>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<DashPattern>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<BoxCorners>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<String>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<f64>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<f32>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<DAffine2>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Footprint>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<DVec2>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<bool>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<u32>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<u64>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<BlendMode>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<GradientStops>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Image<Color>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => String]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => IVec2]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => DVec2]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => DAffine2]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Option<DAffine2>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => bool]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => f64]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => u32]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => u64]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => BlendMode]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Texture]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::application_io::resource::Resource]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::transform::ReferencePoint]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::BooleanOperation]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeCap]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeJoin]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::PaintOrder]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeAlign]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::Stroke]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Box<graphene_std::vector::VectorModification>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::CentroidType]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::PointSpacingType]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Option<f64>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<String>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<NodeIdPath>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<NodeId>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<f64>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<f32>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<u32>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<u64>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<DVec2>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<u8>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<bool>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<DAffine2>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<BlendMode>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<GradientType>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<GradientSpreadMethod>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<AttributeValueDyn>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<graphene_std::vector::style::GradientType>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<graphene_std::vector::style::GradientSpreadMethod>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => AttributeDyn]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => AttributeValueDyn]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => ListDyn]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<BrushTrace>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Graphic]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::text::Font]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<BrushStroke>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => DocumentNode]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::transform::Footprint]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::blending::BlendMode]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::LuminanceCalculation]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::extract_xy::XY]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::text_nodes::StringCapitalization]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::RedGreenBlue]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::RedGreenBlueAlpha]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::animation::RealTimeMode]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::NoiseType]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::FractalType]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::CellularDistanceFunction]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::CellularReturnType]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::DomainWarpType]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::RelativeAbsolute]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::SelectiveColorChoice]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::GridType]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::ArcType]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::RowsOrColumns]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::MergeByDistanceAlgorithm]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::ExtrudeJoiningAlgorithm]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::PointSpacingType]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::GradientType]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::GradientSpreadMethod]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::transform::ReferencePoint]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::CentroidType]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::text::TextAlign]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::transform::ScaleType]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::InterpolationDistribution]),
// Context nullification
#[cfg(feature = "gpu")]
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<&PlatformEditorApi>, Context => Item<graphene_std::ContextFeatures>]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<RenderIntermediate>, Context => Item<graphene_std::ContextFeatures>]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<RenderOutput>, Context => Item<graphene_std::ContextFeatures>]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<AttributeValueDyn>, Context => Item<graphene_std::ContextFeatures>]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => ListDyn, Context => Item<graphene_std::ContextFeatures>]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => &PlatformEditorApi, Context => graphene_std::ContextFeatures]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => RenderIntermediate, Context => graphene_std::ContextFeatures]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => RenderOutput, Context => graphene_std::ContextFeatures]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => AttributeDyn, Context => graphene_std::ContextFeatures]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => AttributeValueDyn, Context => graphene_std::ContextFeatures]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => ListDyn, Context => graphene_std::ContextFeatures]),
#[cfg(target_family = "wasm")]
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<CanvasHandle>, Context => Item<graphene_std::ContextFeatures>]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<&PlatformEditorApi>, Context => Item<graphene_std::ContextFeatures>]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<&wgpu_executor::WgpuExecutor>, Context => Item<graphene_std::ContextFeatures>]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<Option<&wgpu_executor::WgpuExecutor>>, Context => Item<graphene_std::ContextFeatures>]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<wgpu_executor::WgpuPipelineCache>, Context => Item<graphene_std::ContextFeatures>]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => CanvasHandle, Context => graphene_std::ContextFeatures]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => &PlatformEditorApi, Context => graphene_std::ContextFeatures]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => &wgpu_executor::WgpuExecutor, Context => graphene_std::ContextFeatures]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Option<&wgpu_executor::WgpuExecutor>, Context => graphene_std::ContextFeatures]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => wgpu_executor::WgpuPipelineCache, Context => graphene_std::ContextFeatures]),
// ==========
// MEMO NODES
// ==========
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => ()]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => bool]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Artboard>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Graphic>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Vector>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Raster<CPU>>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Color>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Gradient>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Image<Color>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientStops>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<String>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<NodeIdPath>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<NodeId>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<f64>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<DVec2>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<u8>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<bool>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<DAffine2>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<BlendMode>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientType>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientSpreadMethod>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Artboard>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Graphic>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Vector>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Raster<CPU>>]),
#[cfg(feature = "gpu")]
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Raster<GPU>>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Color>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Gradient>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<DashPattern>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<BoxCorners>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<String>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<f64>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<f32>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<DAffine2>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Footprint>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<DVec2>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<bool>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<u32>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<u64>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<BlendMode>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<AttributeValueDyn>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<graphene_std::vector::style::GradientType>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<graphene_std::vector::style::GradientSpreadMethod>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => AttributeDyn]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => AttributeValueDyn]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => ListDyn]),
#[cfg(target_family = "wasm")]
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<CanvasHandle>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<RenderOutput>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<&PlatformEditorApi>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => CanvasHandle]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => f64]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => f32]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => u32]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => u64]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => DVec2]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => String]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => DAffine2]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Footprint]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => RenderOutput]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => &PlatformEditorApi]),
#[cfg(feature = "gpu")]
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Raster<GPU>>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<BrushTrace>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<RenderIntermediate>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<&wgpu_executor::WgpuExecutor>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Option<&wgpu_executor::WgpuExecutor>>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<wgpu_executor::WgpuPipelineCache>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Option<f64>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Option<Color>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Graphic]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => glam::f32::Vec2]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => glam::f32::Affine2]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::Stroke]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::text::Font]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<BrushStroke>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => DocumentNode]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::ContextFeatures]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::transform::Footprint]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Box<graphene_std::vector::VectorModification>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::blending::BlendMode]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::LuminanceCalculation]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::QRCodeErrorCorrectionLevel]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::extract_xy::XY]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::text_nodes::StringCapitalization]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::RedGreenBlue]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::RedGreenBlueAlpha]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::animation::RealTimeMode]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::NoiseType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::FractalType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::CellularDistanceFunction]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::CellularReturnType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::DomainWarpType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::RelativeAbsolute]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::SelectiveColorChoice]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::GridType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::ArcType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::RowsOrColumns]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::MergeByDistanceAlgorithm]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::ExtrudeJoiningAlgorithm]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::PointSpacingType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeCap]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeJoin]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeAlign]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::PaintOrder]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::GradientType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::transform::ReferencePoint]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::CentroidType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::BooleanOperation]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::text::TextAlign]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::transform::ScaleType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::InterpolationDistribution]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => RenderIntermediate]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => &wgpu_executor::WgpuExecutor]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Option<&wgpu_executor::WgpuExecutor>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => wgpu_executor::WgpuPipelineCache]),
];
// The per-connector input adapter, registered per element type: an `Item` or `List` wire passes through unchanged.
// The `name` arm registers an `Into`-based whole-wire shift under the given identifier, serving the `ListDyn` erasure rows.
macro_rules! input_adapter_node {
(element: $element:ty) => {{
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
input_adapter_node!(passthrough: Item<$element>, element: $element),
input_adapter_node!(passthrough: List<$element>, element: $element),
];
entries
}};
(passthrough: $ty:ty, element: $element:ty) => {
(
ProtoNodeIdentifier::new(concat!["input_adapter<", stringify!($element), ">"]),
|mut args| {
Box::pin(async move {
let node = graphene_core::ops::PassthroughNode::new(graphene_std::any::downcast_node::<Context, $ty>(args.pop().unwrap()));
let any: DynAnyNode<Context, $ty, _> = graphene_std::any::DynAnyNode::new(node);
Box::new(any) as TypeErasedBox
})
},
{
let node = graphene_core::ops::PassthroughNode::new(graphene_std::any::PanicNode::<Context, core::pin::Pin<Box<dyn core::future::Future<Output = $ty> + Send>>>::new());
let params = vec![fn_type_fut!(Context, $ty)];
let node_io = NodeIO::<'_, Context>::to_async_node_io(&node, params);
node_io
},
)
};
(name: $name:literal, from: $from:ty, to: $to:ty, element: $element:ty) => {
(
ProtoNodeIdentifier::new(concat![$name, "<", stringify!($element), ">"]),
|mut args| {
Box::pin(async move {
let node = graphene_core::ops::IntoNode::new(
graphene_std::any::downcast_node::<Context, $from>(args.pop().unwrap()),
graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$to>)),
);
let any: DynAnyNode<Context, $to, _> = graphene_std::any::DynAnyNode::new(node);
Box::new(any) as TypeErasedBox
})
},
{
let node = graphene_core::ops::IntoNode::new(
graphene_std::any::PanicNode::<Context, core::pin::Pin<Box<dyn core::future::Future<Output = $from> + Send>>>::new(),
graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$to>)),
);
let params = vec![fn_type_fut!(Context, $from)];
let node_io = NodeIO::<'_, Context>::to_async_node_io(&node, params);
node_io
},
)
};
}
// A conversion row registered under the same `input_adapter<$element>` identifier so a convertible-but-not-identical
// ranked wire can feed an `Item<$element>` connector, converting each element via `Into`
macro_rules! input_adapter_row {
(from_element: $from:ty, element: $element:ty) => {{
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
input_adapter_row!(node: IntoItemNode, from: Item<$from>, to: Item<$element>, element: $element),
input_adapter_row!(node: IntoListNode, from: List<$from>, to: List<$element>, element: $element),
];
entries
}};
(node: $node:ident, from: $from:ty, to: $to:ty, element: $element:ty) => {
(
ProtoNodeIdentifier::new(concat!["input_adapter<", stringify!($element), ">"]),
|mut args| {
Box::pin(async move {
let node = graphene_core::ops::$node::new(
graphene_std::any::downcast_node::<Context, $from>(args.pop().unwrap()),
graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$element>)),
);
let any: DynAnyNode<Context, $to, _> = graphene_std::any::DynAnyNode::new(node);
Box::new(any) as TypeErasedBox
})
},
{
let node = graphene_core::ops::$node::new(
graphene_std::any::PanicNode::<Context, core::pin::Pin<Box<dyn core::future::Future<Output = $from> + Send>>>::new(),
graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$element>)),
);
let params = vec![fn_type_fut!(Context, $from)];
let node_io = NodeIO::<'_, Context>::to_async_node_io(&node, params);
node_io
},
)
};
}
// The promotion adapter inserted by type resolution when an Item wire feeds a List connector: the singleton raise
macro_rules! item_to_list_node {
(element: $element:ty) => {
(
ProtoNodeIdentifier::new(concat!["graphene_core::ops::ItemToListNode<", stringify!($element), ">"]),
|mut args| {
Box::pin(async move {
let node = graphene_core::ops::ItemToListNode::new(graphene_std::any::downcast_node::<Context, Item<$element>>(args.pop().unwrap()));
let any: DynAnyNode<Context, List<$element>, _> = graphene_std::any::DynAnyNode::new(node);
Box::new(any) as TypeErasedBox
})
},
{
let node = graphene_core::ops::ItemToListNode::new(graphene_std::any::PanicNode::<
Context,
core::pin::Pin<Box<dyn core::future::Future<Output = Item<$element>> + Send>>,
>::new());
let params = vec![fn_type_fut!(Context, Item<$element>)];
let node_io = NodeIO::<'_, Context>::to_async_node_io(&node, params);
node_io
},
)
};
}
// A whole-List bundle adapter inserted by type resolution when a List wire feeds an Item<Bundle<X>> connector
macro_rules! bundle_node {
(element: $element:ty) => {
(
ProtoNodeIdentifier::new(concat!["graphene_core::ops::BundleNode<", stringify!($element), ">"]),
|mut args| {
Box::pin(async move {
let node = graphene_core::ops::BundleNode::new(graphene_std::any::downcast_node::<Context, List<$element>>(args.pop().unwrap()));
let any: DynAnyNode<Context, Item<Bundle<$element>>, _> = graphene_std::any::DynAnyNode::new(node);
Box::new(any) as TypeErasedBox
})
},
{
let node = graphene_core::ops::BundleNode::new(graphene_std::any::PanicNode::<
Context,
core::pin::Pin<Box<dyn core::future::Future<Output = List<$element>> + Send>>,
>::new());
let params = vec![fn_type_fut!(Context, List<$element>)];
let node_io = NodeIO::<'_, Context>::to_async_node_io(&node, params);
node_io
},
)
};
}
// The reverse unbundle adapter inserted by type resolution when an Item<Bundle<X>> wire feeds a List connector
macro_rules! unbundle_node {
(element: $element:ty) => {
(
ProtoNodeIdentifier::new(concat!["graphene_core::ops::UnbundleNode<", stringify!($element), ">"]),
|mut args| {
Box::pin(async move {
let node = graphene_core::ops::UnbundleNode::new(graphene_std::any::downcast_node::<Context, Item<Bundle<$element>>>(args.pop().unwrap()));
let any: DynAnyNode<Context, List<$element>, _> = graphene_std::any::DynAnyNode::new(node);
Box::new(any) as TypeErasedBox
})
},
{
let node = graphene_core::ops::UnbundleNode::new(graphene_std::any::PanicNode::<
Context,
core::pin::Pin<Box<dyn core::future::Future<Output = Item<Bundle<$element>>> + Send>>,
>::new());
let params = vec![fn_type_fut!(Context, Item<Bundle<$element>>)];
let node_io = NodeIO::<'_, Context>::to_async_node_io(&node, params);
node_io
},
)
};
}
// ==================
// RANK ADAPTER NODES
// ==================
// Registers the rank adapters (input_adapter, ItemToListNode) for each element type
macro_rules! rank_adapter_nodes {
($($element:ty),* $(,)?) => {{
let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new();
$(
entries.extend(input_adapter_node!(element: $element));
entries.push(item_to_list_node!(element: $element));
)*
entries
}};
}
// The single list of value/enum element types that ride ranked wires as framable node parameters.
// Each needs both a rank promotion adapter and a cache chain (memoize/monitor/context),
// so both registrations below are driven from here by callback, which is what keeps a value type from ending up monitorable but not promotable, or vice versa.
macro_rules! ranked_value_types {
($register:ident) => {
$register!(
i32,
i64,
BlendMode,
StrokeJoin,
StrokeAlign,
StrokeCap,
PaintOrder,
GradientType,
GradientSpreadMethod,
DashPattern,
BoxCorners,
MergeByDistanceAlgorithm,
ExtrudeJoiningAlgorithm,
PointSpacingType,
StringCapitalization,
LuminanceCalculation,
RedGreenBlue,
RedGreenBlueAlpha,
RelativeAbsolute,
SelectiveColorChoice,
BrushTrace,
XY,
ScaleType,
ReferencePoint,
CentroidType,
BooleanOperation,
NoiseType,
FractalType,
CellularDistanceFunction,
CellularReturnType,
DomainWarpType,
RealTimeMode,
GridType,
ArcType,
SpiralType,
TextAlign,
QRCodeErrorCorrectionLevel,
Font,
InterpolationDistribution,
RowsOrColumns,
Resource,
)
};
}
// Primary element types (graphical data and scalars) get promotion adapters here; their monitor/memoize rows are the
// explicit ones near the top of the registry, so they are deliberately absent from the shared value-type list above
node_types.extend(rank_adapter_nodes!(
Vector,
Raster<CPU>,
Graphic,
Color,
Gradient,
String,
f64,
f32,
u64,
u32,
DVec2,
DAffine2,
bool,
NodeIdPath,
Footprint,
Artboard,
));
node_types.extend(ranked_value_types!(rank_adapter_nodes));
// The nested-generic `Box<VectorModification>` registers directly rather than through the shared callback, since the
// extra macro layer mangles the `stringify!` whitespace in its adapter identifier; its cache chain is likewise direct below
node_types.extend(rank_adapter_nodes!(Box<VectorModification>));
#[cfg(feature = "gpu")]
node_types.extend(rank_adapter_nodes!(Raster<GPU>));
// Type-erased rows for the `ListDyn` connectors (`Read Attribute`, `List Length`): any `List` wire erases its element type
macro_rules! list_dyn_rows {
($($element:ty),* $(,)?) => {{
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
$(input_adapter_node!(name: "input_adapter", from: List<$element>, to: ListDyn, element: ListDyn),)*
];
entries
}};
}
node_types.push(input_adapter_node!(passthrough: ListDyn, element: ListDyn));
node_types.extend(list_dyn_rows!(
Artboard,
Graphic,
Vector,
Raster<CPU>,
Color,
Gradient,
f32,
f64,
u32,
u64,
bool,
String,
DVec2,
DAffine2,
BlendMode,
GradientType,
GradientSpreadMethod
));
#[cfg(feature = "gpu")]
node_types.extend(list_dyn_rows!(Raster<GPU>));
// Registers the whole-List bundle adapters for each value type whose entire list may be selected or carried as one opaque cell
macro_rules! bundle_adapter_nodes {
($($element:ty),* $(,)?) => {{
let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new();
$(
entries.push(bundle_node!(element: $element));
entries.push(unbundle_node!(element: $element));
)*
entries
}};
}
node_types.extend(bundle_adapter_nodes!(
bool,
f32,
f64,
u32,
u64,
DVec2,
DAffine2,
Graphic,
Raster<CPU>,
Vector,
String,
Color,
Gradient,
Artboard,
));
#[cfg(feature = "gpu")]
node_types.extend(bundle_adapter_nodes!(Raster<GPU>));
// The memoize + monitor + context-nullification triple for each value type in the shared list above: the compiler wraps
// a ranked connector's broadcast sibling in a Memoize + context-nullification pair, and test instrumentation monitors any wire.
// Node identifiers are passed explicitly since `stringify!` would mangle the path's whitespace through this nested macro.
macro_rules! cache_chain_nodes {
(each: $value:ty) => {{
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
async_node!(identifier: graphene_core::memo::memoize::IDENTIFIER, graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => $value]),
async_node!(identifier: graphene_core::memo::monitor::IDENTIFIER, graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => $value]),
async_node!(identifier: graphene_core::context_modification::context_modification::IDENTIFIER, graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => $value, Context => Item<graphene_std::ContextFeatures>]),
];
entries
}};
($($element:ty),* $(,)?) => {{
let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new();
$(
entries.extend(cache_chain_nodes!(each: Item<$element>));
entries.extend(cache_chain_nodes!(each: List<$element>));
)*
entries
}};
}
node_types.extend(ranked_value_types!(cache_chain_nodes));
// The direct counterpart to `Box<VectorModification>`'s promotion adapter above (see that note)
node_types.extend(cache_chain_nodes!(Box<VectorModification>));
// A position wire may feed a ranked vector connector, each position becoming a single-anchor vector
node_types.extend(input_adapter_row!(from_element: DVec2, element: Vector));
// A string wire may feed the ranked `Item<DashPattern>` dash connector by parsing each element into a dash pattern
node_types.extend(input_adapter_row!(from_element: String, element: DashPattern));
// A number wire may feed the ranked `Item<DashPattern>` dash connector, each number broadcasting element-wise as a one-length pattern
node_types.extend(input_adapter_row!(from_element: f64, element: DashPattern));
// A string wire may feed the ranked `Item<BoxCorners>` connector by parsing each element into a set of corner values
node_types.extend(input_adapter_row!(from_element: String, element: BoxCorners));
// A number wire may feed the ranked `Item<BoxCorners>` connector, each number becoming a uniform radius for all four corners
node_types.extend(input_adapter_row!(from_element: f64, element: BoxCorners));
// The `Convert`-based counterpart of `input_adapter_row!`, for casts the std `Into` trait cannot express
macro_rules! convert_adapter_node {
(from_element: $from:ty, element: $element:ty) => {{
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
input_adapter_row!(node: ConvertItemNode, from: Item<$from>, to: Item<$element>, element: $element),
input_adapter_row!(node: ConvertListNode, from: List<$from>, to: List<$element>, element: $element),
];
entries
}};
}
macro_rules! convert_adapter_wildcard {
(from: $from:ty, to: [$($to:ty),*]) => {{
let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new();
$(entries.extend(convert_adapter_node!(from_element: $from, element: $to));)*
entries
}};
}
// Numeric wires cast between numeric element types, splat to fill both axes of a `DVec2` connector, and format into a `String` connector
node_types.extend(convert_adapter_wildcard!(from: f64, to: [f32, u32, u64, i32, i64, DVec2, String]));
node_types.extend(convert_adapter_wildcard!(from: f32, to: [f64, u32, u64, i32, i64, DVec2, String]));
node_types.extend(convert_adapter_wildcard!(from: u32, to: [f64, f32, u64, i32, i64, DVec2, String]));
node_types.extend(convert_adapter_wildcard!(from: u64, to: [f64, f32, u32, i32, i64, DVec2, String]));
node_types.extend(convert_adapter_wildcard!(from: i32, to: [f64, f32, u32, u64, i64, DVec2, String]));
node_types.extend(convert_adapter_wildcard!(from: i64, to: [f64, f32, u32, u64, i32, DVec2, String]));
// Bool, position, and transform wires may feed a ranked `String` connector by formatting each element as text
node_types.extend(convert_adapter_node!(from_element: bool, element: String));
node_types.extend(convert_adapter_node!(from_element: DVec2, element: String));
node_types.extend(convert_adapter_node!(from_element: DAffine2, element: String));
// The sanctioned attribute value conversions: an Item wire's elements box per cell, while a List wire boxes whole as one value
macro_rules! attribute_value_node {
(Item<$element:ty>) => {
input_adapter_row!(node: ItemToAttributeValueNode, from: Item<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
};
(List<$element:ty>) => {
input_adapter_row!(node: ListToAttributeValueNode, from: List<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
};
}
let attribute_value_rows: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
attribute_value_node!(Item<f64>),
attribute_value_node!(Item<u32>),
attribute_value_node!(Item<u64>),
attribute_value_node!(Item<bool>),
attribute_value_node!(Item<String>),
attribute_value_node!(Item<DVec2>),
attribute_value_node!(Item<DAffine2>),
attribute_value_node!(Item<Color>),
attribute_value_node!(Item<BlendMode>),
attribute_value_node!(Item<GradientType>),
attribute_value_node!(Item<GradientSpreadMethod>),
attribute_value_node!(Item<NodeIdPath>),
attribute_value_node!(List<String>),
attribute_value_node!(List<Color>),
attribute_value_node!(List<Gradient>),
attribute_value_node!(List<Vector>),
attribute_value_node!(List<Raster<CPU>>),
#[cfg(feature = "gpu")]
attribute_value_node!(List<Raster<GPU>>),
attribute_value_node!(List<Graphic>),
];
node_types.extend(attribute_value_rows);
// Whole-List Transform companion rows: a rank-1 content wire composes the matrix onto every item
macro_rules! transform_list_node {
(element: $element:ty) => {
async_node!(
identifier: ProtoNodeIdentifier::new("transform_nodes::transform_nodes::TransformNode"),
graphene_std::transform_nodes::TransformListNode<_, _, _, _, _>,
input: Context,
fn_params: [Context => List<$element>, Context => Item<DVec2>, Context => Item<f64>, Context => Item<DVec2>, Context => Item<DVec2>]
)
};
}
let transform_list_rows: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
transform_list_node!(element: Graphic),
transform_list_node!(element: String),
transform_list_node!(element: Vector),
transform_list_node!(element: Raster<CPU>),
#[cfg(feature = "gpu")]
transform_list_node!(element: Raster<GPU>),
transform_list_node!(element: Color),
transform_list_node!(element: Gradient),
];
node_types.extend(transform_list_rows);
// =============
// CONVERT NODES
// =============
node_types.extend(
[
convert_node!(from: f32, to: numbers),
convert_node!(from: f64, to: numbers),
convert_node!(from: i8, to: numbers),
convert_node!(from: u8, to: numbers),
convert_node!(from: u16, to: numbers),
convert_node!(from: i16, to: numbers),
convert_node!(from: i32, to: numbers),
convert_node!(from: u32, to: numbers),
convert_node!(from: i64, to: numbers),
convert_node!(from: u64, to: numbers),
convert_node!(from: i128, to: numbers),
convert_node!(from: u128, to: numbers),
convert_node!(from: isize, to: numbers),
convert_node!(from: usize, to: numbers),
convert_node!(from: numbers, to: DVec2),
convert_node!(from: numbers, to: String),
]
.into_iter()
.flatten(),
);
let mut map: HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>> = HashMap::new();
// Rank normalization at this merge is the single convergence point for structurally-built and name-encoded `List` types,
// covering the sources which cannot construct them structurally (reflected return values and opaque macro captures)
for (id, entry) in graphene_std::registry::NODE_REGISTRY.lock().unwrap().iter() {
for (constructor, types) in entry.iter() {
map.entry(id.clone()).or_default().insert(types.clone().normalize_rank(), *constructor);
map.entry(id.clone()).or_default().insert(types.clone(), *constructor);
}
}
@@ -586,18 +331,14 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
// This might be caused by the stringify! macro
let mut new_name = id.as_str().replace('\n', " ");
// Remove struct generics for all nodes except the adapter identifiers, whose element suffix distinguishes their rows
let element_suffixed_adapter = new_name.starts_with("input_adapter<")
|| new_name.starts_with("graphene_core::ops::ItemToListNode<")
|| new_name.starts_with("graphene_core::ops::BundleNode<")
|| new_name.starts_with("graphene_core::ops::UnbundleNode<");
if !element_suffixed_adapter && let Some((path, _generics)) = new_name.split_once("<") {
// Remove struct generics for all nodes except for the IntoNode and ConvertNode
if !(new_name.contains("IntoNode") || new_name.contains("ConvertNode"))
&& let Some((path, _generics)) = new_name.split_once("<")
{
new_name = path.to_string();
}
map.entry(ProtoNodeIdentifier::with_owned_string(new_name))
.or_default()
.insert(types.clone().normalize_rank(), node_constructor);
map.entry(ProtoNodeIdentifier::with_owned_string(new_name)).or_default().insert(types.clone(), node_constructor);
}
map
@@ -616,11 +357,8 @@ mod node_registry_macros {
async_node!($path, input: $input, fn_params: [ $(() => $type),*])
};
($path:ty, input: $input:ty, fn_params: [$($arg:ty => $type:ty),*]) => {
async_node!(identifier: ProtoNodeIdentifier::new(stringify!($path)), $path, input: $input, fn_params: [$($arg => $type),*])
};
(identifier: $identifier:expr, $path:ty, input: $input:ty, fn_params: [$($arg:ty => $type:ty),*]) => {
(
$identifier,
ProtoNodeIdentifier::new(stringify!($path)),
|mut args| {
Box::pin(async move {
args.reverse();
@@ -642,5 +380,105 @@ mod node_registry_macros {
};
}
macro_rules! into_node {
(from: $from:ty, to: $to:ty) => {
(
ProtoNodeIdentifier::new(concat!["graphene_core::ops::IntoNode<", stringify!($to), ">"]),
|mut args| {
Box::pin(async move {
let node = graphene_std::ops::IntoNode::new(
graphene_std::any::downcast_node::<Context, $from>(args.pop().unwrap()),
graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$to>)),
);
let any: DynAnyNode<Context, $to, _> = graphene_std::any::DynAnyNode::new(node);
Box::new(any) as TypeErasedBox
})
},
{
let node = graphene_std::ops::IntoNode::new(
graphene_std::any::PanicNode::<Context, core::pin::Pin<Box<dyn core::future::Future<Output = $from> + Send>>>::new(),
graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$to>)),
);
let params = vec![fn_type_fut!(Context, $from)];
let node_io = NodeIO::<'_, Context>::to_async_node_io(&node, params);
node_io
},
)
};
}
macro_rules! convert_node {
(from: $from:ty, to: numbers) => {{
let x: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
convert_node!(from: $from, to: f32),
convert_node!(from: $from, to: f64),
convert_node!(from: $from, to: i8),
convert_node!(from: $from, to: u8),
convert_node!(from: $from, to: u16),
convert_node!(from: $from, to: i16),
convert_node!(from: $from, to: i32),
convert_node!(from: $from, to: u32),
convert_node!(from: $from, to: i64),
convert_node!(from: $from, to: u64),
convert_node!(from: $from, to: i128),
convert_node!(from: $from, to: u128),
convert_node!(from: $from, to: isize),
convert_node!(from: $from, to: usize),
];
x
}};
(from: numbers, to: $to:ty) => {{
let x: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
convert_node!(from: f32, to: $to),
convert_node!(from: f64, to: $to),
convert_node!(from: i8, to: $to),
convert_node!(from: u8, to: $to),
convert_node!(from: u16, to: $to),
convert_node!(from: i16, to: $to),
convert_node!(from: i32, to: $to),
convert_node!(from: u32, to: $to),
convert_node!(from: i64, to: $to),
convert_node!(from: u64, to: $to),
convert_node!(from: i128, to: $to),
convert_node!(from: u128, to: $to),
convert_node!(from: isize, to: $to),
convert_node!(from: usize, to: $to),
];
x
}};
(from: $from:ty, to: $to:ty) => {
convert_node!(from: $from, to: $to, converter: ())
};
(from: $from:ty, to: $to:ty, converter: $convert:ty) => {
(
ProtoNodeIdentifier::new(concat!["graphene_core::ops::ConvertNode<", stringify!($to), ">"]),
|mut args| {
Box::pin(async move {
let mut args = args.drain(..);
let node = graphene_std::ops::ConvertNode::new(
graphene_std::any::downcast_node::<Context, $from>(args.next().expect("Convert node did not get first argument")),
graphene_std::any::downcast_node::<Context, $convert>(args.next().expect("Convert node did not get converter argument")),
graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$to>))
);
let any: DynAnyNode<Context, $to, _> = graphene_std::any::DynAnyNode::new(node);
Box::new(any) as TypeErasedBox
})
},
{
let node = graphene_std::ops::ConvertNode::new(
graphene_std::any::PanicNode::<Context, core::pin::Pin<Box<dyn core::future::Future<Output = $from> + Send>>>::new(),
graphene_std::any::PanicNode::<Context, core::pin::Pin<Box<dyn core::future::Future<Output = $convert> + Send>>>::new(),
graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$to>))
);
let params = vec![fn_type_fut!(Context, $from), fn_type_fut!(Context, $convert)];
let node_io = NodeIO::<'_, Context>::to_async_node_io(&node, params);
node_io
},
)
};
}
pub(crate) use async_node;
pub(crate) use convert_node;
pub(crate) use into_node;
}
+5 -5
View File
@@ -1,8 +1,8 @@
use graph_craft::application_io::PlatformEditorApi;
use graph_craft::concrete;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
use graph_craft::generic;
use graph_craft::{concrete, item};
use graphene_std::Context;
use graphene_std::ContextFeatures;
use graphene_std::uuid::NodeId;
@@ -84,12 +84,12 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
..Default::default()
},
DocumentNode {
call_argument: concrete!(Context),
call_argument: concrete!(graphene_std::application_io::RenderConfig),
inputs: vec![NodeInput::node(NodeId(4), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::create_context::IDENTIFIER),
context_features: graphene_std::ContextDependencies {
// INDEX is never read; it forces a nullification and cache pair onto the `data` parameter's wire so the render cache keys on a stable context
extract: ContextFeatures::VARARGS | ContextFeatures::INDEX,
// We add the extract index annotation here to force the compiler to add a context nullification node before this node so the render context is properly nullified so the render cache node can do its's work
extract: ContextFeatures::INDEX,
inject: ContextFeatures::REAL_TIME | ContextFeatures::ANIMATION_TIME | ContextFeatures::POINTER_POSITION | ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
},
..Default::default()
@@ -114,7 +114,7 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
..Default::default()
},
];
let scope_injections = vec![("editor-api".to_string(), (NodeId(2), item!(&PlatformEditorApi)))];
let scope_injections = vec![("editor-api".to_string(), (NodeId(2), concrete!(&PlatformEditorApi)))];
NodeNetwork {
exports: vec![NodeInput::node(NodeId(1), 0)],
@@ -16,7 +16,6 @@ wgpu = ["dep:raster-types", "raster-types/wgpu"]
# Local dependencies
dyn-any = { workspace = true }
core-types = { workspace = true }
graphene-hash = { workspace = true, features = ["derive"] }
vector-types = { workspace = true }
text-nodes = { workspace = true }
graphene-resource = { workspace = true }
+4 -17
View File
@@ -1,8 +1,6 @@
use core_types::transform::Footprint;
use core_types::{Context, OwnedContextImpl};
use dyn_any::{DynAny, StaticType, StaticTypeSized};
use glam::DVec2;
use graphene_hash::CacheHash;
use std::fmt::Debug;
use std::hash::{Hash, Hasher};
use std::ptr::addr_of;
@@ -56,7 +54,7 @@ pub trait GetEditorPreferences {
fn max_render_region_area(&self) -> u32;
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, CacheHash)]
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ExportFormat {
#[default]
@@ -64,14 +62,14 @@ pub enum ExportFormat {
Raster,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny, CacheHash)]
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TimingInformation {
pub time: f64,
pub animation_time: Duration,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny, CacheHash)]
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RenderConfig {
pub viewport: Footprint,
@@ -83,17 +81,6 @@ pub struct RenderConfig {
pub export_format: ExportFormat,
pub for_export: bool,
pub for_eyedropper: bool,
/// Skip rendering artboard background rectangles, used for pen plotter output.
pub hide_artboard_background: bool,
/// Cut dashed strokes into their visible dash segments so the path geometry itself carries the dash pattern, used for pen plotter output.
pub bake_stroke_dashes: bool,
}
impl RenderConfig {
/// Wraps this render configuration as the sole vararg of a fresh context, the call argument of a compiled network's boundary node.
pub fn into_context(self) -> Context<'static> {
OwnedContextImpl::default().with_vararg(Box::new(self)).into_context()
}
}
struct Logger;
@@ -140,7 +127,7 @@ impl<Io> Hash for EditorApi<Io> {
}
}
impl<Io> CacheHash for EditorApi<Io> {
impl<Io> core_types::graphene_hash::CacheHash for EditorApi<Io> {
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
core::hash::Hash::hash(self, state);
}
@@ -15,7 +15,7 @@ pub trait BoundingBox {
/// Returns the bounding box to use when sizing this value's thumbnail in the Layers panel.
///
/// Diverges from `bounding_box` for types where the rendering bounds wouldn't make a useful thumbnail frame.
/// For instance, `Gradient` is `Infinite` for rendering but returns the line's AABB here, so a `List<Graphic>`
/// For instance, `GradientStops` is `Infinite` for rendering but returns the line's AABB here, so a `List<Graphic>`
/// group of a gradient and a vector frames around the vector's geometry rather than infinity.
/// Types with no meaningful contribution (e.g., `Color`) return `Infinite` from both; the runtime substitutes a
/// small fallback rectangle at the end if no finite bounds remain after combining.
+86 -132
View File
@@ -1,8 +1,7 @@
use crate::bounds::{BoundingBox, RenderBoundingBox};
use crate::math::quad::Quad;
use crate::transform::ApplyTransform;
use crate::uuid::NodeId;
use dyn_any::{DynAny, StaticType, StaticTypeSized};
use dyn_any::{StaticType, StaticTypeSized};
use glam::DAffine2;
use graphene_hash::CacheHash;
use std::fmt::Debug;
@@ -23,7 +22,7 @@ pub const ATTR_OPACITY: &str = "opacity";
pub const ATTR_OPACITY_FILL: &str = "opacity_fill";
/// `bool` for whether an item inherits the alpha of the content beneath it (clipping mask).
pub const ATTR_CLIPPING_MASK: &str = "clipping_mask";
/// `NodeIdPath` path from the root network to the layer node owning this item.
/// `List<NodeId>` path from the root network to the layer node owning this item.
/// Used by editor tools to route clicks/selection back to the originating layer.
pub const ATTR_EDITOR_LAYER_PATH: &str = "editor:layer_path";
/// `List<Graphic>` snapshot of the upstream content that fed into a destructive merge
@@ -80,54 +79,6 @@ pub const ATTR_LETTER_TILT: &str = "letter_tilt";
/// Text item's `TextAlign` horizontal alignment of lines within the block.
pub const ATTR_TEXT_ALIGN: &str = "text_align";
// =====================
// TYPE: NodeIdPath
// =====================
/// A single path of `NodeId`s locating a node (or its owning layer) within the nested document graph.
/// Wraps a `List<NodeId>` so it flows as one rank-0 value (`Item<NodeIdPath>`) rather than a rank-1
/// `List<NodeId>` that the element-wise machinery would wrongly zip over per ID.
#[derive(Default, Debug, Clone, PartialEq, CacheHash, DynAny)]
pub struct NodeIdPath(pub List<NodeId>);
impl From<Vec<NodeId>> for NodeIdPath {
fn from(ids: Vec<NodeId>) -> Self {
Self(ids.into_iter().map(Item::new_from_element).collect())
}
}
// ================
// TYPE: Bundle
// ================
/// A whole `List<T>` treated as one rank-0 value (`Item<Bundle<T>>`) rather than a rank-1 `List<T>`.
/// Bundling a collection lets it pass through a connector that selects or carries the entire collection as one opaque
/// cell (such as a Switch branch), instead of the element-wise machinery zipping over it per element.
#[derive(Clone, Debug, PartialEq)]
pub struct Bundle<T>(pub List<T>);
impl<T> Default for Bundle<T> {
fn default() -> Self {
Self(List::default())
}
}
impl<T: CacheHash> CacheHash for Bundle<T> {
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.0.cache_hash(state);
}
}
impl<T> From<List<T>> for Bundle<T> {
fn from(list: List<T>) -> Self {
Self(list)
}
}
unsafe impl<T: StaticTypeSized> StaticType for Bundle<T> {
type Static = Bundle<T::Static>;
}
// ===========================
// Implicit attribute defaults
// ===========================
@@ -174,13 +125,6 @@ pub trait AnyAttributeValue: std::any::Any + Send + Sync {
/// Returns a debug-formatted string representation of this value.
fn display_string(&self) -> String;
/// Hashes this value into the given hasher (object-safe wrapper around `CacheHash`).
fn cache_hash_dyn(&self, state: &mut dyn core::hash::Hasher);
/// Compares this value to another for value-by-value equality (object-safe wrapper around `PartialEq`).
/// Returns `false` if the underlying types differ.
fn eq_dyn(&self, other: &dyn AnyAttributeValue) -> bool;
/// Wraps this scalar value into a new attribute, preceded by `preceding_defaults` implicit defaults for `key`.
fn into_attribute(self: Box<Self>, key: &str, preceding_defaults: usize) -> Box<dyn AnyAttribute>;
}
@@ -211,17 +155,6 @@ impl<T: Clone + Send + Sync + Default + Sized + Debug + PartialEq + CacheHash +
format!("{:?}", self)
}
/// Hashes this value into the given hasher (object-safe wrapper around `CacheHash`).
fn cache_hash_dyn(&self, state: &mut dyn core::hash::Hasher) {
self.cache_hash(&mut DynHasher(state));
}
/// Compares this value to another for value-by-value equality (object-safe wrapper around `PartialEq`).
/// Returns `false` if the underlying types differ.
fn eq_dyn(&self, other: &dyn AnyAttributeValue) -> bool {
other.as_any().downcast_ref::<Self>().is_some_and(|other| self == other)
}
/// Wraps this scalar value into a new attribute, preceded by `preceding_defaults` implicit defaults for `key`.
fn into_attribute(self: Box<Self>, key: &str, preceding_defaults: usize) -> Box<dyn AnyAttribute> {
let mut attribute: Box<dyn AnyAttribute> = Box::new(Attribute::<T>(Vec::with_capacity(preceding_defaults + 1)));
@@ -428,12 +361,83 @@ impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>
}
}
// ============
// AttributeDyn
// ============
/// Type-erased list of attribute values, used as a node graph parameter type.
/// Lets a node accept any `List<U>` source via the auto-inserted `Convert<AttributeDyn, ()>`
/// without monomorphizing over `U` (so the cartesian product of `(content T, source U)` collapses to just `T`).
pub struct AttributeDyn(pub Box<dyn AnyAttribute>);
impl AttributeDyn {
/// Number of values in this attribute.
pub fn len(&self) -> usize {
self.0.len()
}
/// Whether this attribute has zero values.
pub fn is_empty(&self) -> bool {
self.0.len() == 0
}
/// Builds a new attribute matching `target_len` items, taking values from this attribute (wrapping if shorter, truncating if longer).
pub fn cloned_to_length(&self, key: &str, target_len: usize) -> Box<dyn AnyAttribute> {
let mut result = self.0.new_with_defaults(0);
let source_len = self.0.len();
if source_len == 0 {
pad_with_implicit_default(key, &mut result, target_len);
return result;
}
for i in 0..target_len {
let value = self.0.clone_value(i % source_len).expect("source_len > 0");
result.push(value);
}
result
}
}
impl Clone for AttributeDyn {
fn clone(&self) -> Self {
Self(self.0.clone_box())
}
}
impl Default for AttributeDyn {
fn default() -> Self {
Self(Box::new(Attribute::<bool>(Vec::new())))
}
}
impl Debug for AttributeDyn {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "AttributeDyn(len: {})", self.0.len())
}
}
impl PartialEq for AttributeDyn {
fn eq(&self, other: &Self) -> bool {
self.0.eq_dyn(&*other.0)
}
}
impl CacheHash for AttributeDyn {
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.0.cache_hash_dyn(state);
}
}
unsafe impl StaticType for AttributeDyn {
type Static = Self;
}
// ==================
// AttributeValueDyn
// ==================
/// Type-erased single attribute value, used as a node graph parameter type.
/// Lets a node accept a value of any valid concrete type via the auto-inserted input adapter conversion without monomorphizing over the value type.
/// Lets a node accept a value of any concrete type via the auto-inserted `Convert<AttributeValueDyn, ()>`
/// without monomorphizing over the value type.
pub struct AttributeValueDyn(pub Box<dyn AnyAttributeValue>);
impl Clone for AttributeValueDyn {
@@ -572,17 +576,6 @@ impl Debug for ItemAttributeValues {
}
}
impl PartialEq for ItemAttributeValues {
fn eq(&self, other: &Self) -> bool {
self.0.len() == other.0.len()
&& self
.0
.iter()
.zip(&other.0)
.all(|((self_key, self_value), (other_key, other_value))| self_key == other_key && self_value.eq_dyn(other_value.as_ref()))
}
}
impl ItemAttributeValues {
/// Creates an empty set of attributes.
pub fn new() -> Self {
@@ -653,11 +646,6 @@ impl ItemAttributeValues {
self.0.iter().map(|(key, _)| key.as_str())
}
/// Returns a type-erased reference to the value of the attribute with the given key, if it exists.
pub fn get_any(&self, key: &str) -> Option<&dyn std::any::Any> {
self.0.iter().find_map(|(existing_key, value)| if existing_key == key { Some((**value).as_any()) } else { None })
}
/// Returns a debug-formatted string representation of the attribute value for the given key, if it exists.
/// The `overrides` function can provide custom formatting for specific type.
pub fn display_value(&self, key: &str, overrides: fn(&dyn std::any::Any) -> Option<String>) -> Option<String> {
@@ -1077,6 +1065,14 @@ impl<T> List<T> {
self.attributes.set_value(key, index, value);
}
/// Replaces (or adds) an attribute from a type-erased source. The source is wrapped or truncated to match this list's item count.
pub fn set_attribute_dyn(&mut self, key: impl Into<String>, source: AttributeDyn) {
let key = key.into();
self.attributes.attributes.retain(|(k, _)| k != &key);
let new_attribute = source.cloned_to_length(&key, self.element.len());
self.attributes.attributes.push((key, new_attribute));
}
/// Sets a single type-erased attribute value at the given index, creating the attribute from the value's underlying type if it doesn't exist (padded with defaults to match the list's length).
/// Falls back to default if the value's type doesn't match an existing attribute.
pub fn set_attribute_value_dyn(&mut self, key: impl Into<String>, index: usize, value: AttributeValueDyn) {
@@ -1284,7 +1280,7 @@ impl<T> FromIterator<Item<T>> for List<T> {
/// An owned item containing an element of type `T` and a set of type-erased scalar attributes.
///
/// Used to build individual items before pushing them into a [`List`], or when consuming items out of a list via [`IntoIterator`].
#[derive(Clone, Debug, PartialEq)]
#[derive(Clone, Debug)]
pub struct Item<T> {
element: T,
attributes: ItemAttributeValues,
@@ -1296,15 +1292,9 @@ impl<T: Default> Default for Item<T> {
}
}
impl<T: CacheHash> CacheHash for Item<T> {
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.element.cache_hash(state);
// Hash every attribute (key + value) so attribute changes invalidate downstream caches, mirroring `List`
for (key, attribute) in &self.attributes.0 {
std::hash::Hash::hash(key.as_str(), state);
attribute.cache_hash_dyn(state);
}
impl<T: PartialEq> PartialEq for Item<T> {
fn eq(&self, other: &Self) -> bool {
self.element == other.element
}
}
@@ -1396,42 +1386,6 @@ impl<T> Item<T> {
}
}
impl<T> From<T> for Item<T> {
fn from(element: T) -> Self {
Self::new_from_element(element)
}
}
impl<T> From<Item<T>> for List<T> {
fn from(item: Item<T>) -> Self {
Self::new_from_item(item)
}
}
impl<T> From<T> for List<T> {
fn from(element: T) -> Self {
Self::new_from_element(element)
}
}
impl<T> ApplyTransform for Item<T> {
/// Right-multiplies the modification into the item's transform attribute.
fn apply_transform(&mut self, modification: &DAffine2) {
let transform = self.attribute_mut_or_insert_default::<DAffine2>(ATTR_TRANSFORM);
*transform *= *modification;
}
/// Left-multiplies the modification into the item's transform attribute.
fn left_apply_transform(&mut self, modification: &DAffine2) {
let transform = self.attribute_mut_or_insert_default::<DAffine2>(ATTR_TRANSFORM);
*transform = *modification * *transform;
}
}
unsafe impl<T: StaticTypeSized> StaticType for Item<T> {
type Static = Item<T::Static>;
}
// ===========
// ItemIter<T>
// ===========
+3 -24
View File
@@ -61,27 +61,6 @@ impl Clampable for DVec2 {
}
}
// Implement for ranked wires (element-wise clamping across the frame)
use crate::list::{Item, List};
impl<T: Clampable> Clampable for Item<T> {
fn clamp_hard_min(self, min: f64) -> Self {
let (element, attributes) = self.into_parts();
Item::from_parts(element.clamp_hard_min(min), attributes)
}
fn clamp_hard_max(self, max: f64) -> Self {
let (element, attributes) = self.into_parts();
Item::from_parts(element.clamp_hard_max(max), attributes)
}
}
impl<T: Clampable> Clampable for List<T> {
fn clamp_hard_min(self, min: f64) -> Self {
self.into_iter().map(|item| item.clamp_hard_min(min)).collect()
}
fn clamp_hard_max(self, max: f64) -> Self {
self.into_iter().map(|item| item.clamp_hard_max(max)).collect()
}
}
#[cfg(feature = "serde")]
#[derive(serde::Deserialize)]
struct LegacyTable<T> {
@@ -90,7 +69,7 @@ struct LegacyTable<T> {
}
// TODO: Eventually remove this migration document upgrade code
pub fn migrate_to_color<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<no_std_types::color::Color, D::Error> {
pub fn migrate_to_optional_color<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Option<no_std_types::color::Color>, D::Error> {
use no_std_types::color::Color;
use serde::Deserialize;
@@ -102,8 +81,8 @@ pub fn migrate_to_color<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Re
}
Ok(match ColorFormat::deserialize(deserializer)? {
ColorFormat::OptionalColor(color) => color.unwrap_or(Color::TRANSPARENT),
ColorFormat::List(list) => list.element.into_iter().next().unwrap_or(Color::TRANSPARENT),
ColorFormat::OptionalColor(color) => color,
ColorFormat::List(list) => list.element.into_iter().next(),
})
}
+62 -1
View File
@@ -1,6 +1,8 @@
use crate::Node;
use crate::list::{Attribute, AttributeDyn, AttributeValueDyn, Item, List, ListDyn};
use crate::transform::Footprint;
use glam::DVec2;
use graphene_hash::CacheHash;
use std::future::Future;
use std::marker::PhantomData;
@@ -53,12 +55,71 @@ impl<T: ToString + Send> Convert<String, ()> for T {
}
}
pub trait ListConvert<U> {
fn convert_item(self) -> U;
}
impl<U, T: ListConvert<U> + Send> Convert<List<U>, ()> for List<T> {
async fn convert(self, _: Footprint, _: ()) -> List<U> {
let list: List<U> = self
.into_iter()
.map(|row| {
let (element, attributes) = row.into_parts();
Item::from_parts(element.convert_item(), attributes)
})
.collect();
list
}
}
/// Wraps each row's element into a type-erased attribute. Lets nodes that accept a source attribute
/// from any `List<U>` express their signature as `AttributeDyn` and avoid monomorphizing
/// over `U`; the compiler inserts this convert to bridge concrete-typed graph wires to the dyn input.
impl<T: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static> Convert<AttributeDyn, ()> for List<T> {
async fn convert(self, _: Footprint, _: ()) -> AttributeDyn {
let values: Vec<T> = self.into_iter().map(|row| row.into_element()).collect();
AttributeDyn(Box::new(Attribute(values)))
}
}
/// Wraps a value into a type-erased attribute value. Lets nodes that take a per-item value source
/// (such as `write_attribute`'s value-producing input) be generic over the destination list type
/// alone, with the compiler-inserted convert handling each concrete value type at the wire level.
impl<T: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static> Convert<AttributeValueDyn, ()> for T {
async fn convert(self, _: Footprint, _: ()) -> AttributeValueDyn {
AttributeValueDyn(Box::new(self))
}
}
/// Erases a `List<T>`'s element type, exposing only its attributes and row count. Lets nodes that
/// only need attribute access (such as the `read_attribute_*` family) take a single `ListDyn` input
/// instead of monomorphizing over every possible carrier list type.
impl<T: Send> Convert<ListDyn, ()> for List<T> {
async fn convert(self, _: Footprint, _: ()) -> ListDyn {
self.into()
}
}
impl Convert<DVec2, ()> for DVec2 {
async fn convert(self, _: Footprint, _: ()) -> DVec2 {
self
}
}
/// Constructs `Self` from a single anchor point at the given position. Implemented by the vector crate's
/// path type so a position wire can convert to a single-point path without core-types depending on that crate.
/// path type so the `Convert` impl below can build a single-point path without core-types depending on
/// that crate (mirroring how [`ListConvert`] bridges per-item list conversions).
pub trait FromAnchorPosition {
fn from_anchor_position(position: DVec2) -> Self;
}
// Converts a position into a vector path composed of a single anchor point
impl<T: FromAnchorPosition + Send> Convert<List<T>, ()> for DVec2 {
async fn convert(self, _: Footprint, _: ()) -> List<T> {
List::new_from_item(Item::new_from_element(T::from_anchor_position(self)))
}
}
/// Implements the [`Convert`] trait for conversion between the cartesian product of Rust's primitive numeric types.
macro_rules! impl_convert {
($from:ty, $to:ty) => {
@@ -217,23 +217,6 @@ impl From<()> for Footprint {
}
}
/// Consumes an item's `transform` attribute by baking it into the underlying value itself.
pub trait BakeTransform {
fn bake_transform(&mut self, transform: &DAffine2);
}
impl BakeTransform for DAffine2 {
fn bake_transform(&mut self, transform: &DAffine2) {
*self = *transform * *self;
}
}
impl BakeTransform for DVec2 {
fn bake_transform(&mut self, transform: &DAffine2) {
*self = transform.transform_point2(*self);
}
}
pub trait ApplyTransform {
fn apply_transform(&mut self, modification: &DAffine2);
fn left_apply_transform(&mut self, modification: &DAffine2);
+5 -180
View File
@@ -52,48 +52,8 @@ macro_rules! generic {
($type:ty) => {{ $crate::Type::Generic($crate::Cow::Borrowed(stringify!($type))) }};
}
/// Constructs the [`Type`] of an `Item` holding the given element type, e.g. `item!(f64)` is the type of an `Item<f64>`.
/// The two-argument form tags the element descriptor with an alias, preserving the source spelling for widget dispatch.
#[macro_export]
macro_rules! item {
(Item<$inner:ty>) => {
$crate::Type::Item(Box::new($crate::item!($inner)))
};
($element:ty) => {
$crate::Type::Item(Box::new($crate::concrete!($element)))
};
($element:ty, $alias:ty) => {
$crate::Type::Item(Box::new($crate::concrete!($element, $alias)))
};
}
/// Constructs the [`Type`] of a `List` holding the given element type, e.g. `list!(f64)` is the type of a `List<f64>`.
#[macro_export]
macro_rules! list {
(List<$inner:ty>) => {
$crate::Type::List(Box::new($crate::list!($inner)))
};
($element:ty) => {
$crate::Type::List(Box::new($crate::concrete!($element)))
};
}
// The `List<...>`/`Item<...>` rules must appear before the generic `$type:ty` rules, and in each macro that sees the literal tokens,
// because a type captured as `ty` becomes opaque to any inner macro's ranked pattern
#[macro_export]
macro_rules! future {
(List<$inner:ty>) => {
$crate::Type::Future(Box::new($crate::list!($inner)))
};
(List<$inner:ty>, $name:ty) => {
$crate::Type::Future(Box::new($crate::list!($inner)))
};
(Item<$inner:ty>) => {
$crate::Type::Future(Box::new($crate::item!($inner)))
};
(Item<$inner:ty>, $name:ty) => {
$crate::Type::Future(Box::new($crate::item!($inner, $name)))
};
($type:ty) => {{ $crate::Type::Future(Box::new(concrete!($type))) }};
($type:ty, $name:ty) => {
$crate::Type::Future(Box::new(concrete!($type, $name)))
@@ -102,27 +62,9 @@ macro_rules! future {
#[macro_export]
macro_rules! fn_type {
(List<$inner:ty>) => {
$crate::Type::Fn(Box::new(concrete!(())), Box::new($crate::list!($inner)))
};
(Item<$inner:ty>) => {
$crate::Type::Fn(Box::new(concrete!(())), Box::new($crate::item!($inner)))
};
($type:ty) => {
$crate::Type::Fn(Box::new(concrete!(())), Box::new(concrete!($type)))
};
($in_type:ty, List<$inner:ty>, alias: $outname:ty) => {
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::list!($inner)))
};
($in_type:ty, List<$inner:ty>) => {
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::list!($inner)))
};
($in_type:ty, Item<$inner:ty>, alias: $outname:ty) => {
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::item!($inner, $inner)))
};
($in_type:ty, Item<$inner:ty>) => {
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::item!($inner)))
};
($in_type:ty, $type:ty, alias: $outname:ty) => {
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new(concrete!($type, $outname)))
};
@@ -132,27 +74,9 @@ macro_rules! fn_type {
}
#[macro_export]
macro_rules! fn_type_fut {
(List<$inner:ty>) => {
$crate::Type::Fn(Box::new(concrete!(())), Box::new($crate::Type::Future(Box::new($crate::list!($inner)))))
};
(Item<$inner:ty>) => {
$crate::Type::Fn(Box::new(concrete!(())), Box::new($crate::Type::Future(Box::new($crate::item!($inner)))))
};
($type:ty) => {
$crate::Type::Fn(Box::new(concrete!(())), Box::new(future!($type)))
};
($in_type:ty, List<$inner:ty>, alias: $outname:ty) => {
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::Type::Future(Box::new($crate::list!($inner)))))
};
($in_type:ty, List<$inner:ty>) => {
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::Type::Future(Box::new($crate::list!($inner)))))
};
($in_type:ty, Item<$inner:ty>, alias: $outname:ty) => {
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::Type::Future(Box::new($crate::item!($inner, $inner)))))
};
($in_type:ty, Item<$inner:ty>) => {
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::Type::Future(Box::new($crate::item!($inner)))))
};
($in_type:ty, $type:ty, alias: $outname:ty) => {
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new(future!($type, $outname)))
};
@@ -175,15 +99,6 @@ impl NodeIOTypes {
Self { call_argument, return_value, inputs }
}
/// Applies [`Type::normalize_rank`] to every type in the signature.
pub fn normalize_rank(self) -> Self {
Self {
call_argument: self.call_argument.normalize_rank(),
return_value: self.return_value.normalize_rank(),
inputs: self.inputs.into_iter().map(Type::normalize_rank).collect(),
}
}
pub const fn empty() -> Self {
let tds1 = TypeDescriptor {
id: None,
@@ -320,10 +235,6 @@ pub enum Type {
Fn(Box<Type>, Box<Type>),
/// Represents a future which promises to return the inner type.
Future(Box<Type>),
/// Represents a recursive [Type] allowing nested levels of types to represent the type of an Item<T>.
Item(Box<Type>),
/// Represents a list of this recursive [Type] allowing nested levels of types to represent the type of a List<T>.
List(Box<Type>),
}
impl Default for Type {
@@ -397,8 +308,6 @@ impl Type {
Self::Concrete(ty) => Some(ty.size),
Self::Fn(_, _) => None,
Self::Future(_) => None,
Self::Item(_) => None,
Self::List(_) => None,
}
}
@@ -408,8 +317,6 @@ impl Type {
Self::Concrete(ty) => Some(ty.align),
Self::Fn(_, _) => None,
Self::Future(_) => None,
Self::Item(_) => None,
Self::List(_) => None,
}
}
@@ -419,8 +326,6 @@ impl Type {
Self::Concrete(_) => self,
Self::Fn(_, output) => output.nested_type(),
Self::Future(output) => output.nested_type(),
Self::Item(_) => self,
Self::List(_) => self,
}
}
@@ -433,8 +338,6 @@ impl Type {
Self::Concrete(_) => None,
Self::Fn(_, output) => output.replace_nested(f),
Self::Future(output) => output.replace_nested(f),
Self::Item(_) => None,
Self::List(_) => None,
}
}
@@ -444,62 +347,6 @@ impl Type {
Type::Concrete(ty) => simplify_identifier_name(&ty.name),
Type::Fn(call_arg, return_value) => format!("{} called with {}", return_value.identifier_name(), call_arg.identifier_name()),
Type::Future(ty) => ty.identifier_name(),
Type::Item(element) => element.identifier_name(),
Type::List(element) => format!("{}[]", element.identifier_name()),
}
}
/// Constructs the [`Type`] of a `List` holding elements of the given type, the expression-position counterpart of [`list!`].
pub fn list_of(element: Type) -> Type {
Type::List(Box::new(element))
}
/// The element type if this is a rank-1 `List` wire type.
pub fn list_element(&self) -> Option<&Type> {
match self {
Type::List(element) => Some(element),
_ => None,
}
}
/// The element name if this is the type of an `Item<Bundle<X>>` cell carrying a whole list, e.g. `f64` from `Item<Bundle<f64>>`.
/// The `Bundle` layer stays name-encoded inside the structural `Item` since it has no structural variant.
pub fn bundle_element_name(&self) -> Option<&str> {
let Type::Item(element) = self else { return None };
let Type::Concrete(descriptor) = element.as_ref() else { return None };
descriptor.name.strip_prefix("core_types::list::Bundle<")?.strip_suffix('>')
}
/// Converts a name-encoded `List` or `Item` concrete type into its structural form, recursively.
/// Structurally-built types pass through unchanged, so sources which cannot construct ranked types
/// (reflection and opaque macro captures) converge with macro-built ones at this single point.
pub fn normalize_rank(self) -> Type {
fn parse_element(element_name: &str) -> Type {
let element = Type::Concrete(TypeDescriptor {
id: None,
name: Cow::Owned(element_name.to_string()),
alias: None,
size: 0,
align: 0,
});
element.normalize_rank()
}
match self {
Type::Concrete(descriptor) => {
if let Some(element_name) = descriptor.name.strip_prefix("core_types::list::List<").and_then(|rest| rest.strip_suffix('>')) {
return Type::List(Box::new(parse_element(element_name)));
}
if let Some(element_name) = descriptor.name.strip_prefix("core_types::list::Item<").and_then(|rest| rest.strip_suffix('>')) {
return Type::Item(Box::new(parse_element(element_name)));
}
Type::Concrete(descriptor)
}
Type::Fn(input, output) => Type::Fn(Box::new(input.normalize_rank()), Box::new(output.normalize_rank())),
Type::Future(inner) => Type::Future(Box::new(inner.normalize_rank())),
Type::Item(element) => Type::Item(Box::new(element.normalize_rank())),
Type::List(element) => Type::List(Box::new(element.normalize_rank())),
Type::Generic(_) => self,
}
}
}
@@ -524,13 +371,12 @@ pub fn make_type_user_readable(ty: &str) -> String {
.replace("UVec2", "Vec2")
.replace("&str", "String");
rewrite_ranked_type_wrappers(&ty)
rewrite_list_as_array_brackets(&ty)
}
/// Rewrites `List<T>` and the whole-collection `Bundle<T>` as `T[]`, and unwraps `Item<T>` to `T`, so ranked wires read as their element type.
/// Handles nesting (e.g. `List<List<Vector>>` becomes `Vector[][]`).
/// Respects word boundaries so unrelated identifiers that happen to end in `List` or `Item` are not affected.
fn rewrite_ranked_type_wrappers(input: &str) -> String {
/// Rewrites `List<T>` as `T[]`. Handles nesting (e.g. `List<List<Vector>>` becomes `Vector[][]`).
/// Respects word boundaries so unrelated identifiers that happen to end in `List` are not affected.
fn rewrite_list_as_array_brackets(input: &str) -> String {
let bytes = input.as_bytes();
let mut result = String::with_capacity(input.len());
let mut i = 0;
@@ -541,31 +387,12 @@ fn rewrite_ranked_type_wrappers(input: &str) -> String {
let inner_start = i + b"List<".len();
if let Some(close) = find_matching_angle_bracket(bytes, inner_start) {
let inner = &input[inner_start..close];
result.push_str(&rewrite_ranked_type_wrappers(inner));
result.push_str(&rewrite_list_as_array_brackets(inner));
result.push_str("[]");
i = close + 1;
continue;
}
}
if at_word_boundary && bytes[i..].starts_with(b"Bundle<") {
let inner_start = i + b"Bundle<".len();
if let Some(close) = find_matching_angle_bracket(bytes, inner_start) {
let inner = &input[inner_start..close];
result.push_str(&rewrite_ranked_type_wrappers(inner));
result.push_str("[]");
i = close + 1;
continue;
}
}
if at_word_boundary && bytes[i..].starts_with(b"Item<") {
let inner_start = i + b"Item<".len();
if let Some(close) = find_matching_angle_bracket(bytes, inner_start) {
let inner = &input[inner_start..close];
result.push_str(&rewrite_ranked_type_wrappers(inner));
i = close + 1;
continue;
}
}
if bytes[i].is_ascii() {
result.push(bytes[i] as char);
i += 1;
@@ -614,8 +441,6 @@ impl std::fmt::Display for Type {
Type::Concrete(ty) => write!(f, "{ty}"),
Type::Fn(_, return_value) => write!(f, "{return_value}"),
Type::Future(ty) => write!(f, "{ty}"),
Type::Item(element) => write!(f, "{element}"),
Type::List(element) => write!(f, "{element}[]"),
}
}
}
+1 -23
View File
@@ -1,6 +1,4 @@
use crate::list::Item;
use crate::registry::DynFuture;
use crate::{Node, WasmNotSend};
use crate::Node;
use std::cell::{Cell, RefCell, RefMut};
use std::marker::PhantomData;
@@ -112,26 +110,6 @@ impl<T: Clone> From<T> for ClonedNode<T> {
}
}
/// Yields a precomputed `Item<T>` as a ready future, ignoring its input context.
/// Generated list-content variants feed each already-evaluated content slot through this so the kernel's own
/// context modifications become no-ops (the slot was evaluated once, up front, at the ambient footprint).
pub struct PrecomputedItemNode<T>(pub Item<T>);
impl<'i, T: Clone + WasmNotSend + 'i, I: 'i> Node<'i, I> for PrecomputedItemNode<T> {
type Output = DynFuture<'i, Item<T>>;
#[inline(always)]
fn eval(&'i self, _input: I) -> Self::Output {
let item = self.0.clone();
Box::pin(async move { item })
}
}
impl<T> PrecomputedItemNode<T> {
pub const fn new(item: Item<T>) -> Self {
Self(item)
}
}
#[derive(Clone, Copy)]
/// The DebugClonedNode logs every time it is evaluated.
/// This is useful for debugging.
@@ -57,7 +57,6 @@ impl_via_hash! {
bool, char,
u8, u16, u32, u64, u128, usize,
i8, i16, i32, i64, i128, isize,
core::time::Duration,
// glam integer vector types have Hash
glam::UVec2, glam::UVec3, glam::UVec4,
glam::IVec2, glam::IVec3, glam::IVec4,
@@ -1,31 +1,35 @@
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::graphene_hash::CacheHash;
use core_types::list::{ATTR_FILL, ATTR_STROKE, Item, ItemAttributeValues, List, NodeIdPath};
use core_types::ops::FromAnchorPosition;
use core_types::list::{ATTR_FILL, ATTR_STROKE, ItemAttributeValues, List};
use core_types::ops::{FromAnchorPosition, ListConvert};
use core_types::render_complexity::RenderComplexity;
use core_types::uuid::NodeId;
use core_types::{ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
use dyn_any::DynAny;
use glam::{DAffine2, DVec2};
use raster_types::{CPU, GPU, Raster};
use std::borrow::Cow;
use vector_types::Gradient;
use vector_types::GradientStops;
pub use vector_types::Vector;
/// The possible forms of graphical content that can be rendered by the Render node into either an image or SVG syntax.
#[derive(Clone, Debug, Default, CacheHash, PartialEq, DynAny)]
#[derive(Clone, Debug, CacheHash, PartialEq, DynAny)]
pub enum Graphic {
/// The absence of graphical content, like CSS's `none` keyword: painting it produces nothing.
#[default]
None,
Graphic(List<Graphic>),
Vector(List<Vector>),
RasterCPU(List<Raster<CPU>>),
RasterGPU(List<Raster<GPU>>),
Color(List<Color>),
Gradient(List<Gradient>),
Gradient(List<GradientStops>),
Text(List<String>),
}
impl Default for Graphic {
fn default() -> Self {
Self::Graphic(List::new())
}
}
// Graphic
impl From<List<Graphic>> for Graphic {
fn from(graphic: List<Graphic>) -> Self {
@@ -87,14 +91,14 @@ impl From<List<Color>> for Graphic {
// Note: List conversions handled by blanket impl in gcore
// Note: List<Color> -> Option<Color> is in gcore (Color is defined there)
// Gradient
impl From<Gradient> for Graphic {
fn from(gradient: Gradient) -> Self {
// GradientStops
impl From<GradientStops> for Graphic {
fn from(gradient: GradientStops) -> Self {
Graphic::Gradient(List::new_from_element(gradient))
}
}
impl From<List<Gradient>> for Graphic {
fn from(gradient: List<Gradient>) -> Self {
impl From<List<GradientStops>> for Graphic {
fn from(gradient: List<GradientStops>) -> Self {
Graphic::Gradient(gradient)
}
}
@@ -122,9 +126,9 @@ fn flatten_graphic_list<T>(content: List<Graphic>, extract_variant: fn(Graphic)
let parent_has_transform = current_graphic_item.attribute::<DAffine2>(ATTR_TRANSFORM).is_some();
let parent_has_opacity = current_graphic_item.attribute::<f64>(ATTR_OPACITY).is_some();
let parent_has_fill = current_graphic_item.attribute::<f64>(ATTR_OPACITY_FILL).is_some();
let parent_has_layer_path = current_graphic_item.attribute::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH).is_some();
let parent_has_layer_path = current_graphic_item.attribute::<List<NodeId>>(ATTR_EDITOR_LAYER_PATH).is_some();
let layer_path: NodeIdPath = current_graphic_item.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH);
let layer_path: List<NodeId> = current_graphic_item.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH);
let current_transform: DAffine2 = current_graphic_item.attribute_cloned_or_default(ATTR_TRANSFORM);
let current_opacity: f64 = current_graphic_item.attribute_cloned_or(ATTR_OPACITY, 1.);
let current_fill: f64 = current_graphic_item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.);
@@ -228,7 +232,6 @@ pub fn bake_paint_transforms(attributes: &mut ItemAttributeValues, transform: DA
fn bake_graphic_paint_transform(graphics: &mut List<Graphic>, transform: DAffine2) {
for graphic in graphics.iter_element_values_mut() {
match graphic {
Graphic::None => {}
Graphic::Graphic(list) => bake_list_transform(list, transform),
Graphic::Vector(list) => bake_list_transform(list, transform),
Graphic::RasterCPU(list) => bake_list_transform(list, transform),
@@ -271,7 +274,7 @@ impl TryFromGraphic for Color {
}
}
impl TryFromGraphic for Gradient {
impl TryFromGraphic for GradientStops {
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
if let Graphic::Gradient(t) = graphic { Some(t) } else { None }
}
@@ -304,11 +307,11 @@ impl IntoGraphicList for List<Graphic> {
impl IntoGraphicList for List<Vector> {
fn into_graphic_list(self) -> List<Graphic> {
// Propagate the `editor:layer_path` column (if present) from item 0 onto the wrapper Graphic item so a
// subsequent `flatten_graphic_list` doesn't drop the inner Vector's layer stamp
let layer_path = self.attribute::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH, 0).cloned();
// Propagate `editor:layer_path` from item 0 onto the wrapper Graphic item so a subsequent
// `flatten_graphic_list` doesn't overwrite the inner Vector's stamp with an empty value
let layer_path: List<NodeId> = self.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, 0);
let mut graphic_list = List::new_from_element(Graphic::Vector(self));
if let Some(layer_path) = layer_path {
if !layer_path.is_empty() {
graphic_list.set_attribute(ATTR_EDITOR_LAYER_PATH, 0, layer_path);
}
graphic_list
@@ -333,7 +336,7 @@ impl IntoGraphicList for List<Color> {
}
}
impl IntoGraphicList for List<Gradient> {
impl IntoGraphicList for List<GradientStops> {
fn into_graphic_list(self) -> List<Graphic> {
List::new_from_element(Graphic::Gradient(self))
}
@@ -341,32 +344,32 @@ impl IntoGraphicList for List<Gradient> {
impl IntoGraphicList for List<String> {
fn into_graphic_list(self) -> List<Graphic> {
let layer_path = self.attribute::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH, 0).cloned();
let layer_path: List<NodeId> = self.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, 0);
let mut graphic_list = List::new_from_element(Graphic::Text(self));
if let Some(layer_path) = layer_path {
if !layer_path.is_empty() {
graphic_list.set_attribute(ATTR_EDITOR_LAYER_PATH, 0, layer_path);
}
graphic_list
}
}
impl IntoGraphicList for Item<DAffine2> {
impl IntoGraphicList for DAffine2 {
fn into_graphic_list(self) -> List<Graphic> {
List::new_from_element(Graphic::default())
}
}
// DAffine2
impl From<Item<DAffine2>> for Graphic {
fn from(_: Item<DAffine2>) -> Self {
impl From<DAffine2> for Graphic {
fn from(_: DAffine2) -> Self {
Graphic::default()
}
}
// DVec2
impl From<Item<DVec2>> for Graphic {
fn from(position: Item<DVec2>) -> Self {
Graphic::Vector(List::new_from_element(Vector::from_anchor_position(position.into_element())))
impl From<DVec2> for Graphic {
fn from(position: DVec2) -> Self {
Graphic::Vector(List::new_from_element(Vector::from_anchor_position(position)))
}
}
// Note: List conversions handled by blanket impl in gcore
@@ -420,7 +423,6 @@ impl Graphic {
}
match self {
Graphic::None => true,
Graphic::Vector(list) => all_clipped(list),
Graphic::Graphic(list) => all_clipped(list),
Graphic::RasterCPU(list) => all_clipped(list),
@@ -450,7 +452,6 @@ impl Graphic {
pub fn is_opaque(&self) -> bool {
match self {
Graphic::None => false,
Graphic::Graphic(list) => !list.is_empty() && list.iter_element_values().all(Graphic::is_opaque),
Graphic::Vector(list) => {
let is_paint_opaque_at = |key: &str, index: usize| graphic_list_at(list, index, key).is_some_and(|graphic_list| graphic_list.element(0).is_some_and(|graphic| graphic.is_opaque()));
@@ -473,7 +474,6 @@ impl Graphic {
pub fn is_fully_transparent(&self) -> bool {
match self {
Graphic::None => true,
Graphic::Graphic(list) => list.iter_element_values().all(Graphic::is_fully_transparent),
Graphic::Vector(list) => (0..list.len()).all(|i| {
let Some(vector) = list.element(i) else { return false };
@@ -501,10 +501,9 @@ impl Graphic {
matches!(self, Graphic::Color(_) | Graphic::Gradient(_)) && self.is_opaque()
}
/// Returns true if this graphic contains no content.
/// Returns true if this graphic's inner list is empty.
pub fn is_empty(&self) -> bool {
match self {
Graphic::None => true,
Graphic::Graphic(list) => list.is_empty(),
Graphic::Vector(list) => list.is_empty(),
Graphic::Color(list) => list.is_empty(),
@@ -519,7 +518,6 @@ impl Graphic {
impl BoundingBox for Graphic {
fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
match self {
Graphic::None => RenderBoundingBox::None,
Graphic::Vector(list) => list.bounding_box(transform, include_stroke),
Graphic::RasterCPU(list) => list.bounding_box(transform, include_stroke),
Graphic::RasterGPU(list) => list.bounding_box(transform, include_stroke),
@@ -532,7 +530,6 @@ impl BoundingBox for Graphic {
fn thumbnail_bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
match self {
Graphic::None => RenderBoundingBox::None,
Graphic::Vector(vector) => vector.thumbnail_bounding_box(transform, include_stroke),
Graphic::RasterCPU(raster) => raster.thumbnail_bounding_box(transform, include_stroke),
Graphic::RasterGPU(raster) => raster.thumbnail_bounding_box(transform, include_stroke),
@@ -544,10 +541,25 @@ impl BoundingBox for Graphic {
}
}
impl ListConvert<Graphic> for Vector {
fn convert_item(self) -> Graphic {
Graphic::Vector(List::new_from_element(self))
}
}
impl ListConvert<Graphic> for Raster<CPU> {
fn convert_item(self) -> Graphic {
Graphic::RasterCPU(List::new_from_element(self))
}
}
impl ListConvert<Graphic> for Raster<GPU> {
fn convert_item(self) -> Graphic {
Graphic::RasterGPU(List::new_from_element(self))
}
}
impl RenderComplexity for Graphic {
fn render_complexity(&self) -> usize {
match self {
Self::None => 0,
Self::Graphic(list) => list.render_complexity(),
Self::Vector(list) => list.render_complexity(),
Self::RasterCPU(list) => list.render_complexity(),
@@ -676,7 +688,7 @@ mod graphic_is_opaque_tests {
Graphic::Color(List::new_from_element(color))
}
fn gradient_graphic(gradient: Gradient) -> Graphic {
fn gradient_graphic(gradient: GradientStops) -> Graphic {
let mut gradient_list = List::new_from_element(gradient);
gradient_list.set_attribute(ATTR_SPREAD_METHOD, 0, GradientSpreadMethod::Pad);
Graphic::Gradient(gradient_list)
@@ -704,7 +716,7 @@ mod graphic_is_opaque_tests {
fn gradient_with_all_opaque_stops_is_opaque() {
let color_1 = Color::from_rgbaf32(1., 0., 0., 1.).unwrap();
let color_2 = Color::from_rgbaf32(1., 0., 0., 1.).unwrap();
let gradient = Gradient::new(vec![
let gradient = GradientStops::new(vec![
GradientStop {
position: 0.,
midpoint: 0.5,
@@ -724,7 +736,7 @@ mod graphic_is_opaque_tests {
fn gradient_with_transparent_stop_is_not_opaque() {
let color_1 = Color::from_rgbaf32(1., 0., 0., 0.5).unwrap();
let color_2 = Color::from_rgbaf32(1., 0., 0., 1.).unwrap();
let gradient = Gradient::new(vec![
let gradient = GradientStops::new(vec![
GradientStop {
position: 0.,
midpoint: 0.5,
+10 -10
View File
@@ -20,11 +20,11 @@ pub mod migrations {
use dyn_any::DynAny;
use glam::{DAffine2, DVec2};
use vector_types::vector::{PointDomain, RegionDomain, SegmentDomain, misc::HandleId, style::Stroke};
use vector_types::{Gradient, Vector, vector};
use vector_types::{GradientStops, Vector, vector};
#[derive(Default, Debug, Clone, PartialEq, graphene_hash::CacheHash, DynAny, serde::Serialize, serde::Deserialize)]
pub struct LegacyGradient {
pub stops: Gradient,
pub struct Gradient {
pub stops: GradientStops,
pub gradient_type: vector::style::GradientType,
pub start: DVec2,
pub end: DVec2,
@@ -36,11 +36,11 @@ pub mod migrations {
pub transform: DAffine2,
}
impl LegacyGradient {
impl Gradient {
/// Converts a legacy bounding-box-relative gradient (`start`/`end` in [0,1]) into an absolute one in the geometry's local space.
/// `bounding_box` maps [0,1] onto the geometry's bounding box; `layer_transform` is the layer's own transform,
/// used to bake the elliptical adjustment that reproduces the legacy isotropic radial through a non-uniform layer.
pub fn to_absolute(&self, bounding_box: DAffine2, layer_transform: DAffine2) -> LegacyGradient {
pub fn to_absolute(&self, bounding_box: DAffine2, layer_transform: DAffine2) -> Gradient {
let start = bounding_box.transform_point2(self.start);
let end = bounding_box.transform_point2(self.end);
let direction = end - start;
@@ -63,7 +63,7 @@ pub mod migrations {
DAffine2::IDENTITY
};
LegacyGradient {
Gradient {
start,
end,
transform,
@@ -80,15 +80,15 @@ pub mod migrations {
}
#[derive(Default, Debug, Clone, PartialEq, graphene_hash::CacheHash, DynAny, serde::Serialize, serde::Deserialize)]
pub enum LegacyFill {
pub enum Fill {
#[default]
None,
Solid(Color),
Gradient(LegacyGradient),
Gradient(Gradient),
}
/// The legacy `fill` field is intentionally omitted because vector payload migration only
/// recovers editable vector data. The fill/stroke paints are migrated from the node inputs.
/// recovers editable vector data. The fill/stroke paints are migrated from the the node inputs.
#[derive(serde::Deserialize)]
#[cfg_attr(test, derive(Default, serde::Serialize))]
pub(super) struct PathStyle {
@@ -162,7 +162,7 @@ pub mod migrations {
.unwrap()
.as_object_mut()
.unwrap()
.insert("fill".into(), serde_json::to_value(legacy::LegacyFill::default()).unwrap());
.insert("fill".into(), serde_json::to_value(legacy::Fill::default()).unwrap());
let migrated = migrate_to_optional_vector(value).unwrap().unwrap();
assert_eq!(migrated.stroke.unwrap().weight, 12.);
Loaded 100 of 174 files, more files were not shown because too many files have changed in this diff. Show more