Compare commits

..
Author SHA1 Message Date
Dennis Kobert 4b2a63d0f3 Resurrect from the replay position when folding a snapshot from history 2026-09-24 16:36:51 +00:00
Dennis Kobert 3b9474e346 Stamp a freshly created node's implementation at the origin timestamp 2026-09-24 13:56:16 +00:00
Dennis Kobert dc4fa94012 Make a peer's working registry agree with its own retired snapshot 2026-09-24 13:56:16 +00:00
Dennis Kobert 7b10164b72 Store retired ops past a prefix as runs so a permanent gap cannot grow them 2026-09-24 13:56:16 +00:00
Dennis Kobert c408e6ed69 Record what the retired-beyond set actually bounds 2026-09-24 13:56:16 +00:00
Dennis Kobert e1508acac5 Give hot-op sequence numbers their own type 2026-09-24 13:56:16 +00:00
Dennis Kobert a8d6bb73e7 Vary comment phrasing and cut the repeated constructions 2026-09-24 13:56:16 +00:00
Dennis Kobert ec057cea3b Retry an owed refold and keep the unguarded hot-op path crate-private 2026-09-24 13:56:16 +00:00
Dennis Kobert 1d9653d40f Address review findings 2026-09-24 13:56:16 +00:00
Dennis Kobert 1bbce952e2 Shorten the comments on the retired-state changes 2026-09-24 13:56:16 +00:00
Dennis Kobert 6ae05765d2 Make retired state a function of history alone 2026-09-24 13:56:16 +00:00
Keavon Chambers ddafaaa757 Add an "Output Type" parameter to the 'Math f(x)' and 'Math f(…)' nodes (#4591)
Add an 'Output Type' choice to the 'Math f(x)' and 'Math f(…)' nodes
2026-09-23 20:26:51 -07:00
Keavon Chambers 2c1cca7e99 Rename the TaggedValue I64/F64/F64Array variants to Integer/Number/Numbers (#4590)
Rename the TaggedValue F64/I64/F64Array variants to Number/Integer/Numbers
2026-09-23 18:02:06 -07:00
Keavon Chambers c91d0cd5a3 Update all node parameters with appropriate attributes of #[unit(...)], bounds, etc., deprecating the type alias units pattern (#4589)
Replace the node parameter typedefs with unit and widget attributes
2026-09-23 17:08:05 -07:00
Dennis Kobert 84ed60a404 Route every network interface write through a single-writer store (#4586)
* Route every network interface write through a single-writer store

* Keep the existing previewing behaviour and fix the review findings that remain

* Record what each store write changed and stage it into the working copy

* Fix the delta path's resource staging, batch liveness, and stale comparisons

* Keep batch resource liveness and load-time repairs consistent with what reaches storage

* Correct the delta documentation and stop persisting pinned nodes the network lost

* Swap a node's implementation in place instead of rebuilding the node

* Resolve network attributes through the same source as the IDs they name

* Resolve an implementation swap by timestamp and let an edit report whether it changed the value
2026-09-23 21:52:02 +00:00
Keavon Chambers 942d138fc1 Add #[multiline] and #[progression] node parameter attributes for choosing a type's preferred widget variant (#4587)
Add #[multiline] and #[progression] node parameter attributes for choosing a widget
2026-09-23 13:44:49 -07:00
Keavon Chambers dadc8717ff Narrow node parameters with an integer meaning from i32/f64 to i64 (#4584)
* Narrow node parameters with an integer meaning from i32/f64 to i64

* Update demo artwork
2026-09-23 03:18:41 -07:00
Keavon Chambers 9423dcada7 Replace all node usages of u32/u64 with i64 (#4582)
* Add TODO notes that the raster filters' lengths should scale through the footprint instead of counting whole source pixels

* Standardize the node catalog's integer parameters on i64, replacing u32 and u64 with hard-bounded i64

* Retire the 'As u32' and 'As u64' nodes into 'As Integer' and upgrade stored unsigned values to I64
2026-09-23 00:15:09 -07:00
Keavon Chambers 2941c74051 Replace all node usages of f32 with f64 (#4581)
Retire f32 from the node catalog so every Number is an f64, leaving only the Color and shader internals computing in f32
2026-09-22 21:47:49 -07:00
Keavon Chambers cd00af84f3 Make the node macro reject nodes with unmatched #[implementations] counts (#4580)
Make the node macro reject a node whose #[implementations] row counts differ across parameters instead of padding the shorter lists
2026-09-22 21:04:14 -07:00
Keavon Chambers 951339a6d6 Move the adjustment nodes to 64-bit precision number parameters (#4579)
Declare shader nodes in f64 and have the node macro emit the f32 variant that the shader build computes with
2026-09-22 19:38:19 -07:00
Keavon Chambers f5507c0959 Round half away from zero on every Number to Integer conversion instead of truncating (#4578)
* Add an I64 tagged value as the node graph's integer storage type, with a whole-number widget for it

* Round half away from zero on every Number to Integer conversion instead of truncating
2026-09-22 18:22:24 -07:00
Keavon Chambers 60bba681d3 Have the math expression nodes each use #[data] to cache its parsed expression input (#4577)
Parse each expression node's source once, reusing the tree across list items and frames
2026-09-22 17:44:18 -07:00
Keavon Chambers f868aadd8d Retire the 'Math' node and migrate its documents to 'Math f(x)' and 'Math f(…)' (#4576)
Retire the Math node and migrate its documents to Math f(x) and Math f(…)
2026-09-22 17:14:47 -07:00
Keavon Chambers b610d9bc23 Extend the math expression parser's combinatorics, statistics, roots, powers, and division past the reals (#4574) 2026-09-22 16:00:08 -07:00
187 changed files with 9497 additions and 9466 deletions

No files matched your search

Generated
+49 -1706
View File
File diff suppressed because it is too large. Load diff
-4
View File
@@ -11,8 +11,6 @@ members = [
"document/format",
"document/graph-storage",
"document/container",
"document/peer-transport",
"document/live",
"editor",
"frontend/wrapper",
"libraries/dyn-any",
@@ -100,8 +98,6 @@ graph-craft = { path = "node-graph/graph-craft" }
document-format = { path = "document/format" }
document-graph-storage = { path = "document/graph-storage", default-features = false }
document-container = { path = "document/container" }
peer-transport = { path = "document/peer-transport" }
document-live = { path = "document/live" }
raster-nodes = { path = "node-graph/nodes/raster" }
graphene-std = { path = "node-graph/nodes/gstd" }
interpreted-executor = { path = "node-graph/interpreted-executor" }
-1
View File
@@ -18,7 +18,6 @@ accepted = [
"NCSA", # Keep this list in sync with those in `/deny.toml`
"bzip2-1.0.6", # Keep this list in sync with those in `/deny.toml`
"OFL-1.1", # Keep this list in sync with those in `/deny.toml`
"Unlicense", # Keep this list in sync with those in `/deny.toml`
]
workarounds = ["ring"]
ignore-build-dependencies = true
+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":{"GradientRamp":{"stops":{"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}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"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::AsGraphicNode"}},"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::IntoGroupNode"}},"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":fLine 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":{"GradientRamp":{"stops":{"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}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"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::AsGraphicNode"}},"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::IntoGroupNode"}},"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":fLine 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::AsGraphicNode"}},"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::IntoGroupNode"}},"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":""}}],[194878846429432339,{"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],"remove":[],"delta":[[1,[671.7691453623979,420.00000000000006]],[2,[559.8076211353317,450.0000000000001]],[3,[410.5255888325765,410.0]],[4,[522.4871130596428,380.00000000000006]]]},"segments":{"add":[1,2,3,4],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4]],"end_point":[[1,2],[2,3],[3Line 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::AsGraphicNode"}},"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::IntoGroupNode"}},"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":""}}],[194878846429432339,{"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],"remove":[],"delta":[[1,[671.7691453623979,420.00000000000006]],[2,[559.8076211353317,450.0000000000001]],[3,[410.5255888325765,410.0]],[4,[522.4871130596428,380.00000000000006]]]},"segments":{"add":[1,2,3,4],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4]],"end_point":[[1,2],[2,3],[3Line 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":{"GradientRamp":{"stops":{"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}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"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":{"GradientRamp":{"stops":{"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}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"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_Line 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":{"GradientRamp":{"stops":{"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}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"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::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"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}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"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::adjustments::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":{"I64":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":{"I64":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_vaLine 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":{"GradientRamp":{"stops":{"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}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"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":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"Generic":"T"}]},"import_index":1}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":2}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":3}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":4}},{"Import":{"import_type":{"Item":{"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::sLine 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":{"GradientRamp":{"stops":{"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}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"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":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"Generic":"T"}]},"import_index":1}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":2}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":3}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":4}},{"Import":{"import_type":{"Item":{"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::sLine 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::AsGraphicNode"}},"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::IntoGroupNode"}},"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":{"GradientRamp":{"stops":{"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}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"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":{"node_id":14158287945315818946,"outLine truncated
{"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::AsGraphicNode"}},"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::IntoGroupNode"}},"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":{"GradientRamp":{"stops":{"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}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"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":{"node_id":14158287945315818946,"outLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"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}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"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":{"GradientRamp":{"stops":{"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}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"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::AsGraphicNode"}},"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::IntoGroupNode"}},"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":Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"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}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"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":{"GradientRamp":{"stops":{"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}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"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::AsGraphicNode"}},"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::IntoGroupNode"}},"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":Line 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":{"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":"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":{"GradientRamp":{"stops":{"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}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"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::AsGraphicNode"}},"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::IntoGroupNode"}},"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":2Line truncated
{"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]]]},"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":{"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":"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":{"GradientRamp":{"stops":{"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}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"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::AsGraphicNode"}},"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::IntoGroupNode"}},"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::OwnedContextImpLine 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::AsGraphicNode"}},"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::IntoGroupNode"}},"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::AsGraphicNode"}},"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::IntoGroupNode"}},"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_Line 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::AsGraphicNode"}},"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::IntoGroupNode"}},"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::AsGraphicNode"}},"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::IntoGroupNode"}},"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_Line truncated
-1
View File
@@ -82,7 +82,6 @@ allow = [
"NCSA", # Keep this list in sync with those in `/about.toml`
"bzip2-1.0.6", # Keep this list in sync with those in `/about.toml`
"OFL-1.1", # Keep this list in sync with those in `/about.toml`
"Unlicense", # Keep this list in sync with those in `/about.toml`
]
# The confidence threshold for detecting a license from license text.
# The higher the value, the more closely the license text must be to the
+4 -4
View File
@@ -20,10 +20,10 @@ pub(crate) fn clear_dir(path: &PathBuf) {
if let Err(e) = fs::remove_dir_all(&entry_path) {
tracing::error!("Failed to remove directory at {:?}: {}", entry_path, e);
}
} else if entry_path.is_file() {
if let Err(e) = fs::remove_file(&entry_path) {
tracing::error!("Failed to remove file at {:?}: {}", entry_path, e);
}
} else if entry_path.is_file()
&& let Err(e) = fs::remove_file(&entry_path)
{
tracing::error!("Failed to remove file at {:?}: {}", entry_path, e);
}
}
}
+5 -4
View File
@@ -71,10 +71,11 @@ fn garbage_collect_document_files(state: &PersistedState) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_file() && !valid_paths.contains(&path) {
if let Err(e) = std::fs::remove_file(&path) {
tracing::error!("Failed to remove orphaned document file {path:?}: {e}");
}
if path.is_file()
&& !valid_paths.contains(&path)
&& let Err(e) = std::fs::remove_file(&path)
{
tracing::error!("Failed to remove orphaned document file {path:?}: {e}");
}
}
}
+4 -4
View File
@@ -44,10 +44,10 @@ impl<'a> DesktopWrapperMessageDispatcher<'a> {
pub(super) fn poll_node_graph_evaluation(&mut self) {
let mut responses = VecDeque::new();
if let Err(e) = self.editor.poll_node_graph_evaluation(&mut responses) {
if e != "No active document" {
tracing::error!("Error poling node graph: {}", e);
}
if let Err(e) = self.editor.poll_node_graph_evaluation(&mut responses)
&& e != "No active document"
{
tracing::error!("Error polling node graph: {}", e);
}
while let Some(message) = responses.pop_front() {
self.queue_editor_message(message);
+1 -4
View File
@@ -17,14 +17,11 @@ conversion = ["document-graph-storage/conversion", "dep:graph-craft", "dep:core-
# gates that format's `ExportFormat` arm and sink. The folder/memory codec-free core needs neither.
zip = ["document-container/zip"]
xz = ["document-container/xz"]
# Live collaboration: `Gdd` hosts or joins a `peer_transport` session and mirrors hot ops and retired history to peers.
network = ["dep:peer-transport"]
default = ["conversion", "zip", "xz", "network"]
default = ["conversion", "zip", "xz"]
[dependencies]
document-container = { workspace = true }
document-graph-storage = { workspace = true, default-features = false }
peer-transport = { workspace = true, optional = true }
graph-craft = { workspace = true, optional = true }
graphene-resource = { workspace = true }
core-types = { workspace = true, optional = true }
-4
View File
@@ -47,8 +47,4 @@ pub enum Error {
/// An export marked a resource for embedding but its bytes were absent from the byte store.
#[error("embedded resource {0} missing from the byte store")]
MissingResource(ResourceHash),
/// A packet for the collaboration session failed to encode.
#[cfg(feature = "network")]
#[error("network error: {0}")]
Network(#[from] peer_transport::PacketError),
}
+6 -60
View File
@@ -20,7 +20,7 @@ use document_graph_storage::{CommitError, NodeMetadataSource};
use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session};
#[cfg(feature = "conversion")]
use graphene_resource::LoadResource;
use graphene_resource::{ResourceHash, ResourceStorage};
use graphene_resource::ResourceHash;
pub mod codec;
pub mod error;
@@ -28,8 +28,6 @@ pub mod export;
pub mod io;
pub mod layout;
pub mod manifest;
#[cfg(feature = "network")]
pub mod network;
pub mod persist;
pub mod resource;
pub mod session_state;
@@ -70,8 +68,8 @@ pub const DEFAULT_HOT_LOG_CODEC: Codec = Codec::MessagePackFrames;
/// read.
/// `Clone` shares the working-copy container (`Arc<AnyContainer>`) so a cloned handle reads and writes
/// the *same* on-disk/OPFS working copy — including any writes still queued on the OPFS backend. The
/// `Session` is cloned (a snapshot copy); the container is shared. A live collaboration session is
/// not carried over, so a clone is a read-only copy for asynchronous writes.
/// `Session` is cloned (a snapshot copy); the container is shared.
#[derive(Clone)]
pub struct Gdd<L: Layout = GddV1Layout> {
pub(crate) session: Session,
pub(crate) working: Arc<AnyContainer>,
@@ -86,42 +84,6 @@ pub struct Gdd<L: Layout = GddV1Layout> {
/// Per-network view settings (node-graph nav + previewing), keyed by stable [`NetworkId`]. Same per-peer
/// `session.json` treatment as [`view_settings`](Self::view_settings), but scoped per network.
pub(crate) network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, serde_json::Value>>,
/// Where this document's resource bytes live. `None` means the working copy's own content-addressed
/// store, which is what a standalone handle uses. The editor points this at its application-wide
/// cache, the single store resources are kept in there.
pub(crate) byte_store: Option<Arc<dyn ResourceStorage>>,
#[cfg(feature = "network")]
pub(crate) network: Option<peer_transport::Replica>,
#[cfg(feature = "network")]
pub(crate) pending_persist: PendingPersist,
}
/// Whole-file rewrites the sync path defers to the end of a poll, so one batch of remote packets costs
/// one rewrite of each file rather than one per packet.
#[cfg(feature = "network")]
#[derive(Debug, Default, Clone, Copy)]
pub(crate) struct PendingPersist {
pub(crate) history: bool,
pub(crate) hot_log: bool,
pub(crate) snapshot: bool,
}
impl<L: Layout + Clone> Clone for Gdd<L> {
fn clone(&self) -> Self {
Self {
session: self.session.clone(),
working: self.working.clone(),
layout: self.layout.clone(),
manifest: self.manifest.clone(),
view_settings: self.view_settings.clone(),
network_view_settings: self.network_view_settings.clone(),
byte_store: self.byte_store.clone(),
#[cfg(feature = "network")]
network: None,
#[cfg(feature = "network")]
pending_persist: PendingPersist::default(),
}
}
}
/// Native folder-backed convenience constructors. On wasm the editor builds an OPFS-backed
@@ -182,15 +144,7 @@ impl<L: Layout> Gdd<L> {
(true, true) => {
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
let history = load_history(&working, &layout, codecs.history).await?;
Session::load(
peer,
registry,
history,
session_state.head_rev,
session_state.redo_stack,
session_state.next_node_counter,
session_state.next_hot_sequence,
)
Session::load(peer, registry, history, session_state.head_rev, session_state.redo_stack, session_state.next_node_counter)
}
(true, false) => {
// Registry-only export: synthesize a history that reproduces this state.
@@ -204,6 +158,8 @@ impl<L: Layout> Gdd<L> {
if let Some(rev) = session_state.last_broadcast_rev {
session.publish_up_to(rev);
}
// Every arm must continue this peer's authored-op count too.
session.restore_hot_sequence(session_state.next_hot_sequence);
replay_hot_log(&working, &layout, codecs.hot_log, &mut session).await?;
@@ -214,11 +170,6 @@ impl<L: Layout> Gdd<L> {
manifest,
view_settings: session_state.view_settings,
network_view_settings: session_state.network_view_settings,
byte_store: None,
#[cfg(feature = "network")]
network: None,
#[cfg(feature = "network")]
pending_persist: PendingPersist::default(),
})
}
@@ -241,11 +192,6 @@ impl<L: Layout> Gdd<L> {
manifest,
view_settings: std::collections::BTreeMap::new(),
network_view_settings: std::collections::BTreeMap::new(),
byte_store: None,
#[cfg(feature = "network")]
network: None,
#[cfg(feature = "network")]
pending_persist: PendingPersist::default(),
})
}
}
-162
View File
@@ -1,162 +0,0 @@
//! Live collaboration on the [`Gdd`] handle. `share` / `join` attach a [`Replica`]; the persist path
//! then broadcasts staged hot ops and (as host) retired deltas, and `poll_peers` applies what peers
//! send through the [`SyncTarget`] impl below, which persists inbound state the same way local
//! edits are.
use std::collections::HashSet;
use document_graph_storage::{Delta, HotOp, HotOpId, PeerId, Registry, ResourceHash, RetiredMarks, Rev, Session, UserId};
use peer_transport::{Event, Replica, Role, SyncTarget, TargetError, Transport};
use crate::error::Error;
use crate::layout::Layout;
use crate::{Gdd, PendingPersist};
impl<L: Layout> Gdd<L> {
pub fn share(&mut self, transport: impl Transport + 'static, user: UserId) {
self.network = Some(Replica::host(transport, self.session.peer(), user));
}
pub fn join(&mut self, transport: impl Transport + 'static, user: UserId) {
self.network = Some(Replica::guest(transport, self.session.peer(), user));
}
pub fn leave(&mut self) {
if let Some(mut replica) = self.network.take() {
replica.leave();
}
}
pub fn role(&self) -> Option<Role> {
self.network.as_ref().map(Replica::role)
}
pub fn is_synced(&self) -> bool {
self.network.as_ref().is_none_or(Replica::is_synced)
}
/// Record that the runtime was rebuilt from the registry, so the next staged diff is taken against it.
pub fn mark_runtime_current(&mut self) {
self.session.mark_runtime_current();
}
pub fn poll_peers(&mut self) -> Vec<Event> {
let Some(mut replica) = self.network.take() else { return Vec::new() };
let events = replica.poll(self);
self.network = Some(replica);
events
}
/// Answer an [`Event::ResourceRequested`].
pub fn send_resource(&mut self, to: peer_transport::TransportPeerId, hash: ResourceHash, bytes: Vec<u8>) -> Result<(), Error> {
if let Some(replica) = &mut self.network {
replica.send_resource(to, hash, bytes)?;
}
Ok(())
}
}
impl<L: Layout> SyncTarget for Gdd<L> {
fn peer(&self) -> PeerId {
self.session.peer()
}
fn head(&self) -> Option<Rev> {
self.session.head_rev()
}
fn retired_registry(&self) -> Registry {
self.session.retired_registry().clone()
}
fn hot_log(&self) -> Vec<HotOp> {
self.session.hot_log().to_vec()
}
fn known_revs(&self) -> Vec<Rev> {
self.session.known_revs()
}
fn contains_rev(&self, rev: Rev) -> bool {
self.session.delta(rev).is_some()
}
fn deltas_unknown_to(&self, known: &[Rev]) -> Vec<Delta> {
<Session as SyncTarget>::deltas_unknown_to(&self.session, known)
}
fn load(&mut self, registry: Registry, history: Vec<Delta>, head: Option<Rev>) -> Result<(), TargetError> {
self.session.load(registry, history, head)?;
self.pending_persist = PendingPersist {
history: true,
hot_log: true,
snapshot: true,
};
Ok(())
}
fn apply_remote_hot_ops(&mut self, ops: Vec<HotOp>) -> Result<Vec<HotOp>, TargetError> {
// An op naming an entity that has not arrived here yet is handed back for a later retry, so only
// what actually applied reaches the hot frame log.
let mut deferred = Vec::new();
for hot_op in ops {
if self.session.replay_hot_op(hot_op.clone()).is_err() {
deferred.push(hot_op);
continue;
}
self.append_hot_frame(&hot_op)?;
}
Ok(deferred)
}
fn merge_remote(&mut self, deltas: Vec<Delta>, retires: &[HotOpId]) -> Result<(), TargetError> {
self.session.merge_remote(deltas, retires)?;
// Whatever a peer sent is shared by definition, so it sits behind the published frontier too: a
// guest must no more silently rewind the host's history than the host may rewind its own.
if let Some(head) = self.session.head_rev() {
self.session.publish_up_to(head);
}
self.pending_persist.history = true;
self.pending_persist.hot_log |= !retires.is_empty();
self.pending_persist.snapshot = true;
Ok(())
}
fn retired_marks(&self) -> RetiredMarks {
SyncTarget::retired_marks(&self.session)
}
fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> Result<(), TargetError> {
SyncTarget::absorb_retired_marks(&mut self.session, remote)?;
self.pending_persist.hot_log = true;
Ok(())
}
fn flush(&mut self) -> Result<(), TargetError> {
let pending = std::mem::take(&mut self.pending_persist);
if pending.history {
self.rewrite_history()?;
}
if pending.hot_log {
self.rewrite_hot_log()?;
}
if pending.snapshot {
self.persist_registry_snapshot()?;
self.persist_session_state()?;
}
Ok(())
}
fn missing_resources(&self) -> HashSet<ResourceHash> {
self.unstored_resources().into_iter().collect()
}
fn store_resource(&mut self, _hash: ResourceHash, bytes: &[u8]) -> Result<(), TargetError> {
self.hold_resource(bytes)?;
Ok(())
}
}
+33 -61
View File
@@ -6,7 +6,7 @@
use document_container::AsyncContainer;
#[cfg(feature = "conversion")]
use document_graph_storage::NodeMetadataSource;
use document_graph_storage::{HotOp, RegistryDelta, Rev, TimeStamp};
use document_graph_storage::{HotOp, Rev, TimeStamp};
#[cfg(feature = "conversion")]
use graphene_resource::ResourceStorage;
@@ -62,7 +62,10 @@ impl<L: Layout> Gdd<L> {
byte_store: &dyn ResourceStorage,
) -> Result<document_graph_storage::Declarations, Error> {
let (hot_ops, conversion) = self.session.stage_from_runtime(network, metadata, resources)?;
self.persist_staged(&hot_ops)?;
for hot_op in &hot_ops {
self.append_hot_frame(hot_op)?;
}
// Persist proto-node declaration content to the byte store (the global cache in the editor,
// the working-copy container for standalone export). Content-addressed, so re-storing
@@ -73,20 +76,25 @@ impl<L: Layout> Gdd<L> {
Ok(conversion.declarations)
}
/// Stage raw registry ops as hot ops, for callers that don't go through the runtime diff.
pub fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, Error> {
let hot_ops = self.session.stage_ops(ops)?;
self.persist_staged(&hot_ops)?;
Ok(hot_ops)
}
/// Stage ops the caller built from what the editor recorded, rather than deriving them by converting
/// the whole document and diffing it against the working registry.
///
/// Otherwise identical to [`stage_runtime_snapshot`](Self::stage_runtime_snapshot): each op becomes a
/// hot frame, and the proto-node declaration bytes go to the byte store.
#[cfg(feature = "conversion")]
pub fn stage_constructed_ops(
&mut self,
ops: Vec<document_graph_storage::RegistryDelta>,
declaration_bytes: &document_graph_storage::from_runtime::DeclarationBytes,
byte_store: &dyn ResourceStorage,
) -> Result<(), Error> {
let hot_ops = self.session.stage_computed_ops(ops)?;
fn persist_staged(&mut self, hot_ops: &[HotOp]) -> Result<(), Error> {
for hot_op in hot_ops {
for hot_op in &hot_ops {
self.append_hot_frame(hot_op)?;
}
#[cfg(feature = "network")]
if let Some(replica) = &mut self.network {
replica.broadcast_hot_ops(hot_ops)?;
for bytes in declaration_bytes.values() {
byte_store.store(bytes);
}
Ok(())
}
@@ -174,7 +182,7 @@ impl<L: Layout> Gdd<L> {
/// Rewrite the entire history file from the in-memory session. `history()` yields deltas in
/// topological (append) order, which is a valid replay order, so no separate sort is needed.
pub(crate) fn rewrite_history(&mut self) -> Result<(), Error> {
fn rewrite_history(&mut self) -> Result<(), Error> {
let mut buffer = Vec::new();
for delta in self.session.history() {
self.manifest.codecs.history.append(&mut buffer, delta)?;
@@ -183,7 +191,7 @@ impl<L: Layout> Gdd<L> {
Ok(())
}
pub(crate) fn persist_session_state(&mut self) -> Result<(), Error> {
fn persist_session_state(&mut self) -> Result<(), Error> {
let state = SessionState {
peer_id: self.session.peer(),
head_rev: self.session.head_rev(),
@@ -202,7 +210,7 @@ impl<L: Layout> Gdd<L> {
/// registry to match the persisted `head`, so any cursor move (undo/redo) that rewinds the working
/// registry without retiring must re-persist it or a reopen would read a registry inconsistent with
/// `head`. Synchronous and hot-path-safe (`write_non_blocking`).
pub(crate) fn persist_registry_snapshot(&mut self) -> Result<(), Error> {
fn persist_registry_snapshot(&mut self) -> Result<(), Error> {
io::write_single(&self.working, self.layout.registry_basename(), self.manifest.codecs.registry, self.session.registry())?;
Ok(())
}
@@ -231,7 +239,7 @@ impl<L: Layout> Gdd<L> {
self.persist_session_state()
}
pub(crate) fn append_hot_frame(&mut self, op: &HotOp) -> Result<(), Error> {
fn append_hot_frame(&mut self, op: &HotOp) -> Result<(), Error> {
let mut buffer = Vec::new();
self.manifest.codecs.hot_log.append(&mut buffer, op)?;
self.working.append_non_blocking(&io::path_for(self.layout.hot_log_basename(), self.manifest.codecs.hot_log), &buffer)?;
@@ -248,12 +256,6 @@ impl<L: Layout> Gdd<L> {
/// `interaction_end`: mark the batch's last delta as an interaction boundary (one undo unit) before its
/// history frame is written, so the marker persists on reopen without a later frame rewrite.
fn retire_inner(&mut self, up_to: TimeStamp, interaction_end: bool) -> Result<Vec<Rev>, Error> {
if !self.retires_locally() {
return Ok(Vec::new());
}
#[cfg(feature = "network")]
let retired_hot_ops = self.session.hot_ops_up_to(up_to);
let new_revs = self.session.retire(up_to)?;
// Mark before `append_history_deltas` so the on-disk frame carries the boundary.
@@ -261,51 +263,21 @@ impl<L: Layout> Gdd<L> {
self.session.mark_interaction_end(last);
}
// In a session these deltas are about to reach peers, so the published frontier moves with them.
// Rewinding a commit peers already hold would diverge from them for good, with nothing on the wire
// to tell them, so undo past this point has to go through forward inverse ops instead. Set before
// the persists below so the frontier survives a reopen.
#[cfg(feature = "network")]
if self.network.is_some()
&& let Some(&last) = new_revs.last()
{
self.session.publish_up_to(last);
}
if !new_revs.is_empty() {
self.append_history_deltas(&new_revs)?;
}
self.rewrite_hot_log()?;
// Rewrite hot log with whatever survived retirement.
let mut hot_buffer = Vec::new();
for hot_op in self.session.hot_log() {
self.manifest.codecs.hot_log.append(&mut hot_buffer, hot_op)?;
}
self.working
.write_non_blocking(&io::path_for(self.layout.hot_log_basename(), self.manifest.codecs.hot_log), &hot_buffer)?;
self.persist_registry_snapshot()?;
self.persist_session_state()?;
#[cfg(feature = "network")]
if let Some(replica) = &mut self.network {
let deltas: Vec<_> = new_revs.iter().filter_map(|&rev| self.session.delta(rev).cloned()).collect();
replica.broadcast_retired(&deltas, &retired_hot_ops)?;
}
Ok(new_revs)
}
/// Guests leave retirement to the session host and keep their hot ops until the host's retired
/// deltas arrive.
fn retires_locally(&self) -> bool {
#[cfg(feature = "network")]
{
self.network.as_ref().is_none_or(|replica| replica.role() == peer_transport::Role::Host)
}
#[cfg(not(feature = "network"))]
true
}
pub(crate) fn rewrite_hot_log(&mut self) -> Result<(), Error> {
let mut buffer = Vec::new();
for hot_op in self.session.hot_log() {
self.manifest.codecs.hot_log.append(&mut buffer, hot_op)?;
}
self.working.write_non_blocking(&io::path_for(self.layout.hot_log_basename(), self.manifest.codecs.hot_log), &buffer)?;
Ok(())
}
}
-36
View File
@@ -91,36 +91,6 @@ impl<L: Layout> Gdd<L> {
{
ResourceProxy(self.working.clone(), self.layout.clone())
}
/// Point resource lookups at an external store instead of the working copy, for an embedder that
/// already keeps one cache for every open document.
pub fn set_byte_store(&mut self, byte_store: Arc<dyn ResourceStorage>) {
self.byte_store = Some(byte_store);
}
/// Whether this document's resource bytes are on hand, in whichever store backs it.
pub fn holds_resource(&self, hash: &ResourceHash) -> bool {
match &self.byte_store {
Some(byte_store) => byte_store.contains(hash),
None => self.working.exists_non_blocking(&self.layout.resource_path(hash)),
}
}
/// Put resource bytes into whichever store backs this document.
pub fn hold_resource(&self, bytes: &[u8]) -> Result<(), ContainerError> {
match &self.byte_store {
Some(byte_store) => {
byte_store.store(bytes);
Ok(())
}
None => self.working.write_non_blocking(&self.layout.resource_path(&ResourceHash::from(bytes)), bytes),
}
}
/// Resources the registry or its history names whose bytes are not on hand.
pub fn unstored_resources(&self) -> Vec<ResourceHash> {
self.session.all_referenced_resource_hashes().into_iter().filter(|hash| !self.holds_resource(hash)).collect()
}
}
impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
@@ -134,12 +104,6 @@ impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
pub struct ResourceProxy<T: Layout>(Arc<AnyContainer>, T);
impl<T: Layout + Clone> Clone for ResourceProxy<T> {
fn clone(&self) -> Self {
Self(self.0.clone(), self.1.clone())
}
}
impl<L: Layout + Send + Sync> LoadResource for ResourceProxy<L> {
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
Box::pin(async move {
+6 -5
View File
@@ -4,7 +4,7 @@
//!
//! Lives in `session.json`. Rewritten on retirement.
use document_graph_storage::{NetworkId, PeerId, Rev};
use document_graph_storage::{HotSequence, NetworkId, PeerId, Rev};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
@@ -31,10 +31,6 @@ pub struct SessionState {
/// collide on minted IDs.
#[serde(default)]
pub next_node_counter: u64,
/// How many hot ops this peer has authored, feeding `HotOp::sequence`. Persisted so a reopen
/// continues the run: a reused sequence would look like one already retired and be dropped.
#[serde(default)]
pub next_hot_sequence: u64,
/// Per-peer view settings (PTZ, rulers, overlays, snapping, panel collapse). Local to the viewer,
/// so kept out of the CRDT/history. Editor owns the keys/values (opaque `ui::doc::*` blobs).
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
@@ -43,4 +39,9 @@ pub struct SessionState {
/// Per-peer like [`view_settings`](Self::view_settings); opaque `ui::nav::*` / `ui::previewing` blobs.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub network_view_settings: BTreeMap<NetworkId, BTreeMap<String, serde_json::Value>>,
/// How many hot ops this peer has authored, feeding [`document_graph_storage::HotOp::sequence`]. A
/// reopen continues the run instead of reusing a spent sequence. Appended last: a positional codec
/// decodes these fields in declaration order.
#[serde(default)]
pub next_hot_sequence: HotSequence,
}
+6 -6
View File
@@ -5,7 +5,7 @@
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{Codec, Error, GddV1, GddV1Layout, Layout, Manifest, io, manifest};
use document_graph_storage::{HotOp, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp};
use document_graph_storage::{HotOp, HotSequence, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp};
fn empty_container() -> AnyContainer {
AnyContainer::Memory(MemoryBackend::new())
@@ -128,7 +128,7 @@ fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
sequence: 1,
sequence: HotSequence(1),
};
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
@@ -155,7 +155,7 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
sequence: 1,
sequence: HotSequence(1),
};
let late = HotOp {
op: RegistryDelta::AddNetwork {
@@ -163,7 +163,7 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 10, peer: PeerId(5) },
sequence: 2,
sequence: HotSequence(2),
};
gdd.apply_hot_op(early).unwrap();
gdd.apply_hot_op(late).unwrap();
@@ -203,7 +203,7 @@ fn last_broadcast_rev_persists_across_reopen() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
sequence: 1,
sequence: HotSequence(1),
};
gdd.apply_hot_op(op).unwrap();
let retired = gdd.retire(TimeStamp { counter: 1, peer: PeerId(5) }).unwrap_or_else(|error| panic!("retire failed: {error:?}"));
@@ -659,7 +659,7 @@ fn persist_path_writes_at_manifest_declared_codec_paths() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
sequence: 1,
sequence: HotSequence(1),
};
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
@@ -32,7 +32,6 @@ pub mod node {
pub mod session {
pub mod network {
pub const PREVIEWING: &str = "ui::previewing";
// TODO: Remove these graph ui nav-specific attributes
pub const NAV_PTZ: &str = "ui::nav::ptz";
pub const NAV_TRANSFORM: &str = "ui::nav::transform";
@@ -60,6 +59,11 @@ pub mod network {
/// serialized blob so its shape can evolve (e.g. dropping the `Type`) without a model change. The
/// node references use stable storage IDs, resolved back to runtime-local IDs on conversion.
pub const SCOPE_INJECTIONS: &str = "scope_injections";
/// Whole-vec LWW of the display order of the network's pinned nodes, as stable storage IDs.
/// Concurrent reorders do not merge, but the pinned set is already shared, and a shared set with
/// per-peer ordering would diverge with no way to reconcile.
pub const PINNED_ORDER: &str = "ui::pinned_order";
}
pub mod delta {
+24 -3
View File
@@ -1,4 +1,6 @@
use crate::{Attributes, AttributesWrite, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value, attr, compute_rev};
use crate::{
Attributes, AttributesWrite, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value, attr, compute_rev,
};
use graphene_resource::ResourceHash;
use serde::{Deserialize, Serialize};
@@ -92,7 +94,7 @@ impl Delta {
/// Op payload. Timestamps live on the wrapping `Delta` — one per delta, applied to all LWW-eligible
/// writes within. See `notes/document-format-collaboration.md`.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RegistryDelta {
AddNode {
id: NodeId,
@@ -109,6 +111,25 @@ pub enum RegistryDelta {
index: u32,
new_input: NodeInput,
},
/// A node's whole input list, for a change to the number or order of its slots that the
/// index-addressed `ChangeNodeInput` cannot express. Assigns rather than merging: concurrent
/// per-slot edits are lost, which is inherent to the indices themselves moving.
///
/// Touches only the inputs, leaving the node's attributes and implementation alone, so it composes
/// with attribute ops on the same node instead of reverting them.
SetNodeInputs {
id: NodeId,
inputs: Vec<InputSlot>,
},
/// A node's implementation, for swapping what it computes without rebuilding the node.
///
/// Removing and re-adding the node would express the same change, but would also clear every
/// attribute it carries, so restating them would clobber whatever a concurrent peer wrote to the
/// node's name, lock or pin.
SetNodeImplementation {
id: NodeId,
implementation: Implementation,
},
ChangeNodeAttribute {
id: NodeId,
delta: AttributeDelta,
@@ -190,7 +211,7 @@ pub enum RegistryDelta {
}
/// `value: None` means remove. The timestamp comes from the wrapping `Delta`.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AttributeDelta {
pub key: String,
pub value: Option<serde_json::Value>,
+79 -34
View File
@@ -1,6 +1,6 @@
use crate::{
CrdtError, Delta, ExportSlot, History, HotOp, HotOpId, LamportClock, MAX_EXPORT_SLOTS, NetworkId, NodeId, NodeInput, PeerId, Registry, RegistryDelta, ResourceEntry, RetiredMarks, Rev,
SourceValue, TimeStamp, apply_attribute_delta, reverse_attribute_delta,
CrdtError, Delta, ExportSlot, History, HotOp, HotOpId, HotSequence, LamportClock, MAX_EXPORT_SLOTS, NetworkId, NodeId, NodeInput, PeerId, Registry, RegistryDelta, ResourceEntry, RetiredHotOps,
Rev, SourceValue, TimeStamp, apply_attribute_delta, reverse_attribute_delta,
};
#[derive(Clone, Debug)]
@@ -11,10 +11,10 @@ pub struct Document {
/// Live broadcast stream, applied to the `working_registry` on receive, GC'd at retirement.
/// Persisted for crash recovery so in-flight unretired work survives editor restarts.
pub(crate) hot_log: Vec<HotOp>,
/// Which hot ops history already covers, so one that arrives after its own retirement is recognized
/// and dropped rather than re-entering the hot log for good. Retirement discards the link from a
/// delta back to the hot op it came from, so this is the only record of it. See [`RetiredMarks`].
pub(crate) retired: RetiredMarks,
/// Which hot ops history already covers, so one arriving after its own retirement is dropped instead
/// of re-entering the log. Retirement discards the delta's link back to its hot op, leaving this the
/// only record. See [`RetiredHotOps`].
pub(crate) retired: RetiredHotOps,
/// The registry as of the last retirement, with no un-retired hot ops applied. Retirement computes
/// each delta's `reverse` against this (so LWW reverses capture the true pre-op value, not the
/// hot-polluted working state) and advances it, stamping fields at the fresh `T_retire`. Kept equal
@@ -41,7 +41,10 @@ pub struct Document {
/// reading the same counter still produce distinct IDs.
pub(crate) next_node_counter: u64,
/// Counts this peer's own hot ops, so each carries its position in a gap-free run. See [`HotOp::sequence`].
pub(crate) next_hot_sequence: u64,
pub(crate) next_hot_sequence: HotSequence,
/// Set while the registries are still folded from an older history. A failed refold is retried; the
/// derived state does not stay behind the history it comes from.
pub(crate) refold_owed: bool,
}
impl Document {
@@ -72,12 +75,8 @@ impl Document {
self.revert_delta(target, delta)
}
/// The last delta in canonical history order matching `predicate`, among those reachable from `head`
/// or any history tip (following all parents, including a merge's `extra_parents`). Tips cover deltas
/// absorbed mid-merge that `head` doesn't reach yet.
///
/// Resurrection reads the removed entity out of the match, so every peer has to pick the same one.
/// Canonical order is agreed; a walk from `head` is not, since peers sit on different merge revs.
/// The last match in canonical history order, over everything reachable from `head` or any tip. Not a
/// walk from `head`: peers sit on different merge revs, and resurrection must pick the same delta.
fn find_in_ancestry(&self, predicate: impl Fn(&Delta) -> bool) -> Option<Delta> {
let reachable = self.history.ancestors(self.head.into_iter().chain(self.history.tips()));
@@ -97,9 +96,10 @@ impl Document {
self.apply_op_with(target, delta.kind, delta.timestamp, ApplyMode::Force)
}
/// Apply a live broadcast op. Updates the registry via LWW and appends to the hot log.
/// Doesn't touch history or `head` — hot ops are transient.
pub fn apply_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
/// Apply a locally staged op: LWW into the registry, append to the hot log, leave history and `head`
/// alone. Crate-private because it skips the retirement check an op off the wire needs; staging must
/// not have a covered sequence silently drop local work. Outside callers use [`Session::apply_hot_op`].
pub(crate) fn apply_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
self.apply_op(hot_op.op.clone(), hot_op.timestamp)?;
self.hot_log.push(hot_op);
Ok(())
@@ -109,19 +109,17 @@ impl Document {
/// re-applying an op whose effect is already reflected in the registry is a no-op rather
/// than an error.
pub fn replay_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
// Its effect is already in retired history, and re-adding it would leave an entry no retirement
// list will ever name.
// Already in retired history; re-adding it would leave an entry no retirement will ever name.
if self.is_retired(hot_op.id()) {
return Ok(());
}
// A hot op is identified by its timestamp, so a re-announcement of one already held is a no-op
// rather than a second copy that replays and re-broadcasts as though it were new work.
// Identified by timestamp, so a re-announcement of one already held must not become a second copy.
if self.hot_log.iter().any(|held| held.timestamp == hot_op.timestamp) {
return Ok(());
}
// Replaying our own persisted ops after a reload is what restores the sequence counter.
// Replaying our own ops is what carries the sequence counter across a reload.
if hot_op.timestamp.peer == self.peer {
self.next_hot_sequence = self.next_hot_sequence.max(hot_op.sequence);
}
@@ -143,19 +141,21 @@ impl Document {
self.drop_retired_hot_ops();
}
/// Take on another peer's retirement marks as well as this peer's.
pub(crate) fn absorb_retired(&mut self, remote: &RetiredMarks) {
/// Take on a peer's retirement marks as well as this peer's. Returns whether a hot op was dropped,
/// which owes the caller a refold.
pub(crate) fn absorb_retired(&mut self, remote: &RetiredHotOps) -> bool {
self.retired.absorb(remote);
self.drop_retired_hot_ops();
self.drop_retired_hot_ops()
}
/// Drop hot ops history already covers, so a retired op never sits in the hot log whatever path
/// put it there.
fn drop_retired_hot_ops(&mut self) {
let retired = std::mem::take(&mut self.retired);
self.hot_log.retain(|hot_op| !retired.covers(hot_op.id()));
self.retired = retired;
/// Drop hot ops the retired snapshot already accounts for. A mark alone will not do: it can arrive
/// ahead of the delta carrying the op into history, stranding its effect in the working registry.
fn drop_retired_hot_ops(&mut self) -> bool {
let before = self.hot_log.len();
self.hot_log.retain(|hot_op| !self.history.contains_timestamp(hot_op.timestamp));
before != self.hot_log.len()
}
/// Apply a retired commit. Idempotent on structural ops (AddNode/AddNetwork on existing
@@ -236,6 +236,18 @@ impl Document {
RegistryDelta::RemoveNode { id, .. } => {
registry.node_instances.remove(&id);
}
RegistryDelta::SetNodeInputs { id, inputs } => {
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
// The list is one value rather than independently mergeable slots, so the newest slot stands in
// for a timestamp the list itself does not carry, and an older write is dropped whole.
let newest = node.inputs.iter().map(|slot| slot.timestamp).max().unwrap_or(TimeStamp::ORIGIN);
if force || timestamp > newest {
// The slots arrive carrying the placeholder timestamp they were built with, so they take this
// op's instead. Leaving the placeholder would reset every slot to the origin and make each
// later per-slot gate vacuously true, letting a stale write win.
node.inputs = inputs.into_iter().map(|slot| crate::InputSlot { timestamp, ..slot }).collect();
}
}
RegistryDelta::ChangeNodeInput { id, index, new_input } => {
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
let input = node.inputs.get_mut(index as usize).ok_or(CrdtError::InputIndexOutOfBounds(index as usize))?;
@@ -244,6 +256,13 @@ impl Document {
input.timestamp = timestamp;
}
}
RegistryDelta::SetNodeImplementation { id, implementation } => {
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
if force || timestamp > node.implementation_timestamp {
node.implementation = implementation;
node.implementation_timestamp = timestamp;
}
}
RegistryDelta::ChangeNodeAttribute { id, delta } => {
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
apply_attribute_delta(delta, timestamp, force, &mut node.attributes);
@@ -347,6 +366,20 @@ impl Document {
}
self.ensure_node_exists(target, *id)?;
}
RegistryDelta::SetNodeInputs { id, inputs } => {
for slot in inputs {
if let NodeInput::Node { id: referenced, .. } = slot.input {
self.ensure_node_exists(target, referenced)?;
}
}
self.ensure_node_exists(target, *id)?;
}
RegistryDelta::SetNodeImplementation { id, implementation } => {
if let crate::Implementation::Network(network) = implementation {
self.ensure_network_exists(target, *network)?;
}
self.ensure_node_exists(target, *id)?;
}
RegistryDelta::ChangeNodeAttribute { id, .. } | RegistryDelta::ChangeNodeInputAttribute { id, .. } => self.ensure_node_exists(target, *id)?,
RegistryDelta::SetNetworkExport {
id: network, export: export_target, ..
@@ -373,12 +406,13 @@ impl Document {
}
}
/// The most recent hot removal of a network, for reviving it in the working zone. Returns `None`
/// for the snapshot, which must stay a function of history alone.
/// The most recent hot removal of a network, for reviving it in the working zone. `None` for the
/// snapshot, which stays a function of history alone.
fn hot_log_removal(&self, target: RegistryTarget, network_id: NetworkId) -> Option<(RegistryDelta, TimeStamp)> {
if target != RegistryTarget::Working {
return None;
}
self.hot_log.iter().rev().find_map(|hot_op| match &hot_op.op {
RegistryDelta::RemoveNetwork { id, snapshot } if *id == network_id => Some((RegistryDelta::AddNetwork { id: *id, network: snapshot.clone() }, hot_op.timestamp)),
_ => None,
@@ -390,6 +424,7 @@ impl Document {
if target != RegistryTarget::Working {
return None;
}
self.hot_log.iter().rev().find_map(|hot_op| match &hot_op.op {
RegistryDelta::RemoveNode { id, snapshot } if *id == node_id => Some((RegistryDelta::AddNode { id: *id, node: snapshot.clone() }, hot_op.timestamp)),
_ => None,
@@ -400,8 +435,7 @@ impl Document {
if self.registry_ref(target).networks.contains_key(&network_id) {
return Ok(());
}
// The hot log is this peer's own, so reviving the snapshot zone from it would make the retired
// state depend on which hot ops happened to be here. Only history is shared.
// The hot log is peer-local, so reviving retired state from it would make it peer-dependent.
let removal = self.hot_log_removal(target, network_id);
match removal {
Some((revive, timestamp)) => self.apply_op_with(target, revive, timestamp, ApplyMode::Force),
@@ -417,6 +451,17 @@ impl Document {
Ok(match delta {
RegistryDelta::AddNode { id, node } => RegistryDelta::RemoveNode { id: *id, snapshot: node.clone() },
RegistryDelta::RemoveNode { id, snapshot } => RegistryDelta::AddNode { id: *id, node: snapshot.clone() },
&RegistryDelta::SetNodeInputs { id, .. } => {
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
RegistryDelta::SetNodeInputs { id, inputs: node.inputs.clone() }
}
&RegistryDelta::SetNodeImplementation { id, .. } => {
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
RegistryDelta::SetNodeImplementation {
id,
implementation: node.implementation.clone(),
}
}
&RegistryDelta::ChangeNodeInput { id, index: input_idx, .. } => {
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
let slot = node.inputs().get(input_idx as usize).ok_or(CrdtError::InputIndexOutOfBounds(input_idx as usize))?;
+331 -38
View File
@@ -60,6 +60,34 @@ impl NodePath {
}
}
/// Resolves a node's storage identity: the identity the metadata source holds for it where there is
/// one, and a hash of its location otherwise. Every place a node is named goes through here, so a
/// node's own registry key and every reference to it agree.
///
/// A held identity travels with the node, so moving it between networks keeps it. A hashed one is
/// derived from the node's place in the tree, so it changes when the node moves; it stands in for a
/// node no source names, such as one in a network that has never been stored.
pub(crate) struct NodeIds<'a, M: NodeMetadataSource + ?Sized> {
pub(crate) metadata: Option<&'a M>,
pub(crate) metadata_path: &'a [RuntimeNodeId],
pub(crate) peer: PeerId,
}
impl<M: NodeMetadataSource + ?Sized> Clone for NodeIds<'_, M> {
fn clone(&self) -> Self {
*self
}
}
impl<M: NodeMetadataSource + ?Sized> Copy for NodeIds<'_, M> {}
impl<M: NodeMetadataSource + ?Sized> NodeIds<'_, M> {
fn resolve(&self, path: &NodePath, local_id: RuntimeNodeId) -> NodeId {
self.metadata
.and_then(|metadata| metadata.storage_node_id(self.metadata_path, local_id))
.unwrap_or_else(|| path.to_global_id(self.peer))
}
}
#[derive(Debug, thiserror::Error)]
pub enum ConversionError {
#[error("Failed to serialize value: {0}")]
@@ -168,33 +196,40 @@ fn convert_resources(resources: &graphene_resource::ResourceRegistry, referenced
if !referenced.contains(&id) {
continue;
}
let Some(info) = resources.info(&id) else { continue };
let mut entry = crate::ResourceEntry {
hash: info.hash.copied(),
hash_timestamp: TimeStamp::ORIGIN,
..Default::default()
};
for (position, source) in info.sources.iter().enumerate() {
let key = crate::SourceKey {
priority: crate::Priority::new(position as f64).expect("enumerate index is finite"),
peer,
};
let body = serde_json::to_value(source).map_err(|error| ConversionError::SerializationError(error.to_string()))?;
entry.set_source(
key,
crate::SourceValue {
source: body,
timestamp: TimeStamp::ORIGIN,
},
);
if let Some(entry) = convert_resource_entry(resources, id, peer)? {
registry.resources.insert(id, entry);
}
registry.resources.insert(id, entry);
}
Ok(())
}
/// Snapshot one runtime resource into a storage entry, or `None` if the runtime has no such resource.
pub fn convert_resource_entry(resources: &graphene_resource::ResourceRegistry, id: ResourceId, peer: PeerId) -> Result<Option<crate::ResourceEntry>, ConversionError> {
let Some(info) = resources.info(&id) else { return Ok(None) };
let mut entry = crate::ResourceEntry {
hash: info.hash.copied(),
hash_timestamp: TimeStamp::ORIGIN,
..Default::default()
};
for (position, source) in info.sources.iter().enumerate() {
let key = crate::SourceKey {
priority: crate::Priority::new(position as f64).expect("enumerate index is finite"),
peer,
};
let body = serde_json::to_value(source).map_err(|error| ConversionError::SerializationError(error.to_string()))?;
entry.set_source(
key,
crate::SourceValue {
source: body,
timestamp: TimeStamp::ORIGIN,
},
);
}
Ok(Some(entry))
}
/// Collect the `ResourceId`s referenced by `TaggedValue::Resource` inputs anywhere in the network
/// (recursively through nested networks). These are the resources the document actually uses; the
/// runtime cache may hold more (history-retained orphans) that shouldn't be snapshotted into storage.
@@ -249,6 +284,20 @@ struct ConversionContext<'m, M: NodeMetadataSource + ?Sized> {
peer: PeerId,
}
impl<'m, M: NodeMetadataSource + ?Sized> ConversionContext<'m, M> {
/// The identity resolver for nodes addressed inside the network at `metadata_path`.
fn ids<'a>(&self, metadata_path: &'a [RuntimeNodeId]) -> NodeIds<'a, M>
where
'm: 'a,
{
NodeIds {
metadata: Some(self.metadata),
metadata_path,
peer: self.peer,
}
}
}
fn convert_network<M: NodeMetadataSource + ?Sized>(
node_network: &NodeNetwork,
network_id: NetworkId,
@@ -259,7 +308,7 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
) -> Result<(), ConversionError> {
for (runtime_node_id, doc_node) in &node_network.nodes {
let node_path = child_path(parent_path, network_id, *runtime_node_id);
let global_id = node_path.to_global_id(ctx.peer);
let global_id = ctx.ids(metadata_path).resolve(&node_path, *runtime_node_id);
let location = NodeLocation {
network_id,
@@ -267,7 +316,7 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
metadata_path,
runtime_node_id: *runtime_node_id,
};
let mut node = convert_node(doc_node, location, registry, ctx)?;
let mut node = convert_node(doc_node, location, registry, ctx, true)?;
node.attributes.set(node::ORIGINAL_NODE_ID, serde_json::json!(runtime_node_id.0), TimeStamp::ORIGIN);
registry.node_instances.insert(global_id, node);
}
@@ -277,15 +326,15 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
.iter()
.map(|export| {
Ok(ExportSlot {
target: Some(convert_input(export, parent_path, network_id, ctx.peer)?),
target: Some(convert_input(export, parent_path, network_id, ctx.ids(metadata_path))?),
timestamp: TimeStamp::ORIGIN,
})
})
.collect::<Result<Vec<_>, ConversionError>>()?;
let mut attributes = crate::Attributes::new();
write_ui_network_attributes(&mut attributes, ctx.metadata, metadata_path, TimeStamp::ORIGIN)?;
write_scope_injections(&mut attributes, node_network, parent_path, network_id, ctx.peer, TimeStamp::ORIGIN)?;
write_ui_network_attributes(&mut attributes, node_network, metadata_path, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
write_scope_injections(&mut attributes, node_network, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
registry.networks.insert(network_id, Network { exports, attributes });
ctx.network_ids.insert(metadata_path.to_vec(), network_id);
@@ -296,12 +345,12 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
/// Serialize a network's `scope_injections` onto its attributes as one whole-map LWW blob, remapping
/// each runtime-local node reference to its stable storage global ID so the reference survives a
/// round trip even if runtime IDs are later reshuffled.
fn write_scope_injections(
fn write_scope_injections<M: NodeMetadataSource + ?Sized>(
attributes: &mut crate::Attributes,
node_network: &NodeNetwork,
parent_path: Option<&NodePath>,
network_id: NetworkId,
peer: PeerId,
ids: NodeIds<'_, M>,
timestamp: TimeStamp,
) -> Result<(), ConversionError> {
if node_network.scope_injections.is_empty() {
@@ -312,7 +361,7 @@ fn write_scope_injections(
.scope_injections
.iter()
.map(|(key, (runtime_id, ty))| {
let storage_id = child_path(parent_path, network_id, *runtime_id).to_global_id(peer);
let storage_id = ids.resolve(&child_path(parent_path, network_id, *runtime_id), *runtime_id);
(key.clone(), (storage_id, ty.clone()))
})
.collect();
@@ -339,7 +388,13 @@ struct NodeLocation<'a> {
runtime_node_id: RuntimeNodeId,
}
fn convert_node<M: NodeMetadataSource + ?Sized>(doc_node: &DocumentNode, location: NodeLocation<'_>, registry: &mut Registry, ctx: &mut ConversionContext<'_, M>) -> Result<Node, ConversionError> {
fn convert_node<M: NodeMetadataSource + ?Sized>(
doc_node: &DocumentNode,
location: NodeLocation<'_>,
registry: &mut Registry,
ctx: &mut ConversionContext<'_, M>,
recurse: bool,
) -> Result<Node, ConversionError> {
let NodeLocation {
network_id,
parent_path,
@@ -356,7 +411,7 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(doc_node: &DocumentNode, locatio
write_ui_input_attributes(&mut input_attrs, ctx.metadata, metadata_path, runtime_node_id, input_index, timestamp)?;
inputs.push(InputSlot {
input: convert_input(input, parent_path, network_id, ctx.peer)?,
input: convert_input(input, parent_path, network_id, ctx.ids(metadata_path))?,
timestamp,
attributes: input_attrs,
});
@@ -371,7 +426,7 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(doc_node: &DocumentNode, locatio
} else {
metadata_path
};
let implementation = convert_implementation(&doc_node.implementation, &node_path, child_metadata_path, registry, ctx)?;
let implementation = convert_implementation(&doc_node.implementation, &node_path, child_metadata_path, registry, ctx, recurse)?;
// Defaults match `DocumentNode::default()`; `to_runtime` rehydrates absent keys from the same defaults.
let mut attributes = crate::Attributes::new();
@@ -392,12 +447,57 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(doc_node: &DocumentNode, locatio
Ok(Node {
implementation,
implementation_timestamp: timestamp,
inputs,
attributes,
network: network_id,
})
}
/// The `call_argument` attribute write for a node, cleared when the value is the default that
/// `to_runtime` rehydrates an absent key from. For staging paths that encode this field alone.
pub fn encode_call_argument(call_argument: &core_types::Type) -> Result<crate::AttributeDelta, ConversionError> {
encode_if_not_default(node::CALL_ARGUMENT, call_argument, &concrete!(Context))
}
/// The `context_features` attribute write, cleared at its default like [`encode_call_argument`].
pub fn encode_context_features(context_features: &ContextDependencies) -> Result<crate::AttributeDelta, ConversionError> {
encode_if_not_default(node::CONTEXT_FEATURES, context_features, &ContextDependencies::default())
}
fn encode_if_not_default<T: Serialize + PartialEq>(key: &str, value: &T, default: &T) -> Result<crate::AttributeDelta, ConversionError> {
let value = if value == default {
None
} else {
Some(serde_json::to_value(value).map_err(map_serialization_error(key))?)
};
Ok(crate::AttributeDelta { key: key.to_string(), value })
}
/// Public form of the node ui-attribute encoding, for staging paths that encode single nodes.
pub fn encode_node_ui_attributes<M: NodeMetadataSource + ?Sized>(
attributes: &mut crate::Attributes,
metadata: &M,
metadata_path: &[RuntimeNodeId],
runtime_node_id: RuntimeNodeId,
timestamp: TimeStamp,
) -> Result<(), ConversionError> {
write_ui_attributes(attributes, metadata, metadata_path, runtime_node_id, timestamp)
}
/// Public form of the per-input ui-attribute encoding, matching `encode_node_ui_attributes`.
pub fn encode_input_ui_attributes<M: NodeMetadataSource + ?Sized>(
attributes: &mut crate::Attributes,
metadata: &M,
metadata_path: &[RuntimeNodeId],
runtime_node_id: RuntimeNodeId,
input_index: usize,
timestamp: TimeStamp,
) -> Result<(), ConversionError> {
write_ui_input_attributes(attributes, metadata, metadata_path, runtime_node_id, input_index, timestamp)
}
fn write_ui_attributes<M: NodeMetadataSource + ?Sized>(
attributes: &mut crate::Attributes,
metadata: &M,
@@ -439,11 +539,36 @@ fn write_ui_attributes<M: NodeMetadataSource + ?Sized>(
Ok(())
}
fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(attributes: &mut crate::Attributes, metadata: &M, network_path: &[RuntimeNodeId], timestamp: TimeStamp) -> Result<(), ConversionError> {
/// Node references here are remapped to stable storage IDs for the same reason `write_scope_injections`
/// does it: a runtime ID is not stable across a round trip.
fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(
attributes: &mut crate::Attributes,
node_network: &NodeNetwork,
network_path: &[RuntimeNodeId],
parent_path: Option<&NodePath>,
network_id: NetworkId,
ids: NodeIds<'_, M>,
timestamp: TimeStamp,
) -> Result<(), ConversionError> {
// The same source the IDs resolve through, so a network's attributes and the nodes they name agree.
let Some(metadata) = ids.metadata else { return Ok(()) };
if let Some(reference) = metadata.reference(network_path) {
attributes.set(node::ui::REFERENCE, serde_json::Value::String(reference.to_string()), timestamp);
}
let to_storage_id = |runtime_id: RuntimeNodeId| ids.resolve(&child_path(parent_path, network_id, runtime_id), runtime_id);
// Only nodes the converted network still holds: the read side drops a stored ID it cannot find, so
// persisting one for a node deleted or reparented elsewhere would leave stored state disagreeing with
// what a peer converting the same input produces.
let pinned_order: Vec<_> = metadata.pinned_order(network_path).into_iter().filter(|pinned| node_network.nodes.contains_key(pinned)).collect();
if !pinned_order.is_empty() {
let stored: Vec<NodeId> = pinned_order.into_iter().map(to_storage_id).collect();
attributes
.set_serialized(network::PINNED_ORDER, &stored, timestamp)
.map_err(map_serialization_error(network::PINNED_ORDER))?;
}
Ok(())
}
@@ -474,10 +599,10 @@ fn write_ui_input_attributes<M: NodeMetadataSource + ?Sized>(
Ok(())
}
fn convert_input(input: &GraphCraftNodeInput, parent_path: Option<&NodePath>, network_id: NetworkId, peer: PeerId) -> Result<NodeInput, ConversionError> {
fn convert_input<M: NodeMetadataSource + ?Sized>(input: &GraphCraftNodeInput, parent_path: Option<&NodePath>, network_id: NetworkId, ids: NodeIds<'_, M>) -> Result<NodeInput, ConversionError> {
Ok(match input {
GraphCraftNodeInput::Node { node_id, output_index } => NodeInput::Node {
id: child_path(parent_path, network_id, *node_id).to_global_id(peer),
id: ids.resolve(&child_path(parent_path, network_id, *node_id), *node_id),
index: (*output_index).try_into().map_err(|_| ConversionError::IndexOverflow(*output_index))?,
},
GraphCraftNodeInput::Value { tagged_value, exposed } => {
@@ -494,7 +619,9 @@ fn convert_input(input: &GraphCraftNodeInput, parent_path: Option<&NodePath>, ne
})
}
fn convert_input_attributes(input: &GraphCraftNodeInput) -> Result<crate::Attributes, ConversionError> {
/// The non-ui attributes a slot carries, derived from the input itself: the declared type of an
/// import, and a reflection node's metadata.
pub fn convert_input_attributes(input: &GraphCraftNodeInput) -> Result<crate::Attributes, ConversionError> {
let mut attributes = crate::Attributes::new();
let timestamp = TimeStamp::ORIGIN;
@@ -521,6 +648,7 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
child_metadata_path: &[RuntimeNodeId],
registry: &mut Registry,
ctx: &mut ConversionContext<'_, M>,
recurse: bool,
) -> Result<Implementation, ConversionError> {
Ok(match implementation {
DocumentNodeImplementation::ProtoNode(identifier) => {
@@ -553,10 +681,175 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
// `to_runtime` -> `from_runtime` round trip reproduces the same `NetworkId` (and thus the
// same node-path hashes underneath it).
let nested_network_id = current_node_path.owned_network_id(ctx.peer);
convert_network(nested_network, nested_network_id, Some(current_node_path), child_metadata_path, registry, ctx)?;
if recurse {
convert_network(nested_network, nested_network_id, Some(current_node_path), child_metadata_path, registry, ctx)?;
}
Implementation::Network(nested_network_id)
}
// TODO: Support Extract in the Registry format.
DocumentNodeImplementation::Extract => return Err(ConversionError::UnsupportedImplementation),
})
}
/// Derives the storage IDs for entities addressed by runtime network paths, resolving each through
/// the same [`NodeIds`] a whole-document conversion uses so scoped and whole-document conversions agree.
pub struct PathResolver<'m> {
metadata: Option<&'m dyn NodeMetadataSource>,
peer: PeerId,
}
impl<'m> PathResolver<'m> {
/// Without a metadata source every node falls back to a hash of its location, which only matches a
/// whole-document conversion while no node has a stored identity.
pub fn new(metadata: Option<&'m dyn NodeMetadataSource>, peer: PeerId) -> Self {
Self { metadata, peer }
}
/// The storage `NetworkId` of the network at `local_path` (`ROOT_NETWORK` for the empty path).
pub fn network_id(&self, local_path: &[RuntimeNodeId]) -> NetworkId {
match self.owner_path(local_path) {
None => ROOT_NETWORK,
Some(owner) => owner.owned_network_id(self.peer),
}
}
/// The storage `NodeId` of the node with `local_id` inside the network at `local_path`.
pub fn node_id(&self, local_path: &[RuntimeNodeId], local_id: RuntimeNodeId) -> NodeId {
let owner = self.owner_path(local_path);
self.ids(local_path).resolve(&child_path(owner.as_ref(), self.network_id(local_path), local_id), local_id)
}
/// Converts one runtime input inside the network at `local_path` to its storage form, resolving
/// node references to their storage IDs.
pub fn convert_input_at(&self, input: &GraphCraftNodeInput, local_path: &[RuntimeNodeId]) -> Result<NodeInput, ConversionError> {
let owner = self.owner_path(local_path);
convert_input(input, owner.as_ref(), self.network_id(local_path), self.ids(local_path))
}
/// The identity resolver for nodes addressed inside the network at `local_path`.
fn ids<'a>(&self, local_path: &'a [RuntimeNodeId]) -> NodeIds<'a, dyn NodeMetadataSource + 'm>
where
'm: 'a,
{
NodeIds {
metadata: self.metadata,
metadata_path: local_path,
peer: self.peer,
}
}
/// The `NodePath` of the node owning the network at `local_path`, or `None` for the root network.
fn owner_path(&self, local_path: &[RuntimeNodeId]) -> Option<NodePath> {
let mut owner: Option<NodePath> = None;
for &local_id in local_path {
let network_id = match &owner {
None => ROOT_NETWORK,
Some(owner) => owner.owned_network_id(self.peer),
};
owner = Some(child_path(owner.as_ref(), network_id, local_id));
}
owner
}
}
/// Converts a chosen subset of runtime entities into a scratch [`Registry`] through the same
/// encoders as a whole-document conversion, so staging can derive deltas for just those entities.
pub struct ScopedConversion<'m> {
ctx: ConversionContext<'m, dyn NodeMetadataSource + 'm>,
resolver: PathResolver<'m>,
}
impl<'m> ScopedConversion<'m> {
pub fn new(metadata: &'m dyn NodeMetadataSource, peer: PeerId) -> Self {
Self {
ctx: ConversionContext {
declaration_ids: HashMap::new(),
declaration_bytes: HashMap::new(),
declarations: HashMap::new(),
network_ids: HashMap::new(),
metadata,
peer,
},
resolver: PathResolver::new(Some(metadata), peer),
}
}
/// Converts the node with `local_id` in the network at `local_path` into `registry` under its
/// stable IDs. `recurse` also converts the contents of any nested network the node implements;
/// without it only the node itself is converted, with its nested network referenced by ID.
pub fn convert_node_at(&mut self, registry: &mut Registry, local_path: &[RuntimeNodeId], local_id: RuntimeNodeId, doc_node: &DocumentNode, recurse: bool) -> Result<(), ConversionError> {
let owner_path = self.resolver.owner_path(local_path);
let location = NodeLocation {
network_id: self.resolver.network_id(local_path),
parent_path: owner_path.as_ref(),
metadata_path: local_path,
runtime_node_id: local_id,
};
let mut node = convert_node(doc_node, location, registry, &mut self.ctx, recurse)?;
node.attributes.set(node::ORIGINAL_NODE_ID, serde_json::json!(local_id.0), TimeStamp::ORIGIN);
registry.node_instances.insert(self.resolver.node_id(local_path, local_id), node);
Ok(())
}
/// Converts the entry of the network at `local_path` (its export slots and network-level
/// attributes, not its nodes) into `registry`.
pub fn convert_network_entry_at(&mut self, registry: &mut Registry, local_path: &[RuntimeNodeId], node_network: &NodeNetwork) -> Result<(), ConversionError> {
let owner_path = self.resolver.owner_path(local_path);
let network_id = self.resolver.network_id(local_path);
let exports = node_network
.exports
.iter()
.map(|export| {
Ok(ExportSlot {
target: Some(convert_input(export, owner_path.as_ref(), network_id, self.ctx.ids(local_path))?),
timestamp: TimeStamp::ORIGIN,
})
})
.collect::<Result<Vec<_>, ConversionError>>()?;
let mut attributes = crate::Attributes::new();
write_ui_network_attributes(&mut attributes, node_network, local_path, owner_path.as_ref(), network_id, self.ctx.ids(local_path), TimeStamp::ORIGIN)?;
write_scope_injections(&mut attributes, node_network, owner_path.as_ref(), network_id, self.ctx.ids(local_path), TimeStamp::ORIGIN)?;
registry.networks.insert(network_id, Network { exports, attributes });
Ok(())
}
/// The extracted proto-node declarations: the bytes for the caller's byte store, and the same
/// declarations decoded for its declaration cache.
pub fn finish(self) -> (DeclarationBytes, crate::Declarations) {
(self.ctx.declaration_bytes, self.ctx.declarations)
}
}
/// The `TaggedValue::Resource` IDs referenced by a stored node's value inputs.
///
/// Peeks at the externally-tagged serde shape (`{"Resource": <id>}`) rather than deserializing the
/// whole `TaggedValue`, which can be arbitrarily large. `resource_ref_shape_matches_serde` asserts
/// this stays in lockstep with the real serialization.
pub fn node_value_resource_refs(node: &Node) -> impl Iterator<Item = ResourceId> + '_ {
node.inputs.iter().filter_map(|slot| value_resource_ref(&slot.input))
}
/// The `TaggedValue::Resource` ID referenced by a stored value input, if any.
pub fn value_resource_ref(input: &NodeInput) -> Option<ResourceId> {
match input {
NodeInput::Value { value, .. } => value.get("Resource").and_then(|id| serde_json::from_value(id.clone()).ok()),
_ => None,
}
}
#[cfg(test)]
mod resource_ref_shape {
use super::*;
#[test]
fn resource_ref_shape_matches_serde() {
let id = ResourceId::from_hash(&ResourceHash::from(b"shape test".as_slice()));
let value = serde_json::to_value(TaggedValue::Resource(id)).expect("TaggedValue::Resource serializes");
let parsed: Option<ResourceId> = value.get("Resource").and_then(|inner| serde_json::from_value(inner.clone()).ok());
assert_eq!(parsed, Some(id), "The shape peek in node_value_resource_refs must match TaggedValue's serde form");
}
}
+7 -3
View File
@@ -39,6 +39,11 @@ impl History {
self.index.contains_key(&rev)
}
/// Whether history holds a delta authored at `timestamp`.
pub fn contains_timestamp(&self, timestamp: TimeStamp) -> bool {
self.deltas.iter().any(|delta| delta.timestamp == timestamp)
}
pub fn len(&self) -> usize {
self.deltas.len()
}
@@ -67,9 +72,8 @@ impl History {
/// Re-order `deltas` into the canonical topological order and rebuild the index: parents precede
/// children, and among deltas whose parents are all emitted the lowest `Rev` goes first. O(V + E).
///
/// The sort is deterministic, so two peers that absorb the same delta set produce byte-identical
/// history, not merely two different valid orderings. This is the history-convergence mechanism:
/// arrival order is erased.
/// Deterministic: two peers that absorb the same delta set end up with byte-identical history, not two
/// different valid orderings. Arrival order is erased.
pub fn canonical_sort(&mut self) {
// Unsatisfied in-history parent count per delta, plus reverse edges to decrement as parents emit.
let mut pending_parents: HashMap<Rev, usize> = HashMap::with_capacity(self.deltas.len());
+4 -1
View File
@@ -29,7 +29,10 @@ pub use resources::*;
pub use session::*;
#[cfg(any(feature = "conversion", test))]
pub use from_runtime::{RuntimeConversion, decode_declaration, encode_declaration};
pub use from_runtime::{
PathResolver, RuntimeConversion, ScopedConversion, convert_input_attributes, convert_resource_entry, decode_declaration, encode_declaration, encode_input_ui_attributes, encode_node_ui_attributes,
node_value_resource_refs, value_resource_ref,
};
#[cfg(any(feature = "conversion", test))]
pub use metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NoMetadata, NodeMetadataEntry, NodeMetadataSource, Position};
#[cfg(any(feature = "conversion", test))]
+22 -28
View File
@@ -8,11 +8,15 @@ use std::collections::HashMap;
use core_types::uuid::NodeId as RuntimeNodeId;
/// One node's editor-side metadata, produced by `Registry::to_runtime_with_metadata`.
/// One node's editor-side metadata, produced by `Registry::to_runtime_with_metadata`. One entry per
/// node, since every node carries an identity to restore even when it carries no `ui::*` attribute.
#[derive(Clone, Debug, PartialEq)]
pub struct NodeMetadataEntry {
pub network_path: Vec<RuntimeNodeId>,
pub local_id: RuntimeNodeId,
/// The node's storage identity. Restoring it pins the node to this identity, so a later conversion
/// keeps it instead of re-deriving one from the node's location.
pub storage_id: crate::NodeId,
pub position: Option<Position>,
pub is_layer: bool,
pub display_name: Option<String>,
@@ -24,19 +28,7 @@ pub struct NodeMetadataEntry {
pub output_names: Vec<String>,
}
impl NodeMetadataEntry {
pub fn is_empty(&self) -> bool {
self.position.is_none()
&& !self.is_layer
&& self.display_name.is_none()
&& !self.locked
&& !self.pinned
&& self.output_names.is_empty()
&& self.input_metadata.iter().all(InputMetadataEntry::is_empty)
}
}
/// Per-network metadata (navigation, previewing). Separate from `NodeMetadataEntry` since these are
/// Per-network metadata. Separate from `NodeMetadataEntry` since these are
/// properties of a network, not of any node.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct NetworkMetadataEntry {
@@ -44,16 +36,12 @@ pub struct NetworkMetadataEntry {
/// Empty = root network.
pub network_path: Vec<RuntimeNodeId>,
/// Stable storage id of this network. Lets the editor associate per-network, per-peer view state
/// (node-graph nav + previewing, in `session.json`) with a network across reparenting.
/// (the node-graph nav, in `session.json`) with a network across reparenting.
pub network_id: crate::NetworkId,
/// Matches the runtime's `NodeNetworkPersistentMetadata::reference` — definition lineage tag.
/// Matches the runtime's `NodeNetworkPersistentMetadata::reference`: the definition lineage tag.
pub reference: Option<String>,
}
impl NetworkMetadataEntry {
pub fn is_empty(&self) -> bool {
self.reference.is_none()
}
/// The display order of the network's pinned nodes.
pub pinned_order: Vec<RuntimeNodeId>,
}
/// Per-input editor metadata. Mirrors `InputPersistentMetadata` but wraps strings in `Option` so
@@ -67,12 +55,6 @@ pub struct InputMetadataEntry {
pub input_data: HashMap<String, serde_json::Value>,
}
impl InputMetadataEntry {
pub fn is_empty(&self) -> bool {
self.input_name.is_none() && self.input_description.is_none() && self.widget_override.is_none() && self.input_data.is_empty()
}
}
/// Editor-side metadata source. Methods default to "no data" so implementors only override what
/// they carry. Returns are JSON-shaped where the underlying types live editor-side (PTZ, etc.).
pub trait NodeMetadataSource {
@@ -110,9 +92,21 @@ pub trait NodeMetadataSource {
HashMap::new()
}
/// The storage identity this node is pinned to, if it has one. A node the source does not name
/// falls back to a hash of its location.
fn storage_node_id(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId) -> Option<crate::NodeId> {
None
}
/// The definition the network was instantiated from, if it still names one.
fn reference(&self, _network_path: &[RuntimeNodeId]) -> Option<&str> {
None
}
/// The display order of the network's pinned nodes.
fn pinned_order(&self, _network_path: &[RuntimeNodeId]) -> Vec<RuntimeNodeId> {
Vec::new()
}
}
/// No-op metadata source. Use when there's nothing to attach (synthetic networks, CLI tools).
+22 -1
View File
@@ -5,6 +5,10 @@ use std::borrow::Cow;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Node {
pub(crate) implementation: Implementation,
/// When the implementation was last written, so a swap resolves by last-writer-wins rather than by
/// the order ops happen to arrive in. Absent from documents written before swaps were expressible.
#[serde(default)]
pub(crate) implementation_timestamp: TimeStamp,
pub(crate) inputs: Vec<InputSlot>,
pub(crate) attributes: Attributes,
pub(crate) network: NetworkId,
@@ -47,9 +51,11 @@ impl Node {
/// `ChangeNodeInput`. The slot count is fixed at creation, since changing an input addresses a
/// slot by position.
pub fn new(network: NetworkId, implementation: Implementation, inputs: usize) -> Self {
// `to_runtime` reads this back as a `TaggedValue`, whose unit `None` variant encodes as this string.
// Pinned by `unset_input_slot_deserializes_as_tagged_value_none`.
let slot = InputSlot {
input: NodeInput::Value {
value: serde_json::Value::Null,
value: serde_json::Value::String("None".to_string()),
exposed: false,
},
timestamp: TimeStamp::ORIGIN,
@@ -58,6 +64,7 @@ impl Node {
Self {
implementation,
implementation_timestamp: TimeStamp::ORIGIN,
inputs: vec![slot; inputs],
attributes: Attributes::new(),
network,
@@ -68,6 +75,7 @@ impl Node {
pub(crate) fn dummy() -> Self {
Self {
implementation: Implementation::ProtoNode(ResourceId::new()),
implementation_timestamp: TimeStamp::default(),
inputs: vec![],
attributes: Attributes::new(),
network: crate::ROOT_NETWORK,
@@ -175,6 +183,19 @@ mod tests {
}
}
/// `to_runtime` has to read back what `Node::new` writes into an unset slot, so its literal must stay
/// in step with how `TaggedValue::None` serializes.
#[test]
fn unset_input_slot_deserializes_as_tagged_value_none() {
let node = Node::new(crate::ROOT_NETWORK, Implementation::Network(crate::ROOT_NETWORK), 1);
let NodeInput::Value { value, .. } = &node.inputs()[0].input else {
panic!("a fresh slot holds a value input");
};
let tagged: graph_craft::document::value::TaggedValue = serde_json::from_value(value.clone()).expect("the unset slot value must deserialize");
assert_eq!(tagged, graph_craft::document::value::TaggedValue::None);
}
/// A `SetExport(None)` truncation leaves a trailing empty slot. Such a network is value-equal to
/// the same network without that slot, so the soak oracle doesn't false-report drift.
#[test]
+209 -96
View File
@@ -39,14 +39,15 @@ impl Session {
retired_snapshot: Registry::default(),
history: History::new(),
hot_log: Vec::new(),
retired: RetiredMarks::default(),
retired: RetiredHotOps::default(),
head: None,
redo_stack: Vec::new(),
clock: LamportClock::new(peer),
peer,
last_broadcast_rev: None,
next_node_counter: 0,
next_hot_sequence: 0,
next_hot_sequence: HotSequence::NONE,
refold_owed: false,
},
remote_tips: HashMap::new(),
runtime_base: None,
@@ -85,8 +86,11 @@ impl Session {
let conversion = Registry::convert_from_runtime(network, metadata, resources, self.document.peer)?;
let base = self.runtime_base.as_ref().unwrap_or(&self.document.working_registry);
let ops = crate::delta::compute_deltas(base, &conversion.registry);
self.runtime_base = Some(conversion.registry.clone());
// The base moves only once the ops are staged, so a failure leaves the next diff covering them.
let hot_ops = self.stage_ops(ops)?;
self.runtime_base = Some(conversion.registry.clone());
Ok((hot_ops, conversion))
}
@@ -141,13 +145,19 @@ impl Session {
Ok(revs)
}
/// Stages ops computed outside the session (an incremental runtime projection) as hot ops, the
/// same way `stage_from_runtime` stages a diff's ops.
pub fn stage_computed_ops(&mut self, ops: Vec<RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
self.stage_ops(ops)
}
/// Apply each op as a hot op with a freshly-ticked timestamp, returning the staged frames in
/// order. Each tick is strictly later than the last, so the final frame carries the latest
/// timestamp, which is what the caller passes to `retire`.
///
/// The peer's first contribution is preceded by a `RegisterPeer` op, so the device's
/// `PeerId → UserId` mapping is established (and, under causal delivery, observed by other peers)
/// before any of its edits. A no-op batch doesn't register — registration rides a real edit.
/// before any of its edits. A no-op batch doesn't register, since registration rides a real edit.
pub fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
let mut pending: Vec<RegistryDelta> = ops.into_iter().collect();
if pending.is_empty() {
@@ -161,13 +171,16 @@ impl Session {
let mut staged = Vec::with_capacity(pending.len());
for op in pending {
self.document.next_hot_sequence += 1;
// The counter advances only once the op is in the log, so a failure leaves no gap in the run.
let sequence = self.document.next_hot_sequence.next();
let hot_op = HotOp {
op,
timestamp: self.document.clock.tick(),
sequence: self.document.next_hot_sequence,
sequence,
};
self.document.apply_hot_op(hot_op.clone())?;
self.document.next_hot_sequence = sequence;
staged.push(hot_op);
}
Ok(staged)
@@ -183,11 +196,18 @@ impl Session {
/// `idempotent`: pass `true` when the snapshot already reflects the op (retirement of an already-
/// applied hot op) so duplicate structural inserts no-op rather than error.
fn commit_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>, idempotent: bool) -> Result<Vec<Rev>, CrdtError> {
self.commit_ops_authored_at(ops.into_iter().map(|op| (op, None)), idempotent)
}
/// [`commit_ops`](Self::commit_ops) for ops authored elsewhere, paired with the timestamp they were
/// authored at (`None` to mint one). The delta's timestamp is what the registry resolves LWW on, so
/// retirement passes the op's own; a coarsened delta passes the newest it fuses.
fn commit_ops_authored_at(&mut self, ops: impl IntoIterator<Item = (RegistryDelta, Option<TimeStamp>)>, idempotent: bool) -> Result<Vec<Rev>, CrdtError> {
let target = RegistryTarget::Snapshot;
let ops = ops.into_iter();
let mut produced = Vec::with_capacity(ops.size_hint().0);
for op in ops {
for (op, authored_at) in ops {
// A new edit abandons any undone-forward branch: those revs stay in the DAG but are no
// longer reachable via redo. (Mirrors the legacy editor clearing its redo history on
// commit.) Done on the first real op so a no-op commit doesn't silently disable redo.
@@ -198,9 +218,9 @@ impl Session {
// The reverse must read the pre-op value of a target that may have been concurrently removed.
self.document.ensure_referenced_exist(target, &op)?;
let reverse = self.document.compute_reverse_delta(target, &op)?;
let timestamp = self.document.clock.tick();
let timestamp = authored_at.unwrap_or_else(|| self.document.clock.tick());
let parent = self.document.head;
let author = self.document.peer;
let author = timestamp.peer;
let delta = Delta::new(parent, author, timestamp, op, reverse);
let rev = delta.id;
@@ -224,7 +244,7 @@ impl Session {
/// Wrap an already-materialized snapshot. Trusts `registry` to match `history`; advances the
/// clock past every observed timestamp but does not re-apply ops. `history` is taken in on-disk
/// (topological) order.
pub fn load(peer: PeerId, registry: Registry, history: Vec<Delta>, head: Option<Rev>, redo_stack: Vec<Rev>, next_node_counter: u64, next_hot_sequence: u64) -> Self {
pub fn load(peer: PeerId, registry: Registry, history: Vec<Delta>, head: Option<Rev>, redo_stack: Vec<Rev>, next_node_counter: u64) -> Self {
let mut clock = LamportClock::new(peer);
for delta in &history {
clock.observe(delta.timestamp);
@@ -238,14 +258,15 @@ impl Session {
working_registry: registry,
history: History::from_ordered(history),
hot_log: Vec::new(),
retired: RetiredMarks::default(),
retired: RetiredHotOps::default(),
head,
redo_stack,
clock,
peer,
last_broadcast_rev: None,
next_node_counter,
next_hot_sequence,
next_hot_sequence: HotSequence::NONE,
refold_owed: false,
},
remote_tips: HashMap::new(),
runtime_base: None,
@@ -270,33 +291,46 @@ impl Session {
Ok(session)
}
/// Apply a hot op received from another peer.
/// Apply a hot op from another peer. Idempotent, and a no-op for one history already covers: a late
/// delivery must not put a retired op back in the hot log.
pub fn apply_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
self.document.apply_hot_op(hot_op)
self.document.replay_hot_op(hot_op)
}
/// The hot ops a `retire(up_to)` call would drain. Broadcast alongside the retired deltas so guests
/// drop exactly these; a cutoff alone doesn't transfer, since a lagging peer's op can carry a
/// timestamp below the cutoff yet reach the host only after that retirement.
/// The hot ops a `retire(up_to)` call would drain. Sent with the deltas for peers to drop exactly
/// these; the cutoff alone doesn't transfer, a lagging op can arrive below it afterwards.
pub fn hot_ops_up_to(&self, up_to: TimeStamp) -> Vec<HotOpId> {
self.document.hot_log.iter().filter(|hot_op| hot_op.timestamp <= up_to).map(HotOp::id).collect()
}
/// Drop hot ops another peer has retired without retiring them locally.
pub fn discard_hot_ops(&mut self, retired: &[HotOpId]) {
/// Drop hot ops another peer has retired without retiring them locally. Refolds like
/// [`absorb_retired_marks`](Self::absorb_retired_marks).
pub fn discard_hot_ops(&mut self, retired: &[HotOpId]) -> Result<(), CrdtError> {
let before = self.document.hot_log.len();
self.document.hot_log.retain(|hot_op| !retired.contains(&hot_op.id()));
// How a peer that did not retire these learns they are in history now.
self.document.mark_retired(retired.iter().copied());
if before != self.document.hot_log.len() {
self.refold_registries()?;
}
Ok(())
}
/// Which hot ops history already covers, for a peer catching up. See [`RetiredMarks`].
pub fn retired_marks(&self) -> &RetiredMarks {
/// Which hot ops history already covers, for a peer catching up. See [`RetiredHotOps`].
pub fn retired_marks(&self) -> &RetiredHotOps {
&self.document.retired
}
/// Take on another peer's retirement marks as well as this peer's.
pub fn absorb_retired_marks(&mut self, remote: &RetiredMarks) {
self.document.absorb_retired(remote);
/// See [`RetiredHotOps::absorb`]. A drop owes a refold, since the working registry holds the op's
/// effect in hot-log order where the snapshot holds it in canonical order.
pub fn absorb_retired_marks(&mut self, remote: &RetiredHotOps) -> Result<(), CrdtError> {
if self.document.absorb_retired(remote) {
self.refold_registries()?;
}
Ok(())
}
/// Replay a persisted hot op. Idempotent on structural ops, suitable for crash recovery
@@ -305,19 +339,37 @@ impl Session {
self.document.replay_hot_op(hot_op)
}
/// Rebuild both registries by refolding canonically sorted history, then re-layering the hot tail.
/// Every peer sorts history the same way, so the result no longer depends on the order deltas
/// happened to arrive in. Costs a full replay, so callers check that it is needed first.
fn refold_registries(&mut self) -> Result<(), CrdtError> {
let replay: Vec<(RegistryDelta, TimeStamp)> = self.document.history.iter().map(|delta| (delta.kind.clone(), delta.timestamp)).collect();
/// The retired snapshot as canonical history alone produces it, independent of arrival order and the
/// hot log. Folded on a clone, over `head`'s ancestry only: an undone delta stays in the DAG for redo
/// to find, and folding all of history would restore work the user undid.
///
/// The clone's history grows with the replay, as it did when each delta first landed. Resurrection
/// takes the last removal in canonical order, and with the whole history in view that can be one past
/// the replay position, whose snapshot places the entity in a network the replay has not created yet.
pub fn snapshot_from_history(&self) -> Result<Registry, CrdtError> {
let reachable = self.document.history.ancestors(self.document.head);
self.document.retired_snapshot = Registry::default();
for (kind, timestamp) in replay {
self.document.apply_op_with(RegistryTarget::Snapshot, kind, timestamp, ApplyMode::Idempotent)?;
let mut folded = self.clone();
folded.document.retired_snapshot = Registry::default();
folded.document.history = History::new();
for delta in self.document.history.iter().filter(|delta| reachable.contains(&delta.id)) {
folded.document.apply_op_with(RegistryTarget::Snapshot, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
folded.document.history.push(delta.clone());
}
// A hot op the refold left unapplicable is kept rather than dropped, since a later delta or hot
// op can still supply the referent it names.
Ok(folded.document.retired_snapshot)
}
/// Rebuild both registries from canonical history, then re-layer the hot tail. A full replay; callers
/// check it is needed first.
fn refold_registries(&mut self) -> Result<(), CrdtError> {
// Cleared only on the way out. The deltas are in history either way, and a failure here leaves the
// registries derived from an older one until something retries.
self.document.refold_owed = true;
self.document.retired_snapshot = self.snapshot_from_history()?;
// One left unapplicable is kept, not dropped: a later delta or hot op can still supply its referent.
self.document.working_registry = self.document.retired_snapshot.clone();
let mut failure = None;
for hot_op in std::mem::take(&mut self.document.hot_log) {
@@ -327,10 +379,12 @@ impl Session {
}
}
match failure {
Some(error) => Err(error),
None => Ok(()),
if let Some(error) = failure {
return Err(error);
}
self.document.refold_owed = false;
Ok(())
}
/// Integrate `incoming` retired deltas (in causal order) from another peer. Moves `head` forward
@@ -349,24 +403,25 @@ impl Session {
}
arrival_order.push(delta.id);
self.document.apply_op_idempotent(delta.kind.clone(), delta.timestamp)?;
// The working registry is the snapshot plus the hot tail, so a retired delta lands on both
// rather than cloning one over the other, which would promote unretired hot ops.
// Working is snapshot plus hot tail, so a delta lands on both; cloning would promote hot ops.
self.document.apply_op_with(RegistryTarget::Snapshot, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
absorbed_ids.insert(delta.id);
self.document.history.push(delta);
}
if absorbed_ids.is_empty() {
// Nothing new, but a refold left owed by an earlier failure is still the only way the registries
// catch up with the history they are derived from.
if self.document.refold_owed {
self.refold_registries()?;
}
return Ok(MergeOutcome::NoOp);
}
self.document.history.canonical_sort();
// The registries were folded in arrival order, and concurrent ops do not all commute: a remove
// and a change to the same target resolve by whichever lands second. Refold unless the sort
// happened to leave the batch appended in the order it was applied.
// The loop folds in arrival order, and concurrent ops do not all commute: a remove and a change to
// the same target resolve by whichever lands second.
let folded_in_canonical_order = self.document.history.iter().skip(length_before).map(|delta| delta.id).eq(arrival_order.iter().copied());
if !folded_in_canonical_order {
self.refold_registries()?;
}
let history = &self.document.history;
let mut candidates: Vec<Rev> = history.tips().into_iter().filter(|tip| absorbed_ids.contains(tip)).collect();
@@ -387,29 +442,47 @@ impl Session {
};
self.document.head = outcome.head();
// After `head`, since the fold is over its ancestry.
if !folded_in_canonical_order || self.document.refold_owed {
self.refold_registries()?;
}
Ok(outcome)
}
/// Promote hot ops with timestamp `≤ up_to` into retired deltas, re-applied with fresh
/// retirement timestamps so LWW arms bump field timestamps to `T_retire`.
/// Promote hot ops with timestamp `≤ up_to` into retired deltas, each keeping the timestamp it was
/// authored at.
///
/// Today: one retired delta per hot op. Coarsening is a future step.
pub fn retire(&mut self, up_to: TimeStamp) -> Result<Vec<Rev>, CrdtError> {
// Drained in hot-log order, which is causal, so the deltas commit in an order their references
// survive.
// Hot-log order is causal, so the deltas commit in an order their references survive.
let mut drained = Vec::new();
let mut remaining = Vec::with_capacity(self.document.hot_log.len());
// Retiring by timestamp reorders against the hot-log order the working registry applied: past a
// skipped op, everything drained was applied here before it.
let mut skipped = false;
let mut reordered = false;
for hot_op in self.document.hot_log.drain(..) {
if hot_op.timestamp <= up_to {
reordered |= skipped;
drained.push(hot_op);
} else {
skipped = true;
remaining.push(hot_op);
}
}
self.document.hot_log = remaining;
self.document.mark_retired(drained.iter().map(HotOp::id));
self.commit_ops(drained.into_iter().map(|hot_op| hot_op.op), true)
let revs = self.commit_ops_authored_at(drained.into_iter().map(|hot_op| (hot_op.op, Some(hot_op.timestamp))), true)?;
// Structural ops have no timestamp to arbitrate, so the reorder changes the outcome.
if reordered {
self.refold_registries()?;
}
Ok(revs)
}
/// Mark a retired delta as the end of a user interaction, so the undo cursor treats it as a checkpoint.
@@ -463,11 +536,9 @@ impl Session {
!self.document.redo_stack.is_empty()
}
/// Silent-zone undo of one *interaction*: revert deltas walking `head` back along first-parents until
/// it reaches the previous interaction boundary (a delta marked `interaction_end`) or the empty root. One
/// interaction spans several deltas (one `commit_from_runtime` batch), so undo reverts the whole run,
/// not a single delta — matching the legacy per-interaction undo granularity. The undone interaction's
/// `head` rev is pushed onto the redo stack. Reflog semantics: the DAG is never rewritten.
/// Silent-zone undo of one *interaction*: revert deltas back along first-parents until `head` reaches
/// the previous `interaction_end` boundary or the root. An interaction is a whole `commit_from_runtime`
/// batch, so the run reverts together. Its `head` rev goes on the redo stack; the DAG is not rewritten.
pub fn undo(&mut self) -> Result<Rev, CrdtError> {
if !self.can_undo() {
return Err(CrdtError::NothingToUndo);
@@ -484,8 +555,7 @@ impl Session {
let parent = delta.parent;
self.document.revert_delta(RegistryTarget::Working, delta.clone())?;
// The working registry is the snapshot plus the hot tail, so rewind both rather than copying
// one over the other, which would promote unretired hot ops into retired state.
// Working is snapshot plus hot tail, so rewind both; copying would promote unretired hot ops.
self.document.revert_delta(RegistryTarget::Snapshot, delta)?;
self.document.head = parent;
@@ -663,11 +733,16 @@ impl Session {
self.document.next_node_counter
}
/// How many hot ops this peer has authored. Persisted and carried across a reload so a fresh op
/// never reuses a sequence an earlier one already spent. See [`HotOp::sequence`].
pub fn next_hot_sequence(&self) -> u64 {
/// How many hot ops this peer has authored. Carried across a reload; no sequence is spent twice.
pub fn next_hot_sequence(&self) -> HotSequence {
self.document.next_hot_sequence
}
/// Restore the authored-op count after a load, keeping a fresh op off a spent sequence. Raises only:
/// replaying a persisted hot log afterwards cannot lower it.
pub fn restore_hot_sequence(&mut self, sequence: HotSequence) {
self.document.next_hot_sequence = self.document.next_hot_sequence.max(sequence);
}
}
/// Errors from `Session::commit_from_runtime`.
@@ -710,10 +785,9 @@ impl MergeOutcome {
pub struct HotOp {
pub op: RegistryDelta,
pub timestamp: TimeStamp,
/// Position in its author's own run of hot ops, counting from 1 with no gaps. The Lamport counter
/// skips whenever a higher remote timestamp is observed, so it cannot tell a missing op from a
/// skipped tick; this can, which is what lets a watermark stand for a contiguous prefix.
pub sequence: u64,
/// Position in its author's run, from 1 with no gaps. A watermark over it therefore means a contiguous
/// prefix; one over the Lamport counter cannot, since that skips on observing a higher remote stamp.
pub sequence: HotSequence,
}
impl HotOp {
@@ -726,69 +800,108 @@ impl HotOp {
}
}
/// One hot op's author and position in that author's run. Retirement names the ops it promoted with
/// these rather than with timestamps, so a receiver can tell which prefix history now covers.
/// Position in one author's run of hot ops, counting from 1 with no gaps. Kept apart from the Lamport
/// counter, which skips on observing a higher remote timestamp and so cannot bound a contiguous prefix.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct HotSequence(pub u64);
impl HotSequence {
/// Before this author has written anything, covering no op.
pub const NONE: Self = Self(0);
/// The next position in the run.
pub fn next(self) -> Self {
Self(self.0 + 1)
}
}
/// One hot op's author and position in its run. Retirement names promoted ops by these, which tells a
/// receiver which prefix history covers.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct HotOpId {
pub peer: PeerId,
pub sequence: u64,
pub sequence: HotSequence,
}
/// Which hot ops history already covers. `through` is how far each author's run has retired without a
/// gap, and `above` names the retired ops past that point, which is where an op lands when it retires
/// before an earlier one from the same author has arrived. Replicated so a peer catching up can tell
/// an op already in the history it was handed from one still owed to it.
/// Which hot ops history already covers: `retired_up_to` is each author's gap-free retired prefix, and
/// `unretired` the retired ops past it. Replicated, letting a peer catching up separate an op already in
/// history from one still owed to it.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct RetiredMarks {
pub through: HashMap<PeerId, u64>,
pub above: HashSet<HotOpId>,
pub struct RetiredHotOps {
pub retired_up_to: HashMap<PeerId, HotSequence>,
/// Retired ops sitting past their author's prefix, as inclusive runs. A gap that never fills pins the
/// prefix and everything later from that author lands here, so runs keep this proportional to the
/// number of gaps instead of the number of ops.
pub retired_beyond: HashMap<PeerId, Vec<(HotSequence, HotSequence)>>,
}
impl RetiredMarks {
/// Sort and coalesce runs, joining any that touch or abut.
fn coalesce(runs: &mut Vec<(HotSequence, HotSequence)>) {
runs.sort_unstable();
let mut merged: Vec<(HotSequence, HotSequence)> = Vec::with_capacity(runs.len());
for &(start, end) in runs.iter() {
match merged.last_mut() {
Some((_, last_end)) if start <= last_end.next() => *last_end = (*last_end).max(end),
_ => merged.push((start, end)),
}
}
*runs = merged;
}
impl RetiredHotOps {
/// Whether history already holds this hot op.
pub fn covers(&self, id: HotOpId) -> bool {
self.through.get(&id.peer).is_some_and(|&through| id.sequence <= through) || self.above.contains(&id)
if self.retired_up_to.get(&id.peer).is_some_and(|&through| id.sequence <= through) {
return true;
}
self.retired_beyond
.get(&id.peer)
.is_some_and(|runs| runs.iter().any(|&(start, end)| id.sequence >= start && id.sequence <= end))
}
/// Take on `remote`'s coverage as well as this one's.
pub fn absorb(&mut self, remote: &Self) {
for (&peer, &remote_through) in &remote.through {
let through = self.through.entry(peer).or_default();
for (&peer, &remote_through) in &remote.retired_up_to {
let through = self.retired_up_to.entry(peer).or_default();
*through = (*through).max(remote_through);
}
self.above.extend(remote.above.iter().copied());
for (&peer, runs) in &remote.retired_beyond {
self.retired_beyond.entry(peer).or_default().extend(runs.iter().copied());
}
self.compact();
}
/// Record newly retired ops.
pub fn extend(&mut self, retired: impl IntoIterator<Item = HotOpId>) {
self.above.extend(retired);
for id in retired {
self.retired_beyond.entry(id.peer).or_default().push((id.sequence, id.sequence));
}
self.compact();
}
/// Fold every exception that continues its author's prefix into `through`, so the set only ever
/// holds ops still separated from the prefix by a gap.
/// Fold runs that continue their author's prefix into `retired_up_to`, leaving only those past a gap.
fn compact(&mut self) {
let mut by_author: HashMap<PeerId, Vec<u64>> = HashMap::new();
for id in &self.above {
by_author.entry(id.peer).or_default().push(id.sequence);
}
for (&peer, runs) in &mut self.retired_beyond {
coalesce(runs);
for (peer, mut sequences) in by_author {
sequences.sort_unstable();
let through = self.through.entry(peer).or_default();
for sequence in sequences {
if sequence == *through + 1 {
*through = sequence;
}
let mut through = self.retired_up_to.get(&peer).copied().unwrap_or(HotSequence::NONE);
while runs.first().is_some_and(|&(start, _)| start <= through.next()) {
let (_, end) = runs.remove(0);
through = through.max(end);
}
if through != HotSequence::NONE {
self.retired_up_to.insert(peer, through);
}
}
let through = std::mem::take(&mut self.through);
self.above.retain(|id| through.get(&id.peer).is_none_or(|&covered| id.sequence > covered));
self.through = through;
self.retired_beyond.retain(|_, runs| !runs.is_empty());
}
}
+258 -32
View File
@@ -40,7 +40,7 @@ fn apply_hot_op_advances_clock_past_observed_timestamp() {
let hot_op = HotOp {
op: remove_node_op(NodeId(99)),
timestamp: observed,
sequence: 1,
sequence: crate::HotSequence(1),
};
document.apply_hot_op(hot_op).expect("RemoveNode on absent node is a no-op, not an error");
@@ -862,6 +862,7 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
Node {
implementation: implementation.clone(),
implementation_timestamp: Default::default(),
inputs,
attributes,
network: ROOT_NETWORK,
@@ -905,8 +906,8 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
assert_eq!(delta_forward.id, delta_reversed.id, "Rev must not depend on attribute insertion order");
}
/// Commit a retired delta and mirror it onto the working registry, which sits at
/// `retired_snapshot + hot tail`. `commit_op_for_test` alone only advances the snapshot zone.
/// Commit a retired delta and mirror it onto the working registry; `commit_op_for_test` alone only
/// advances the snapshot zone.
fn commit_retired(session: &mut Session, op: RegistryDelta) {
let before = session.history().count();
session.commit_op_for_test(op).expect("commit failed");
@@ -916,8 +917,7 @@ fn commit_retired(session: &mut Session, op: RegistryDelta) {
}
}
/// Merge `deltas` into a copy of `base` in the given order and report whether node 7 survived,
/// with the stamp on its `tint` attribute.
/// Merge `deltas` into a copy of `base` in the given order, reporting node 7's surviving `tint`.
fn merge_order_outcome(base: &Session, deltas: &[Delta], order: [usize; 2]) -> Option<(serde_json::Value, TimeStamp)> {
let mut session = base.clone();
let ordered: Vec<Delta> = order.iter().map(|&index| deltas[index].clone()).collect();
@@ -931,10 +931,8 @@ fn merge_order_outcome(base: &Session, deltas: &[Delta], order: [usize; 2]) -> O
.map(|value| (value.value.clone(), value.timestamp))
}
/// Retired deltas reach the registries in arrival order while only `history` is canonically sorted,
/// so concurrent deltas must commute. A remove concurrent with an attribute change does not: applied
/// change-then-remove the node is gone, while remove-then-change resurrects it from the removal's
/// embedded snapshot and reapplies the change on top.
/// The raw ops are arrival-order dependent: change-first leaves the node gone, remove-first resurrects
/// it from the removal's snapshot. Merge has to fold both orders onto the same retired registry.
#[test]
fn a_concurrent_remove_and_attribute_change_commute() {
let network_id = NetworkId(5);
@@ -978,56 +976,60 @@ fn a_concurrent_remove_and_attribute_change_commute() {
assert_eq!(removal_first, change_first, "the retired registry must not depend on delta arrival order");
}
/// A hot op can retire before an earlier one from the same author has arrived, so the marks have to
/// cover it out of order. The prefix absorbs it once the gap fills, which is what keeps the exception
/// set from growing.
/// An op can retire before an earlier one from its author arrives, so the marks cover it out of order.
/// The prefix absorbs it once the gap fills, which bounds the exception set.
#[test]
fn retired_marks_cover_a_gap_and_compact_once_it_fills() {
let author = PeerId(1);
let id = |sequence| crate::HotOpId { peer: author, sequence };
let id = |sequence: u64| crate::HotOpId {
peer: author,
sequence: crate::HotSequence(sequence),
};
let mut marks = crate::RetiredMarks::default();
let mut marks = crate::RetiredHotOps::default();
marks.extend([id(1), id(2)]);
assert_eq!(marks.through.get(&author), Some(&2), "a contiguous run folds straight into the prefix");
assert!(marks.above.is_empty());
assert_eq!(marks.retired_up_to.get(&author), Some(&crate::HotSequence(2)), "a contiguous run folds straight into the prefix");
assert!(marks.retired_beyond.is_empty());
// Sequence 3 never arrived, so 4 retires above the prefix rather than extending it.
marks.extend([id(4)]);
assert_eq!(marks.through.get(&author), Some(&2));
assert_eq!(marks.retired_up_to.get(&author), Some(&crate::HotSequence(2)));
assert!(marks.covers(id(4)), "an op past the gap is still recognized as retired");
assert!(!marks.covers(id(3)), "the missing op is not claimed");
// The gap fills, so the prefix swallows both it and the exception behind it.
marks.extend([id(3)]);
assert_eq!(marks.through.get(&author), Some(&4));
assert!(marks.above.is_empty(), "the exception set empties once the prefix reaches it");
assert_eq!(marks.retired_up_to.get(&author), Some(&crate::HotSequence(4)));
assert!(marks.retired_beyond.is_empty(), "the exception set empties once the prefix reaches it");
}
/// Marks merge by union, and a peer adopting another's wholesale must not lose its own coverage.
/// Marks merge by union, so adopting a peer's wholesale must not lose local coverage.
#[test]
fn absorbing_marks_keeps_both_sides_coverage() {
let author = PeerId(1);
let id = |sequence| crate::HotOpId { peer: author, sequence };
let id = |sequence: u64| crate::HotOpId {
peer: author,
sequence: crate::HotSequence(sequence),
};
let mut local = crate::RetiredMarks::default();
let mut local = crate::RetiredHotOps::default();
local.extend([id(1), id(4)]);
let mut remote = crate::RetiredMarks::default();
let mut remote = crate::RetiredHotOps::default();
remote.extend([id(1), id(2), id(3), id(5)]);
local.absorb(&remote);
// The union is 1..=5 contiguous, so it all collapses into the prefix.
assert_eq!(local.through.get(&author), Some(&5));
assert!(local.above.is_empty());
assert_eq!(local.retired_up_to.get(&author), Some(&crate::HotSequence(5)));
assert!(local.retired_beyond.is_empty());
for sequence in 1..=5 {
assert!(local.covers(id(sequence)), "sequence {sequence} must stay covered");
}
}
/// Undo rewinds retired history, so it must leave the hot tail alone. The retired snapshot is the
/// state history alone produces; copying the working registry onto it promotes live work nobody has
/// retired, which is the same mistake `Session::merge` used to make.
/// Undo rewinds retired history and must leave the hot tail alone: copying the working registry onto
/// the snapshot promotes unretired work. Hot ops exist between staging and retirement even solo.
#[test]
fn undo_does_not_promote_hot_ops_into_the_retired_snapshot() {
let mut session = Session::with_peer(PeerId(1));
@@ -1052,8 +1054,7 @@ fn undo_does_not_promote_hot_ops_into_the_retired_snapshot() {
);
}
/// Redo puts the interaction back on both zones, so the pair stays `snapshot + hot tail` rather than
/// drifting apart in the other direction.
/// Redo puts the interaction back on both zones, so the pair does not drift the other way.
#[test]
fn redo_restores_the_retired_snapshot_without_the_hot_tail() {
let mut session = Session::with_peer(PeerId(1));
@@ -1075,8 +1076,8 @@ fn redo_restores_the_retired_snapshot_without_the_hot_tail() {
assert!(session.registry().attributes.contains_key("hot"), "the hot op must survive an undo/redo round trip");
}
/// Silent undo rewrites the local registries without emitting anything, so it is only legal while a
/// commit is still unpublished. Once peers hold it, a rewind would diverge from them for good.
/// Silent undo emits nothing, so it is only legal while a commit is unpublished. Once peers hold it, a
/// rewind would diverge from them for good.
#[test]
fn publishing_a_commit_disables_silent_undo() {
let mut session = Session::with_peer(PeerId(1));
@@ -1093,3 +1094,228 @@ fn publishing_a_commit_disables_silent_undo() {
assert!(!session.can_undo(), "a published interaction must not be silently rewound");
}
/// An undone delta stays in the DAG for redo, outside `head`'s ancestry. A fold that ignores that
/// restores work the user undid.
#[test]
fn snapshot_from_history_ignores_undone_deltas() {
let mut session = Session::with_peer(PeerId(1));
commit_retired(&mut session, set_document_attribute("first", 1));
let boundary = session.history().last().expect("a committed delta").id;
session.mark_interaction_end(boundary);
commit_retired(&mut session, set_document_attribute("second", 2));
session.undo().expect("undo");
assert!(!session.retired_registry().attributes.contains_key("second"), "undo rewound the snapshot");
let folded = session.snapshot_from_history().expect("fold");
assert!(folded.attributes.contains_key("first"), "history still holds the kept interaction");
assert!(!folded.attributes.contains_key("second"), "a fold restored an undone delta");
}
/// Resurrection takes the last removal of the entity in canonical order. When the deltas first landed
/// that was the latest one so far, but a fold over finished history also sees the removals after the
/// replay position, and one of those can carry the node in a network the replay has not created yet
/// (simulation seed 3588534).
#[test]
fn snapshot_from_history_resurrects_from_the_replay_position() {
let node_id = NodeId(3);
let first_network = NetworkId(1);
let later_network = NetworkId(3);
let node_in = |network: NetworkId| Node { network, ..Node::dummy() };
let mut session = Session::with_peer(PeerId(1));
commit_retired(
&mut session,
RegistryDelta::AddNetwork {
id: first_network,
network: Network::default(),
},
);
commit_retired(
&mut session,
RegistryDelta::AddNode {
id: node_id,
node: node_in(first_network),
},
);
commit_retired(
&mut session,
RegistryDelta::RemoveNode {
id: node_id,
snapshot: node_in(first_network),
},
);
// Resurrects the node from the removal above, the only one so far.
commit_retired(
&mut session,
RegistryDelta::SetNetworkExport {
id: first_network,
index: 0,
export: Some(crate::NodeInput::Node { id: node_id, index: 0 }),
},
);
commit_retired(
&mut session,
RegistryDelta::AddNetwork {
id: later_network,
network: Network::default(),
},
);
// A later removal whose snapshot places the node in the network created after the export.
commit_retired(
&mut session,
RegistryDelta::RemoveNode {
id: node_id,
snapshot: node_in(later_network),
},
);
let folded = session.snapshot_from_history().expect("a fold must resurrect from what the replay has seen, not from a later removal");
assert_eq!(&folded, session.retired_registry(), "the fold must reproduce the snapshot the deltas built as they landed");
}
/// A failed refold leaves the registries on an older history, and the deltas are already absorbed, so
/// re-merging them is a no-op. Without a retry the registries never catch up.
#[test]
fn an_owed_refold_is_retried_by_a_merge_that_absorbs_nothing() {
let mut session = Session::with_peer(PeerId(1));
commit_retired(&mut session, set_document_attribute("first", 1));
// Stand in for a refold that failed partway: history moved on, the snapshot did not.
session.document.retired_snapshot = crate::Registry::default();
session.document.refold_owed = true;
let outcome = session.merge(Vec::new()).expect("a merge absorbing nothing still settles the refold");
assert_eq!(outcome, crate::MergeOutcome::NoOp);
assert!(!session.document.refold_owed, "the refold must not stay owed");
assert!(
session.retired_registry().attributes.contains_key("first"),
"the retried refold must bring the snapshot back to its history"
);
}
/// The newtype is `#[serde(transparent)]`, so persisted state and the wire carry a bare number and the
/// field's encoding is unchanged.
#[test]
fn hot_sequence_serializes_as_a_bare_number() {
let encoded = serde_json::to_string(&crate::HotSequence(7)).expect("serialize");
assert_eq!(encoded, "7");
assert_eq!(serde_json::from_str::<crate::HotSequence>("7").expect("deserialize"), crate::HotSequence(7));
}
/// Retirement drains the hot log, so a retirer that never received an author's earlier op cannot
/// retire it. The later op still retires, landing beyond the author's prefix instead of extending it.
#[test]
fn retiring_over_a_gap_lands_beyond_the_prefix() {
let author = PeerId(2);
let mut host = Session::with_peer(PeerId(1));
// Only the author's second op reaches this peer; the first was lost with the link that carried it.
let second = HotOp {
op: set_document_attribute("late", 1),
timestamp: TimeStamp { counter: 9, peer: author },
sequence: crate::HotSequence(2),
};
host.apply_hot_op(second.clone()).expect("apply");
host.retire(second.timestamp).expect("retire");
let retired = host.retired_marks();
let prefix = retired.retired_up_to.get(&author).copied().unwrap_or(crate::HotSequence::NONE);
assert_eq!(prefix, crate::HotSequence::NONE, "sequence 1 never arrived, so the prefix cannot move");
assert!(retired.retired_beyond.contains_key(&author), "the retired op has to be recorded past the gap");
assert!(retired.covers(second.id()), "and still count as retired");
}
/// A gap that never fills pins the prefix, so every later op from that author lands past it. Stored as
/// runs, that stays one entry however many ops follow.
#[test]
fn a_permanent_gap_accumulates_every_later_op() {
let author = PeerId(2);
let id = |sequence: u64| crate::HotOpId {
peer: author,
sequence: crate::HotSequence(sequence),
};
let mut marks = crate::RetiredHotOps::default();
// Sequence 1 is lost for good; everything this author writes afterwards still retires.
for sequence in 2..=20 {
marks.extend([id(sequence)]);
}
let runs = marks.retired_beyond.get(&author).map(Vec::len).unwrap_or_default();
assert_eq!(runs, 1, "the ops after the gap coalesce into a single run");
for sequence in 2..=20 {
assert!(marks.covers(id(sequence)), "sequence {sequence} must stay covered");
}
assert!(!marks.covers(id(1)), "the lost op is not claimed");
}
/// A retired delta keeps its op's authoring timestamp, so the snapshot resolves LWW on the same stamps
/// the live view did rather than on retirement order.
#[test]
fn retirement_preserves_the_live_lww_winner() {
let mut host = Session::with_peer(PeerId(1));
// Same key from two authors, the newer op arriving first, so LWW keeps it and discards the older.
let newer = HotOp {
op: set_document_attribute("k", 1),
timestamp: TimeStamp { counter: 10, peer: PeerId(2) },
sequence: crate::HotSequence(1),
};
let older = HotOp {
op: set_document_attribute("k", 2),
timestamp: TimeStamp { counter: 5, peer: PeerId(3) },
sequence: crate::HotSequence(1),
};
host.apply_hot_op(newer.clone()).expect("apply newer");
host.apply_hot_op(older).expect("apply older");
let live = host.registry().attributes.get("k").cloned();
host.retire(newer.timestamp).expect("retire");
assert_eq!(host.registry().attributes.get("k"), live.as_ref(), "retirement must not move the live value");
assert_eq!(
host.retired_registry().attributes.get("k").map(|attribute| &attribute.value),
live.as_ref().map(|attribute| &attribute.value),
"the snapshot has to record the value the live view settled on"
);
}
/// A straggler LWW discarded still retires, and must not return by doing so: stamped at retirement it
/// would outrank the op that beat it, putting the discarded value into history itself.
#[test]
fn retiring_a_straggler_leaves_the_discarded_value_behind() {
let mut host = Session::with_peer(PeerId(1));
let winner = HotOp {
op: set_document_attribute("k", 1),
timestamp: TimeStamp { counter: 10, peer: PeerId(2) },
sequence: crate::HotSequence(1),
};
host.apply_hot_op(winner.clone()).expect("apply winner");
host.retire(winner.timestamp).expect("retire winner");
// Arriving behind the winner, this op loses in the live view and its value is dropped.
let straggler = HotOp {
op: set_document_attribute("k", 2),
timestamp: TimeStamp { counter: 5, peer: PeerId(3) },
sequence: crate::HotSequence(1),
};
host.apply_hot_op(straggler.clone()).expect("apply straggler");
host.retire(straggler.timestamp).expect("retire straggler");
let value = |registry: &crate::Registry| registry.attributes.get("k").map(|attribute| attribute.value.clone());
assert_eq!(value(host.registry()), Some(serde_json::json!(1)), "the live view keeps the winner");
assert_eq!(value(host.retired_registry()), Some(serde_json::json!(1)), "and retiring the straggler must not overwrite it");
let replayed = host.snapshot_from_history().expect("refold");
assert_eq!(value(&replayed), Some(serde_json::json!(1)), "nor may history replay to the discarded value");
}
@@ -609,7 +609,7 @@ fn unreferenced_runtime_resource_is_not_snapshotted() {
assert!(!registry.resources.contains_key(&orphan), "the unreferenced (orphan) resource must not be snapshotted");
}
/// A node-input `TaggedValue::F64` must survive the storage round-trip bit-exact. Inputs are stored as a
/// A node-input `TaggedValue::Number` must survive the storage round-trip bit-exact. Inputs are stored as a
/// self-describing `serde_json::Value` (encoded with the registry's MessagePack codec), so this guards
/// against any precision loss in the f64 -> serde_json::Number -> f64 path for a value with a full
/// 17-significant-digit mantissa.
@@ -623,7 +623,7 @@ fn node_input_f64_round_trips_bit_exact() {
nodes: [(
NodeId(0),
DocumentNode {
inputs: vec![NodeInput::value(TaggedValue::F64(precise), false)],
inputs: vec![NodeInput::value(TaggedValue::Number(precise), false)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::identity::IdentityNode")),
..Default::default()
},
@@ -640,8 +640,8 @@ fn node_input_f64_round_trips_bit_exact() {
let NodeInput::Value { tagged_value, .. } = input else {
panic!("expected a value input, got {input:?}")
};
let TaggedValue::F64(actual) = &**tagged_value else {
panic!("expected F64, got {:?}", tagged_value)
let TaggedValue::Number(actual) = &**tagged_value else {
panic!("expected Number, got {:?}", tagged_value)
};
assert_eq!(actual.to_bits(), precise.to_bits(), "f64 node input drifted: {actual} != {precise}");
@@ -759,6 +759,7 @@ fn cyclic_network_reference_is_rejected() {
crate::NodeId(0),
Node {
implementation: Implementation::Network(child_network_id),
implementation_timestamp: Default::default(),
inputs: Vec::new(),
attributes: crate::Attributes::default(),
network: crate::ROOT_NETWORK,
@@ -768,6 +769,7 @@ fn cyclic_network_reference_is_rejected() {
crate::NodeId(1),
Node {
implementation: Implementation::Network(crate::ROOT_NETWORK),
implementation_timestamp: Default::default(),
inputs: Vec::new(),
attributes: crate::Attributes::default(),
network: child_network_id,
+30 -14
View File
@@ -38,7 +38,8 @@ pub enum ConversionError {
pub type Declarations = std::collections::HashMap<ResourceId, ProtoNode>;
impl Registry {
/// Returns the network plus per-node metadata entries (one per node carrying any `ui::*` attribute).
/// Returns the network plus one metadata entry per node, since every node carries an identity to
/// restore even when it has no `ui::*` attribute.
pub fn to_runtime_with_metadata(&self, declarations: &Declarations) -> Result<(NodeNetwork, Vec<NodeMetadataEntry>), ConversionError> {
let (network, node_entries, _) = self.to_runtime_with_full_metadata(declarations)?;
Ok((network, node_entries))
@@ -168,7 +169,7 @@ fn convert_network(
let network = context.registry.networks.get(&network_id).ok_or(ConversionError::NetworkNotFound(network_id))?;
if let Some(collector) = network_collector.as_mut() {
collector.push(extract_network_metadata(&network.attributes, metadata_path, network_id));
collector.push(extract_network_metadata(context.registry, &network.attributes, metadata_path, network_id));
}
let mut nodes: FxHashMap<RuntimeNodeId, DocumentNode> = FxHashMap::default();
@@ -176,10 +177,8 @@ fn convert_network(
let local_id = node.attributes.get(node::ORIGINAL_NODE_ID).and_then(|v| v.value.as_u64()).unwrap_or(global_id.0);
let runtime_id = RuntimeNodeId(local_id);
if let Some(collector) = node_collector.as_mut()
&& let Some(entry) = extract_ui_metadata(node, metadata_path, runtime_id)
{
collector.push(entry);
if let Some(collector) = node_collector.as_mut() {
collector.push(extract_ui_metadata(node, global_id, metadata_path, runtime_id));
}
let doc_node = convert_node(context, node, metadata_path, runtime_id, node_collector, network_collector)?;
@@ -239,10 +238,10 @@ fn read_scope_injections(registry: &Registry, network_id: NetworkId, attributes:
.collect()
}
/// Returns `None` when the node has no `ui::*` attributes at all so callers don't end up with
/// empty entries for unconverted-from-runtime nodes. `input_metadata` is always sized to match
/// `node.inputs.len()` for a strict slot-by-slot rebuild; empty slots use `InputMetadataEntry::default()`.
fn extract_ui_metadata(node: &crate::Node, network_path: &[RuntimeNodeId], local_id: RuntimeNodeId) -> Option<NodeMetadataEntry> {
/// Emitted for every node, since `storage_id` is worth restoring even where no `ui::*` attribute is.
/// `input_metadata` is always sized to match `node.inputs.len()` for a strict slot-by-slot rebuild;
/// empty slots use `InputMetadataEntry::default()`.
fn extract_ui_metadata(node: &crate::Node, storage_id: NodeId, network_path: &[RuntimeNodeId], local_id: RuntimeNodeId) -> NodeMetadataEntry {
let position: Option<Position> = node.attributes.get_typed(node::ui::POSITION);
let is_layer = node.attributes.get_or(node::ui::IS_LAYER, false);
let display_name: Option<String> = node.attributes.get_typed(node::ui::DISPLAY_NAME);
@@ -252,9 +251,10 @@ fn extract_ui_metadata(node: &crate::Node, network_path: &[RuntimeNodeId], local
let input_metadata: Vec<InputMetadataEntry> = node.inputs.iter().map(|slot| &slot.attributes).map(extract_input_metadata).collect();
let entry = NodeMetadataEntry {
NodeMetadataEntry {
network_path: network_path.to_vec(),
local_id,
storage_id,
position,
is_layer,
display_name,
@@ -262,15 +262,31 @@ fn extract_ui_metadata(node: &crate::Node, network_path: &[RuntimeNodeId], local
pinned,
input_metadata,
output_names,
};
(!entry.is_empty()).then_some(entry)
}
}
fn extract_network_metadata(attributes: &crate::Attributes, network_path: &[RuntimeNodeId], network_id: NetworkId) -> NetworkMetadataEntry {
/// Node references stored here are storage IDs, resolved back to runtime-local IDs the way
/// `read_scope_injections` does. A reference to a node that is no longer in this network is dropped
/// rather than failing the conversion: a pinned node can have been deleted.
fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes, network_path: &[RuntimeNodeId], network_id: NetworkId) -> NetworkMetadataEntry {
let to_runtime_id = |storage_id: NodeId| {
let node = registry.node_instances.get(&storage_id).filter(|node| node.network == network_id)?;
let local_id = node.attributes.get(node::ORIGINAL_NODE_ID).and_then(|value| value.value.as_u64()).unwrap_or(storage_id.0);
Some(RuntimeNodeId(local_id))
};
let pinned_order = attributes
.get_typed::<Vec<NodeId>>(network::PINNED_ORDER)
.unwrap_or_default()
.into_iter()
.filter_map(to_runtime_id)
.collect();
NetworkMetadataEntry {
network_path: network_path.to_vec(),
network_id,
reference: attributes.get_typed(node::ui::REFERENCE),
pinned_order,
}
}
-21
View File
@@ -1,21 +0,0 @@
[package]
name = "document-live"
description = "A memory-backed document following or hosting a collaborative session, for viewers and embedders"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
publish.workspace = true
[dependencies]
document-container = { workspace = true }
document-format = { workspace = true }
document-graph-storage = { workspace = true }
peer-transport = { workspace = true }
graph-craft = { workspace = true }
thiserror = { workspace = true }
log = { workspace = true }
[lints]
workspace = true
-116
View File
@@ -1,116 +0,0 @@
//! A document that lives in a collaborative session rather than on disk. Hosts a session or follows
//! one, and hands out the current runtime `NodeNetwork` on demand. Owns no executor, window, or
//! async runtime: the caller spawns the transport driver and decides how to render.
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout, ResourceProxy};
use document_graph_storage::{PeerId, UserId};
use graph_craft::document::NodeNetwork;
use peer_transport::{Room, SyncTarget};
pub use document_format::Error as FormatError;
pub use document_graph_storage::to_runtime::ConversionError;
pub use peer_transport::{DEFAULT_SIGNALING_SERVER, Event, MessageLoopFuture, Role, SessionToken};
#[derive(Debug, thiserror::Error)]
pub enum LiveError {
#[error(transparent)]
Format(#[from] FormatError),
#[error(transparent)]
Conversion(#[from] ConversionError),
}
pub struct LiveDocument {
gdd: GddV1,
token: SessionToken,
}
impl LiveDocument {
/// Create an empty document and host a session under `token`. `spawn` must drive the returned
/// future for as long as the session lives.
pub async fn host(signaling_server: &str, token: SessionToken, peer: PeerId, user: UserId, spawn: impl FnOnce(MessageLoopFuture)) -> Result<Self, LiveError> {
let gdd = Self::empty_document(peer).await?;
Ok(Self::host_document(gdd, signaling_server, token, user, spawn))
}
/// Host a session on an already opened document.
pub fn host_document(mut gdd: GddV1, signaling_server: &str, token: SessionToken, user: UserId, spawn: impl FnOnce(MessageLoopFuture)) -> Self {
let (room, driver) = Room::connect(&token.signaling_url(signaling_server));
spawn(driver);
gdd.share(room, user);
Self { gdd, token }
}
/// Join the session under `token`; the document fills in once the host's sync arrives.
pub async fn join(signaling_server: &str, token: SessionToken, peer: PeerId, user: UserId, spawn: impl FnOnce(MessageLoopFuture)) -> Result<Self, LiveError> {
let mut gdd = Self::empty_document(peer).await?;
let (room, driver) = Room::connect(&token.signaling_url(signaling_server));
spawn(driver);
gdd.join(room, user);
Ok(Self { gdd, token })
}
async fn empty_document(peer: PeerId) -> Result<GddV1, FormatError> {
let version = env!("CARGO_PKG_VERSION").to_string();
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, peer, peer.0, version.clone(), version).await
}
pub fn token(&self) -> SessionToken {
self.token
}
pub fn role(&self) -> Option<Role> {
self.gdd.role()
}
pub fn is_synced(&self) -> bool {
self.gdd.is_synced()
}
/// Synced and holding every resource the document references, so `network` can be built and run.
pub fn is_ready(&self) -> bool {
self.is_synced() && SyncTarget::missing_resources(&self.gdd).is_empty()
}
/// Apply whatever peers sent since the last call and answer their resource requests. Call it regularly.
pub async fn poll(&mut self) -> Vec<Event> {
let events = self.gdd.poll_peers();
for event in &events {
let Event::ResourceRequested { from, hash } = event else { continue };
match self.gdd.read_resource(hash).await {
Ok(bytes) => {
if let Err(error) = self.gdd.send_resource(*from, *hash, bytes.as_slice().to_vec()) {
log::warn!("Failed to send resource {hash}: {error}");
}
}
Err(error) => log::warn!("Peer asked for resource {hash} which is not in this document: {error}"),
}
}
events
}
pub fn document(&self) -> &GddV1 {
&self.gdd
}
pub fn document_mut(&mut self) -> &mut GddV1 {
&mut self.gdd
}
/// The current runtime graph, rebuilt from the registry. Async because proto-node declarations are resources.
pub async fn network(&self) -> Result<NodeNetwork, LiveError> {
let declarations = self.gdd.declarations(&self.gdd).await;
let (network, _metadata) = self.gdd.registry().to_runtime_with_metadata(&declarations)?;
Ok(network)
}
/// Byte store for resources received from peers, for an executor to load from.
pub fn resource_proxy(&self) -> ResourceProxy<GddV1Layout> {
self.gdd.resource_proxy()
}
pub fn leave(&mut self) {
self.gdd.leave();
}
}
-34
View File
@@ -1,34 +0,0 @@
[package]
name = "peer-transport"
description = "Peer-to-peer sync of hot ops and retired history between document-graph-storage sessions over WebRTC"
rust-version.workspace = true
edition.workspace = true
authors.workspace = true
homepage.workspace = true
repository.workspace = true
license.workspace = true
version.workspace = true
publish.workspace = true
[dependencies]
core-types = { workspace = true }
document-graph-storage = { workspace = true }
matchbox_socket = "0.14.0"
futures = { workspace = true }
log = { workspace = true }
serde = { workspace = true }
serde_bytes = { workspace = true }
rmp-serde = { workspace = true }
base64 = { workspace = true }
thiserror = { workspace = true }
uuid = "1"
[target.'cfg(not(target_family = "wasm"))'.dependencies]
rustls = { version = "0.23", default-features = false, features = ["ring"] }
[dev-dependencies]
serde_json = { workspace = true }
env_logger = { workspace = true }
[lints]
workspace = true
-19
View File
@@ -1,19 +0,0 @@
pub mod mock;
mod packet;
mod replica;
mod room;
mod target;
mod token;
mod transport;
pub use packet::{PacketError, Role, SyncPacket, SyncPayload};
pub use replica::{Event, Replica, ReplicaError};
pub use room::Room;
pub use target::{SyncTarget, TargetError};
pub use token::{InvalidSessionToken, SessionToken};
pub use transport::{Transport, TransportEvent, TransportPeerId};
pub use matchbox_socket::MessageLoopFuture;
/// Matchbox signaling server for sessions, behind TLS so browsers on HTTPS pages can reach it.
pub const DEFAULT_SIGNALING_SERVER: &str = "wss://graphite.kobert.dev";
-175
View File
@@ -1,175 +0,0 @@
//! In-process transport for deterministic simulation. Every packet sits in a per-(sender, receiver)
//! queue until `step` delivers it, so interleavings across peers are driven by the seed while each
//! pair stays ordered like a reliable channel.
use crate::packet::{PacketError, SyncPacket};
use crate::transport::{Transport, TransportEvent, TransportPeerId};
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::sync::{Arc, Mutex};
#[derive(Default)]
struct Shared {
connected: Vec<TransportPeerId>,
inboxes: HashMap<TransportPeerId, VecDeque<TransportEvent>>,
in_flight: BTreeMap<(TransportPeerId, TransportPeerId), VecDeque<SyncPacket>>,
next_peer: u128,
}
impl Shared {
fn disconnect(&mut self, id: TransportPeerId) {
self.connected.retain(|&other| other != id);
self.in_flight.retain(|&(from, to), _| from != id && to != id);
for &other in &self.connected.clone() {
self.inboxes.entry(other).or_default().push_back(TransportEvent::PeerDisconnected(id));
self.inboxes.entry(id).or_default().push_back(TransportEvent::PeerDisconnected(other));
}
}
}
pub struct MockNetwork {
shared: Arc<Mutex<Shared>>,
rng: SplitMix64,
}
impl MockNetwork {
pub fn new(seed: u64) -> Self {
Self {
shared: Arc::new(Mutex::new(Shared::default())),
rng: SplitMix64(seed),
}
}
/// A new, not yet connected peer.
pub fn endpoint(&mut self) -> MockEndpoint {
let mut shared = self.shared.lock().unwrap();
shared.next_peer += 1;
let id = TransportPeerId(uuid::Uuid::from_u128(shared.next_peer));
shared.inboxes.insert(id, VecDeque::new());
MockEndpoint {
id,
shared: self.shared.clone(),
known_peers: Vec::new(),
}
}
pub fn connect(&mut self, id: TransportPeerId) {
let mut shared = self.shared.lock().unwrap();
if shared.connected.contains(&id) {
return;
}
for &other in &shared.connected.clone() {
shared.inboxes.entry(other).or_default().push_back(TransportEvent::PeerConnected(id));
shared.inboxes.entry(id).or_default().push_back(TransportEvent::PeerConnected(other));
}
shared.connected.push(id);
}
pub fn disconnect(&mut self, id: TransportPeerId) {
self.shared.lock().unwrap().disconnect(id);
}
pub fn pending(&self) -> usize {
self.shared.lock().unwrap().in_flight.values().map(VecDeque::len).sum()
}
/// Deliver one in-flight packet from a randomly chosen sender/receiver pair.
pub fn step(&mut self) -> bool {
let mut shared = self.shared.lock().unwrap();
let queues: Vec<_> = shared.in_flight.iter().filter(|(_, queue)| !queue.is_empty()).map(|(&key, _)| key).collect();
if queues.is_empty() {
return false;
}
let (from, to) = queues[self.rng.below(queues.len())];
let packet = shared.in_flight.get_mut(&(from, to)).and_then(VecDeque::pop_front).expect("queue is non-empty");
shared.inboxes.entry(to).or_default().push_back(TransportEvent::Packet(from, packet));
true
}
pub fn deliver_all(&mut self) {
while self.step() {}
}
/// Deliver everything in flight to one peer, leaving every other peer's queues untouched. Random
/// stepping cannot target a receiver, so this is how a test puts a packet in one peer's hands and
/// not another's.
pub fn deliver_to(&mut self, to: TransportPeerId) {
let mut shared = self.shared.lock().unwrap();
let queues: Vec<_> = shared.in_flight.keys().copied().filter(|&(_, receiver)| receiver == to).collect();
for key in queues {
let packets: VecDeque<SyncPacket> = shared.in_flight.get_mut(&key).map(std::mem::take).unwrap_or_default();
for packet in packets {
shared.inboxes.entry(to).or_default().push_back(TransportEvent::Packet(key.0, packet));
}
}
}
pub fn random_below(&mut self, bound: usize) -> usize {
self.rng.below(bound)
}
}
/// Like a real socket, an endpoint only knows the peers whose connect events it has polled, so it
/// can't send to a peer before it had the chance to greet it.
pub struct MockEndpoint {
id: TransportPeerId,
shared: Arc<Mutex<Shared>>,
known_peers: Vec<TransportPeerId>,
}
impl MockEndpoint {
pub fn id(&self) -> TransportPeerId {
self.id
}
}
impl Transport for MockEndpoint {
fn send(&mut self, to: TransportPeerId, packet: &SyncPacket) -> Result<(), PacketError> {
if self.known_peers.contains(&to) {
self.shared.lock().unwrap().in_flight.entry((self.id, to)).or_default().push_back(packet.clone());
}
Ok(())
}
fn broadcast_except(&mut self, excluded: Option<TransportPeerId>, packet: &SyncPacket) -> Result<(), PacketError> {
for to in self.known_peers.clone() {
if Some(to) != excluded {
self.send(to, packet)?;
}
}
Ok(())
}
fn poll(&mut self) -> Vec<TransportEvent> {
let events: Vec<_> = self.shared.lock().unwrap().inboxes.get_mut(&self.id).map(|inbox| inbox.drain(..).collect()).unwrap_or_default();
for event in &events {
match event {
TransportEvent::PeerConnected(peer) => self.known_peers.push(*peer),
TransportEvent::PeerDisconnected(peer) => self.known_peers.retain(|known| known != peer),
_ => {}
}
}
events
}
fn close(&mut self) {
self.shared.lock().unwrap().disconnect(self.id);
}
}
struct SplitMix64(u64);
impl SplitMix64 {
fn next(&mut self) -> u64 {
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = self.0;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
fn below(&mut self, bound: usize) -> usize {
(self.next() % bound as u64) as usize
}
}
-100
View File
@@ -1,100 +0,0 @@
use document_graph_storage::{Delta, HotOp, HotOpId, PeerId, Registry, ResourceHash, RetiredMarks, Rev, UserId};
use serde::{Deserialize, Serialize};
/// The host is the single peer that retires hot ops.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Role {
Host,
Guest,
}
/// How far one peer's broadcasts had got. A peer keeps its `PeerId` across a reconnect but restarts
/// `seq`, so `epoch` names the incarnation that produced it and counters from different epochs are
/// never compared.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PeerSeq {
pub peer: PeerId,
pub epoch: u64,
pub seq: u64,
}
/// MessagePack-encoded on the wire.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum SyncPacket {
/// Sent first on every new connection. `epoch` and `seq` anchor the receiver's counter for this
/// sender, since broadcasts made before the connection were never sent to it.
Hello {
peer: PeerId,
user: UserId,
role: Role,
epoch: u64,
seq: u64,
},
/// `known_revs` come from `Session::known_revs`, so the host can send only what's missing.
SyncRequest {
known_revs: Vec<Rev>,
},
Sync(Box<SyncPayload>),
Broadcast(Broadcast),
ResourceRequest(Vec<ResourceHash>),
Resource {
hash: ResourceHash,
#[serde(with = "serde_bytes")]
bytes: Vec<u8>,
},
}
/// The host's answer to a `SyncRequest`. `registry` is only sent when the host recognized none of
/// the requester's revs; otherwise `deltas` extend the requester's history. `seen` is the host's
/// delivery vector at snapshot time, which the guest adopts so later broadcasts line up.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SyncPayload {
pub registry: Option<Registry>,
pub deltas: Vec<Delta>,
pub head: Option<Rev>,
pub hot_log: Vec<HotOp>,
pub known_revs: Vec<Rev>,
pub seen: Vec<PeerSeq>,
/// Which hot ops the history being handed over already covers, so the requester can recognize one
/// it is holding rather than re-entering it as live work.
pub retired: RetiredMarks,
}
/// Causal broadcast envelope. `seq` numbers the sender's broadcasts from 1 within `epoch`, and `seen`
/// is the sender's delivery vector; a receiver holds the packet until it has delivered everything in
/// `seen`.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Broadcast {
pub epoch: u64,
pub seq: u64,
pub seen: Vec<PeerSeq>,
pub body: BroadcastBody,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum BroadcastBody {
HotOps(Vec<HotOp>),
/// `deltas` are in causal order. `retires` names the hot ops they replace (empty for a plain history transfer).
Deltas {
deltas: Vec<Delta>,
retires: Vec<HotOpId>,
},
}
#[derive(Debug, thiserror::Error)]
pub enum PacketError {
#[error("failed to encode packet: {0}")]
Encode(#[from] rmp_serde::encode::Error),
#[error("failed to decode packet: {0}")]
Decode(#[from] rmp_serde::decode::Error),
}
impl SyncPacket {
pub fn encode(&self) -> Result<Box<[u8]>, PacketError> {
Ok(rmp_serde::to_vec(self)?.into_boxed_slice())
}
pub fn decode(bytes: &[u8]) -> Result<Self, PacketError> {
Ok(rmp_serde::from_slice(bytes)?)
}
}
-588
View File
@@ -1,588 +0,0 @@
use crate::packet::{Broadcast, BroadcastBody, PacketError, PeerSeq, Role, SyncPacket, SyncPayload};
use crate::target::{SyncTarget, TargetError};
use crate::transport::{Transport, TransportEvent, TransportPeerId};
use document_graph_storage::{Delta, HotOp, HotOpId, PeerId, ResourceHash, UserId};
use std::collections::{HashMap, HashSet};
pub enum Event {
PeerJoined {
peer: PeerId,
user: UserId,
},
PeerLeft {
peer: PeerId,
},
/// The guest has applied the host's state.
Synced,
/// Remote ops changed the target.
Changed,
ResourceReceived {
hash: ResourceHash,
bytes: Vec<u8>,
},
/// The target couldn't serve this synchronously; answer with `send_resource`.
ResourceRequested {
from: TransportPeerId,
hash: ResourceHash,
},
}
#[derive(Debug, thiserror::Error)]
pub enum ReplicaError {
#[error(transparent)]
Packet(#[from] PacketError),
#[error(transparent)]
Target(#[from] TargetError),
}
struct RemotePeer {
peer: PeerId,
#[expect(dead_code, reason = "Read once peers are surfaced in the UI")]
user: UserId,
#[expect(dead_code, reason = "Read once host handover is implemented")]
role: Role,
}
/// How far one peer's broadcasts have been delivered here.
#[derive(Clone, Copy)]
struct PeerProgress {
epoch: u64,
seq: u64,
}
/// Broadcasts that arrive before the host's `Sync` are held back, since they target state the guest
/// doesn't have yet.
enum SyncState {
Synced,
AwaitingSync { pending: Vec<(PeerId, Broadcast)> },
}
/// Protocol state for one peer in a room. Owns no document; `poll` applies into a `SyncTarget`.
///
/// Broadcasts are delivered in causal order: each carries the sender's sequence number and delivery
/// vector, and is held until everything the sender had delivered has been delivered here too.
pub struct Replica {
transport: Box<dyn Transport>,
role: Role,
peer: PeerId,
user: UserId,
peers: HashMap<TransportPeerId, RemotePeer>,
sync: SyncState,
/// This incarnation, drawn fresh so a reconnect or a reload never reuses one. See [`PeerSeq`].
epoch: u64,
seq: u64,
delivered: HashMap<PeerId, PeerProgress>,
held: Vec<(PeerId, Broadcast)>,
/// Hot ops whose referents had not arrived when they did, retried as later ops fill the gaps.
/// A missing entity is not distinguishable from one that was concurrently removed, so the op is
/// kept rather than applied against state it does not fit.
deferred: Vec<HotOp>,
/// Broadcasts that arrived before their sender's hello, parked rather than dropped so a reordering
/// on a fresh link cannot lose ops.
ungreeted: HashMap<TransportPeerId, Vec<Broadcast>>,
/// Resources asked for and not yet received, so a standing request is not resent every poll.
requested_resources: HashSet<ResourceHash>,
/// Requests that arrived before the bytes did, answered once they turn up here.
owed_resources: HashMap<ResourceHash, HashSet<TransportPeerId>>,
/// Whether the target's resource references may have moved since they were last examined.
resources_stale: bool,
}
impl Replica {
pub fn host(transport: impl Transport + 'static, peer: PeerId, user: UserId) -> Self {
Self::new(Box::new(transport), Role::Host, peer, user, SyncState::Synced)
}
pub fn guest(transport: impl Transport + 'static, peer: PeerId, user: UserId) -> Self {
Self::new(Box::new(transport), Role::Guest, peer, user, SyncState::AwaitingSync { pending: Vec::new() })
}
fn new(transport: Box<dyn Transport>, role: Role, peer: PeerId, user: UserId, sync: SyncState) -> Self {
Self {
transport,
role,
peer,
user,
peers: HashMap::new(),
sync,
epoch: core_types::uuid::generate_uuid(),
seq: 0,
delivered: HashMap::new(),
held: Vec::new(),
deferred: Vec::new(),
ungreeted: HashMap::new(),
requested_resources: HashSet::new(),
owed_resources: HashMap::new(),
resources_stale: false,
}
}
pub fn role(&self) -> Role {
self.role
}
pub fn is_synced(&self) -> bool {
matches!(self.sync, SyncState::Synced)
}
/// Broadcasts waiting on causal dependencies. Non-zero in an idle room means a stuck delivery.
pub fn held_broadcasts(&self) -> usize {
self.held.len()
}
/// Ops held back for a referent that had not arrived. Non-zero in an idle room means one never did.
pub fn deferred_ops(&self) -> usize {
self.deferred.len()
}
/// Resources asked for whose bytes have not come back yet.
pub fn pending_resource_requests(&self) -> impl Iterator<Item = ResourceHash> + '_ {
self.requested_resources.iter().copied()
}
pub fn broadcast_hot_ops(&mut self, ops: &[HotOp]) -> Result<(), PacketError> {
if ops.is_empty() {
return Ok(());
}
// A local edit can name a resource whose bytes are not here, a pasted node referencing a font for
// instance, so the references are worth re-examining even though nothing arrived from the wire.
self.resources_stale = true;
self.broadcast(BroadcastBody::HotOps(ops.to_vec()))
}
/// Host only.
pub fn broadcast_retired(&mut self, deltas: &[Delta], retires: &[HotOpId]) -> Result<(), PacketError> {
debug_assert_eq!(self.role, Role::Host);
if deltas.is_empty() {
return Ok(());
}
// Retirement moves ops into history, which referenced resources are read from as well as from the
// registry, so a hash the registry has since overwritten becomes referenced again from here.
self.resources_stale = true;
self.broadcast(BroadcastBody::Deltas {
deltas: deltas.to_vec(),
retires: retires.to_vec(),
})
}
fn broadcast(&mut self, body: BroadcastBody) -> Result<(), PacketError> {
self.seq += 1;
let broadcast = Broadcast {
epoch: self.epoch,
seq: self.seq,
seen: self.seen_vector(),
body,
};
self.transport.broadcast(&SyncPacket::Broadcast(broadcast))
}
/// Everything delivered here, including this peer's own broadcasts.
fn seen_vector(&self) -> Vec<PeerSeq> {
let delivered = self.delivered.iter().map(|(&peer, progress)| PeerSeq {
peer,
epoch: progress.epoch,
seq: progress.seq,
});
delivered
.chain([PeerSeq {
peer: self.peer,
epoch: self.epoch,
seq: self.seq,
}])
.collect()
}
pub fn send_resource(&mut self, to: TransportPeerId, hash: ResourceHash, bytes: Vec<u8>) -> Result<(), PacketError> {
self.transport.send(to, &SyncPacket::Resource { hash, bytes })
}
pub fn leave(&mut self) {
self.transport.close();
}
pub fn poll(&mut self, target: &mut dyn SyncTarget) -> Vec<Event> {
let mut events = Vec::new();
let transport_events = self.transport.poll();
// Greet every new peer before handling anything else in the batch. A transport adds them to its
// send set for the whole batch up front, so a broadcast made while handling an earlier event
// would reach a peer that has not been greeted; the hello that followed would then carry a
// sequence number covering it, and the receiver would rightly treat those ops as unneeded.
for transport_event in &transport_events {
if let TransportEvent::PeerConnected(transport_peer) = transport_event
&& let Err(error) = self.send_hello(*transport_peer)
{
log::error!("Sync error: {error}");
}
}
for transport_event in transport_events {
let result = match transport_event {
TransportEvent::PeerConnected(_) => Ok(()),
TransportEvent::PeerDisconnected(transport_peer) => {
let departed = self.peers.remove(&transport_peer);
if let Some(remote) = &departed {
events.push(Event::PeerLeft { peer: remote.peer });
}
// A peer that left may have been the one still owing bytes, so let the rest be asked again.
self.requested_resources.clear();
self.resources_stale = true;
// The hello those were waiting on is never coming now.
self.ungreeted.remove(&transport_peer);
match departed {
Some(remote) => self.close_epoch(remote.peer, target, &mut events),
None => Ok(()),
}
}
TransportEvent::Packet(transport_peer, packet) => self.handle_packet(transport_peer, packet, target, &mut events),
TransportEvent::Malformed(transport_peer, error) => {
log::warn!("Dropping malformed packet from {transport_peer}: {error}");
Ok(())
}
};
if let Err(error) = result {
log::error!("Sync error: {error}");
}
}
self.retry_deferred(target, &mut events);
if let Err(error) = target.flush() {
log::error!("Sync error: {error}");
}
if let Err(error) = self.request_missing_resources(target) {
log::error!("Sync error: {error}");
}
if let Err(error) = self.serve_owed_resources(target) {
log::error!("Sync error: {error}");
}
events
}
/// Re-announce every hot op held here that history does not yet cover, whoever wrote it. A peer can
/// hold the only copy of another's op, so replaying only our own would leave that one to die with the
/// connection it arrived on. Ops the watermark covers replay as no-ops on every receiver.
fn reannounce_hot_ops(&mut self, target: &dyn SyncTarget) -> Result<(), PacketError> {
let retired = target.retired_marks();
let unretired: Vec<HotOp> = target.hot_log().into_iter().filter(|hot_op| !retired.covers(hot_op.id())).collect();
self.broadcast_hot_ops(&unretired)
}
/// Retry ops held back for a missing referent. A later op can supply the entity an earlier one
/// named, so this runs once per poll rather than only where the op arrived.
fn retry_deferred(&mut self, target: &mut dyn SyncTarget, events: &mut Vec<Event>) {
if self.deferred.is_empty() {
return;
}
let pending = std::mem::take(&mut self.deferred);
let waiting = pending.len();
match target.apply_remote_hot_ops(pending) {
Ok(deferred) => {
// One that finally applied can name a resource nobody here has seen, and leaves the target
// changed, neither of which anything else in the poll would notice.
if deferred.len() < waiting {
self.resources_stale = true;
events.push(Event::Changed);
}
self.deferred = deferred;
}
Err(error) => log::error!("Retrying deferred hot ops: {error}"),
}
}
/// Ask the room for referenced bytes nobody here has yet. Runs after every batch of packets rather
/// than once at sync, since an op delivered later can reference a resource this peer has never seen.
/// Only the hashes without a standing request go out, so a slow transfer is not re-requested.
fn request_missing_resources(&mut self, target: &dyn SyncTarget) -> Result<(), PacketError> {
if !self.resources_stale {
return Ok(());
}
self.resources_stale = false;
let missing = target.missing_resources();
// A resource that turned up some other way, staged here for instance, leaves its request behind.
// Clearing those keeps a later ask for the same hash from being suppressed.
self.requested_resources.retain(|hash| missing.contains(hash));
let unasked: Vec<ResourceHash> = missing.into_iter().filter(|hash| !self.requested_resources.contains(hash)).collect();
if unasked.is_empty() {
return Ok(());
}
self.requested_resources.extend(unasked.iter().copied());
self.transport.broadcast(&SyncPacket::ResourceRequest(unasked))
}
/// Answer requests that arrived before their bytes did. A resource can turn up locally rather than
/// over the wire, so this runs every poll; a requester never asks twice, so nothing else would.
fn serve_owed_resources(&mut self, target: &dyn SyncTarget) -> Result<(), PacketError> {
if self.owed_resources.is_empty() {
return Ok(());
}
let ready: Vec<(ResourceHash, Vec<u8>)> = self.owed_resources.keys().filter_map(|&hash| target.resource_bytes(hash).map(|bytes| (hash, bytes))).collect();
for (hash, bytes) in ready {
for to in self.owed_resources.remove(&hash).unwrap_or_default() {
self.transport.send(to, &SyncPacket::Resource { hash, bytes: bytes.clone() })?;
}
}
Ok(())
}
fn send_hello(&mut self, transport_peer: TransportPeerId) -> Result<(), ReplicaError> {
let hello = SyncPacket::Hello {
peer: self.peer,
user: self.user,
role: self.role,
epoch: self.epoch,
seq: self.seq,
};
self.transport.send(transport_peer, &hello)?;
Ok(())
}
fn handle_packet(&mut self, from: TransportPeerId, packet: SyncPacket, target: &mut dyn SyncTarget, events: &mut Vec<Event>) -> Result<(), ReplicaError> {
match packet {
SyncPacket::Hello { peer, user, role, epoch, seq } => {
self.peers.insert(from, RemotePeer { peer, user, role });
self.anchor_delivered(peer, epoch, seq);
// Now that the sender is known, whatever arrived ahead of its hello can be handled.
for broadcast in self.ungreeted.remove(&from).unwrap_or_default() {
self.handle_packet(from, SyncPacket::Broadcast(broadcast), target, events)?;
}
// The anchor can unblock broadcasts held against the counter an earlier link reached.
self.deliver_held(target, events)?;
self.reannounce_hot_ops(&*target)?;
events.push(Event::PeerJoined { peer, user });
// A fresh peer may hold bytes nobody else here could serve.
self.requested_resources.clear();
self.resources_stale = true;
if role == Role::Host && !self.is_synced() {
self.transport.send(from, &SyncPacket::SyncRequest { known_revs: target.known_revs() })?;
}
}
SyncPacket::SyncRequest { known_revs } => {
if self.role != Role::Host {
return Ok(());
}
let shares_history = known_revs.iter().any(|&rev| target.contains_rev(rev));
let sync = SyncPayload {
registry: (!shares_history).then(|| target.retired_registry()),
deltas: target.deltas_unknown_to(&known_revs),
head: target.head(),
hot_log: target.hot_log(),
known_revs: target.known_revs(),
seen: self.seen_vector(),
retired: target.retired_marks(),
};
self.transport.send(from, &SyncPacket::Sync(Box::new(sync)))?;
}
SyncPacket::Sync(sync) => {
let SyncState::AwaitingSync { pending } = std::mem::replace(&mut self.sync, SyncState::Synced) else {
return Ok(());
};
match sync.registry {
Some(registry) => target.load(registry, sync.deltas, sync.head)?,
None => target.merge_remote(sync.deltas, &[])?,
}
target.absorb_retired_marks(&sync.retired)?;
self.deferred.extend(target.apply_remote_hot_ops(sync.hot_log)?);
self.resources_stale = true;
// The host's hot log is not a superset of the room's: this peer may hold the only copy of an
// op that never reached the host, and history is the only way it survives.
self.reannounce_hot_ops(&*target)?;
// Broadcasts the host had delivered before answering are already reflected in the snapshot.
for mark in sync.seen {
self.observe_delivered(mark);
}
// An earlier seq is baked into the snapshot already.
let worth_holding: Vec<(PeerId, Broadcast)> = pending.into_iter().filter(|(sender, broadcast)| self.worth_holding(*sender, broadcast)).collect();
self.held.extend(worth_holding);
self.deliver_held(target, events)?;
let host_is_missing = target.deltas_unknown_to(&sync.known_revs);
if !host_is_missing.is_empty() {
self.broadcast(BroadcastBody::Deltas {
deltas: host_is_missing,
retires: Vec::new(),
})?;
}
// Hot ops only ever existed in flight, so a drop loses them where retired work survives in
// history. Re-announce the ones authored here.
let own_hot_ops: Vec<HotOp> = target.hot_log().into_iter().filter(|hot_op| hot_op.timestamp.peer == self.peer).collect();
self.broadcast_hot_ops(&own_hot_ops)?;
events.push(Event::Synced);
}
SyncPacket::Broadcast(broadcast) => {
// Its sender is only known from a hello, so park it rather than drop it.
let Some(remote) = self.peers.get(&from) else {
self.ungreeted.entry(from).or_default().push(broadcast);
return Ok(());
};
let sender = remote.peer;
match &mut self.sync {
SyncState::AwaitingSync { pending } => pending.push((sender, broadcast)),
SyncState::Synced => {
if self.worth_holding(sender, &broadcast) {
self.held.push((sender, broadcast));
self.deliver_held(target, events)?;
}
}
}
}
SyncPacket::ResourceRequest(hashes) => {
for hash in hashes {
match target.resource_bytes(hash) {
Some(bytes) => self.transport.send(from, &SyncPacket::Resource { hash, bytes })?,
None => {
self.owed_resources.entry(hash).or_default().insert(from);
events.push(Event::ResourceRequested { from, hash });
}
}
}
}
SyncPacket::Resource { hash, bytes } => {
if ResourceHash::from(bytes.as_slice()) != hash {
log::warn!("Resource from {from} does not match its hash; dropping");
return Ok(());
}
target.store_resource(hash, &bytes)?;
self.requested_resources.remove(&hash);
events.push(Event::ResourceReceived { hash, bytes });
}
}
Ok(())
}
/// Record that a peer's broadcasts up to `mark` need not be waited for. Monotonic, since a hello
/// and a host's `seen` vector can carry the same fact in either order.
fn observe_delivered(&mut self, mark: PeerSeq) {
if mark.peer == self.peer {
return;
}
match self.delivered.get_mut(&mark.peer) {
Some(progress) if progress.epoch == mark.epoch => progress.seq = progress.seq.max(mark.seq),
Some(_) => {}
None => {
self.delivered.insert(mark.peer, PeerProgress { epoch: mark.epoch, seq: mark.seq });
}
}
}
/// Set where a peer's broadcasts resume on a newly opened link. Nothing before its hello was ever
/// sent here, so this replaces rather than raises.
fn anchor_delivered(&mut self, peer: PeerId, epoch: u64, seq: u64) {
if peer == self.peer {
return;
}
self.delivered.insert(peer, PeerProgress { epoch, seq });
// Held broadcasts from an earlier incarnation can never be delivered in order, and the sender
// re-announces what is still hot once it resyncs.
self.held.retain(|(sender, broadcast)| *sender != peer || broadcast.epoch == epoch);
}
/// Settle up after a peer leaves: its own held broadcasts can never fill their gaps, and anything
/// waiting on it is now free to go.
fn close_epoch(&mut self, peer: PeerId, target: &mut dyn SyncTarget, events: &mut Vec<Event>) -> Result<(), ReplicaError> {
// Buffered broadcasts go too, in both queues. Applying them after their author left would mint a
// fresh orphan with no departure left to clean it up, and nothing has been applied yet, so
// dropping them breaks no dependency. Anything else waiting on this peer is released instead.
if let SyncState::AwaitingSync { pending } = &mut self.sync {
pending.retain(|(sender, _)| *sender != peer);
}
self.held.retain(|(sender, _)| *sender != peer);
// Its ops waiting on a referent have nobody left to supply one, so they stop being held open.
// Retirement drains the rest: an op the watermark covers replays as a no-op and leaves the queue.
self.deferred.retain(|hot_op| hot_op.timestamp.peer != peer);
self.deliver_held(target, events)?;
// The departed peer's unretired work reached some peers and not others, and it can no longer
// re-announce the difference itself. Passing on the whole hot tail covers it along with anything
// that depends on it, so the host can retire the lot into history.
self.reannounce_hot_ops(&*target)?;
Ok(())
}
/// Whether a link to this peer is open, meaning more of its broadcasts may still turn up.
fn is_connected(&self, peer: PeerId) -> bool {
self.peers.values().any(|remote| remote.peer == peer)
}
/// Deliver every held broadcast whose causal dependencies are met, repeating since each delivery
/// can unblock others.
fn deliver_held(&mut self, target: &mut dyn SyncTarget, events: &mut Vec<Event>) -> Result<(), ReplicaError> {
while let Some(index) = self.held.iter().position(|(sender, broadcast)| self.is_deliverable(*sender, broadcast)) {
let (sender, broadcast) = self.held.remove(index);
self.delivered.insert(
sender,
PeerProgress {
epoch: broadcast.epoch,
seq: broadcast.seq,
},
);
// Applying is best effort: the ops that did land still have to be accounted for, so a failure
// is reported rather than abandoning the bookkeeping and the rest of the queue.
let applied = match broadcast.body {
BroadcastBody::HotOps(ops) => target.apply_remote_hot_ops(ops).map(|deferred| self.deferred.extend(deferred)),
BroadcastBody::Deltas { deltas, retires } => target.merge_remote(deltas, &retires),
};
if let Err(error) = applied {
log::error!("Applying a delivered broadcast: {error}");
}
self.resources_stale = true;
events.push(Event::Changed);
}
Ok(())
}
fn is_deliverable(&self, sender: PeerId, broadcast: &Broadcast) -> bool {
let Some(progress) = self.delivered.get(&sender) else { return false };
if progress.epoch != broadcast.epoch || broadcast.seq != progress.seq + 1 {
return false;
}
broadcast.seen.iter().all(|&mark| mark.peer == sender || self.has_delivered(mark))
}
/// Whether a broadcast can still come up for delivery. A stale epoch or an already-delivered seq
/// never will, so holding one would park it for good.
fn worth_holding(&self, sender: PeerId, broadcast: &Broadcast) -> bool {
self.delivered.get(&sender).is_none_or(|progress| progress.epoch == broadcast.epoch && broadcast.seq > progress.seq)
}
/// Whether one of a broadcast's dependencies is met. Dependencies that can never be met count as
/// met, rather than stalling their sender for good.
fn has_delivered(&self, mark: PeerSeq) -> bool {
if mark.peer == self.peer {
return mark.epoch != self.epoch || mark.seq <= self.seq;
}
match self.delivered.get(&mark.peer) {
Some(progress) if progress.epoch != mark.epoch => true,
Some(progress) if progress.seq >= mark.seq => true,
// A peer with no open link sends nothing more, including one whose hello never arrived.
_ => !self.is_connected(mark.peer),
}
}
}
-229
View File
@@ -1,229 +0,0 @@
use crate::packet::{PacketError, SyncPacket};
use crate::transport::{Transport, TransportEvent, TransportPeerId};
use matchbox_socket::{MessageLoopFuture, PeerState, WebRtcSocket};
use std::collections::HashMap;
const CHANNEL: usize = 0;
/// Largest SCTP message every browser accepts.
const CHUNK_BYTES: usize = 16 * 1024;
const FRAME_FINAL: u8 = 1;
const FRAME_MORE: u8 = 0;
/// Split a packet into `[flag][bytes]` chunks, the last carrying [`FRAME_FINAL`] so a receiver finds
/// the packet boundary without a length prefix.
fn frames(bytes: &[u8]) -> Vec<Box<[u8]>> {
// An empty packet still gets one frame. Chunking it would yield none at all, and the packet would
// leave no trace on the wire rather than arriving empty.
let chunks: Vec<&[u8]> = if bytes.is_empty() { vec![&[]] } else { bytes.chunks(CHUNK_BYTES).collect() };
chunks
.iter()
.enumerate()
.map(|(index, chunk)| {
let flag = if index + 1 == chunks.len() { FRAME_FINAL } else { FRAME_MORE };
std::iter::once(flag).chain(chunk.iter().copied()).collect()
})
.collect()
}
/// Per-peer reassembly of framed packets. The channel is reliable and ordered per peer, so chunks
/// arrive in the order they were sent and a packet ends at the first [`FRAME_FINAL`].
#[derive(Default)]
struct Reassembler {
partial: HashMap<TransportPeerId, Vec<u8>>,
}
impl Reassembler {
/// The packet's bytes once its final chunk lands, or `None` while more are still to come.
fn accept(&mut self, peer: TransportPeerId, frame: &[u8]) -> Option<Vec<u8>> {
let (&flag, chunk) = frame.split_first()?;
let buffer = self.partial.entry(peer).or_default();
buffer.extend_from_slice(chunk);
(flag == FRAME_FINAL).then(|| std::mem::take(buffer))
}
/// Drop a peer's half-received packet, which nothing will ever complete.
fn forget(&mut self, peer: TransportPeerId) {
self.partial.remove(&peer);
}
}
/// One matchbox room over WebRTC. Packets are split into `[flag][bytes]` chunks; the reliable
/// channel is ordered per peer, so the receiver reassembles by appending until the final flag.
/// The returned future must be polled continuously by the caller.
pub struct Room {
socket: WebRtcSocket,
incoming: Reassembler,
}
impl Room {
pub fn connect(signaling_url: &str) -> (Self, MessageLoopFuture) {
// WebRTC's DTLS goes through rustls, which needs one provider chosen when several are linked.
#[cfg(not(target_family = "wasm"))]
let _ = rustls::crypto::ring::default_provider().install_default();
let (socket, driver) = WebRtcSocket::new_reliable(signaling_url);
(
Self {
socket,
incoming: Reassembler::default(),
},
driver,
)
}
fn send_chunks(&mut self, bytes: &[u8], peers: &[TransportPeerId]) {
let channel = self.socket.channel_mut(CHANNEL);
for frame in frames(bytes) {
for &peer in peers {
channel.send(frame.clone(), peer);
}
}
}
}
impl Transport for Room {
fn send(&mut self, to: TransportPeerId, packet: &SyncPacket) -> Result<(), PacketError> {
let bytes = packet.encode()?;
self.send_chunks(&bytes, &[to]);
Ok(())
}
fn broadcast_except(&mut self, excluded: Option<TransportPeerId>, packet: &SyncPacket) -> Result<(), PacketError> {
let bytes = packet.encode()?;
let peers: Vec<_> = self.socket.connected_peers().filter(|&peer| Some(peer) != excluded).collect();
self.send_chunks(&bytes, &peers);
Ok(())
}
fn poll(&mut self) -> Vec<TransportEvent> {
let mut events = Vec::new();
for (peer, state) in self.socket.update_peers() {
events.push(match state {
PeerState::Connected => TransportEvent::PeerConnected(peer),
PeerState::Disconnected => {
self.incoming.forget(peer);
TransportEvent::PeerDisconnected(peer)
}
});
}
let received: Vec<_> = self.socket.channel_mut(CHANNEL).receive();
for (peer, frame) in received {
let Some(bytes) = self.incoming.accept(peer, &frame) else { continue };
events.push(match SyncPacket::decode(&bytes) {
Ok(packet) => TransportEvent::Packet(peer, packet),
Err(error) => TransportEvent::Malformed(peer, error),
});
}
events
}
fn close(&mut self) {
self.socket.close();
}
}
#[cfg(test)]
mod tests {
use super::*;
fn peer(byte: u128) -> TransportPeerId {
TransportPeerId(uuid::Uuid::from_u128(byte))
}
/// Push every frame at a reassembler and collect whatever packets come back out.
fn round_trip(bytes: &[u8]) -> Vec<Vec<u8>> {
let mut incoming = Reassembler::default();
frames(bytes).into_iter().filter_map(|frame| incoming.accept(peer(1), &frame)).collect()
}
/// A packet within one chunk travels as a single final frame.
#[test]
fn a_small_packet_is_one_frame() {
let bytes = b"hello".to_vec();
let framed = frames(&bytes);
assert_eq!(framed.len(), 1);
assert_eq!(framed[0][0], FRAME_FINAL);
assert_eq!(round_trip(&bytes), vec![bytes]);
}
/// Chunking an empty packet yields no chunks at all, so it needs a frame of its own or it would
/// leave no trace on the wire.
#[test]
fn an_empty_packet_still_produces_one_frame() {
let framed = frames(&[]);
assert_eq!(framed.len(), 1, "an empty packet must still be framed");
assert_eq!(framed[0][0], FRAME_FINAL);
assert_eq!(round_trip(&[]), vec![Vec::<u8>::new()]);
}
/// The boundary either side of the SCTP limit: exactly one chunk stays one frame, one byte more
/// splits, and both rebuild byte for byte.
#[test]
fn packets_around_the_chunk_boundary_round_trip() {
for length in [CHUNK_BYTES - 1, CHUNK_BYTES, CHUNK_BYTES + 1, CHUNK_BYTES * 3 + 7] {
let bytes: Vec<u8> = (0..length).map(|index| (index % 251) as u8).collect();
let framed = frames(&bytes);
assert_eq!(framed.len(), length.div_ceil(CHUNK_BYTES), "wrong frame count for {length} bytes");
assert!(framed.iter().all(|frame| frame.len() <= CHUNK_BYTES + 1), "a frame exceeded the SCTP limit");
assert!(framed.iter().rev().skip(1).all(|frame| frame[0] == FRAME_MORE), "only the last frame is final");
assert_eq!(framed.last().expect("at least one frame")[0], FRAME_FINAL);
assert_eq!(round_trip(&bytes), vec![bytes], "{length} bytes did not round trip");
}
}
/// Two peers' chunks interleave on one channel, so reassembly is per peer or one packet would be
/// spliced into the other.
#[test]
fn interleaved_peers_reassemble_separately() {
let (first, second) = (peer(1), peer(2));
let mut incoming = Reassembler::default();
let long: Vec<u8> = (0..CHUNK_BYTES + 32).map(|index| (index % 97) as u8).collect();
let short = b"short".to_vec();
let long_frames = frames(&long);
let short_frames = frames(&short);
assert_eq!(long_frames.len(), 2, "the long packet must span two frames to interleave");
// The short packet arrives whole between the long packet's two chunks.
assert_eq!(incoming.accept(first, &long_frames[0]), None);
assert_eq!(incoming.accept(second, &short_frames[0]), Some(short));
assert_eq!(incoming.accept(first, &long_frames[1]), Some(long));
}
/// A peer that drops mid-packet leaves a partial buffer, which must not be prepended to whatever
/// the next peer to reuse that id sends.
#[test]
fn forgetting_a_peer_discards_its_partial_packet() {
let sender = peer(1);
let mut incoming = Reassembler::default();
let long: Vec<u8> = (0..CHUNK_BYTES + 8).map(|index| (index % 89) as u8).collect();
assert_eq!(incoming.accept(sender, &frames(&long)[0]), None);
incoming.forget(sender);
let fresh = b"fresh".to_vec();
assert_eq!(incoming.accept(sender, &frames(&fresh)[0]), Some(fresh), "the abandoned prefix must be gone");
}
/// A zero-length frame carries no flag byte, so it is ignored rather than read past its end.
#[test]
fn an_empty_frame_is_ignored() {
let mut incoming = Reassembler::default();
assert_eq!(incoming.accept(peer(1), &[]), None);
}
}
-114
View File
@@ -1,114 +0,0 @@
use document_graph_storage::{Delta, HotOp, HotOpId, PeerId, Registry, ResourceHash, RetiredMarks, Rev, Session};
use std::collections::HashSet;
pub type TargetError = Box<dyn std::error::Error>;
/// The document state a `Replica` reads from and applies remote changes to.
pub trait SyncTarget {
fn peer(&self) -> PeerId;
fn head(&self) -> Option<Rev>;
fn retired_registry(&self) -> Registry;
fn hot_log(&self) -> Vec<HotOp>;
fn known_revs(&self) -> Vec<Rev>;
fn contains_rev(&self, rev: Rev) -> bool;
fn deltas_unknown_to(&self, known: &[Rev]) -> Vec<Delta>;
/// Highest hot-op counter retired per author.
fn retired_marks(&self) -> RetiredMarks;
/// Take on a peer's retirement watermark, dropping any hot op it shows as already retired.
fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> Result<(), TargetError>;
/// Replace all state with the given retired state.
fn load(&mut self, registry: Registry, history: Vec<Delta>, head: Option<Rev>) -> Result<(), TargetError>;
/// Must be idempotent on structural ops: a buffered op may already be reflected by the sync.
/// Returns the ops it could not apply, whose referents have not arrived yet; the caller retries
/// them as later ops fill the gaps.
fn apply_remote_hot_ops(&mut self, ops: Vec<HotOp>) -> Result<Vec<HotOp>, TargetError>;
fn merge_remote(&mut self, deltas: Vec<Delta>, retires: &[HotOpId]) -> Result<(), TargetError>;
/// Make everything applied since the last flush durable. Called once per [`Replica::poll`](crate::Replica::poll),
/// so a target that rewrites whole files can do it once for a batch rather than once per packet.
fn flush(&mut self) -> Result<(), TargetError> {
Ok(())
}
/// Referenced resources whose bytes are not available locally.
fn missing_resources(&self) -> HashSet<ResourceHash> {
HashSet::new()
}
/// `None` when the bytes can't be produced synchronously; the request is then surfaced as an event.
fn resource_bytes(&self, hash: ResourceHash) -> Option<Vec<u8>> {
let _ = hash;
None
}
fn store_resource(&mut self, hash: ResourceHash, bytes: &[u8]) -> Result<(), TargetError> {
let _ = (hash, bytes);
Ok(())
}
}
impl SyncTarget for Session {
fn peer(&self) -> PeerId {
Session::peer(self)
}
fn head(&self) -> Option<Rev> {
self.head_rev()
}
fn retired_registry(&self) -> Registry {
Session::retired_registry(self).clone()
}
fn hot_log(&self) -> Vec<HotOp> {
Session::hot_log(self).to_vec()
}
fn known_revs(&self) -> Vec<Rev> {
Session::known_revs(self)
}
fn contains_rev(&self, rev: Rev) -> bool {
self.delta(rev).is_some()
}
fn deltas_unknown_to(&self, known: &[Rev]) -> Vec<Delta> {
Session::deltas_unknown_to(self, known.iter().copied()).into_iter().cloned().collect()
}
fn load(&mut self, registry: Registry, history: Vec<Delta>, head: Option<Rev>) -> Result<(), TargetError> {
// Kept across the replace: a sequence this peer already spent must not come round again, or an
// op of its own would be taken for one already retired.
*self = Session::load(self.peer(), registry, history, head, Vec::new(), self.next_node_counter(), self.next_hot_sequence());
Ok(())
}
fn apply_remote_hot_ops(&mut self, ops: Vec<HotOp>) -> Result<Vec<HotOp>, TargetError> {
// Every op gets its turn even if one fails, since the broadcast that carried them is consumed by
// the time this runs. A failure usually means the entity the op names has not arrived here yet,
// so it is handed back to be retried rather than dropped.
let mut deferred = Vec::new();
for hot_op in ops {
if self.replay_hot_op(hot_op.clone()).is_err() {
deferred.push(hot_op);
}
}
Ok(deferred)
}
fn merge_remote(&mut self, deltas: Vec<Delta>, retires: &[HotOpId]) -> Result<(), TargetError> {
// Hot ops stay until after the merge: a delta may target something a still-hot removal took away.
self.merge(deltas)?;
self.discard_hot_ops(retires);
Ok(())
}
fn retired_marks(&self) -> RetiredMarks {
Session::retired_marks(self).clone()
}
fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> Result<(), TargetError> {
Session::absorb_retired_marks(self, remote);
Ok(())
}
}
-55
View File
@@ -1,55 +0,0 @@
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use std::fmt;
use std::str::FromStr;
/// Identifies the text form as a Graphite session token, like GitLab's `glpat-` tokens.
const PREFIX: &str = "graphite-";
/// Random session ID, used as the matchbox room name. Entropy is supplied by the caller.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct SessionToken(pub [u8; 16]);
impl SessionToken {
pub fn signaling_url(&self, signaling_server: &str) -> String {
format!("{}/{}", signaling_server.trim_end_matches('/'), self)
}
}
impl fmt::Display for SessionToken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{PREFIX}{}", URL_SAFE_NO_PAD.encode(self.0))
}
}
#[derive(Debug, thiserror::Error)]
#[error("invalid session token")]
pub struct InvalidSessionToken;
impl FromStr for SessionToken {
type Err = InvalidSessionToken;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let encoded = s.strip_prefix(PREFIX).ok_or(InvalidSessionToken)?;
let bytes = URL_SAFE_NO_PAD.decode(encoded).map_err(|_| InvalidSessionToken)?;
let bytes = bytes.try_into().map_err(|_| InvalidSessionToken)?;
Ok(Self(bytes))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trips_through_string() {
let token = SessionToken([7; 16]);
assert_eq!(token.to_string().parse::<SessionToken>().unwrap(), token);
}
#[test]
fn rejects_wrong_length_or_missing_prefix() {
assert!("graphite-AAAA".parse::<SessionToken>().is_err());
assert!("BwcHBwcHBwcHBwcHBwcHBw".parse::<SessionToken>().is_err());
}
}
-23
View File
@@ -1,23 +0,0 @@
use crate::packet::{PacketError, SyncPacket};
pub use matchbox_socket::PeerId as TransportPeerId;
pub enum TransportEvent {
PeerConnected(TransportPeerId),
PeerDisconnected(TransportPeerId),
Packet(TransportPeerId, SyncPacket),
Malformed(TransportPeerId, PacketError),
}
/// Packet delivery between the peers of one session. Delivery must be reliable and ordered per
/// sender, which is what lets the `Replica` skip acknowledgements and buffering.
pub trait Transport: Send + Sync {
fn send(&mut self, to: TransportPeerId, packet: &SyncPacket) -> Result<(), PacketError>;
fn broadcast_except(&mut self, excluded: Option<TransportPeerId>, packet: &SyncPacket) -> Result<(), PacketError>;
fn poll(&mut self) -> Vec<TransportEvent>;
fn close(&mut self);
fn broadcast(&mut self, packet: &SyncPacket) -> Result<(), PacketError> {
self.broadcast_except(None, packet)
}
}
-735
View File
@@ -1,735 +0,0 @@
//! Deterministic simulation over the mock transport: random edits on every peer, random delivery
//! order, random host retirement. After quiescence every peer must hold the same retired state.
//!
//! Inspect one run with `SEED=<n> GUESTS=<n> cargo test -p peer-transport --test simulation inspect_seed -- --ignored --nocapture`.
use document_graph_storage::{
AttributeDelta, Delta, HotOp, HotOpId, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, Priority, Registry, RegistryDelta, ResourceHash, ResourceId, RetiredMarks, Rev,
Session, SourceKey, TimeStamp, UserId,
};
use peer_transport::mock::{MockEndpoint, MockNetwork};
use peer_transport::{Event, Replica, Role, SyncTarget, TargetError, TransportPeerId};
use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicUsize, Ordering};
static TOTAL_NODES: AtomicUsize = AtomicUsize::new(0);
static TOTAL_WIRED: AtomicUsize = AtomicUsize::new(0);
static TOTAL_EXPORTS: AtomicUsize = AtomicUsize::new(0);
static TOTAL_INPUT_ATTRIBUTES: AtomicUsize = AtomicUsize::new(0);
static TOTAL_SOURCES: AtomicUsize = AtomicUsize::new(0);
/// A peer's document plus the byte store the editor keeps application-wide. Bare `Session` takes the
/// trait's no-op resource defaults, which would leave the whole request path unexercised.
struct SimTarget {
session: Session,
resources: HashMap<ResourceHash, Vec<u8>>,
/// History as of the last `flush`, to check the sync path never leaves applied state undurable.
durable_history: Vec<Rev>,
flushes: usize,
/// Every rev this peer has ever held, to check none is later dropped. See [`SimTarget::flush`].
seen_revs: HashSet<Rev>,
seed: u64,
}
impl SimTarget {
fn new(peer: PeerId, seed: u64) -> Self {
Self {
session: Session::with_peer(peer),
resources: HashMap::new(),
durable_history: Vec::new(),
flushes: 0,
seen_revs: HashSet::new(),
seed,
}
}
fn history_revs(&self) -> Vec<Rev> {
self.session.history().map(|delta| delta.id).collect()
}
}
impl SyncTarget for SimTarget {
fn peer(&self) -> PeerId {
SyncTarget::peer(&self.session)
}
fn head(&self) -> Option<Rev> {
SyncTarget::head(&self.session)
}
fn retired_registry(&self) -> Registry {
SyncTarget::retired_registry(&self.session)
}
fn hot_log(&self) -> Vec<HotOp> {
SyncTarget::hot_log(&self.session)
}
fn known_revs(&self) -> Vec<Rev> {
SyncTarget::known_revs(&self.session)
}
fn contains_rev(&self, rev: Rev) -> bool {
SyncTarget::contains_rev(&self.session, rev)
}
fn deltas_unknown_to(&self, known: &[Rev]) -> Vec<Delta> {
SyncTarget::deltas_unknown_to(&self.session, known)
}
fn load(&mut self, registry: Registry, history: Vec<Delta>, head: Option<Rev>) -> Result<(), TargetError> {
SyncTarget::load(&mut self.session, registry, history, head)
}
fn apply_remote_hot_ops(&mut self, ops: Vec<HotOp>) -> Result<Vec<HotOp>, TargetError> {
SyncTarget::apply_remote_hot_ops(&mut self.session, ops)
}
fn merge_remote(&mut self, deltas: Vec<Delta>, retires: &[HotOpId]) -> Result<(), TargetError> {
SyncTarget::merge_remote(&mut self.session, deltas, retires)
}
fn retired_marks(&self) -> RetiredMarks {
SyncTarget::retired_marks(&self.session)
}
fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> Result<(), TargetError> {
SyncTarget::absorb_retired_marks(&mut self.session, remote)
}
fn flush(&mut self) -> Result<(), TargetError> {
// History is append-only. Hot ops are explicitly transient and a rejoin may drop the lot, but a
// retired delta is the durable record, so losing one is data loss no convergence check would see.
let current: HashSet<Rev> = self.history_revs().into_iter().collect();
if let Some(dropped) = self.seen_revs.iter().find(|rev| !current.contains(rev)) {
panic!("seed {}: peer {:?} dropped retired delta {dropped:?} from history", self.seed, self.session.peer());
}
self.seen_revs.extend(current);
self.durable_history = self.history_revs();
self.flushes += 1;
Ok(())
}
fn missing_resources(&self) -> HashSet<ResourceHash> {
self.session.all_referenced_resource_hashes().into_iter().filter(|hash| !self.resources.contains_key(hash)).collect()
}
fn resource_bytes(&self, hash: ResourceHash) -> Option<Vec<u8>> {
self.resources.get(&hash).cloned()
}
fn store_resource(&mut self, hash: ResourceHash, bytes: &[u8]) -> Result<(), TargetError> {
self.resources.insert(hash, bytes.to_vec());
Ok(())
}
}
struct Peer {
target: SimTarget,
replica: Replica,
peer: PeerId,
user: UserId,
transport: TransportPeerId,
/// Gone for good, unlike a rejoin. Its document stops taking part and stops being asserted on.
departed: bool,
}
impl Peer {
fn new(endpoint: MockEndpoint, role: Role, index: u64, seed: u64) -> Self {
let (peer, user) = (PeerId(index), UserId(index));
let transport = endpoint.id();
let replica = match role {
Role::Host => Replica::host(endpoint, peer, user),
Role::Guest => Replica::guest(endpoint, peer, user),
};
Self {
target: SimTarget::new(peer, seed),
replica,
peer,
user,
transport,
departed: false,
}
}
/// Drop off the room, keeping the document. The editor rebuilds the `Replica` on a reconnect but
/// reuses the `Gdd`'s persisted `PeerId`, so protocol state resets while document state does not.
fn rejoin(&mut self, network: &mut MockNetwork) {
network.disconnect(self.transport);
let endpoint = network.endpoint();
self.transport = endpoint.id();
self.replica = Replica::guest(endpoint, self.peer, self.user);
network.connect(self.transport);
}
/// Close the tab. The peer is never heard from again, so the room has to settle without whatever
/// it alone knew.
fn depart(&mut self, network: &mut MockNetwork) {
network.disconnect(self.transport);
self.departed = true;
}
fn session(&self) -> &Session {
&self.target.session
}
fn stage(&mut self, op: RegistryDelta) {
let hot_ops = self.target.session.stage_ops([op]).expect("stage");
self.replica.broadcast_hot_ops(&hot_ops).expect("broadcast");
}
/// Introduce a resource only this peer holds the bytes for, so every other peer has to fetch them.
fn stage_resource(&mut self, bytes: Vec<u8>) {
let hash = ResourceHash::from(bytes.as_slice());
self.target.resources.insert(hash, bytes);
// Each peer names its resources itself, the way live resources get a fresh `ResourceId`. Deriving
// the id from the content instead would collide across peers, which `AddResource` resolves by
// replay order rather than by merging.
let id = ResourceId::from(u64::from(ResourceId::from_hash(&hash)) ^ self.peer.0);
let hot_ops = self.target.session.stage_embedded_resource(id, hash).expect("stage resource");
self.replica.broadcast_hot_ops(&hot_ops).expect("broadcast");
}
fn retire(&mut self) {
let Some(up_to) = self.target.session.hot_log().iter().map(|hot_op| hot_op.timestamp).max() else {
return;
};
self.retire_up_to(up_to);
}
/// Retire only part of the hot log, leaving newer ops live. A later op of one author can then retire
/// while an earlier one is still in flight, which is what puts entries above the retired prefix.
fn retire_prefix(&mut self, nth: usize) {
let mut timestamps: Vec<TimeStamp> = self.target.session.hot_log().iter().map(|hot_op| hot_op.timestamp).collect();
if timestamps.is_empty() {
return;
}
timestamps.sort();
self.retire_up_to(timestamps[nth.min(timestamps.len() - 1)]);
}
fn retire_up_to(&mut self, up_to: TimeStamp) {
let retired_hot_ops = self.target.session.hot_ops_up_to(up_to);
let revs = self.target.session.retire(up_to).expect("retire");
let deltas: Vec<_> = revs.iter().filter_map(|&rev| self.target.session.delta(rev).cloned()).collect();
self.replica.broadcast_retired(&deltas, &retired_hot_ops).expect("broadcast retired");
}
fn poll(&mut self) -> Vec<Event> {
let flushes_before = self.target.flushes;
let events = self.replica.poll(&mut self.target);
assert_eq!(self.target.flushes, flushes_before + 1, "poll must flush the target exactly once");
events
}
}
/// Node-level ops, which reach the input-slot LWW arms and the resurrection path a concurrent remove
/// triggers. `None` when the registry holds nothing the drawn op could target.
fn random_node_op(network: &mut MockNetwork, session: &Session) -> Option<RegistryDelta> {
let registry = session.registry();
let node_id = NodeId(1 + network.random_below(4) as u64);
let live_nodes: Vec<NodeId> = registry.node_instances.keys().copied().collect();
let live_networks: Vec<NetworkId> = registry.networks.keys().copied().collect();
match network.random_below(8) {
// Per-slot attributes, the one place `InputSlot.attributes` is written.
6 => {
let node = registry.node_instances.get(&node_id)?;
let index = network.random_below(node.inputs().len().max(1)) as u32;
Some(RegistryDelta::ChangeNodeInputAttribute {
id: node_id,
index,
delta: AttributeDelta {
key: "label".into(),
value: Some(serde_json::json!(network.random_below(100))),
},
})
}
// A node needs a live network to sit in, and `AddNode` errors on one that already exists.
0 | 1 if !registry.node_instances.contains_key(&node_id) => {
let network_id = *pick(network, &live_networks)?;
Some(RegistryDelta::AddNode {
id: node_id,
node: Node::new(network_id, Implementation::ProtoNode(ResourceId::from(7)), 2),
})
}
2 => registry.node_instances.get(&node_id).map(|node| RegistryDelta::RemoveNode { id: node_id, snapshot: node.clone() }),
3 | 4 => {
let node = registry.node_instances.get(&node_id)?;
let index = network.random_below(node.inputs().len().max(1)) as u32;
// Wiring to a node that is live here can still land on a peer that concurrently removed it,
// which is what drives the resurrection path.
let wire_to = pick(network, &live_nodes).copied();
let new_input = match wire_to {
Some(target) if network.random_below(3) > 0 => NodeInput::Node { id: target, index: 0 },
_ => NodeInput::Value {
value: serde_json::json!(network.random_below(100)),
exposed: false,
},
};
Some(RegistryDelta::ChangeNodeInput { id: node_id, index, new_input })
}
_ => pick(network, &live_nodes).copied().map(|node_id| RegistryDelta::ChangeNodeAttribute {
id: node_id,
delta: AttributeDelta {
key: "name".into(),
value: Some(serde_json::json!(network.random_below(100))),
},
}),
}
}
/// Resource-lifecycle ops past creation. `AddResource` already rides the staged-resource path, so
/// these cover the rest of the chain: the resolved hash, the source fallback list, and removal.
/// `None` when the registry holds no resource to target.
fn random_resource_op(network: &mut MockNetwork, target: &SimTarget) -> Option<RegistryDelta> {
let session = &target.session;
let registry = session.registry();
let live: Vec<ResourceId> = registry.resources.keys().copied().collect();
let id = *pick(network, &live)?;
// A small pool of priorities, so concurrent adds sometimes collide on a key and sometimes stack up
// as distinct entries in the same chain.
let key = SourceKey {
priority: Priority::new(network.random_below(3) as f64).expect("a whole number is finite"),
peer: session.peer(),
};
Some(match network.random_below(5) {
// Only a hash this peer holds the bytes for: a resolved hash is content derived, so in the editor
// the peer that resolves a resource is the one that fetched it.
0 => {
let held: Vec<ResourceHash> = target.resources.keys().copied().collect();
RegistryDelta::SetResourceHash {
id,
hash: Some(*pick(network, &held)?),
}
}
1 => RegistryDelta::SetResourceHash { id, hash: None },
2 => RegistryDelta::AddSource {
id,
key,
source: serde_json::json!("Embedded"),
},
3 => RegistryDelta::RemoveSource { id, key },
_ => RegistryDelta::RemoveResource {
id,
snapshot: registry.resources.get(&id)?.clone(),
},
})
}
/// One element at random, or `None` when there is nothing to choose from.
fn pick<'a, T>(network: &mut MockNetwork, options: &'a [T]) -> Option<&'a T> {
(!options.is_empty()).then(|| &options[network.random_below(options.len())])
}
fn random_op(network: &mut MockNetwork, target: &SimTarget) -> RegistryDelta {
let session = &target.session;
let network_id = NetworkId(1 + network.random_below(3) as u64);
// Half the ops are node-level, falling through to the network-level ones when nothing fits.
if network.random_below(2) == 0
&& let Some(op) = random_node_op(network, session)
{
return op;
}
// Resources exist only once a peer has staged one, so this yields nothing early in a run.
if network.random_below(5) == 0
&& let Some(op) = random_resource_op(network, target)
{
return op;
}
match network.random_below(6) {
// Export slots resize on demand and LWW per slot, and clearing one leaves a tombstone that must
// still compare equal to the slot being absent.
4 | 5 if session.registry().networks.contains_key(&network_id) => {
let live_nodes: Vec<NodeId> = session.registry().node_instances.keys().copied().collect();
let export = match pick(network, &live_nodes).copied() {
Some(id) if network.random_below(4) > 0 => Some(NodeInput::Node { id, index: 0 }),
_ => None,
};
RegistryDelta::SetNetworkExport {
id: network_id,
index: network.random_below(3) as u32,
export,
}
}
0 | 1 => RegistryDelta::ChangeDocumentAttribute {
delta: AttributeDelta {
key: format!("key{}", network.random_below(3)),
value: Some(serde_json::json!(network.random_below(100))),
},
},
2 if let Some(network) = session.registry().networks.get(&network_id) => RegistryDelta::RemoveNetwork {
id: network_id,
snapshot: network.clone(),
},
_ if session.registry().networks.contains_key(&network_id) => RegistryDelta::ChangeNetworkAttribute {
id: network_id,
delta: AttributeDelta {
key: "name".into(),
value: Some(serde_json::json!(network.random_below(100))),
},
},
_ => RegistryDelta::AddNetwork {
id: network_id,
network: Network::default(),
},
}
}
fn present_guests(peers: &[Peer]) -> usize {
peers.iter().skip(1).filter(|peer| !peer.departed).count()
}
/// Run until nothing is in flight and no peer reports progress. Resource transfers need several
/// rounds (request out, bytes back), so this is not a fixed number of passes.
fn quiesce(network: &mut MockNetwork, peers: &mut [Peer]) {
for _ in 0..1000 {
network.deliver_all();
let events: usize = peers.iter_mut().filter(|peer| !peer.departed).map(|peer| peer.poll().len()).sum();
if events == 0 && network.pending() == 0 {
return;
}
}
panic!("the room never went idle");
}
fn simulate(seed: u64, guest_count: usize, steps: usize) -> (MockNetwork, Vec<Peer>) {
let mut network = MockNetwork::new(seed);
let mut peers: Vec<Peer> = (0..=guest_count)
.map(|index| {
let endpoint = network.endpoint();
let id = endpoint.id();
let role = if index == 0 { Role::Host } else { Role::Guest };
let peer = Peer::new(endpoint, role, index as u64 + 1, seed);
network.connect(id);
peer
})
.collect();
for _ in 0..steps {
let index = network.random_below(peers.len());
if peers[index].departed {
continue;
}
match network.random_below(16) {
// A guest edits only once synced; anything staged earlier would be invisible to its peers.
0..=2 if peers[index].replica.is_synced() => {
let op = random_op(&mut network, &peers[index].target);
peers[index].stage(op);
}
// A small pool of distinct payloads, so peers sometimes introduce the same resource
// concurrently and sometimes one nobody else can serve.
8 if peers[index].replica.is_synced() => {
let bytes = format!("resource-{}", network.random_below(5)).into_bytes();
peers[index].stage_resource(bytes);
}
0..=2 | 8 => {}
// Mostly a partial retire, so the host's history lags its hot log the way a real one does.
3 => {
let nth = network.random_below(4);
peers[0].retire_prefix(nth);
}
4..=7 => {
network.step();
}
// The host cannot hand over, so only guests drop and come back.
9 if index > 0 => peers[index].rejoin(&mut network),
9 => {
let endpoint = network.endpoint();
let id = endpoint.id();
peers.push(Peer::new(endpoint, Role::Guest, peers.len() as u64 + 1, seed));
network.connect(id);
}
// Keep one guest around, so the room stays a room.
10 if index > 0 && present_guests(&peers) > 1 => peers[index].depart(&mut network),
_ => {
peers[index].poll();
}
}
}
quiesce(&mut network, &mut peers);
peers[0].retire();
quiesce(&mut network, &mut peers);
(network, peers)
}
/// Dump every peer's state for one seed: `SIM_DUMP=<seed> cargo test ... -- --nocapture`.
fn dump_if_requested(seed: u64, peers: &[Peer]) {
if std::env::var("SIM_DUMP").ok().and_then(|value| value.parse::<u64>().ok()) != Some(seed) {
return;
}
for (index, peer) in peers.iter().enumerate() {
eprintln!(
"DUMP {index} {:?} departed {} synced {} held {} pending_resources {} history {} hot {:?} watermark {:?}",
peer.peer,
peer.departed,
peer.replica.is_synced(),
peer.replica.held_broadcasts(),
peer.replica.pending_resource_requests().count(),
peer.session().history().count(),
peer.session()
.hot_log()
.iter()
.map(|h| format!("{}:{}#{}", h.timestamp.peer.0, h.timestamp.counter, h.sequence))
.collect::<Vec<_>>(),
{
let retired = peer.session().retired_marks();
let mut through: Vec<_> = retired.through.iter().map(|(p, c)| (p.0, *c)).collect();
through.sort();
let mut above: Vec<_> = retired.above.iter().map(|id| (id.peer.0, id.sequence)).collect();
above.sort();
format!("{through:?} above {above:?}")
}
);
}
}
/// Whether every `AddNode` in history names a network that history itself creates. Retirement promotes
/// whatever the host managed to apply, so a referent that only ever existed as an unretired hot op
/// could in principle leave a durable hole here.
fn assert_history_self_contained(seed: u64, peers: &[Peer]) {
for (index, peer) in peers.iter().enumerate().filter(|(_, peer)| !peer.departed) {
let created: HashSet<NetworkId> = peer
.session()
.history()
.filter_map(|delta| match delta.kind {
RegistryDelta::AddNetwork { id, .. } => Some(id),
_ => None,
})
.chain(peer.session().history().filter_map(|delta| match delta.reverse {
RegistryDelta::AddNetwork { id, .. } => Some(id),
_ => None,
}))
.collect();
for delta in peer.session().history() {
if let RegistryDelta::AddNode { node, .. } = &delta.kind {
assert!(
created.contains(&node.network()),
"seed {seed}: peer {index} history has AddNode into {:?} that nothing in history creates",
node.network()
);
}
}
}
}
/// A hot op is identified by its timestamp, so holding one twice means some path appended a copy of
/// something already there, which then replays and re-broadcasts as if it were new work.
fn assert_no_duplicate_hot_ops(seed: u64, peers: &[Peer]) {
for (index, peer) in peers.iter().enumerate() {
let mut seen = HashSet::new();
for hot_op in peer.session().hot_log() {
assert!(seen.insert(hot_op.timestamp), "seed {seed}: peer {index} holds {:?} twice", hot_op.timestamp);
}
}
}
fn assert_converged(seed: u64, peers: &[Peer]) {
dump_if_requested(seed, peers);
assert_no_duplicate_hot_ops(seed, peers);
assert_history_self_contained(seed, peers);
let present = || peers.iter().enumerate().filter(|(_, peer)| !peer.departed);
// A sparse `known_revs` sample only describes a peer's state if history is parent-complete, so a
// hole makes the host under-send on the next resync.
for (index, peer) in present() {
let present_revs: HashSet<Rev> = peer.session().history().map(|delta| delta.id).collect();
for delta in peer.session().history() {
for parent in delta.all_parents() {
assert!(present_revs.contains(&parent), "seed {seed}: peer {index} has {:?} without its parent {parent:?}", delta.id);
}
}
}
let host = &peers[0];
let host_history: Vec<_> = host.session().history().map(|delta| delta.id).collect();
for (index, guest) in present().skip(1) {
let guest_history: Vec<_> = guest.session().history().map(|delta| delta.id).collect();
assert_eq!(guest_history, host_history, "seed {seed}: guest {index} history diverged");
assert_eq!(guest.session().head_rev(), host.session().head_rev(), "seed {seed}: guest {index} head diverged");
assert_eq!(guest.session().retired_registry(), host.session().retired_registry(), "seed {seed}: guest {index} registry diverged");
assert!(guest.session().hot_log().is_empty(), "seed {seed}: guest {index} still holds hot ops");
}
// Bytes that left with a departed peer are gone for good, so the room is only answerable for the
// resources someone still in it could have served.
let servable: HashSet<ResourceHash> = present().flat_map(|(_, peer)| peer.target.resources.keys().copied()).collect();
// An idle room with anything outstanding is stuck, which convergence of content alone can miss:
// a broadcast held forever behind a dependency that will never arrive changes nothing observable.
for (index, peer) in present() {
assert_eq!(peer.replica.held_broadcasts(), 0, "seed {seed}: peer {index} still holds undelivered broadcasts");
assert_eq!(peer.replica.deferred_ops(), 0, "seed {seed}: peer {index} still holds ops waiting on a referent");
assert_eq!(peer.target.durable_history, peer.target.history_revs(), "seed {seed}: peer {index} has unflushed history");
let unserved: Vec<_> = SyncTarget::missing_resources(&peer.target).into_iter().filter(|hash| servable.contains(hash)).collect();
assert!(unserved.is_empty(), "seed {seed}: peer {index} is missing resource bytes another peer holds: {unserved:?}");
}
}
#[test]
fn peers_converge_under_random_interleavings() {
// The committed corpus is the first 1000 seeds; `SIM_SEEDS` pushes the frontier further by hand.
let seeds = std::env::var("SIM_SEEDS").ok().and_then(|value| value.parse::<u64>().ok()).unwrap_or(1000);
for seed in 0..seeds {
let (_, peers) = simulate(seed, 1 + (seed % 3) as usize, 200);
{
let registry = peers[0].session().retired_registry();
TOTAL_NODES.fetch_add(registry.node_instances.len(), Ordering::Relaxed);
let wired = registry
.node_instances
.values()
.flat_map(|node| node.inputs())
.filter(|slot| matches!(slot.input, NodeInput::Node { .. }))
.count();
TOTAL_WIRED.fetch_add(wired, Ordering::Relaxed);
let exports = registry.networks.values().flat_map(|net| &net.exports).filter(|slot| slot.target.is_some()).count();
TOTAL_EXPORTS.fetch_add(exports, Ordering::Relaxed);
let input_attributes = registry.node_instances.values().flat_map(|node| node.inputs()).filter(|slot| !slot.attributes.is_empty()).count();
TOTAL_INPUT_ATTRIBUTES.fetch_add(input_attributes, Ordering::Relaxed);
// More than one source on a resource can only come from `AddSource`, which the staging path
// never emits, so this is what proves the resource-chain ops reach the registry.
let stacked_sources = registry.resources.values().filter(|entry| entry.sources.len() > 1).count();
TOTAL_SOURCES.fetch_add(stacked_sources, Ordering::Relaxed);
}
assert_converged(seed, &peers);
}
// The node ops are guarded on what the registry holds, so a generator change can quietly stop
// producing them. Without nodes wired to other nodes nothing reaches the resurrection path.
assert!(TOTAL_NODES.load(Ordering::Relaxed) > 0, "the corpus produced no nodes");
assert!(TOTAL_WIRED.load(Ordering::Relaxed) > 0, "the corpus produced no node-to-node inputs");
assert!(TOTAL_EXPORTS.load(Ordering::Relaxed) > 0, "the corpus set no network exports");
assert!(TOTAL_INPUT_ATTRIBUTES.load(Ordering::Relaxed) > 0, "the corpus wrote no input-slot attributes");
assert!(TOTAL_SOURCES.load(Ordering::Relaxed) > 0, "the corpus never stacked a second source on a resource");
}
/// A guest that drops and comes back keeps its `PeerId` but gets a fresh `Replica`, so its broadcast
/// sequence restarts. The room must follow the restart rather than keep waiting on the sequence the
/// old connection had reached.
#[test]
fn a_rejoining_guest_is_still_heard() {
let mut network = MockNetwork::new(0);
let mut peers: Vec<Peer> = (0..2)
.map(|index| {
let endpoint = network.endpoint();
let id = endpoint.id();
let role = if index == 0 { Role::Host } else { Role::Guest };
let peer = Peer::new(endpoint, role, index as u64 + 1, 0);
network.connect(id);
peer
})
.collect();
quiesce(&mut network, &mut peers);
peers[1].stage(RegistryDelta::AddNetwork {
id: NetworkId(1),
network: Network::default(),
});
quiesce(&mut network, &mut peers);
assert!(peers[0].session().registry().networks.contains_key(&NetworkId(1)), "the host missed the first edit");
peers[1].rejoin(&mut network);
quiesce(&mut network, &mut peers);
peers[1].stage(RegistryDelta::AddNetwork {
id: NetworkId(2),
network: Network::default(),
});
quiesce(&mut network, &mut peers);
assert_eq!(peers[0].replica.held_broadcasts(), 0, "the host is holding the rejoined guest's broadcast");
assert!(peers[0].session().registry().networks.contains_key(&NetworkId(2)), "the host missed the edit made after the rejoin");
}
#[test]
#[ignore = "manual inspection of one seed"]
fn inspect_seed() {
let _ = env_logger::builder().is_test(true).try_init();
let seed = std::env::var("SEED").ok().and_then(|value| value.parse().ok()).unwrap_or(0);
let guests = std::env::var("GUESTS").ok().and_then(|value| value.parse().ok()).unwrap_or(1);
let (_, peers) = simulate(seed, guests, 200);
for (index, peer) in peers.iter().enumerate() {
eprintln!("=== peer {index} head {:?}", peer.session().head_rev());
eprintln!("registry {}", serde_json::to_string(peer.session().retired_registry()).unwrap());
eprintln!("hot log {:?}", peer.session().hot_log());
eprintln!("resources {:?}", peer.target.resources.keys().collect::<Vec<_>>());
for delta in peer.session().history() {
eprintln!("{:?} parent {:?} author {:?} ts {} {:?}", delta.id, delta.parent, delta.author, delta.timestamp.counter, delta.kind);
}
}
assert_converged(seed, &peers);
}
/// A hot op can reach one guest and not the host, and its author can then leave for good. The guest
/// holds the only copy, so unless it passes the op on the work is lost with the peer that made it.
/// Random delivery reaches this only by luck, so it is built by hand.
#[test]
fn a_guest_holding_the_only_copy_gets_it_retired() {
let mut network = MockNetwork::new(0);
let mut peers: Vec<Peer> = (0..3)
.map(|index| {
let endpoint = network.endpoint();
let id = endpoint.id();
let role = if index == 0 { Role::Host } else { Role::Guest };
let peer = Peer::new(endpoint, role, index as u64 + 1, 0);
network.connect(id);
peer
})
.collect();
quiesce(&mut network, &mut peers);
// The author stages one op, and only the other guest is allowed to receive it.
let author_transport = peers[1].transport;
peers[1].stage(RegistryDelta::AddNetwork {
id: NetworkId(9),
network: Network::default(),
});
let witness_transport = peers[2].transport;
network.deliver_to(witness_transport);
peers[2].poll();
assert!(peers[2].session().registry().networks.contains_key(&NetworkId(9)), "the witness must have received the op");
assert!(peers[0].session().hot_log().is_empty(), "the host must not have received it yet");
// The author leaves for good, taking its own copy and its undelivered packets with it.
network.disconnect(author_transport);
peers[1].departed = true;
quiesce(&mut network, &mut peers);
peers[0].retire();
quiesce(&mut network, &mut peers);
assert!(
peers[0].session().retired_registry().networks.contains_key(&NetworkId(9)),
"the op the witness alone held never reached history"
);
assert_converged(0, &peers);
}
-1
View File
@@ -19,7 +19,6 @@ graph-craft = { workspace = true }
document-format = { workspace = true }
document-graph-storage = { workspace = true, features = ["conversion"] }
document-container = { workspace = true }
peer-transport = { workspace = true }
graphene-hash = { workspace = true }
interpreted-executor = { workspace = true }
graphene-std = { workspace = true } # NOTE: `core-types` should not be added here because `graphene-std` re-exports its contents
+4 -8
View File
@@ -496,15 +496,11 @@ mod test {
if let FrontendMessage::UpdateLayout {
layout_target: LayoutTarget::DialogColumn1,
diff,
} = response
} = response && let DiffUpdate::Layout(sub_layout) = &diff[0].new_value
&& let LayoutGroup::Row(WidgetRow { widgets }) = &sub_layout.0[0]
&& let Widget::TextLabel(TextLabel { value, .. }) = &*widgets[0].widget
{
if let DiffUpdate::Layout(sub_layout) = &diff[0].new_value {
if let LayoutGroup::Row(WidgetRow { widgets }) = &sub_layout.0[0] {
if let Widget::TextLabel(TextLabel { value, .. }) = &*widgets[0].widget {
print_problem_to_terminal_on_failure(value);
}
}
}
print_problem_to_terminal_on_failure(value);
}
}
}
@@ -95,7 +95,7 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
.network_interface
.node_metadata(&layer.to_node(), &[])
.map(|node| node.persistent_metadata.display_name.clone())
.and_then(|name| if name.is_empty() { None } else { Some(name) })
.filter(|name| !name.is_empty())
.unwrap_or_else(|| "Artboard".to_string());
(layer, name)
})
@@ -150,10 +150,6 @@ pub enum FrontendMessage {
url: String,
},
TriggerClipboardRead,
/// Copy a link to join the live session behind `token`, built from the page's own origin.
TriggerSessionLinkCopy {
token: String,
},
TriggerClipboardWrite {
content: String,
},
@@ -465,7 +465,7 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
];
let (mut key_up, mut key_down, mut key_up_no_repeat, mut key_down_no_repeat, mut double_click, mut wheel_scroll, mut pointer_move, mut pointer_shake) = mappings;
let sort = |list: &mut KeyMappingEntries| list.0.sort_by(|a, b| b.modifiers.count_ones().cmp(&a.modifiers.count_ones()));
let sort = |list: &mut KeyMappingEntries| list.0.sort_by_key(|entry| std::cmp::Reverse(entry.modifiers.count_ones()));
// Sort the sublists of `key_up`, `key_down`, `key_up_no_repeat`, and `key_down_no_repeat`
for list in [&mut key_up, &mut key_down, &mut key_up_no_repeat, &mut key_down_no_repeat] {
for sublist in list {
@@ -173,17 +173,6 @@ impl LayoutHolder for MenuBarMessageHandler {
.on_commit(|_| DialogMessage::RequestExportDialog.into())
.disabled(no_active_document),
],
vec![
MenuListEntry::new("Share Live Session")
.label("Share Live Session")
.icon("Link")
.on_commit(|_| SyncMessage::Share.into())
.disabled(no_active_document),
MenuListEntry::new("Leave Live Session")
.label("Leave Live Session")
.on_commit(|_| SyncMessage::Leave.into())
.disabled(no_active_document),
],
#[cfg(not(target_os = "macos"))]
vec![preferences],
])
@@ -215,10 +215,6 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
List<Gradient>,
List<String>,
List<f64>,
List<f32>,
List<u32>,
List<u64>,
List<i32>,
List<i64>,
List<bool>,
List<DVec2>,
@@ -275,10 +271,6 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
Item<Gradient>,
Item<String>,
Item<f64>,
Item<f32>,
Item<u32>,
Item<u64>,
Item<i32>,
Item<i64>,
Item<bool>,
Item<DVec2>,
@@ -577,7 +569,7 @@ impl TableItemLayout for Coverage {
impl TableItemLayout for TransferCurve {
fn type_name() -> &'static str {
"Transfer Curve"
"TransferCurve"
}
fn identifier(&self) -> String {
let points = self.points().len();
@@ -842,37 +834,12 @@ impl TableItemLayout for Gradient {
}
}
macro_rules! impl_table_item_layout_for_number {
($($ty:ty => $type_name:literal),* $(,)?) => {
$(
impl TableItemLayout for $ty {
fn type_name() -> &'static str {
$type_name
}
fn identifier(&self) -> String {
format!("{self}")
}
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
}
}
)*
}
}
impl_table_item_layout_for_number!(
u32 => "Number (u32)",
i32 => "Number (i32)",
u64 => "Number (u64)",
i64 => "Number (i64)",
);
impl TableItemLayout for f32 {
impl TableItemLayout for i64 {
fn type_name() -> &'static str {
"Number (f32)"
"Integer"
}
fn identifier(&self) -> String {
// Only infinity widens to f64 without gaining digits, so finite values keep the f32 spelling
if self.is_infinite() { format_f64(*self as f64) } else { format!("{self}") }
format!("{self}")
}
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
@@ -968,26 +935,6 @@ fn string_preview(value: &str) -> String {
first_line.chars().take(MAX_CHARACTERS - 1).chain(['…']).collect()
}
impl TableItemLayout for Option<f64> {
fn type_name() -> &'static str {
"Option<f64>"
}
fn identifier(&self) -> String {
"Option<f64>".to_string()
}
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
let text = match self {
Some(value) => format!("Some({})", format_f64(round_away_float_noise(*value))),
None => "None".to_string(),
};
vec![TextLabel::new(text).selectable(true).narrow(true).widget_instance()]
}
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
vec![LayoutGroup::row(self.value_widgets(PathStep::Element(0), _data))]
}
}
impl TableItemLayout for DVec2 {
fn type_name() -> &'static str {
"Vec2"
@@ -1272,13 +1219,8 @@ macro_rules! known_item_types {
DVec2,
Affine2,
Vec2,
Option<f64>,
f64,
f32,
u8,
u32,
u64,
i32,
i64,
bool,
String,
@@ -2,9 +2,10 @@ use std::collections::VecDeque;
use std::collections::{BTreeMap, HashSet};
use document_graph_storage::{Declarations, Registry};
use graph_craft::application_io::resource::{ResourceHash, ResourceId, ResourceRegistry, ResourceStorage};
use graph_craft::application_io::resource::{ResourceId, ResourceRegistry, ResourceStorage};
use super::utility_types::network_interface::NodeNetworkInterface;
use super::utility_types::network_interface::editor_delta::{EditorDelta, construct_batch};
use super::utility_types::network_interface::storage_metadata::{StorageMetadataView, build_interface_from_storage, collect_network_view_settings};
/// Per-document undo/redo state: the legacy snapshot stacks plus the `Gdd` working-copy cursor that is
@@ -28,6 +29,12 @@ pub struct DocumentHistory {
/// and extended on each staging, so a cursor rebuild never touches the byte store.
#[derivative(Debug = "ignore")]
declarations: Declarations,
/// Whether the next commit must convert the whole document rather than stage what the store recorded.
///
/// True when the working copy holds no baseline for a batch to apply to, and whenever the runtime has
/// moved without recording it (an upgrade on open), since the recorded batch would then describe only
/// part of the distance between the two.
needs_whole_document_stage: bool,
}
/// Why [`DocumentHistory::move_cursor`] produced no interface.
@@ -94,10 +101,17 @@ impl DocumentHistory {
/// Attach the `Gdd` working copy once the mount future resolves, with the declarations it references.
pub fn set_storage(&mut self, storage: document_format::GddV1, declarations: Declarations) {
self.needs_whole_document_stage |= storage.registry().node_instances.is_empty();
self.storage = Some(storage);
self.declarations = declarations;
}
/// Marks the working copy as needing a whole-document stage on its next commit, for a change to the
/// runtime that went unrecorded and so cannot be described by the recorded batch.
pub fn require_whole_document_stage(&mut self) {
self.needs_whole_document_stage = true;
}
/// Retire the pending staged hot ops into durable Gdd history as one undo unit. Called at each undo-step
/// boundary (a new `StartTransaction`) and before undo/redo, so the per-`CommitTransaction` staging
/// coalesces into one interaction aligned with the legacy step. No-op while unmounted.
@@ -108,39 +122,92 @@ impl DocumentHistory {
}
}
/// Stage the runtime snapshot into the `Gdd` working copy at each `CommitTransaction`. No-op while
/// unmounted. Proto-node declaration bytes go into `byte_store` (the app-global resource cache). The
/// staged hot ops are retired by [`retire_storage_interaction`](Self::retire_storage_interaction) at
/// undo-step boundaries. `validate` (the `validate_storage_round_trip` preference) gates the per-commit
/// round-trip check, off by default for its perf cost.
/// Stage a `CommitTransaction` into the `Gdd` working copy: the first commit writes the whole document,
/// every later one stages the `deltas` the store recorded. No-op while unmounted. Proto-node declaration
/// bytes go into `byte_store` (the app-global resource cache). The staged hot ops are retired by
/// [`retire_storage_interaction`](Self::retire_storage_interaction) at undo-step boundaries.
pub fn stage_snapshot(
&mut self,
deltas: &[EditorDelta],
interface: &NodeNetworkInterface,
registry: &ResourceRegistry,
view_settings: BTreeMap<String, serde_json::Value>,
legacy_document: &str,
byte_store: &dyn ResourceStorage,
) {
let needs_whole_document_stage = self.needs_whole_document_stage;
let Some(storage) = self.storage.as_mut() else { return };
let network = interface.document_network();
let metadata_view = StorageMetadataView::new(interface);
let network_view_settings = storage
.network_ids(network, &metadata_view)
.ok()
.map(|network_ids| collect_network_view_settings(interface, &network_ids));
// Stage without retiring: a tool drag fires several `CommitTransaction`s but is one legacy undo
// step, so the deltas accumulate as hot ops and coalesce at the next undo-step boundary.
match storage.stage_runtime_snapshot(network, &metadata_view, registry, byte_store) {
Ok(declarations) => self.declarations.extend(declarations),
let staged = match needs_whole_document_stage {
true => Self::stage_whole_document(storage, interface, registry, byte_store),
// An autosave with nothing edited since the last commit still persists the view state below.
false if deltas.is_empty() => Ok(Declarations::new()),
// The batch is drained by the time it reaches here, so a failed staging would leave the working copy
// permanently behind. Converting the whole document restages the same edit from whatever the working
// copy holds, including a batch that failed partway through.
false => Self::stage_recorded(storage, deltas, interface, registry, byte_store).or_else(|error| {
log::error!("Staging recorded deltas failed, falling back to a whole document snapshot: {error}");
Self::stage_whole_document(storage, interface, registry, byte_store)
}),
};
match staged {
Ok(declarations) => {
self.declarations.extend(declarations);
self.needs_whole_document_stage = false;
}
Err(error) => {
log::error!("Storage snapshot staging failed: {error}");
return;
}
}
self.persist_view_state(interface, view_settings, legacy_document);
}
/// Converts the whole document and stages the difference from what the working copy holds.
///
/// Stages without retiring: a tool drag fires several `CommitTransaction`s but is one legacy undo
/// step, so the ops accumulate in the hot log and coalesce at the next undo-step boundary.
fn stage_whole_document(storage: &mut document_format::GddV1, interface: &NodeNetworkInterface, registry: &ResourceRegistry, byte_store: &dyn ResourceStorage) -> Result<Declarations, String> {
let metadata_view = StorageMetadataView::new(interface);
storage
.stage_runtime_snapshot(interface.document_network(), &metadata_view, registry, byte_store)
.map_err(|error| error.to_string())
}
/// Stages what the store recorded since the last drain.
///
/// This and the whole-document conversion produce the same registry for the same edit, which
/// `verify_round_trip` checks when the `validate_storage_round_trip` preference is on. They differ in
/// what they cost and in what they can miss: a conversion sees every change however it was made,
/// while this sees only what went through the store, so a write that bypasses it is not persisted.
fn stage_recorded(
storage: &mut document_format::GddV1,
deltas: &[EditorDelta],
interface: &NodeNetworkInterface,
registry: &ResourceRegistry,
byte_store: &dyn ResourceStorage,
) -> Result<Declarations, String> {
let peer = storage.session().peer();
let metadata_view = StorageMetadataView::new(interface);
let constructed = construct_batch(deltas, storage.registry(), registry, &metadata_view, peer).map_err(|error| error.to_string())?;
storage
.stage_constructed_ops(constructed.ops, &constructed.declarations.bytes, byte_store)
.map_err(|error| error.to_string())?;
Ok(constructed.declarations.decoded)
}
/// The parts of a commit that are not the graph: the per-peer view settings, and the legacy bytes the
/// dual-write soak validates the new format against.
fn persist_view_state(&mut self, interface: &NodeNetworkInterface, view_settings: BTreeMap<String, serde_json::Value>, legacy_document: &str) {
let Some(storage) = self.storage.as_mut() else { return };
let network_view_settings = storage
.network_ids(interface.document_network(), &StorageMetadataView::new(interface))
.ok()
.map(|network_ids| collect_network_view_settings(interface, &network_ids));
if let Err(error) = storage.set_view_settings(view_settings) {
log::error!("Persisting view settings failed: {error}");
}
@@ -151,8 +218,6 @@ impl DocumentHistory {
log::error!("Persisting per-network view settings failed: {error}");
}
// Dual-write soak: embed the legacy `.graphite` bytes so the new format
// can be validated against (and recovered from) the old one on open.
if let Err(error) = storage.store_legacy_document(legacy_document.as_bytes()) {
log::error!("Embedding legacy document into working copy failed: {error}");
}
@@ -181,48 +246,15 @@ impl DocumentHistory {
return Err(CursorMoveError::NotMoved);
}
self.rebuild_interface().ok_or(CursorMoveError::RebuildFailed)
}
/// Build a fresh interface from the working registry, using the declaration cache so no resource load
/// is needed. `None` (logged) when the registry does not convert.
pub fn rebuild_interface(&self) -> Option<NodeNetworkInterface> {
let storage = self.storage.as_ref()?;
let rebuilt = storage
storage
.registry()
.to_runtime_with_full_metadata(&self.declarations)
.map_err(|error| error.to_string())
.and_then(|(network, node_entries, network_entries)| build_interface_from_storage(network, node_entries, network_entries).map_err(|error| error.to_string()));
match rebuilt {
Ok(interface) => Some(interface),
Err(error) => {
log::error!("Storage interface rebuild failed: {error}");
None
}
}
}
/// Cache a resource that arrived from a peer as a proto-node declaration, under every declaration
/// resource referencing its hash. Ignores resources no declaration refers to (images, fonts).
pub fn cache_declaration_bytes(&mut self, hash: ResourceHash, bytes: &[u8]) {
let Some(storage) = self.storage.as_ref() else { return };
let referencing: Vec<ResourceId> = storage
.session()
.all_declaration_resources()
.into_iter()
.filter_map(|(id, declaration_hash)| (declaration_hash == Some(hash)).then_some(id))
.collect();
if referencing.is_empty() {
return;
}
match document_graph_storage::decode_declaration(bytes) {
Ok(declaration) => self.declarations.extend(referencing.into_iter().map(|id| (id, declaration.clone()))),
Err(error) => log::error!("Failed to deserialize a received ProtoNode declaration: {error}"),
}
.and_then(|(network, node_entries, network_entries)| build_interface_from_storage(network, node_entries, network_entries).map_err(|error| error.to_string()))
.map_err(|error| {
log::error!("Storage undo/redo rebuild failed: {error}");
CursorMoveError::RebuildFailed
})
}
/// Step the cursor back the other way, undoing a [`move_cursor`](Self::move_cursor) in the `undo`
@@ -34,7 +34,7 @@ use crate::messages::tool::utility_types::ToolType;
use crate::node_graph_executor::NodeGraphExecutor;
use document_graph_storage::Declarations;
use glam::{DAffine2, DVec2};
use graph_craft::application_io::resource::{ResourceId, ResourceStorage};
use graph_craft::application_io::resource::ResourceId;
use graph_craft::application_io::wgpu_available;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput, NodeNetwork, OldNodeNetwork};
@@ -149,10 +149,6 @@ pub struct DocumentMessageHandler {
/// Undo/redo state: the legacy snapshot stacks plus the `Gdd` working-copy cursor.
#[serde(skip)]
history: DocumentHistory,
/// Peers changed the registry and the interface hasn't been rebuilt from it yet, so a staged diff
/// would read as reverting their edits.
#[serde(skip)]
pub(crate) runtime_stale: bool,
/// Hash of the document snapshot that was most recently saved to disk by the user.
#[serde(skip)]
saved_hash: Option<u64>,
@@ -204,7 +200,6 @@ impl Default for DocumentMessageHandler {
breadcrumb_network_path: Vec::new(),
selection_network_path: Vec::new(),
history: DocumentHistory::default(),
runtime_stale: false,
saved_hash: None,
auto_saved_hash: None,
layer_range_selection_reference: None,
@@ -412,8 +407,8 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![] });
self.layer_range_selection_reference = None;
}
DocumentMessage::DocumentHistoryBackward => self.undo_with_history(viewport, resource_storage, preferences.validate_storage_round_trip, responses),
DocumentMessage::DocumentHistoryForward => self.redo_with_history(viewport, resource_storage, preferences.validate_storage_round_trip, responses),
DocumentMessage::DocumentHistoryBackward => self.undo_with_history(viewport, preferences.validate_storage_round_trip, responses),
DocumentMessage::DocumentHistoryForward => self.redo_with_history(viewport, preferences.validate_storage_round_trip, responses),
DocumentMessage::DocumentStructureChanged => {
if layers_panel_open {
self.network_interface.load_structure();
@@ -1814,14 +1809,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
impl DocumentMessageHandler {
/// Build a document handler from a `.gdd` working copy.
pub fn from_storage(
interface: NodeNetworkInterface,
storage: document_format::GddV1,
declarations: Declarations,
byte_store: Arc<dyn ResourceStorage>,
name: String,
path: Option<std::path::PathBuf>,
) -> Self {
pub fn from_storage(interface: NodeNetworkInterface, storage: document_format::GddV1, declarations: Declarations, name: String, path: Option<std::path::PathBuf>) -> Self {
let mut document = Self {
network_interface: interface,
name,
@@ -1830,7 +1818,11 @@ impl DocumentMessageHandler {
};
document.apply_stored_document_settings(storage.view_settings());
document.set_storage(storage, declarations, byte_store);
match storage.registry().to_resource_registry() {
Ok(resource_registry) => document.resources.registry = resource_registry,
Err(error) => log::error!("Opening .gdd: failed to rebuild resource registry: {error}"),
}
document.history.set_storage(storage, declarations);
document
}
@@ -1842,6 +1834,12 @@ impl DocumentMessageHandler {
self.network_interface.validate_output_names(node_id, node, &path);
}
// Restoring the parallel-array invariant is how the document arrives, not an edit to it, so what the
// fix-ups recorded must not ride along in the first real commit. They still have to reach storage,
// so the next commit converts the whole document rather than staging the batch that follows them.
self.network_interface.discard_deltas();
self.history.require_whole_document_stage();
self.network_interface.load_structure();
}
@@ -2026,10 +2024,8 @@ impl DocumentMessageHandler {
}
/// Attach the `Gdd` working copy once the mount future resolves, with the declarations it references.
pub fn set_storage(&mut self, mut storage: document_format::GddV1, declarations: Declarations, byte_store: Arc<dyn ResourceStorage>) {
storage.set_byte_store(byte_store);
pub fn set_storage(&mut self, storage: document_format::GddV1, declarations: Declarations) {
self.history.set_storage(storage, declarations);
self.refresh_resource_registry();
}
/// Retire the pending staged hot ops into durable Gdd history as one undo unit.
@@ -2037,14 +2033,36 @@ impl DocumentMessageHandler {
self.history.retire_storage_interaction();
}
/// Stages the runtime network into the `Gdd` working copy.
pub fn commit_storage_snapshot(&mut self, byte_store: &dyn graph_craft::application_io::resource::ResourceStorage, validate: bool) {
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::DocumentSettings;
/// Marks the working copy as needing a whole-document stage on its next commit, for a change to the
/// runtime that went unrecorded.
pub(crate) fn require_whole_document_stage(&mut self) {
self.history.require_whole_document_stage();
}
if self.history.storage().is_none() || self.runtime_stale {
/// Stages what the store recorded since the last commit into the `Gdd` working copy.
///
/// The batch boundary: everything the interface recorded since the last one is this commit's batch.
/// Draining happens whether or not a working copy is mounted, so the buffer cannot grow across a
/// session that never mounts one.
pub fn commit_storage_snapshot(&mut self, byte_store: &dyn graph_craft::application_io::resource::ResourceStorage, validate: bool) {
let deltas = self.network_interface.take_deltas();
if self.history.storage().is_none() {
return;
}
let (view_settings, legacy_document) = self.storage_side_channels();
self.history
.stage_snapshot(&deltas, &self.network_interface, &self.resources.registry, view_settings, legacy_document.as_str(), byte_store);
if validate {
self.history.verify_round_trip(&self.network_interface, &self.resources.registry);
}
}
/// The per-peer view settings and legacy bytes that ride along with either kind of staging.
fn storage_side_channels(&self) -> (std::collections::BTreeMap<String, serde_json::Value>, String) {
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::DocumentSettings;
let view_settings = DocumentSettings {
document_ptz: &self.document_ptz,
render_mode: &self.render_mode,
@@ -2055,14 +2073,7 @@ impl DocumentMessageHandler {
}
.to_view_map();
let legacy_document = self.serialize_document();
self.history
.stage_snapshot(&self.network_interface, &self.resources.registry, view_settings, legacy_document.as_str(), byte_store);
if validate {
self.history.verify_round_trip(&self.network_interface, &self.resources.registry);
}
(view_settings, self.serialize_document())
}
/// Restore `view_settings` map into the document.
@@ -2108,29 +2119,6 @@ impl DocumentMessageHandler {
}
}
/// Rebuild the runtime resource registry from storage, which holds each resource's id, content hash
/// and sources. The preprocessor resolves a node's `Resource` input through it, so an interface
/// swapped in from storage needs it refreshed alongside. Keeps the current registry on failure.
fn refresh_resource_registry(&mut self) {
let Some(storage) = self.history.storage() else { return };
match storage.registry().to_resource_registry() {
Ok(resource_registry) => self.resources.registry = resource_registry,
Err(error) => log::error!("Failed to rebuild the resource registry from storage: {error}"),
}
}
/// Swap in an interface rebuilt from the registry a peer's changes left behind.
pub(crate) fn apply_remote_changes(&mut self, responses: &mut VecDeque<Message>) {
let Some(rebuilt) = self.history.rebuild_interface() else { return };
self.apply_gdd_cursor_rebuild(rebuilt, false, false, responses);
}
/// Cache a resource received from a peer as a proto-node declaration, so a rebuild can resolve it.
pub(crate) fn cache_declaration_bytes(&mut self, hash: graph_craft::application_io::resource::ResourceHash, bytes: &[u8]) {
self.history.cache_declaration_bytes(hash, bytes);
}
/// Swap in the interface rebuilt from the `Gdd` cursor. Always overwrites the interface.
fn apply_gdd_cursor_rebuild(&mut self, mut rebuilt: NodeNetworkInterface, had_oracle: bool, validate: bool, responses: &mut VecDeque<Message>) {
rebuilt.copy_all_transient_view_state(&self.network_interface);
@@ -2142,11 +2130,6 @@ impl DocumentMessageHandler {
}
self.network_interface = rebuilt;
self.runtime_stale = false;
if let Some(gdd) = self.history.storage_mut() {
gdd.mark_runtime_current();
}
self.refresh_resource_registry();
if validate {
let current_resources: std::collections::HashSet<_> = self.used_resources(false).iter().copied().collect();
@@ -2448,7 +2431,7 @@ impl DocumentMessageHandler {
paths
}
pub fn undo_with_history(&mut self, viewport: &ViewportMessageHandler, resource_storage: &ResourceStorageMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
pub fn undo_with_history(&mut self, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
let legacy_applied = if let Some(previous_network) = self.undo(viewport, responses) {
self.history.push_redo(previous_network);
true
@@ -2456,23 +2439,9 @@ impl DocumentMessageHandler {
false
};
if self.is_in_session() {
self.stage_session_undo(resource_storage);
return;
}
self.drive_storage_undo_redo(legacy_applied, true, validate, responses);
}
fn is_in_session(&self) -> bool {
self.storage().is_some_and(|gdd| gdd.role().is_some())
}
/// In a session every op is already public, so an undo is a new forward edit: the restored snapshot
/// diffs against the last staged state into the inverse ops, broadcast like any other change.
fn stage_session_undo(&mut self, resource_storage: &ResourceStorageMessageHandler) {
self.commit_storage_snapshot(&resource_storage.resources_mut(), false);
}
/// Installs a history snapshot as the active network interface, carrying over the current view state and structure load, and returns the replaced interface.
fn install_history_snapshot(&mut self, mut network_interface: NodeNetworkInterface, viewport: &ViewportMessageHandler) -> NodeNetworkInterface {
// Set the previous network navigation metadata to the current navigation metadata
@@ -2504,7 +2473,7 @@ impl DocumentMessageHandler {
Some(previous_network)
}
pub fn redo_with_history(&mut self, viewport: &ViewportMessageHandler, resource_storage: &ResourceStorageMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
pub fn redo_with_history(&mut self, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
let legacy_applied = if let Some(previous_network) = self.redo(viewport, responses) {
self.history.push_undo(previous_network);
true
@@ -2512,10 +2481,6 @@ impl DocumentMessageHandler {
false
};
if self.is_in_session() {
self.stage_session_undo(resource_storage);
return;
}
self.drive_storage_undo_redo(legacy_applied, false, validate, responses);
}
@@ -2851,9 +2816,9 @@ impl DocumentMessageHandler {
self.network_interface.move_node_to_chain_start(&solidify_id, layer, &[], false);
if has_fill && has_stroke {
let (existing_index, new_index) = (0_f64, 1_f64);
let (existing_index, new_index) = (0_i64, 1_i64);
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 = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Integer(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);
@@ -2875,7 +2840,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 = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Integer(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);
@@ -4162,10 +4127,11 @@ mod document_message_handler_tests {
async fn get_layer_by_bounds(editor: &mut EditorTestUtils, min_x: f64, min_y: f64) -> Option<LayerNodeIdentifier> {
let document = editor.active_document();
for layer in document.metadata().all_layers() {
if let Some(bbox) = document.metadata().bounding_box_viewport(layer) {
if (bbox[0].x - min_x).abs() < 1. && (bbox[0].y - min_y).abs() < 1. {
return Some(layer);
}
if let Some(bbox) = document.metadata().bounding_box_viewport(layer)
&& (bbox[0].x - min_x).abs() < 1.
&& (bbox[0].y - min_y).abs() < 1.
{
return Some(layer);
}
}
None
@@ -4222,7 +4188,6 @@ mod document_message_handler_tests {
// The operation completed without crashing
// Verifying application still functions by performing another operation
editor.handle_message(DocumentMessage::CreateEmptyFolder).await;
assert!(true, "Application didn't crash after folder move operation");
}
// Merging nodes whose output isn't wired downstream produces an encapsulating subnetwork with no exports.
@@ -287,7 +287,7 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
// Insert the main chain node (Blend or Morph) depending on whether a blend count is provided, referencing
// its control path input by the Blend template's named position or the Morph proto node's parameter symbol
let (path_input_connector, layer_alias, path_alias) = if let Some(count) = blend_count {
let blend_node_id = modify_inputs.insert_blend_data(layer, count as f64);
let blend_node_id = modify_inputs.insert_blend_data(layer, count as i64);
(InputConnector::node_at_index(blend_node_id, BLEND_PATH_INPUT_INDEX), "Blend", "Blend Path")
} else {
let morph_node_id = modify_inputs.insert_morph_data(layer);
@@ -881,9 +881,9 @@ fn insert_brush_strokes_chain(network_interface: &mut NodeNetworkInterface, laye
let strokes_node = strokes_node_type.node_template_input_override([
Some(NodeInput::value(TaggedValue::Strokes(Vec::new()), false)),
Some(NodeInput::value(TaggedValue::Color(color), false)),
Some(NodeInput::value(TaggedValue::F64(diameter), false)),
Some(NodeInput::value(TaggedValue::F64(hardness), false)),
Some(NodeInput::value(TaggedValue::F64(flow), false)),
Some(NodeInput::value(TaggedValue::Number(diameter), false)),
Some(NodeInput::value(TaggedValue::Number(hardness), false)),
Some(NodeInput::value(TaggedValue::Number(flow), false)),
]);
network_interface.insert_node(strokes_node_id, strokes_node, &[]);
network_interface.set_input(&InputConnector::node_at_index(layer.to_node(), 1), NodeInput::node(strokes_node_id, 0), &[]);
@@ -19,7 +19,7 @@ pub fn update_transform(network_interface: &mut NodeNetworkInterface, node_id: &
);
network_interface.set_input(
&InputConnector::node(*node_id, graphene_std::transform_nodes::transform::RotationInput),
NodeInput::value(TaggedValue::F64(rotation), false),
NodeInput::value(TaggedValue::Number(rotation), false),
&[],
);
network_interface.set_input(
@@ -70,7 +70,7 @@ pub fn get_current_transform(inputs: &[NodeInput]) -> DAffine2 {
} else {
DVec2::ZERO
};
let rotation = if let Some(&TaggedValue::F64(rotation)) = inputs[2].as_value() { rotation } else { 0. };
let rotation = if let Some(&TaggedValue::Number(rotation)) = inputs[2].as_value() { rotation } else { 0. };
let scale = if let Some(&TaggedValue::DVec2(scale)) = inputs[3].as_value() { scale } else { DVec2::ONE };
let skew = if let Some(&TaggedValue::DVec2(skew)) = inputs[4].as_value() { skew } else { DVec2::ZERO };
@@ -94,10 +94,10 @@ impl<'a> ModifyInputsContext<'a> {
self.network_interface.move_node_to_chain_start(&boolean_id, layer, &[], self.import);
}
pub fn insert_blend_data(&mut self, layer: LayerNodeIdentifier, count: f64) -> NodeId {
pub fn insert_blend_data(&mut self, layer: LayerNodeIdentifier, count: i64) -> 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(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::Integer(count), false))]);
let blend_id = NodeId::new();
self.network_interface.insert_node(blend_id, blend, &[]);
@@ -109,7 +109,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(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::Number(0.5), false))]);
let morph_id = NodeId::new();
self.network_interface.insert_node(morph_id, morph, &[]);
@@ -131,7 +131,7 @@ impl<'a> ModifyInputsContext<'a> {
// Add Auto-Tangents node (between Origins to Polyline and Path), with spread=1 and preserve_existing=false
let auto_tangents = resolve_proto_node_type(graphene_std::vector::auto_tangents::IDENTIFIER)
.expect("Auto-Tangents node does not exist")
.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(1.), false)), Some(NodeInput::value(TaggedValue::Bool(false), false))]);
.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Number(1.), false)), Some(NodeInput::value(TaggedValue::Bool(false), false))]);
let auto_tangents_id = NodeId::new();
self.network_interface.insert_node(auto_tangents_id, auto_tangents, &[]);
self.network_interface.move_node_to_chain_start(&auto_tangents_id, layer, &[], self.import);
@@ -193,14 +193,14 @@ impl<'a> ModifyInputsContext<'a> {
Some(NodeInput::value(TaggedValue::None, false)),
Some(NodeInput::value(TaggedValue::String(text), false)),
Some(NodeInput::value(TaggedValue::Resource(font_resource_id), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.font_size), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.line_height_ratio), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.letter_spacing), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.letter_tilt), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.font_size), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.line_height_ratio), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.letter_spacing), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.letter_tilt), false)),
Some(NodeInput::value(TaggedValue::Bool(typesetting.max_width.is_some()), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.max_width.unwrap_or(100.)), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.max_width.unwrap_or(100.)), false)),
Some(NodeInput::value(TaggedValue::Bool(typesetting.max_height.is_some()), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.max_height.unwrap_or(100.)), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.max_height.unwrap_or(100.)), false)),
Some(NodeInput::value(TaggedValue::TextAlign(typesetting.align), false)),
]);
let text_to_vector = resolve_proto_node_type(graphene_std::text::text_to_vector::IDENTIFIER)
@@ -526,7 +526,7 @@ impl<'a> ModifyInputsContext<'a> {
);
self.set_input_with_refresh(
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::OpacityInput),
NodeInput::value(TaggedValue::F64(opacity * 100.), false),
NodeInput::value(TaggedValue::Number(opacity * 100.), false),
false,
);
}
@@ -555,7 +555,7 @@ impl<'a> ModifyInputsContext<'a> {
);
self.set_input_with_refresh(
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::FillInput),
NodeInput::value(TaggedValue::F64(fill * 100.), false),
NodeInput::value(TaggedValue::Number(fill * 100.), false),
false,
);
}
@@ -666,7 +666,7 @@ impl<'a> ModifyInputsContext<'a> {
}
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_positions::PositionsInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64Array(positions), false), false);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Numbers(positions), false), false);
}
/// The 'Gradient Midpoints' counterpart of [`Self::gradient_positions_set`], likewise update-only.
@@ -690,7 +690,7 @@ impl<'a> ModifyInputsContext<'a> {
}
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_midpoints::MidpointsInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64Array(midpoints), false), false);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Numbers(midpoints), false), false);
}
/// Update the transform to map the unit gradient ((0,0), (1, 0)) to the geometry's local space.
@@ -865,7 +865,7 @@ impl<'a> ModifyInputsContext<'a> {
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintInput);
self.set_input_with_refresh(input_connector, NodeInput::value(color.map_or_else(TaggedValue::no_paint, TaggedValue::Color), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::WeightInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.weight), false), true);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.weight), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::AlignInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::StrokeAlign(stroke.align), false), false);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::CapInput);
@@ -873,11 +873,11 @@ impl<'a> ModifyInputsContext<'a> {
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::JoinInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::StrokeJoin(stroke.join), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::MiterLimitInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.join_miter_limit), false), false);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.join_miter_limit), false), false);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashPatternInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::DashPattern(stroke.dash_lengths), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.dash_offset), false), true);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.dash_offset), false), true);
}
/// Update the transform value of the upstream Transform node based a change to its existing value and the given parent transform.
@@ -40,17 +40,30 @@ pub struct NodePropertiesContext<'a> {
impl NodePropertiesContext<'_> {
pub fn call_widget_override(&mut self, node_id: &NodeId, index: usize) -> Option<Vec<LayoutGroup>> {
let input_properties_row = self.network_interface.persistent_input_metadata(node_id, index, self.selection_network_path)?;
if let Some(widget_override) = &input_properties_row.widget_override {
let Some(widget_override_lambda) = INPUT_OVERRIDES.get(widget_override) else {
log::error!("Could not get widget override '{widget_override}' lambda in call_widget_override");
// The stored override wins, falling back to the definition's own so documents saved before it gained one still
// pick it up. Only `Custom` is recovered, since the other kinds also need input data stored at insertion time.
let widget_override = input_properties_row.widget_override.clone().or_else(|| {
let implementation = self.network_interface.implementation(node_id, self.selection_network_path)?;
let DocumentNodeImplementation::ProtoNode(proto_node_identifier) = implementation else {
return None;
};
widget_override_lambda(*node_id, index, self)
.map_err(|error| log::error!("Error in widget override lambda: {error}"))
.ok()
} else {
None
}
let metadata = registry::NODE_METADATA.lock().unwrap();
let field = metadata.get(proto_node_identifier)?.fields.get(index)?;
match field.widget_override {
registry::RegistryWidgetOverride::Custom(name) => Some(name.to_string()),
_ => None,
}
})?;
let Some(widget_override_lambda) = INPUT_OVERRIDES.get(&widget_override) else {
log::error!("Could not get widget override '{widget_override}' lambda in call_widget_override");
return None;
};
widget_override_lambda(*node_id, index, self)
.map_err(|error| log::error!("Error in widget override lambda: {error}"))
.ok()
}
}
@@ -348,14 +361,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
// 2: Max (clamp subpath count to at least 1 for empty path case)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::value(TaggedValue::F64(1.), false)],
inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::value(TaggedValue::Number(1.), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 2)),
..Default::default()
},
// 3: Floor (integer count per subpath)
// 3: As Number (the integer count enters the network's decimal math)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::floor::IDENTIFIER),
inputs: vec![NodeInput::import(item!(f64), 1)],
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER),
inputs: vec![NodeInput::import(item!(i64), 1)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 13)),
..Default::default()
},
@@ -369,14 +382,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
// 5: Subtract (count - 1, open subpath denominator)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::subtract::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::F64(1.), false)],
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::Number(1.), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 14)),
..Default::default()
},
// 6: Read Index (current repetition index)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(context::read_index::IDENTIFIER),
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::U32(0), false)],
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::Integer(0), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 7)),
..Default::default()
},
@@ -425,7 +438,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
// 13: Multiply (fraction × 0.9999999999 to avoid overflowing to the next subpath)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::multiply::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(12), 0), NodeInput::value(TaggedValue::F64(0.9999999999), false)],
inputs: vec![NodeInput::node(NodeId(12), 0), NodeInput::value(TaggedValue::Number(0.9999999999), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 7)),
..Default::default()
},
@@ -459,14 +472,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
// 17: Max (clamp count to at least 1)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(3), 0), NodeInput::value(TaggedValue::F64(1.), false)],
inputs: vec![NodeInput::node(NodeId(3), 0), NodeInput::value(TaggedValue::Number(1.), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 13)),
..Default::default()
},
// 18: Max (clamp open-path denominator to at least 1 to avoid division by zero when count = 1)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(5), 0), NodeInput::value(TaggedValue::F64(1.), false)],
inputs: vec![NodeInput::node(NodeId(5), 0), NodeInput::value(TaggedValue::Number(1.), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 14)),
..Default::default()
},
@@ -479,7 +492,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
}),
inputs: vec![
NodeInput::type_default(list!(Vector), true),
NodeInput::value(TaggedValue::F64(10.), false),
NodeInput::value(TaggedValue::Integer(10), false),
NodeInput::value(TaggedValue::Bool(Default::default()), false),
NodeInput::value(TaggedValue::InterpolationDistribution(Default::default()), false),
NodeInput::type_default(item!(Vector), false),
@@ -801,7 +814,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
inputs: vec![
NodeInput::import(item!(String), 0),
NodeInput::import(item!(String), 1),
NodeInput::import(item!(f64), 2),
NodeInput::import(item!(i64), 2),
NodeInput::import(item!(bool), 3),
NodeInput::import(item!(bool), 4),
],
@@ -811,14 +824,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
// 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)
NodeTemplate {
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::F64(0.), false)],
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::item_at_index::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 0)),
..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
NodeTemplate {
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::F64(0.), false)],
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::remove_at_index::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 2)),
..Default::default()
@@ -833,7 +846,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
inputs: vec![
NodeInput::value(TaggedValue::String(String::new()), true),
NodeInput::value(TaggedValue::String(String::new()), false),
NodeInput::value(TaggedValue::F64(0.), false),
NodeInput::value(TaggedValue::Integer(0), false),
NodeInput::value(TaggedValue::Bool(false), false),
NodeInput::value(TaggedValue::Bool(false), false),
],
@@ -927,7 +940,6 @@ fn static_node_properties() -> NodeProperties {
map.insert("offset_path_properties".to_string(), Box::new(node_properties::offset_path_properties));
map.insert("selective_color_properties".to_string(), Box::new(node_properties::selective_color_properties));
map.insert("exposure_properties".to_string(), Box::new(node_properties::exposure_properties));
map.insert("math_properties".to_string(), Box::new(node_properties::math_properties));
map.insert("format_number_properties".to_string(), Box::new(node_properties::format_number_properties));
map.insert("string_capitalization_properties".to_string(), Box::new(node_properties::string_capitalization_properties));
map.insert("rectangle_properties".to_string(), Box::new(node_properties::rectangle_properties));
@@ -1098,6 +1110,11 @@ fn static_input_properties() -> InputProperties {
))])
}),
);
map.insert(
// A type-witness input, whose stored value's type selects the node's row: the dropdown lists the types the rows accept there
"type_choice".to_string(),
Box::new(|node_id, index, context| Ok(vec![node_properties::type_choice_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context))])),
);
map.insert(
"vec2".to_string(),
Box::new(|node_id, index, context| {
@@ -1351,7 +1368,7 @@ fn static_input_properties() -> InputProperties {
let Some(input) = document_node.inputs.get(index) else {
return Err("Input not found in transform rotation input override".to_string());
};
if let Some(&TaggedValue::F64(val)) = input.as_non_exposed_value() {
if let Some(&TaggedValue::Number(val)) = input.as_non_exposed_value() {
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(val))
@@ -1360,7 +1377,7 @@ fn static_input_properties() -> InputProperties {
.range_min(Some(-180.))
.range_max(Some(180.))
.on_update(node_properties::update_value_at_index(
|number_input: &NumberInput| TaggedValue::F64(number_input.value.unwrap()),
|number_input: &NumberInput| TaggedValue::Number(number_input.value.unwrap()),
node_id,
index,
))
@@ -2704,7 +2704,7 @@ impl NodeGraphMessageHandler {
added_wires
}
fn collect_nodes(&self, network_interface: &mut NodeNetworkInterface, breadcrumb_network_path: &[NodeId]) -> Vec<FrontendNode> {
pub(crate) fn collect_nodes(&self, network_interface: &mut NodeNetworkInterface, breadcrumb_network_path: &[NodeId]) -> Vec<FrontendNode> {
let Some(network) = network_interface.nested_network(breadcrumb_network_path) else {
log::error!("Could not get nested network when collecting nodes");
return Vec::new();
@@ -2739,15 +2739,14 @@ impl NodeGraphMessageHandler {
(false, false)
};
let is_export = network_interface
.input_from_connector(&InputConnector::Export(0), breadcrumb_network_path)
.is_some_and(|export| export.as_node().is_some_and(|export_node_id| node_id == export_node_id));
let is_root_node = network_interface.root_node(breadcrumb_network_path).is_some_and(|root_node| root_node.node_id == node_id);
let Some(position) = network_interface.position(&node_id, breadcrumb_network_path) else {
log::error!("Could not get position for node: {node_id}");
continue;
};
let is_export = network_interface
.input_from_connector(&InputConnector::Export(0), breadcrumb_network_path)
.is_some_and(|export| export.as_node().is_some_and(|export_node_id| node_id == export_node_id));
let is_root_node = network_interface.root_node(breadcrumb_network_path).is_some_and(|root_node| root_node.node_id == node_id);
let previewed = is_export && !is_root_node;
let locked = network_interface.is_locked(&node_id, breadcrumb_network_path);
@@ -24,7 +24,7 @@ use graphene_std::raster::{
AdjustmentChannel, BlendMode, CellularDistanceFunction, CellularReturnType, Color, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RedGreenBlueAlpha,
RelativeAbsolute, SelectiveColorChoice, TonalRange,
};
use graphene_std::raster_types::Image;
use graphene_std::raster_types::{CPU, GPU, Image, Raster};
use graphene_std::text::{Font, TextAlign};
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
use graphene_std::transfer_curve::TransferCurve;
@@ -38,6 +38,7 @@ use graphene_std::vector::style::{
build_transform_with_y_preservation,
};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
use graphene_std::{Artboard, Graphic, Vector};
use graphene_std::{NodeParameter, ParameterRef};
use std::path::PathBuf;
@@ -170,14 +171,19 @@ pub fn start_widgets(parameter_widgets_info: &ParameterWidgetsInfo) -> Vec<Widge
widgets
}
/// The numeric bounds and widget mode of a number parameter, sourced from the node's field metadata.
/// The presentation of a parameter's widget, sourced from the node's field metadata: numeric bounds, widget modes, and unit of measure.
#[derive(Clone, Copy, Default)]
pub(crate) struct NumberOptions {
pub(crate) struct ParameterOptions {
pub soft_min: Option<f64>,
pub soft_max: Option<f64>,
pub hard_min: Option<f64>,
pub hard_max: Option<f64>,
pub slider: bool,
pub multiline: bool,
pub progression: bool,
pub unit: Option<&'static str>,
pub display_decimal_places: Option<u32>,
pub step: Option<f64>,
}
/// The values a range slider's two ends map to linearly and the one its double-click restores, if known.
@@ -206,29 +212,25 @@ fn definition_default_number(parameter_widgets_info: &ParameterWidgetsInfo) -> O
let input = resolve_document_node_type(&identifier)?.node_template.inputs.get(parameter_widgets_info.index)?;
match input.as_value()? {
TaggedValue::F64(value) => Some(*value),
TaggedValue::F32(value) => Some(*value as f64),
TaggedValue::Number(value) => Some(*value),
_ => None,
}
}
pub(crate) fn property_from_type(
node_id: NodeId,
index: usize,
ty: &Type,
number_options: NumberOptions,
unit: Option<&str>,
display_decimal_places: Option<u32>,
step: Option<f64>,
context: &mut NodePropertiesContext,
) -> Result<Vec<LayoutGroup>, Vec<LayoutGroup>> {
let NumberOptions {
pub(crate) fn property_from_type(node_id: NodeId, index: usize, ty: &Type, options: ParameterOptions, context: &mut NodePropertiesContext) -> Result<Vec<LayoutGroup>, Vec<LayoutGroup>> {
let ParameterOptions {
soft_min,
soft_max,
hard_min,
hard_max,
slider,
} = number_options;
multiline,
progression,
unit,
display_decimal_places,
step,
} = options;
let mut number_input = NumberInput::default();
if slider {
number_input = number_input.mode_range();
@@ -243,10 +245,8 @@ pub(crate) fn property_from_type(
number_input = number_input.step(step);
}
// Applies the parameter's typing clamp and slider extent to the widget, given the type's own default bounds.
// Per end: the clamp is the hard bound (or unbounded if only a soft bound is given, since soft is a suggested
// extent rather than a limit), and the slider extent is the soft bound, each falling back to the hard bound
// and then to the type default when unspecified. An end with any explicit bound ignores the type default.
// The hard bound sets the typing clamp, and the soft bound (or the hard one) the slider extent, each falling
// back to the passed-in default. A soft bound alone leaves that end unclamped, since soft is only a suggestion.
let bounded = |number_input: NumberInput, type_min: f64, type_max: f64| {
let clamp_min = hard_min.unwrap_or(if soft_min.is_some() { f64::NEG_INFINITY } else { type_min });
let clamp_max = hard_max.unwrap_or(if soft_max.is_some() { f64::INFINITY } else { type_max });
@@ -260,12 +260,11 @@ pub(crate) fn property_from_type(
.range_max(Some(extent_max).filter(|bound| bound.is_finite()))
};
// A range-mode number clamped at both ends by its own hard bounds, or by a type whose extent is a true limit, becomes a range
// slider beside its number input, unless a soft bound lets typing pass the slider. An Angle's type default is no such limit.
// A range-mode number hard-clamped at both ends becomes a range slider beside its number input, unless a soft bound lets typing pass it
let no_soft_bounds = soft_min.is_none() && soft_max.is_none();
let hard_both_ends = hard_min.is_some() && hard_max.is_some();
let number_or_slider = |default_info: ParameterWidgetsInfo, number_input: NumberInput, type_limits: bool| -> LayoutGroup {
let fixed_extent = number_input.mode == NumberInputMode::Range && no_soft_bounds && (hard_both_ends || type_limits);
let number_or_slider = |default_info: ParameterWidgetsInfo, number_input: NumberInput| -> LayoutGroup {
let fixed_extent = number_input.mode == NumberInputMode::Range && no_soft_bounds && hard_both_ends;
match (number_input.min, number_input.max) {
(Some(min), Some(max)) if fixed_extent && min.is_finite() && max.is_finite() && min < max => {
let default = definition_default_number(&default_info);
@@ -298,112 +297,98 @@ pub(crate) fn property_from_type(
let mut extra_widgets = vec![];
let widgets = match ty {
Type::Concrete(concrete_type) => {
match concrete_type.alias.as_ref().map(|x| x.as_ref()) {
// Aliased types (ambiguous values)
Some("Percentage") | Some("PercentageF32") => number_or_slider(default_info, bounded(number_input.percentage(), 0., 100.), true),
Some("SignedPercentage") | Some("SignedPercentageF32") => number_or_slider(default_info, bounded(number_input.percentage(), -100., 100.), true),
Some("Angle") | Some("AngleF32") => number_or_slider(default_info, bounded(number_input.mode_range(), -180., 180.).unit(unit.unwrap_or("°")), false),
Some("Multiplier") => number_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY).unit(unit.unwrap_or("x"))).into(),
Some("PixelLength") => number_widget(default_info, bounded(number_input, 0., f64::INFINITY).unit(unit.unwrap_or(" px"))).into(),
Some("Length") => number_widget(default_info, bounded(number_input, 0., f64::INFINITY)).into(),
Some("Fraction") => number_or_slider(default_info, bounded(number_input.mode_range(), 0., 1.), true),
Some("Progression") => progression_widget(default_info, bounded(number_input, 0., f64::INFINITY)).into(),
Some("SignedInteger") => number_widget(default_info, bounded(number_input.int(), f64::NEG_INFINITY, f64::INFINITY)).into(),
Some("SeedValue") => number_widget(default_info, bounded(number_input.int(), 0., f64::INFINITY)).into(),
Some("PixelSize") => vec2_widget(default_info, "X", "Y", unit.unwrap_or(" px"), None, false),
Some("TextArea") => text_area_widget(default_info).into(),
use std::any::TypeId;
// 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>()
}
// 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_or_slider(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY), false),
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)),
// ============
// STRUCT TYPES
// ============
Some(x) if id_is::<Font>(x) => font_widget(default_info),
Some(x) if id_is::<TransferCurve>(x) => transfer_curve_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 id_is::<Resource>(x) => resource_widget(default_info, Vec::new()).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),
// =========================
// AUTO-GENERATED ENUM TYPES
// =========================
Some(x) if id_is::<GradientForm>(x) => enum_choice::<GradientForm>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientSpread>(x) => enum_choice::<GradientSpread>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientSpace>(x) => enum_choice::<GradientSpace>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientHueDirection>(x) => enum_choice::<GradientHueDirection>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientInterpolation>(x) => enum_choice::<GradientInterpolation>().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::<TextDenomination>(x) => enum_choice::<TextDenomination>().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::<TonalRange>(x) => enum_choice::<TonalRange>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<AdjustmentChannel>(x) => enum_choice::<AdjustmentChannel>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<HueSaturationRange>(x) => enum_choice::<HueSaturationRange>().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::<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::<DesaturateMethod>(x) => enum_choice::<DesaturateMethod>().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(),
// =====
// OTHER
// =====
_ => return Err(unsupported_widgets(default_info, concrete_type.to_string())),
}
}
match concrete_type.id {
// ===============
// PRIMITIVE TYPES
// ===============
Some(x) if id_is::<f64>(x) => match progression {
true => progression_widget(default_info, bounded(number_input, 0., f64::INFINITY)).into(),
false => number_or_slider(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)),
},
Some(x) if id_is::<i64>(x) => number_widget(default_info, bounded(number_input.int(), f64::NEG_INFINITY, f64::INFINITY)).into(),
Some(x) if id_is::<bool>(x) => bool_widget(default_info, CheckboxInput::default()).into(),
Some(x) if id_is::<String>(x) => match multiline {
true => text_area_widget(default_info).into(),
false => text_widget(default_info).into(),
},
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", unit.unwrap_or(""), None, false),
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)),
// ============
// STRUCT TYPES
// ============
Some(x) if id_is::<Font>(x) => font_widget(default_info),
Some(x) if id_is::<TransferCurve>(x) => transfer_curve_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 id_is::<Resource>(x) => resource_widget(default_info, Vec::new()).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),
// =========================
// AUTO-GENERATED ENUM TYPES
// =========================
Some(x) if id_is::<GradientForm>(x) => enum_choice::<GradientForm>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientSpread>(x) => enum_choice::<GradientSpread>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientSpace>(x) => enum_choice::<GradientSpace>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientHueDirection>(x) => enum_choice::<GradientHueDirection>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientInterpolation>(x) => enum_choice::<GradientInterpolation>().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::<TextDenomination>(x) => enum_choice::<TextDenomination>().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::<TonalRange>(x) => enum_choice::<TonalRange>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<AdjustmentChannel>(x) => enum_choice::<AdjustmentChannel>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<HueSaturationRange>(x) => enum_choice::<HueSaturationRange>().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::<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::<DesaturateMethod>(x) => enum_choice::<DesaturateMethod>().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(),
// =====
// OTHER
// =====
_ => return Err(unsupported_widgets(default_info, concrete_type.to_string())),
}
}
Type::Item(element) => return property_from_type(node_id, index, element, number_options, unit, display_decimal_places, step, context),
Type::Item(element) => return property_from_type(node_id, index, element, options, 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),
Type::Fn(_, out) => return property_from_type(node_id, index, out, options, context),
Type::Future(out) => return property_from_type(node_id, index, out, options, context),
};
extra_widgets.push(widgets);
@@ -807,7 +792,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.widget_instance(),
]);
}
Some(&TaggedValue::F64(value)) => {
Some(&TaggedValue::Number(value)) => {
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(value))
@@ -846,14 +831,14 @@ pub fn array_of_number_widget(parameter_widgets_info: ParameterWidgetsInfo, text
.filter(|x| !x.is_empty())
.map(graphene_std::core_types::misc::parse_f64)
.collect::<Option<Vec<_>>>()
.map(TaggedValue::F64Array)
.map(TaggedValue::Numbers)
};
let Some(input) = parameter_widgets_info.input() else {
log::warn!("A widget failed to be built because its node's input index is invalid.");
return vec![];
};
if let Some(TaggedValue::F64Array(values)) = &input.as_non_exposed_value() {
if let Some(TaggedValue::Numbers(values)) = &input.as_non_exposed_value() {
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
text_input
@@ -1008,7 +993,7 @@ pub fn progression_widget(parameter_widgets_info: ParameterWidgetsInfo, number_p
log::warn!("A widget failed to be built because its node's input index is invalid.");
return vec![];
};
if let Some(&TaggedValue::F64(x)) = input.as_non_exposed_value() {
if let Some(&TaggedValue::Number(x)) = input.as_non_exposed_value() {
let whole_part = x.trunc();
let fractional_part = x.fract();
@@ -1021,7 +1006,7 @@ pub fn progression_widget(parameter_widgets_info: ParameterWidgetsInfo, number_p
.min(0.)
.max(0.99999)
.value(Some(fractional_part))
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::F64(whole_part + input.value.unwrap())))
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::Number(whole_part + input.value.unwrap())))
.on_commit(commit_value)
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
@@ -1033,7 +1018,7 @@ pub fn progression_widget(parameter_widgets_info: ParameterWidgetsInfo, number_p
.min(0.)
.is_integer(true)
.value(Some(whole_part))
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::F64(input.value.unwrap() + fractional_part)))
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::Number(input.value.unwrap() + fractional_part)))
.on_commit(commit_value)
.widget_instance(),
])
@@ -1120,35 +1105,19 @@ pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
return vec![];
};
match input.as_non_exposed_value() {
Some(&TaggedValue::F64(x)) => widgets.extend_from_slice(&[
Some(&TaggedValue::Number(x)) => widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
number_props
.value(Some(x))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::F64(x.value.unwrap())))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::Number(x.value.unwrap())))
.on_commit(commit_value)
.widget_instance(),
]),
Some(&TaggedValue::F32(x)) => widgets.extend_from_slice(&[
Some(&TaggedValue::Integer(x)) => widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
number_props
.value(Some(x as f64))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::F32(x.value.unwrap() as f32)))
.on_commit(commit_value)
.widget_instance(),
]),
Some(&TaggedValue::U32(x)) => widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
number_props
.value(Some(x as f64))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::U32((x.value.unwrap()) as u32)))
.on_commit(commit_value)
.widget_instance(),
]),
Some(&TaggedValue::U64(x)) => widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
number_props
.value(Some(x as f64))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::U64((x.value.unwrap()) as u64)))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::Integer(x.value.unwrap().round() as i64)))
.on_commit(commit_value)
.widget_instance(),
]),
@@ -1157,7 +1126,7 @@ pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
number_props
// We use an arbitrary `y` instead of an arbitrary `x` here because the "Grid" node's "Spacing" value's height should be used from rectangular mode when transferred to "Y Spacing" in isometric mode
.value(Some(dvec2.y))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::F64(x.value.unwrap())))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::Number(x.value.unwrap())))
.on_commit(commit_value)
.widget_instance(),
]),
@@ -1201,6 +1170,96 @@ pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Layout
LayoutGroup::row(widgets).with_tooltip_description("Formula used for blending.")
}
/// A dropdown choosing among the types this input takes across the node's registered rows. The input is a type witness:
/// its stored value's type, not the value itself, selects the row, which is how a node offers a choice of output type.
pub fn type_choice_widget(parameter_widgets_info: ParameterWidgetsInfo) -> LayoutGroup {
let mut widgets = start_widgets(&parameter_widgets_info);
let Some(current) = parameter_widgets_info.input().and_then(|input| input.as_non_exposed_value()) else {
return LayoutGroup::row(widgets);
};
// Every element type the node's rows accept at this input
let mut offered: Vec<Type> = Vec::new();
let implementation = parameter_widgets_info
.network_interface
.implementation(&parameter_widgets_info.node_id, parameter_widgets_info.selection_network_path);
if let Some(DocumentNodeImplementation::ProtoNode(identifier)) = implementation
&& let Some(rows) = interpreted_executor::node_registry::NODE_REGISTRY.get(identifier)
{
for row in rows.keys() {
let Some(ty) = row.inputs.get(parameter_widgets_info.index) else { continue };
let element = wire_element(ty);
if !offered.contains(&element) {
offered.push(element);
}
}
}
let sections = type_choice_sections(&offered);
let entry_sections = sections
.iter()
.map(|section| {
section
.iter()
.map(|ty| {
let chosen = TaggedValue::from_type_or_none(ty);
MenuListEntry::new(ty.to_string())
.label(ty.to_string())
.on_update(parameter_widgets_info.update_value(move |_| chosen.clone()))
.on_commit(commit_value)
})
.collect()
})
.collect();
// The dropdown counts its selection across every section, since separators divide the entries without renumbering them
let current_element = wire_element(&current.ty());
let selected = sections.iter().flatten().position(|ty| *ty == current_element).map(|position| position as u32);
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
DropdownInput::new(entry_sections).selected_index(selected).widget_instance(),
]);
LayoutGroup::row(widgets)
}
/// The element a wire type carries, peeling the `Item` or `List` rank a registry row or stored value wraps it in.
fn wire_element(ty: &Type) -> Type {
match ty.nested_type() {
Type::Item(element) | Type::List(element) => (**element).clone(),
other => other.clone(),
}
}
/// The canonical order and grouping of the graph's types, which a type choice renders as dropdown sections divided by separators.
/// Enums stay unlisted on purpose, joining any other unnamed type in a trailing alphabetical section.
fn type_choice_sections(offered: &[Type]) -> Vec<Vec<Type>> {
let vocabulary = [
vec![concrete!(bool), concrete!(i64), concrete!(f64)],
vec![concrete!(DVec2)],
vec![concrete!(DAffine2)],
vec![concrete!(Artboard)],
vec![
concrete!(Graphic),
concrete!(Vector),
concrete!(Raster<CPU>),
concrete!(Raster<GPU>),
concrete!(Color),
concrete!(Gradient),
concrete!(String),
],
];
let mut sections: Vec<Vec<Type>> = vocabulary.iter().map(|section| section.iter().filter(|ty| offered.contains(ty)).cloned().collect()).collect();
let mut unlisted: Vec<Type> = offered.iter().filter(|ty| !vocabulary.iter().any(|section| section.contains(ty))).cloned().collect();
unlisted.sort_by_key(|ty| ty.to_string());
sections.push(unlisted);
sections.retain(|section| !section.is_empty());
sections
}
pub fn color_widget(parameter_widgets_info: ParameterWidgetsInfo, color_button: ColorInput) -> LayoutGroup {
let mut widgets = start_widgets(&parameter_widgets_info);
@@ -1719,7 +1778,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodePropertiesCont
let exposed = input.is_some_and(|input| input.is_exposed());
let value = input
.and_then(|input| input.as_value())
.and_then(|tagged| if let TaggedValue::F32(value) = tagged { Some(*value as f64) } else { None })
.and_then(|tagged| if let TaggedValue::Number(value) = tagged { Some(*value) } else { None })
.unwrap_or(0.);
(exposed, value)
})
@@ -1842,7 +1901,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodePropertiesCont
NodeGraphMessage::SetInputValue {
node_id,
input_index,
value: TaggedValue::F32(scale.value(scale_position) as f32).into(),
value: TaggedValue::Number(scale.value(scale_position)).into(),
}
.into()
}
@@ -1878,11 +1937,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodePropertiesCont
.value(Some(current))
.min_width(60)
.max_width(60)
.on_update(update_value_at_index(
move |widget: &NumberInput| TaggedValue::F32(widget.value.unwrap_or(0.) as f32),
node_id,
input_index,
))
.on_update(update_value_at_index(move |widget: &NumberInput| TaggedValue::Number(widget.value.unwrap_or(0.)), node_id, input_index))
.on_commit(commit_value)
.widget_instance(),
);
@@ -1906,8 +1961,8 @@ pub(crate) fn hue_saturation_properties(node_id: NodeId, context: &mut NodePrope
Some(TaggedValue::HueSaturationRange(range)) => *range,
_ => HueSaturationRange::Master,
};
let f32_value = |parameter: &ParameterRef| match document_node.inputs.get(parameter.input_index).and_then(|input| input.as_value()) {
Some(TaggedValue::F32(value)) => *value,
let slider_value = |parameter: &ParameterRef| match document_node.inputs.get(parameter.input_index).and_then(|input| input.as_value()) {
Some(TaggedValue::Number(value)) => *value as f32,
_ => 0.,
};
@@ -1975,9 +2030,9 @@ pub(crate) fn hue_saturation_properties(node_id: NodeId, context: &mut NodePrope
Gradient::from((0..=stops).map(stop).collect::<Vec<_>>())
};
let saturation_track = if colorize_value {
toward_hue(f32_value(&hue) / 360.)
toward_hue(slider_value(&hue) / 360.)
} else if let Some([_, range_start, range_end, _]) = &range_values {
let (start, end) = (f32_value(range_start), f32_value(range_end));
let (start, end) = (slider_value(range_start), slider_value(range_end));
let center = start + (end - start).rem_euclid(360.) / 2.;
toward_hue(center / 360.)
} else {
@@ -2121,8 +2176,7 @@ fn slider_row(
};
// An exposed input shows only its label and source
let (current, tagged_value): (f64, fn(f64) -> TaggedValue) = match input.as_non_exposed_value() {
Some(&TaggedValue::F64(value)) => (value, TaggedValue::F64),
Some(&TaggedValue::F32(value)) => (value as f64, |value| TaggedValue::F32(value as f32)),
Some(&TaggedValue::Number(value)) => (value, TaggedValue::Number),
_ => return widgets,
};
let ParameterWidgetsInfo { node_id, index, .. } = parameter_widgets_info;
@@ -2184,7 +2238,7 @@ fn gradient_slider_row(
.ok()
.and_then(|document_node| document_node.inputs.get(input_index))
.and_then(|input| input.as_non_exposed_value())
.and_then(|tagged| if let TaggedValue::F32(value) = tagged { Some(*value as f64) } else { None });
.and_then(|tagged| if let TaggedValue::Number(value) = tagged { Some(*value) } else { None });
// Only add the slider and number widgets when the input is not exposed
if let Some(current) = current {
@@ -2193,7 +2247,7 @@ fn gradient_slider_row(
max: value_max,
default: Some(default_value),
};
let value_at = move |position| TaggedValue::F32(slider.value(position) as f32);
let value_at = move |position| TaggedValue::Number(slider.value(position));
row.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
row.push(
@@ -2216,11 +2270,7 @@ fn gradient_slider_row(
.min_width(60)
.max_width(60)
.display_decimal_places(0)
.on_update(update_value_at_index(
move |widget: &NumberInput| TaggedValue::F32(widget.value.unwrap_or(0.) as f32),
node_id,
input_index,
))
.on_update(update_value_at_index(move |widget: &NumberInput| TaggedValue::Number(widget.value.unwrap_or(0.)), node_id, input_index))
.on_commit(commit_value)
.widget_instance(),
);
@@ -2642,7 +2692,7 @@ pub(crate) fn format_number_properties(node_id: NodeId, context: &mut NodeProper
let (no_decimals, decimal_sep_value, use_thousands, thousands_sep_value) = match get_document_node(node_id, context) {
Ok(document_node) => {
let decimal_places = match document_node.input(DecimalPlacesInput).and_then(|input| input.as_value()) {
Some(&TaggedValue::U32(x)) => x,
Some(&TaggedValue::Integer(x)) => x,
_ => 2,
};
let decimal_sep = match document_node.input(DecimalSeparatorInput).and_then(|input| input.as_non_exposed_value()) {
@@ -2966,10 +3016,7 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
return Vec::new();
};
let mut number_options = NumberOptions::default();
let mut display_decimal_places = None;
let mut step = None;
let mut unit_suffix = None;
let mut options = ParameterOptions::default();
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
@@ -2982,16 +3029,18 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
.get(&proto_node_identifier)
.and_then(|metadata| metadata.fields.get(input_index))
{
number_options = NumberOptions {
options = ParameterOptions {
soft_min: field.number_soft_min,
soft_max: field.number_soft_max,
hard_min: field.number_hard_min,
hard_max: field.number_hard_max,
slider: field.number_mode_range,
multiline: field.multiline,
progression: field.progression,
unit: field.unit,
display_decimal_places: field.number_display_decimal_places,
step: field.number_step,
};
display_decimal_places = field.number_display_decimal_places;
unit_suffix = field.unit;
step = field.number_step;
default_type = field.default_type.clone();
}
@@ -3019,7 +3068,7 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
.unwrap_or(concrete!(())),
};
property_from_type(node_id, input_index, &input_type, number_options, unit_suffix, display_decimal_places, step, context).unwrap_or_else(|value| value)
property_from_type(node_id, input_index, &input_type, options, context).unwrap_or_else(|value| value)
});
layout.extend(row);
@@ -3404,63 +3453,6 @@ pub fn offset_path_properties(node_id: NodeId, context: &mut NodePropertiesConte
vec![LayoutGroup::row(distance), join, LayoutGroup::row(miter_limit)]
}
pub fn math_properties(node_id: NodeId, context: &mut NodePropertiesContext) -> Vec<LayoutGroup> {
use graphene_std::math_nodes::math::*;
let expression = (|| {
let mut widgets = start_widgets(&ParameterWidgetsInfo::new(node_id, ExpressionInput, true, context));
let document_node = match get_document_node(node_id, context) {
Ok(document_node) => document_node,
Err(err) => {
log::error!("Could not get document node in offset_path_properties: {err}");
return Vec::new();
}
};
let Some(input) = document_node.input(ExpressionInput) else {
log::warn!("A widget failed to be built because its node's input index is invalid.");
return vec![];
};
if let Some(TaggedValue::String(x)) = &input.as_non_exposed_value() {
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextInput::new(x.clone())
.centered(true)
.on_update(update_value(
|x: &TextInput| {
TaggedValue::String({
let mut expression = x.value.trim().to_string();
if ["+", "-", "*", "/", "^"].iter().any(|&infix| infix == expression) {
expression = format!("A {expression} B");
} else if expression == "^" {
expression = String::from("A^B");
} else if expression == "%" || expression == "mod" {
expression = String::from("mod(a, b)");
}
expression
})
},
node_id,
ExpressionInput,
))
.on_commit(commit_value)
.widget_instance(),
])
}
widgets
})();
let operand_b = number_widget(ParameterWidgetsInfo::new(node_id, OperandBInput, true, context), NumberInput::default());
let operand_a_hint = vec![TextLabel::new("(Operand A is the primary input)").widget_instance()];
vec![
LayoutGroup::row(expression).with_tooltip_description(r#"A math expression that may incorporate "A" and/or "B", such as "sqrt(A + B) - B^2"."#),
LayoutGroup::row(operand_b).with_tooltip_description(r#"The value of "B" when calculating the expression."#),
LayoutGroup::row(operand_a_hint).with_tooltip_description(r#""A" is fed by the value from the previous node in the primary data flow, or it is 0 if disconnected."#),
]
}
pub struct ParameterWidgetsInfo<'a> {
document_id: DocumentId,
network_interface: &'a NodeNetworkInterface,
@@ -3699,3 +3691,23 @@ pub mod choice {
pub struct ForValue<W>(PhantomData<W>);
}
#[cfg(test)]
mod tests {
use super::*;
use graph_craft::{item, list};
#[test]
fn wire_element_reads_every_spelling_down_to_the_element() {
// A stored value's ranked type, a registry row's fn type, and a mapped row's list all carry the same element
let row = Type::Fn(Box::new(concrete!(())), Box::new(Type::Future(Box::new(item!(f64)))));
let mapped_row = Type::Fn(Box::new(concrete!(())), Box::new(Type::Future(Box::new(list!(f64)))));
for ty in [TaggedValue::Number(0.).ty(), item!(f64), list!(f64), row, mapped_row] {
assert_eq!(wire_element(&ty), concrete!(f64), "{ty:?} should read down to its element");
}
// The element of a stored value and of the row that accepts it agree, which is what selects the dropdown entry
assert_eq!(wire_element(&TaggedValue::Integer(0).ty()), wire_element(&item!(i64)));
assert_ne!(wire_element(&TaggedValue::Integer(0).ty()), wire_element(&item!(f64)));
}
}
@@ -33,7 +33,7 @@ impl FrontendGraphDataType {
"Color" => Self::Color,
"Gradient" => Self::Gradient,
"String" => Self::Typography,
"f64" | "f32" | "u32" | "u64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
raster if raster.starts_with("Raster") => Self::Raster,
_ => Self::General,
}
@@ -4,7 +4,7 @@
//! metadata survives the conversion. The end-to-end save/reopen pipeline is covered separately in
//! [`round_trip_tests`](super::round_trip_tests).
use std::collections::HashMap;
use std::collections::{BTreeSet, HashMap};
use document_graph_storage::{NodeMetadataSource, PeerId, Registry};
@@ -57,22 +57,6 @@ fn editor_metadata_round_trip_against_demo() {
|| !source.input_data(&network_path, local_id, i).is_empty()
});
let any_metadata = expected_position.is_some()
|| expected_is_layer
|| expected_display.as_deref().is_some_and(|s| !s.is_empty())
|| expected_locked
|| expected_pinned
|| any_input_metadata_present
|| !expected_output_names.is_empty();
if !any_metadata {
assert!(
!entries_by_address.contains_key(&(network_path.clone(), local_id)),
"node {local_id:?} in network {network_path:?} has no editor metadata but produced an entry"
);
continue;
}
let entry = entries_by_address
.get(&(network_path.clone(), local_id))
.unwrap_or_else(|| panic!("missing entry for node {local_id:?} in network {network_path:?}"));
@@ -262,6 +246,76 @@ fn editor_interface_rebuild_round_trip() {
assert!(checked_any_reference, "demo artwork produced no reference metadata: fixture is wrong or extraction is broken");
}
/// The rebuild pins every node to the identity storage named it, rather than leaving it to be
/// re-derived. Re-converting under a different peer is the sharp test: a location hash mixes the peer
/// in, so it would produce an entirely different set of IDs.
#[test]
fn rebuilt_interface_keeps_storage_identities() {
let document = load_demo("changing-seasons.graphite");
let view = StorageMetadataView::new(&document.network_interface);
let network = document.network_interface.document_network().clone();
let conversion = Registry::convert_from_runtime(&network, &view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
let declarations = conversion.declarations;
let registry = conversion.registry;
let (rebuilt_network, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime_with_full_metadata failed");
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries).expect("build_interface_from_storage failed");
let reconverted_network = rebuilt.document_network().clone();
let reconverted = Registry::convert_from_runtime(&reconverted_network, &StorageMetadataView::new(&rebuilt), &Default::default(), PeerId(9)).expect("re-convert from_runtime failed");
let stored_ids: BTreeSet<_> = registry.node_instances.keys().copied().collect();
let reconverted_ids: BTreeSet<_> = reconverted.registry.node_instances.keys().copied().collect();
assert!(!stored_ids.is_empty(), "demo artwork produced no nodes: fixture is wrong");
assert_eq!(reconverted_ids, stored_ids, "re-converting the rebuilt interface under a different peer changed the node identities");
}
/// Migrating an opened document must leave the recorded-delta buffer empty.
#[test]
fn migrating_a_document_records_no_changes() {
let mut document = load_demo("painted-dreams.graphite");
document.network_interface.discard_deltas();
crate::messages::portfolio::document_migration::document_migration_upgrades(&mut document, false);
let recorded = document.network_interface.take_deltas();
assert!(recorded.is_empty(), "migration left {} recorded changes behind", recorded.len());
}
/// The pinned display order is document state, so it survives a registry round trip. It names nodes and
/// the stored form uses storage IDs, so this also checks the references resolve back to the right
/// runtime nodes.
#[test]
fn pinned_order_round_trips_through_the_registry() {
let mut document = load_demo("changing-seasons.graphite");
let pinned: Vec<_> = document.network_interface.document_network().nodes.keys().copied().take(3).collect();
assert_eq!(pinned.len(), 3, "demo artwork should have at least three nodes: fixture is wrong");
{
let interface = &mut document.network_interface;
let Some(mut network) = interface.network_mut(&[]) else {
panic!("the document network should resolve")
};
network.set_pinned_order(pinned.clone());
}
let network = document.network_interface.document_network().clone();
let view = StorageMetadataView::new(&document.network_interface);
let conversion = Registry::convert_from_runtime(&network, &view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
let declarations = conversion.declarations;
let (rebuilt_network, node_entries, network_entries) = conversion.registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime failed");
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries).expect("build_interface_from_storage failed");
let rebuilt_metadata = rebuilt.network_metadata(&[]).expect("the rebuilt document network should resolve");
assert_eq!(
rebuilt_metadata.persistent_metadata.pinned_node_order, pinned,
"the pinned display order did not survive the registry round trip"
);
}
/// Per-peer view settings (`ui::doc::*`) survive the `session.json` round-trip: serialize them into
/// the view map, then apply it onto a fresh handler and confirm each field matches.
#[test]
@@ -4,13 +4,11 @@
//! MessagePack codecs, hot-op retirement, file layout, replay-on-open) that the debug-only
//! `verify_storage_round_trip` only checks in-process without an actual save/reopen.
use crate::messages::resource_storage::ResourcesHandle;
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use document_graph_storage::{NodeMetadataSource, PeerId};
use graph_craft::application_io::resource::HashMapResourceStorage;
use std::sync::Arc;
use super::test_support::{RoundTrip, node_paths, round_trip_through_gdd};
use crate::messages::portfolio::document::document_message_handler::DocumentMessageHandler;
@@ -158,7 +156,7 @@ async fn edit_after_open_commits_cleanly() {
// Persist the document into a fresh Gdd and reopen it, then build a runtime document from the
// reopened registry: the editor's .gdd-open path.
let byte_store = ResourcesHandle::new(Arc::new(HashMapResourceStorage::new()));
let byte_store = HashMapResourceStorage::new();
let source = editor.active_document();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
.await
@@ -178,7 +176,7 @@ async fn edit_after_open_commits_cleanly() {
{
let document = editor.active_document_mut();
document.network_interface = rebuilt;
document.set_storage(reopened, declarations, byte_store.storage());
document.set_storage(reopened, declarations);
document.finalize_storage_load();
}
@@ -676,13 +674,12 @@ fn assert_cursor_matches_runtime(document: &DocumentMessageHandler, at: &str) {
/// Mount a fresh in-memory `Gdd` onto the active document so `commit_storage_snapshot` (the real
/// autosave path) runs against it. Returns the byte store the document's resources resolve through.
async fn mount_in_memory_storage(editor: &mut EditorTestUtils) -> ResourcesHandle {
async fn mount_in_memory_storage(editor: &mut EditorTestUtils) -> HashMapResourceStorage {
let gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0x5EED, "test".into(), "test".into())
.await
.expect("create_in");
let byte_store = ResourcesHandle::new(Arc::new(HashMapResourceStorage::new()));
editor.active_document_mut().set_storage(gdd, Default::default(), byte_store.storage());
byte_store
editor.active_document_mut().set_storage(gdd, Default::default());
HashMapResourceStorage::new()
}
/// Open a real demo artwork, mount storage, edit it, and trigger autosave. The autosave runs
@@ -1,14 +1,22 @@
mod apply;
mod caches;
#[cfg(test)]
mod characterization_tests;
mod deserialization;
pub mod editor_delta;
#[cfg(test)]
mod editor_delta_tests;
mod frontend;
mod geometry;
mod hit_tests;
mod invalidation;
mod layout;
mod memo_network;
mod mutations;
mod queries;
mod resolved_types;
pub mod storage_metadata;
mod store;
mod structure;
mod template;
mod types;
@@ -16,6 +24,9 @@ mod types;
mod validation;
mod view;
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
use store::Guarded;
pub use store::NodeLocator;
pub use template::*;
pub use types::*;
pub use view::{NetworkError, NetworkView};
@@ -59,9 +70,9 @@ use std::sync::Arc;
pub struct NodeNetworkInterface {
/// The node graph that generates this document's artwork. It recursively stores its sub-graphs, so this root graph is the whole snapshot of the document content.
/// A public mutable reference should never be created. It should only be mutated through custom setters which perform the necessary side effects to keep network_metadata in sync
network: MemoNetwork,
network: Guarded<MemoNetwork>,
/// Stores all editor information for a NodeNetwork. Should automatically kept in sync by the setter methods when changes to the document network are made.
network_metadata: NodeNetworkMetadata,
network_metadata: Guarded<NodeNetworkMetadata>,
// TODO: Wrap in a TransientCache
/// Stores the document network's structural topology. Should automatically kept in sync by the setter methods when changes to the document network are made.
#[serde(skip)]
@@ -71,6 +82,14 @@ pub struct NodeNetworkInterface {
pub resolved_types: ResolvedDocumentNodeTypes,
#[serde(skip)]
transaction_status: TransactionStatus,
/// What the writes since the last drain changed, in write order, appended by `store.rs` alone.
///
/// Emitting here rather than in the mutators makes it impossible to write without saying what was
/// written, the same way writing through the store makes it impossible to update one tree without
/// the other. Transient: a snapshot clone starts empty, since the snapshot is a state rather than
/// a set of changes.
#[serde(skip)]
deltas: Vec<EditorDelta>,
}
impl Clone for NodeNetworkInterface {
@@ -81,6 +100,7 @@ impl Clone for NodeNetworkInterface {
document_metadata: Default::default(),
resolved_types: Default::default(),
transaction_status: TransactionStatus::Finished,
deltas: Vec::new(),
}
}
}
@@ -92,9 +112,14 @@ impl PartialEq for NodeNetworkInterface {
}
impl NodeNetworkInterface {
/// Normalizes the stored types of every node at every nesting level, for an older document whose stored types predate the current form.
pub fn normalize_stored_types(&mut self) {
self.migrate_graph(NodeNetwork::normalize_stored_types);
}
/// Add DocumentNodePath input to the PathModifyNode protonode
pub fn migrate_path_modify_node(&mut self) {
fix_network(self.document_network_mut());
self.migrate_graph(fix_network);
fn fix_network(network: &mut NodeNetwork) {
for node in network.nodes.values_mut() {
if let Some(network) = node.implementation.get_network_mut() {
@@ -136,11 +161,11 @@ mod network_interface_tests {
content: ClipboardContentRaw::Text(clipboard),
})
.await;
let nodes = &mut editor.active_document_mut().network_interface.network_mut(&[]).unwrap().nodes;
let orignal = nodes.remove(&rectangle).expect("original node should exist");
let nodes = &editor.active_document().network_interface.document_network().nodes;
let original = nodes.get(&rectangle).expect("original node should exist");
assert!(
nodes.values().any(|other| *other == orignal),
"duplicated node should exist\nother nodes: {nodes:#?}\norignal {orignal:#?}"
nodes.iter().any(|(node_id, other)| *node_id != rectangle && other == original),
"duplicated node should exist\nother nodes: {nodes:#?}\noriginal {original:#?}"
);
}
}
@@ -0,0 +1,124 @@
use super::*;
use graph_craft::runtime_delta::RuntimeDelta;
impl NodeNetworkInterface {
/// Mirrors a delta into the interface without recording it.
///
/// A delta reaching here came from somewhere else, so recording it would offer a change this peer
/// never made back to whoever sent it. Writing through the store and then dropping what the store
/// recorded keeps the two parallel trees written by one place, which is the property the store
/// exists for, without the echo.
#[cfg_attr(not(test), expect(dead_code, reason = "no caller until deltas from another peer are replayed; the replay tests exercise it"))]
pub(crate) fn apply(&mut self, delta: &EditorDelta) {
let recorded = self.deltas.len();
self.mirror(delta);
self.deltas.truncate(recorded);
}
fn mirror(&mut self, delta: &EditorDelta) {
match delta {
// The metadata arrives separately, so a node lands with default metadata that the paired
// snapshot then fills in
EditorDelta::Graph(RuntimeDelta::AddNode { network_path, node_id, node }) | EditorDelta::Graph(RuntimeDelta::ReplaceNode { network_path, node_id, node }) => {
let template = NodeTemplate::from_parts((**node).clone(), DocumentNodePersistentMetadata::default());
self.insert_node_entry(NodeLocator::new(*node_id, network_path), template);
}
EditorDelta::Graph(RuntimeDelta::RemoveNode { network_path, node_id }) => {
self.remove_node_entry(NodeLocator::new(*node_id, network_path));
}
EditorDelta::Graph(RuntimeDelta::SetInput {
network_path,
node_id,
input_index,
input,
}) => {
self.set_input_slot(&InputConnector::node_at_index(*node_id, *input_index), network_path, input.clone());
}
EditorDelta::Graph(RuntimeDelta::SetInputs { network_path, node_id, inputs }) => {
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else { return };
// The slots are what changed; their metadata follows in the paired delta. Resizing keeps the
// two arrays the same length in the meantime, which the rest of the interface assumes.
let mut input_metadata = node.input_metadata().to_vec();
input_metadata.resize(inputs.len(), InputMetadata::default());
node.replace_inputs(inputs.clone(), input_metadata);
}
EditorDelta::Graph(RuntimeDelta::SetExport { network_path, export_index, input }) => match input {
None => {
self.remove_export_slot(network_path, *export_index);
}
// A peer can name a slot past the end of this network's exports, which is an insert here
// rather than a write to a slot that does not exist yet.
Some(input) if *export_index >= self.number_of_exports(network_path) => {
self.insert_export_slot(network_path, *export_index, input.clone(), String::new());
}
Some(input) => {
self.set_input_slot(&InputConnector::Export(*export_index), network_path, input.clone());
}
},
EditorDelta::Graph(RuntimeDelta::SetVisibility { network_path, node_id, visible }) => {
if let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) {
node.set_visible(*visible);
}
}
EditorDelta::Graph(RuntimeDelta::SetCallArgument { network_path, node_id, call_argument }) => {
if let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) {
node.set_call_argument(call_argument.clone());
}
}
EditorDelta::Graph(RuntimeDelta::SetContextFeatures {
network_path,
node_id,
context_features,
}) => {
if let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) {
node.set_context_features(*context_features);
}
}
EditorDelta::NodeMetadataSnapshot { network_path, node_id, metadata } => {
if let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) {
node.replace_metadata((**metadata).clone());
}
}
EditorDelta::NodeInputMetadata {
network_path,
node_id,
input_metadata,
} => {
if let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) {
node.set_input_metadata(input_metadata.clone());
}
}
EditorDelta::NodeMetadata { network_path, node_id, change } => {
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else { return };
match change {
NodeMetadataChange::NodeType(node_type) => node.set_node_type(node_type.clone()),
NodeMetadataChange::DisplayName(display_name) => node.set_display_name(display_name.clone()),
NodeMetadataChange::Locked(locked) => node.set_locked(*locked),
NodeMetadataChange::Pinned(pinned) => node.set_pinned(*pinned),
NodeMetadataChange::OutputNames(output_names) => node.set_output_names(output_names.clone()),
NodeMetadataChange::InputName { index, name } => node.set_input_name(*index, name.clone()),
NodeMetadataChange::WidgetOverride { index, widget_override } => node.set_widget_override(*index, widget_override.clone()),
};
}
EditorDelta::NetworkMetadata { network_path, change } => {
let Some(mut network) = self.network_mut(network_path) else { return };
match change {
NetworkMetadataChange::Reference(reference) => network.set_reference(reference.clone()),
NetworkMetadataChange::PinnedOrder(order) => network.set_pinned_order(order.clone()),
};
}
}
}
}
@@ -29,48 +29,47 @@ impl NodeNetworkInterface {
};
self.unload_stack_dependents(network_path);
let Some(network_metadata) = self.network_metadata_mut(network_path) else {
log::error!("Could not get nested network_metadata in selected_nodes");
let Some(history) = self.selection_history_mut(network_path) else {
log::error!("Could not get nested network_metadata in selected_nodes_mut");
return None;
};
// Initialize default value if selection_undo_history is empty
if network_metadata.persistent_metadata.selection_undo_history.is_empty() {
network_metadata.persistent_metadata.selection_undo_history.push_back(SelectedNodes::default());
if history.undo.is_empty() {
history.undo.push_back(SelectedNodes::default());
}
// Update history only if selection is non-empty/does not contain only artboards
if !is_selection_empty && prev_state.as_ref() != Some(&last_selection_state) {
network_metadata.persistent_metadata.selection_undo_history.push_back(last_selection_state);
network_metadata.persistent_metadata.selection_redo_history.clear();
history.undo.push_back(last_selection_state);
history.redo.clear();
if network_metadata.persistent_metadata.selection_undo_history.len() > crate::consts::MAX_UNDO_HISTORY_LEN {
network_metadata.persistent_metadata.selection_undo_history.pop_front();
if history.undo.len() > crate::consts::MAX_UNDO_HISTORY_LEN {
history.undo.pop_front();
}
}
network_metadata.persistent_metadata.selection_undo_history.back_mut()
history.undo.back_mut()
}
pub fn selection_step_back(&mut self, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata_mut(network_path) else {
let Some(history) = self.selection_history_mut(network_path) else {
log::error!("Could not get nested network_metadata in selection_step_back");
return;
};
if let Some(selection_state) = network_metadata.persistent_metadata.selection_undo_history.pop_back() {
network_metadata.persistent_metadata.selection_redo_history.push_front(selection_state);
if let Some(selection_state) = history.undo.pop_back() {
history.redo.push_front(selection_state);
}
}
pub fn selection_step_forward(&mut self, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata_mut(network_path) else {
let Some(history) = self.selection_history_mut(network_path) else {
log::error!("Could not get nested network_metadata in selection_step_forward");
return;
};
if let Some(selection_state) = network_metadata.persistent_metadata.selection_redo_history.pop_front() {
network_metadata.persistent_metadata.selection_undo_history.push_back(selection_state);
if let Some(selection_state) = history.redo.pop_front() {
history.undo.push_back(selection_state);
}
}
@@ -81,7 +80,7 @@ impl NodeNetworkInterface {
pub(crate) fn try_load_stack_dependents(&self, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in stack_dependents");
log::error!("Could not get nested network_metadata in try_load_stack_dependents");
return;
};
@@ -96,12 +95,12 @@ impl NodeNetworkInterface {
}
pub(crate) fn try_get_stack_dependents(&mut self, network_path: &[NodeId]) -> Option<&HashMap<NodeId, LayerOwner>> {
let Some(network_metadata) = self.network_metadata_mut(network_path) else {
let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in try_get_stack_dependents");
return None;
};
let Some(stack_dependents) = network_metadata.transient_metadata.stack_dependents.get_loaded_mut() else {
log::error!("could not load stack_dependents");
let Some(stack_dependents) = transient.stack_dependents.get_loaded_mut() else {
log::error!("Could not load stack dependents in try_get_stack_dependents");
return None;
};
Some(stack_dependents)
@@ -148,7 +147,7 @@ impl NodeNetworkInterface {
.get(&OutputConnector::primary_output(current_node))
.map(|layer_outward_wires| layer_outward_wires.first().copied())
}) else {
log::error!("Cannot load outward wires in load_stack_dependents");
log::error!("Cannot load outward wires in load_stack_dependents_for_nodes");
return;
};
let Some(first_downstream_input) = first_downstream_input else {
@@ -188,7 +187,7 @@ impl NodeNetworkInterface {
new_owned_nodes.insert(*layer_sole_dependent);
}
let Some(layer_node) = self.node_metadata(&upstream_layer, network_path) else {
log::error!("Could not get layer node in load_stack_dependents");
log::error!("Could not get layer node in load_stack_dependents_for_nodes");
continue;
};
layer_node.transient_metadata.owned_nodes.store(new_owned_nodes);
@@ -232,7 +231,7 @@ impl NodeNetworkInterface {
}
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get current network in load_stack_dependents");
log::error!("Could not get current network in load_stack_dependents_for_nodes");
return;
};
@@ -240,14 +239,14 @@ impl NodeNetworkInterface {
}
pub fn unload_stack_dependents(&mut self, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata_mut(network_path) else {
let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in unload_stack_dependents");
return;
};
network_metadata.transient_metadata.stack_dependents.unload();
transient.stack_dependents.unload();
// Drag offsets are only meaningful relative to the stack dependents snapshot they were accumulated against, so they must not outlive it
network_metadata.transient_metadata.drag_offsets.borrow_mut().clear();
transient.drag_offsets.borrow_mut().clear();
}
/// The vertical distance the node has been pushed from its resting position during the current drag.
@@ -274,14 +273,14 @@ impl NodeNetworkInterface {
}
pub fn import_export_ports(&mut self, network_path: &[NodeId]) -> Option<&Ports> {
self.try_load_import_export_ports(network_path);
self.load_import_export_ports(network_path);
let Some(network_metadata) = self.network_metadata_mut(network_path) else {
log::error!("Could not get nested network_metadata in export_ports");
let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in import_export_ports");
return None;
};
let Some(ports) = network_metadata.transient_metadata.import_export_ports.get_loaded_mut() else {
log::error!("could not load import ports");
let Some(ports) = transient.import_export_ports.get_loaded_mut() else {
log::error!("Could not load import export ports in import_export_ports");
return None;
};
Some(ports)
@@ -289,65 +288,37 @@ impl NodeNetworkInterface {
/// Reads the import/export ports through &self, loading them first if needed.
pub(crate) fn with_import_export_ports<R>(&self, network_path: &[NodeId], read: impl FnOnce(&Ports) -> R) -> Option<R> {
self.try_load_import_export_ports(network_path);
self.network_metadata(network_path)?.transient_metadata.import_export_ports.with_loaded(read)
}
fn try_load_import_export_ports(&self, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in export_ports");
return;
};
if !network_metadata.transient_metadata.import_export_ports.is_loaded() {
self.load_import_export_ports(network_path);
}
self.network_metadata(network_path)?
.transient_metadata
.import_export_ports
.with_loaded_or(|| self.compute_import_export_ports(network_path), read)
}
pub fn load_import_export_ports(&self, network_path: &[NodeId]) {
let Some(import_export_position) = self.import_export_position(network_path) else {
log::error!("Could not get import_export_position");
return;
};
let Some(network) = self.nested_network(network_path) else { return };
let mut import_export_ports = Ports::new();
if !network_path.is_empty() {
let import_start_index = if self.hidden_primary_import(network_path) { 1 } else { 0 };
for import_index in import_start_index..self.number_of_imports(network_path) {
import_export_ports.insert_output_port_at_center(import_index, import_export_position.0.as_dvec2() + DVec2::new(0., import_index as f64 * 24.));
}
}
let export_start_index = if self.hidden_primary_export(network_path) { 1 } else { 0 };
for export_index in export_start_index..network.exports.len() {
import_export_ports.insert_input_port_at_center(export_index, import_export_position.1.as_dvec2() + DVec2::new(0., export_index as f64 * 24.));
}
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get current network in load_export_ports");
log::error!("Could not get nested network_metadata in load_import_export_ports");
return;
};
network_metadata.transient_metadata.import_export_ports.store(import_export_ports);
network_metadata.transient_metadata.import_export_ports.ensure_loaded(|| self.compute_import_export_ports(network_path));
}
pub(crate) fn unload_import_export_ports(&mut self, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata_mut(network_path) else {
log::error!("Could not get nested network_metadata in unload_export_ports");
let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in unload_import_export_ports");
return;
};
network_metadata.transient_metadata.import_export_ports.unload();
transient.import_export_ports.unload();
// Always unload all wires connected to them as well
let number_of_imports = self.number_of_imports(network_path);
let Some(outward_wires) = self.outward_wires(network_path) else {
log::error!("Could not get outward wires in remove_import");
log::error!("Could not get outward wires in unload_import_export_ports");
return;
};
let mut input_connectors = Vec::new();
for import_index in 0..number_of_imports {
let Some(outward_wires_for_import) = outward_wires.get(&OutputConnector::Import(import_index)).cloned() else {
log::error!("Could not get outward wires for import in remove_import");
log::error!("Could not get outward wires for import in unload_import_export_ports");
return;
};
input_connectors.extend(outward_wires_for_import);
@@ -364,93 +335,36 @@ impl NodeNetworkInterface {
}
pub fn modify_import_export(&mut self, network_path: &[NodeId]) -> Option<&ModifyImportExportClickTarget> {
let Some(network_metadata) = self.network_metadata(network_path) else {
self.load_modify_import_export(network_path);
let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in modify_import_export");
return None;
};
if !network_metadata.transient_metadata.modify_import_export.is_loaded() {
self.load_modify_import_export(network_path);
}
let Some(network_metadata) = self.network_metadata_mut(network_path) else {
log::error!("Could not get nested network_metadata in modify_import_export");
return None;
};
let Some(click_targets) = network_metadata.transient_metadata.modify_import_export.get_loaded_mut() else {
log::error!("could not load modify import export ports");
let Some(click_targets) = transient.modify_import_export.get_loaded_mut() else {
log::error!("Could not load modify import export in modify_import_export");
return None;
};
Some(click_targets)
}
pub fn load_modify_import_export(&self, network_path: &[NodeId]) {
let mut reorder_imports_exports = Ports::new();
let mut remove_imports_exports = Ports::new();
if !network_path.is_empty() {
let ports_built = self.with_import_export_ports(network_path, |import_exports| {
for (import_index, import_click_target) in import_exports.output_ports() {
let Some(import_bounding_box) = import_click_target.bounding_box() else {
log::error!("Could not get export bounding box in load_modify_import_export");
continue;
};
let reorder_import_center = (import_bounding_box[0] + import_bounding_box[1]) / 2. + DVec2::new(-12., 0.);
if *import_index == 0 {
let remove_import_center = reorder_import_center + DVec2::new(-4., 0.);
let remove_import = ClickTarget::new_with_path(rectangle_path(remove_import_center - DVec2::new(8., 8.), remove_import_center + DVec2::new(8., 8.)), 0.);
remove_imports_exports.insert_custom_output_port(*import_index, remove_import);
} else {
let remove_import_center = reorder_import_center + DVec2::new(-12., 0.);
let reorder_import = ClickTarget::new_with_path(rectangle_path(reorder_import_center - DVec2::new(3., 4.), reorder_import_center + DVec2::new(3., 4.)), 0.);
let remove_import = ClickTarget::new_with_path(rectangle_path(remove_import_center - DVec2::new(8., 8.), remove_import_center + DVec2::new(8., 8.)), 0.);
reorder_imports_exports.insert_custom_output_port(*import_index, reorder_import);
remove_imports_exports.insert_custom_output_port(*import_index, remove_import);
}
}
for (export_index, export_click_target) in import_exports.input_ports() {
let Some(export_bounding_box) = export_click_target.bounding_box() else {
log::error!("Could not get export bounding box in load_modify_import_export");
continue;
};
let reorder_export_center = (export_bounding_box[0] + export_bounding_box[1]) / 2. + DVec2::new(12., 0.);
if *export_index == 0 {
let remove_export_center = reorder_export_center + DVec2::new(4., 0.);
let remove_export = ClickTarget::new_with_path(rectangle_path(remove_export_center - DVec2::new(8., 8.), remove_export_center + DVec2::new(8., 8.)), 0.);
remove_imports_exports.insert_custom_input_port(*export_index, remove_export);
} else {
let remove_export_center = reorder_export_center + DVec2::new(12., 0.);
let reorder_export = ClickTarget::new_with_path(rectangle_path(reorder_export_center - DVec2::new(3., 4.), reorder_export_center + DVec2::new(3., 4.)), 0.);
let remove_export = ClickTarget::new_with_path(rectangle_path(remove_export_center - DVec2::new(8., 8.), remove_export_center + DVec2::new(8., 8.)), 0.);
reorder_imports_exports.insert_custom_input_port(*export_index, reorder_export);
remove_imports_exports.insert_custom_input_port(*export_index, remove_export);
}
}
});
if ports_built.is_none() {
log::error!("Could not get import_export_ports in load_modify_import_export");
return;
}
}
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get current network in load_modify_import_export");
log::error!("Could not get nested network_metadata in load_modify_import_export");
return;
};
network_metadata.transient_metadata.modify_import_export.store(ModifyImportExportClickTarget {
remove_imports_exports,
reorder_imports_exports,
});
network_metadata
.transient_metadata
.modify_import_export
.ensure_loaded(|| self.compute_modify_import_export(network_path));
}
pub(crate) fn unload_modify_import_export(&mut self, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata_mut(network_path) else {
log::error!("Could not get nested network_metadata in unload_export_ports");
let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in unload_modify_import_export");
return;
};
network_metadata.transient_metadata.modify_import_export.unload();
transient.modify_import_export.unload();
}
/// Reads the owned nodes of a layer through &self if they are loaded.
@@ -468,52 +382,48 @@ impl NodeNetworkInterface {
return None;
};
if !network_metadata.transient_metadata.all_nodes_bounding_box.is_loaded() {
self.load_all_nodes_bounding_box(network_path);
}
let bounding_box = self.network_metadata(network_path)?.transient_metadata.all_nodes_bounding_box.with_loaded(|bounds| *bounds);
let bounding_box = network_metadata
.transient_metadata
.all_nodes_bounding_box
.with_loaded_or(|| self.compute_all_nodes_bounding_box(network_path), |bounds| *bounds);
if bounding_box.is_none() {
log::error!("could not load all nodes bounding box");
log::error!("Could not load all nodes bounding box in all_nodes_bounding_box");
}
bounding_box
}
pub fn load_all_nodes_bounding_box(&self, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in load_all_nodes_bounding_box");
return;
};
/// The combined bounds of every node in the network, in node graph space.
fn compute_all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
let network_metadata = self.network_metadata(network_path)?;
let nodes = network_metadata.persistent_metadata.node_metadata.keys().copied().collect::<Vec<_>>();
let all_nodes_bounding_box = nodes
.iter()
.filter_map(|node_id| self.node_bounding_box(node_id, network_path))
.reduce(Quad::combine_bounds)
.unwrap_or([DVec2::new(0., 0.), DVec2::new(0., 0.)]);
let Some(network_metadata) = self.network_metadata(network_path) else { return };
network_metadata.transient_metadata.all_nodes_bounding_box.store(all_nodes_bounding_box);
Some(
nodes
.iter()
.filter_map(|node_id| self.node_bounding_box(node_id, network_path))
.reduce(Quad::combine_bounds)
.unwrap_or([DVec2::new(0., 0.), DVec2::new(0., 0.)]),
)
}
pub fn unload_all_nodes_bounding_box(&mut self, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata_mut(network_path) else {
let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in unload_all_nodes_bounding_box");
return;
};
network_metadata.transient_metadata.all_nodes_bounding_box.unload();
transient.all_nodes_bounding_box.unload();
self.unload_import_export_ports(network_path);
}
pub fn outward_wires(&mut self, network_path: &[NodeId]) -> Option<&HashMap<OutputConnector, Vec<InputConnector>>> {
self.try_load_outward_wires(network_path);
self.load_outward_wires(network_path);
let Some(network_metadata) = self.network_metadata_mut(network_path) else {
let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in outward_wires");
return None;
};
let Some(outward_wires) = network_metadata.transient_metadata.outward_wires.get_loaded_mut() else {
log::error!("could not load outward wires");
let Some(outward_wires) = transient.outward_wires.get_loaded_mut() else {
log::error!("Could not load outward wires in outward_wires");
return None;
};
@@ -522,28 +432,29 @@ impl NodeNetworkInterface {
/// Reads the outward wires through &self, loading them first if needed.
pub(crate) fn with_outward_wires<R>(&self, network_path: &[NodeId], read: impl FnOnce(&HashMap<OutputConnector, Vec<InputConnector>>) -> R) -> Option<R> {
self.try_load_outward_wires(network_path);
self.network_metadata(network_path)?.transient_metadata.outward_wires.with_loaded(read)
}
fn try_load_outward_wires(&self, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in outward_wires");
return;
};
if !network_metadata.transient_metadata.outward_wires.is_loaded() {
self.load_outward_wires(network_path);
}
self.network_metadata(network_path)?
.transient_metadata
.outward_wires
.with_loaded_or(|| self.compute_outward_wires(network_path), read)
}
fn load_outward_wires(&self, network_path: &[NodeId]) {
let mut outward_wires = HashMap::new();
let Some(network) = self.nested_network(network_path) else {
log::error!("Could not get nested network in load_outward_wires");
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in load_outward_wires");
return;
};
network_metadata.transient_metadata.outward_wires.ensure_loaded(|| self.compute_outward_wires(network_path));
}
/// Every input fed by each node output and each import of the network.
fn compute_outward_wires(&self, network_path: &[NodeId]) -> Option<HashMap<OutputConnector, Vec<InputConnector>>> {
let mut outward_wires = HashMap::new();
let Some(network) = self.nested_network(network_path) else {
log::error!("Could not get nested network in compute_outward_wires");
return None;
};
// Initialize all output connectors for nodes
for (node_id, _) in network.nodes.iter() {
for node_id in network.nodes.keys() {
let number_of_outputs = self.number_of_outputs(node_id, network_path);
for output_index in 0..number_of_outputs {
outward_wires.insert(OutputConnector::node(*node_id, output_index), Vec::new());
@@ -557,7 +468,7 @@ impl NodeNetworkInterface {
// A missing entry means a wire references a node output or import that does not exist, so log it and register the connector anyway rather than crashing
let push_outward_wire = |outward_wires: &mut HashMap<OutputConnector, Vec<InputConnector>>, output_connector: OutputConnector, input_connector: InputConnector| {
let outward_wires_entry = outward_wires.entry(output_connector).or_insert_with(|| {
log::error!("Output connector {output_connector:?} should be initialized in load_outward_wires");
log::error!("Output connector {output_connector:?} should be initialized in compute_outward_wires");
Vec::new()
});
outward_wires_entry.push(input_connector);
@@ -583,9 +494,7 @@ impl NodeNetworkInterface {
}
}
let Some(network_metadata) = self.network_metadata(network_path) else { return };
network_metadata.transient_metadata.outward_wires.store(outward_wires);
Some(outward_wires)
}
pub(crate) fn unload_outward_wires(&mut self, network_path: &[NodeId]) {
@@ -600,10 +509,10 @@ impl NodeNetworkInterface {
/// avoiding a full rebuild. If the cache is not loaded, this is a no-op (it will be fully
/// rebuilt on the next read via `outward_wires()`).
pub(crate) fn update_outward_wires(&mut self, network_path: &[NodeId], input_connector: &InputConnector, old_input: &NodeInput, new_input: &NodeInput) {
let Some(network_metadata) = self.network_metadata_mut(network_path) else {
let Some(transient) = self.network_transient_mut(network_path) else {
return;
};
let Some(outward_wires) = network_metadata.transient_metadata.outward_wires.get_loaded_mut() else {
let Some(outward_wires) = transient.outward_wires.get_loaded_mut() else {
return;
};
@@ -630,55 +539,22 @@ impl NodeNetworkInterface {
return None;
}
if !node_metadata.transient_metadata.layer_width.is_loaded() {
self.load_layer_width(node_id, network_path);
}
let node_metadata = self.node_metadata(node_id, network_path)?;
node_metadata.transient_metadata.layer_width.with_loaded(|layer_width| *layer_width)
node_metadata
.transient_metadata
.layer_width
.with_loaded_or(|| Some(self.compute_layer_width(node_id, network_path)), |layer_width| *layer_width)
}
pub fn load_layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) {
const GAP_WIDTH: f64 = 8.;
const FONT_SIZE: f64 = 14.;
let left_thumbnail_padding = GRID_SIZE as f64 / 2.;
let thumbnail_width = 3. * GRID_SIZE as f64;
let layer_text = self.display_name(node_id, network_path);
let text_width = text_width(&layer_text, FONT_SIZE);
let grip_padding = 4.;
let grip_width = 8.;
let lock_icon_width = if self.is_locked(node_id, network_path) { GRID_SIZE as f64 } else { 0. };
let icon_overhang_width = GRID_SIZE as f64 / 2.;
let layer_width_pixels = left_thumbnail_padding + thumbnail_width + GAP_WIDTH + text_width + grip_padding + grip_width + lock_icon_width + icon_overhang_width;
let layer_width = ((layer_width_pixels / 24.).ceil() as u32).max(8);
let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
log::error!("Could not get nested node_metadata in load_layer_width");
return;
};
// Ensure layer width is not loaded for a non layer node
if node_metadata.persistent_metadata.is_layer() {
node_metadata.transient_metadata.layer_width.store(layer_width);
} else {
log::warn!("Tried loading layer width for non layer node");
}
}
/// Unloads layer width if the node is a layer
/// Unloads layer width if the node is a layer.
pub fn try_unload_layer_width(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
let is_layer = self.is_layer(node_id, network_path);
let Some(node_metadata) = self.node_metadata_mut(node_id, network_path) else {
let Some(transient) = self.node_transient_mut(node_id, network_path) else {
return;
};
// If the node is a layer, then the width and click targets need to be recalculated
if is_layer {
node_metadata.transient_metadata.layer_width.unload();
transient.layer_width.unload();
}
}
@@ -721,14 +597,8 @@ impl NodeNetworkInterface {
}
fn load_wire(&self, input: &InputConnector, graph_wire_style: GraphWireStyle, network_path: &[NodeId]) {
let dashed = match self.previewing(network_path) {
Previewing::Yes { .. } => match input {
InputConnector::Node { .. } => false,
InputConnector::Export(export_index) => *export_index == 0,
},
Previewing::No => false,
};
let Some(wire) = self.wire_path_from_input(input, graph_wire_style, dashed, network_path) else {
// The export keeps its own solid wire while previewing, since previewing does not rewire it
let Some(wire) = self.wire_path_from_input(input, graph_wire_style, false, network_path) else {
log::error!("Could not load wire path from input");
return;
};
@@ -785,7 +655,7 @@ impl NodeNetworkInterface {
fn unload_wires_for_node(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
let number_of_outputs = self.number_of_outputs(node_id, network_path);
let Some(outward_wires) = self.outward_wires(network_path) else {
log::error!("Could not get outward wires in reorder_export");
log::error!("Could not get outward wires in unload_wires_for_node");
return;
};
let mut input_connectors = Vec::new();
@@ -847,7 +717,7 @@ impl NodeNetworkInterface {
path_string,
data_type,
thick,
dashed: false,
dashed: true,
is_list,
center_path_string,
});
@@ -870,7 +740,7 @@ impl NodeNetworkInterface {
return Some((BezPath::new(), 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);
log::error!("Could not get output port for wire start: {upstream_output:?}");
return None;
};
let vertical_end = input.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path) && input.input_index() == 0);
@@ -903,46 +773,38 @@ impl NodeNetworkInterface {
}
pub fn node_click_targets(&mut self, node_id: &NodeId, network_path: &[NodeId]) -> Option<&DocumentNodeClickTargets> {
self.try_load_node_click_targets(node_id, network_path);
self.load_node_click_targets(node_id, network_path);
let node_metadata = self.node_metadata_mut(node_id, network_path)?;
let Some(click_targets) = node_metadata.transient_metadata.click_targets.get_loaded_mut() else {
log::error!("Could not load node type metadata when getting click targets");
let transient = self.node_transient_mut(node_id, network_path)?;
let Some(click_targets) = transient.click_targets.get_loaded_mut() else {
log::error!("Could not load click targets in node_click_targets");
return None;
};
Some(click_targets)
}
pub(crate) fn try_load_node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) {
pub(crate) fn load_node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) {
let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
log::error!("Could not get nested node_metadata in node_click_targets");
log::error!("Could not get nested node_metadata in load_node_click_targets");
return;
};
if !node_metadata.transient_metadata.click_targets.is_loaded() {
self.load_node_click_targets(node_id, network_path)
};
node_metadata.transient_metadata.click_targets.ensure_loaded(|| self.compute_node_click_targets(node_id, network_path));
}
/// Loads the node click targets if needed, then reads them through &self.
pub(crate) fn with_node_click_targets<R>(&self, node_id: &NodeId, network_path: &[NodeId], read: impl FnOnce(&DocumentNodeClickTargets) -> R) -> Option<R> {
self.try_load_node_click_targets(node_id, network_path);
self.with_node_click_targets_if_loaded(node_id, network_path, read)
self.node_metadata(node_id, network_path)?
.transient_metadata
.click_targets
.with_loaded_or(|| self.compute_node_click_targets(node_id, network_path), read)
}
/// Reads the modify import/export click targets through &self, loading them first if needed.
pub(crate) fn with_modify_import_export<R>(&self, network_path: &[NodeId], read: impl FnOnce(&ModifyImportExportClickTarget) -> R) -> Option<R> {
self.try_load_modify_import_export(network_path);
self.network_metadata(network_path)?.transient_metadata.modify_import_export.with_loaded(read)
}
fn try_load_modify_import_export(&self, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in modify_import_export");
return;
};
if !network_metadata.transient_metadata.modify_import_export.is_loaded() {
self.load_modify_import_export(network_path);
}
self.network_metadata(network_path)?
.transient_metadata
.modify_import_export
.with_loaded_or(|| self.compute_modify_import_export(network_path), read)
}
/// Reads the node click targets through &self if they are already loaded.
@@ -950,289 +812,39 @@ impl NodeNetworkInterface {
let node_metadata = self.node_metadata(node_id, network_path)?;
let result = node_metadata.transient_metadata.click_targets.with_loaded(read);
if result.is_none() {
log::error!("Could not load node type metadata when getting click targets");
log::error!("Could not load click targets in with_node_click_targets_if_loaded");
}
result
}
pub fn load_node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) {
let Some(node_position) = self.position_from_downstream_node(node_id, network_path) else {
log::error!("Could not get node position in load_node_click_targets for node {node_id}");
return;
};
let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
log::error!("Could not get nested node_metadata in load_node_click_targets");
return;
};
let Some(document_node) = self.document_node(node_id, network_path) else {
log::error!("Could not get document node in load_node_click_targets");
return;
};
let node_top_left = node_position.as_dvec2() * GRID_SIZE as f64;
let mut port_click_targets = Ports::new();
let document_node_click_targets = if !node_metadata.persistent_metadata.is_layer() {
// Create input/output click targets
let mut input_row_count = 0;
for (input_index, input) in document_node.inputs.iter().enumerate() {
if input.is_exposed() {
port_click_targets.insert_node_input(input_index, input_row_count, node_top_left);
}
// Primary input row is always displayed, even if the input is not exposed
if input_index == 0 || input.is_exposed() {
input_row_count += 1;
}
}
let number_of_outputs = match &document_node.implementation {
DocumentNodeImplementation::Network(network) => network.exports.len(),
_ => 1,
};
// If the node has a hidden primary output, do not display the first output
let start_index = if self.hidden_primary_output(node_id, network_path) { 1 } else { 0 };
for output_index in start_index..number_of_outputs {
port_click_targets.insert_node_output(output_index, node_top_left);
}
let height = input_row_count.max(number_of_outputs).max(1) as u32 * GRID_SIZE;
let width = 5 * GRID_SIZE;
// Offset down by half a grid so the click target sits below the top connector strip.
let node_click_target_top_left = node_top_left + DVec2::new(0., HALF_GRID_SIZE as f64);
let node_click_target_bottom_right = node_click_target_top_left + DVec2::new(width as f64, height as f64);
let radius = 3.;
let path = rounded_rectangle_path(node_click_target_top_left, node_click_target_bottom_right, [radius; 4]);
let node_click_target = ClickTarget::new_with_path(path, 0.);
DocumentNodeClickTargets {
node_click_target,
port_click_targets,
node_type_metadata: NodeTypeClickTargets::Node,
}
} else {
// Layer inputs
port_click_targets.insert_layer_input(0, node_top_left);
if document_node.inputs.iter().filter(|input| input.is_exposed()).count() > 1 {
port_click_targets.insert_layer_input(1, node_top_left);
}
port_click_targets.insert_layer_output(node_top_left);
let layer_width_cells = self.layer_width(node_id, network_path).unwrap_or_else(|| {
log::error!("Could not get layer width in load_node_click_targets");
0
});
let width = layer_width_cells * GRID_SIZE;
let height = 2 * GRID_SIZE;
let locked = self.is_locked(node_id, network_path);
// The layer is `2 * GRID_SIZE` tall, so its vertical center sits one grid unit below `node_top_left.y`.
// Visibility/lock buttons fill a 1-grid-cell square (so half-extents of HALF_GRID_SIZE each side of center).
const LAYER_VERTICAL_CENTER: f64 = GRID_SIZE as f64;
const ICON_HALF_EXTENT: f64 = HALF_GRID_SIZE as f64;
// Update visibility button click target
let visibility_offset = node_top_left + DVec2::new(width as f64, LAYER_VERTICAL_CENTER);
let path = rounded_rectangle_path(
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + visibility_offset,
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + visibility_offset,
[3.; 4],
);
let visibility_click_target = ClickTarget::new_with_path(path, 0.);
// Update lock button click target, positioned one grid unit to the left of the visibility button (only when locked)
let lock_click_target = if locked {
let lock_offset = node_top_left + DVec2::new(width as f64 - GRID_SIZE as f64, LAYER_VERTICAL_CENTER);
let path = rounded_rectangle_path(
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + lock_offset,
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + lock_offset,
[3.; 4],
);
Some(ClickTarget::new_with_path(path, 0.))
} else {
None
};
// Update grip button click target, which is positioned to the left of the leftmost icon.
// The grip is 8px wide but spans the full layer-vertical-center band.
const GRIP_WIDTH: f64 = 8.;
let icons_width = if locked { GRID_SIZE as f64 } else { 0. };
let grip_offset_right_edge = node_top_left + DVec2::new(width as f64 - ICON_HALF_EXTENT - icons_width, LAYER_VERTICAL_CENTER);
let path = rounded_rectangle_path(
DVec2::new(-GRIP_WIDTH, -ICON_HALF_EXTENT) + grip_offset_right_edge,
DVec2::new(0., ICON_HALF_EXTENT) + grip_offset_right_edge,
[0.; 4],
);
let grip_click_target = ClickTarget::new_with_path(path, 0.);
// Update display-name text click target, used to detect double-click rename. Sized to the text bounds
// (not the surrounding `.details` area) so the rest of the layer still drills into the subgraph on double-click.
/// `.layer` margin-left (= 12), for chain layers the negative margin-left and positive padding-left cancel out, keeping content at this same offset
const LAYER_LEFT_MARGIN: f64 = HALF_GRID_SIZE as f64;
/// `.thumbnail` (70px) + its 1px side margins (= 72)
const THUMBNAIL_BLOCK_WIDTH: f64 = 3. * GRID_SIZE as f64;
/// `.details` margin-left
const DETAILS_LEFT_MARGIN: f64 = 8.;
const NAME_LEFT_OFFSET: f64 = LAYER_LEFT_MARGIN + THUMBNAIL_BLOCK_WIDTH + DETAILS_LEFT_MARGIN;
/// Distance from layer's right edge to visibility's left edge (= 12)
const VISIBILITY_INSET_FROM_LAYER_RIGHT: f64 = HALF_GRID_SIZE as f64;
const FONT_SIZE: f64 = 14.;
let display_name = self.display_name(node_id, network_path);
let name_click_target = if display_name.is_empty() {
None
} else {
let name_left = node_top_left.x + NAME_LEFT_OFFSET;
let icons_reserve = VISIBILITY_INSET_FROM_LAYER_RIGHT + icons_width + GRIP_WIDTH;
let name_right_max = node_top_left.x + width as f64 - icons_reserve;
let name_width = text_width(&display_name, FONT_SIZE);
let name_right = (name_left + name_width).min(name_right_max);
if name_right > name_left {
// The 1-grid-tall name strip is centered vertically in the 2-grid-tall layer.
let name_top = node_top_left.y + HALF_GRID_SIZE as f64;
let name_bottom = node_top_left.y + GRID_SIZE as f64 + HALF_GRID_SIZE as f64;
let path = rounded_rectangle_path(DVec2::new(name_left, name_top), DVec2::new(name_right, name_bottom), [3.; 4]);
Some(ClickTarget::new_with_path(path, 0.))
} else {
None
}
};
// Create layer click target, which is contains the layer and the chain background
let chain_width_grid_spaces = self.chain_width(node_id, network_path);
let node_bottom_right = node_top_left + DVec2::new(width as f64, height as f64);
let chain_top_left = node_top_left - DVec2::new((chain_width_grid_spaces * GRID_SIZE) as f64, 0.);
const CORNER_RADIUS: f64 = 10.;
let path = rounded_rectangle_path(chain_top_left, node_bottom_right, [CORNER_RADIUS; 4]);
let node_click_target = ClickTarget::new_with_path(path, 0.);
DocumentNodeClickTargets {
node_click_target,
port_click_targets,
node_type_metadata: NodeTypeClickTargets::Layer(Box::new(LayerClickTargets {
visibility_click_target,
lock_click_target,
grip_click_target,
name_click_target,
})),
}
};
let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
log::error!("Could not get nested node_metadata in load_node_click_targets");
return;
};
node_metadata.transient_metadata.click_targets.store(document_node_click_targets);
}
pub fn node_bounding_box(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
self.try_load_node_click_targets(node_id, network_path);
self.try_get_node_bounding_box(node_id, network_path)
self.with_node_click_targets(node_id, network_path, |click_targets| click_targets.node_click_target.bounding_box())
.flatten()
}
/// The bounding box only if the click targets are already loaded, for a caller that is walking many
/// nodes and cannot afford to load each one it looks at.
pub fn try_get_node_bounding_box(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
self.with_node_click_targets_if_loaded(node_id, network_path, |click_targets| click_targets.node_click_target.bounding_box())
.flatten()
}
pub fn try_load_all_node_click_targets(&self, network_path: &[NodeId]) {
pub fn load_all_node_click_targets(&self, network_path: &[NodeId]) {
let Some(network) = self.nested_network(network_path) else {
log::error!("Could not get network in load_all_node_click_targets");
return;
};
for node_id in network.nodes.keys().cloned().collect::<Vec<_>>() {
self.try_load_node_click_targets(&node_id, network_path);
}
}
/// Get the top left position in node graph coordinates for a node by recursively iterating downstream through cached positions, which means the iteration can be broken once a known position is reached.
pub fn position_from_downstream_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<IVec2> {
let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
log::error!("Could not get nested node_metadata in position_from_downstream_node");
return None;
};
match &node_metadata.persistent_metadata.node_type_metadata {
NodeTypePersistentMetadata::Layer(layer_metadata) => {
match layer_metadata.position {
LayerPosition::Absolute(position) => Some(position),
LayerPosition::Stack(y_offset) => {
let Some(downstream_node_connectors) = self
.with_outward_wires(network_path, |outward_wires| outward_wires.get(&OutputConnector::primary_output(*node_id)).cloned())
.flatten()
else {
log::error!("Could not get downstream node in position_from_downstream_node");
return None;
};
let downstream_connector = downstream_node_connectors
.iter()
.find_map(|input_connector| input_connector.node_id().map(|node_id| (node_id, input_connector.input_index())));
let Some((downstream_node_id, _)) = downstream_connector else {
log::error!("Could not get downstream node input connector for node {node_id}");
return None;
};
// Get the height of the node to ensure nodes do not overlap
let Some(downstream_node_height) = self.height_from_click_target(&downstream_node_id, network_path) else {
log::error!("Could not get click target height in position_from_downstream_node");
return None;
};
self.position(&downstream_node_id, network_path)
.map(|position| position + IVec2::new(0, 1 + downstream_node_height as i32 + y_offset as i32))
}
}
}
NodeTypePersistentMetadata::Node(node_metadata) => {
match node_metadata.position {
NodePosition::Absolute(position) => Some(position),
NodePosition::Chain => {
// Iterate through primary flow to find the first Layer
let mut current_node_id = *node_id;
let mut node_distance_from_layer = 1;
loop {
// TODO: Use root node to restore if previewing
let Some(downstream_node_connectors) = self
.with_outward_wires(network_path, |outward_wires| outward_wires.get(&OutputConnector::primary_output(current_node_id)).cloned())
.flatten()
else {
log::error!("Could not get downstream node for node {node_id} with Position::Chain");
return None;
};
let Some(downstream_node_id) = downstream_node_connectors.iter().find_map(|input_connector| {
if let InputConnector::Node { node_id, input_index } = input_connector {
let downstream_input_index = if self.is_layer(node_id, network_path) { 1 } else { 0 };
if *input_index == downstream_input_index { Some(node_id) } else { None }
} else {
None
}
}) else {
log::error!("Could not get downstream node input connector with input index 1 for node with Position::Chain");
return None;
};
let Some(downstream_node_metadata) = self.network_metadata(network_path)?.persistent_metadata.node_metadata.get(downstream_node_id) else {
log::error!("Downstream node metadata not found in node_metadata for node with Position::Chain");
return None;
};
if downstream_node_metadata.persistent_metadata.is_layer() {
// Get the position of the layer
let layer_position = self.position(downstream_node_id, network_path)?;
return Some(layer_position + IVec2::new(-node_distance_from_layer * NODE_CHAIN_WIDTH, 0));
}
node_distance_from_layer += 1;
current_node_id = *downstream_node_id;
}
}
}
}
self.load_node_click_targets(&node_id, network_path);
}
}
pub fn unload_node_click_targets(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
let Some(node_metadata) = self.node_metadata_mut(node_id, network_path) else {
log::error!("Could not get nested node_metadata in unload_node_click_target");
let Some(transient) = self.node_transient_mut(node_id, network_path) else {
log::error!("Could not get nested node_metadata in unload_node_click_targets");
return;
};
node_metadata.transient_metadata.click_targets.unload();
transient.click_targets.unload();
self.unload_wires_for_node(node_id, network_path);
}
@@ -126,6 +126,52 @@ async fn cyclic_connection_is_rejected_without_side_effects() {
assert_invariants(&editor, "after rejecting a cyclic connection");
}
/// The check answers for the network with the proposed input substituted, so it has to see a loop that
/// closes through intermediate nodes rather than only one that connects two neighbors.
#[tokio::test]
async fn a_cycle_closing_through_a_chain_is_rejected() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let a = editor.create_node_by_name(rectangle_definition()).await;
let b = editor.create_node_by_name(rectangle_definition()).await;
let c = editor.create_node_by_name(rectangle_definition()).await;
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.set_input(&InputConnector::node_at_index(a, 1), NodeInput::node(b, 0), &[]);
network_interface.set_input(&InputConnector::node_at_index(b, 1), NodeInput::node(c, 0), &[]);
// `a` already reaches `c` through `b`, so feeding `a` back into `c` closes a three-node loop
let input_before = network_interface.input_from_connector(&InputConnector::node_at_index(c, 1), &[]).cloned();
network_interface.set_input(&InputConnector::node_at_index(c, 1), NodeInput::node(a, 0), &[]);
let input_after = network_interface.input_from_connector(&InputConnector::node_at_index(c, 1), &[]).cloned();
assert_eq!(input_before, input_after, "A cycle closing through an intermediate node should be rejected");
assert_invariants(&editor, "after rejecting a chained cyclic connection");
}
/// An export is not something a node takes as input, so connecting one cannot close a loop and must
/// not be refused.
#[tokio::test]
async fn connecting_an_export_is_never_cyclic() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let node = editor.create_node_by_name(rectangle_definition()).await;
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.set_input(&InputConnector::Export(0), NodeInput::node(node, 0), &[]);
assert_eq!(
network_interface.input_from_connector(&InputConnector::Export(0), &[]).cloned(),
Some(NodeInput::node(node, 0)),
"Connecting a node to the export should be accepted"
);
assert_invariants(&editor, "after connecting the export");
}
#[tokio::test]
async fn toggling_preview_on_a_disconnected_export() {
let mut editor = EditorTestUtils::create();
@@ -141,6 +141,8 @@ impl From<DocumentNodePersistentMetadataStringReference> for DocumentNodePersist
metadata.persistent_metadata.reference = old.reference;
}
DocumentNodePersistentMetadata {
// Predates stored identities, so this node falls back to a hash of its location
storage_id: None,
display_name: old.display_name,
input_metadata: old.input_metadata,
output_names: old.output_names,
@@ -0,0 +1,927 @@
use super::storage_metadata::position_from_runtime;
use super::{DocumentNodeMetadata, DocumentNodePersistentMetadata, LayerPosition, NodePosition, NodeTypePersistentMetadata};
use super::{InputMetadata, InputPersistentMetadata};
use document_graph_storage::attr::network as network_attr;
use document_graph_storage::attr::node as node_attr;
use document_graph_storage::from_runtime::{ConversionError, DeclarationBytes};
use document_graph_storage::{AttributeDelta, Attributes, Implementation, NodeMetadataSource, PathResolver, Position, Registry, RegistryDelta, ScopedConversion, TimeStamp};
use document_graph_storage::{convert_input_attributes, convert_resource_entry, encode_input_ui_attributes, encode_node_ui_attributes, node_value_resource_refs, value_resource_ref};
use graph_craft::application_io::resource::{ResourceId, ResourceRegistry};
use graph_craft::document::NodeId;
use graph_craft::runtime_delta::RuntimeDelta;
use std::collections::{HashMap, HashSet};
/// A [`RuntimeDelta`] extended with the editor-only change kinds, which carry the `ui::*` metadata
/// the compiler has no use for. The compiler consumes only the `Graph` variant.
#[derive(Debug, Clone, PartialEq)]
pub enum EditorDelta {
Graph(RuntimeDelta),
/// Every `ui::*` attribute of a node that has just been added, including everything nested under
/// it, so one delta covers a group and its contents.
///
/// Asserting the whole set is sound here precisely because the node is new: every field was just
/// written, so there is no concurrent peer holding state for it to clobber. An edit to an existing
/// node must use [`EditorDelta::NodeMetadata`] instead.
NodeMetadataSnapshot {
network_path: Vec<NodeId>,
node_id: NodeId,
metadata: Box<DocumentNodePersistentMetadata>,
},
/// One field of an existing node's metadata.
NodeMetadata {
network_path: Vec<NodeId>,
node_id: NodeId,
change: NodeMetadataChange,
},
/// A node's whole input metadata array, paired with the `SetInputs` that changed the slots it
/// indexes. Whole-array for the same reason: an insert shifts every later entry.
NodeInputMetadata {
network_path: Vec<NodeId>,
node_id: NodeId,
input_metadata: Vec<InputMetadata>,
},
/// One field of an existing network's metadata.
NetworkMetadata {
network_path: Vec<NodeId>,
change: NetworkMetadataChange,
},
}
/// One field of a node's persistent metadata, named the way the store writes it so each write has
/// exactly one delta. Every variant carries the post-change value, never a difference.
#[derive(Debug, Clone, PartialEq)]
pub enum NodeMetadataChange {
/// Whether the node is displayed as a layer and where it sits, which are one choice: a layer and a
/// node do not have the same kinds of position. Encodes to `ui::position` and `ui::is_layer`, which
/// merge independently, so a concurrent move and a concurrent layer toggle both survive.
NodeType(NodeTypePersistentMetadata),
DisplayName(String),
Locked(bool),
Pinned(bool),
/// The whole vec, since the encoding is one array-valued attribute rather than a slot each.
OutputNames(Vec<String>),
InputName {
index: usize,
name: String,
},
WidgetOverride {
index: usize,
widget_override: Option<String>,
},
}
/// One field of a network's persistent metadata. The navigation transform and width are absent
/// deliberately: they are per-peer view state, persisted to `session.json` rather than the registry.
#[derive(Debug, Clone, PartialEq)]
pub enum NetworkMetadataChange {
/// The definition the network was instantiated from, dropped once it is edited away from it.
Reference(Option<String>),
/// The whole order, since the encoding is one array-valued attribute rather than a slot each.
PinnedOrder(Vec<NodeId>),
}
pub struct ConstructedOps {
pub ops: Vec<RegistryDelta>,
pub declarations: BatchDeclarations,
}
/// The proto-node declarations a batch extracted: the bytes for the caller's byte store, and the same
/// declarations decoded for its declaration cache, which a cursor rebuild reads instead of the bytes.
#[derive(Default)]
pub struct BatchDeclarations {
pub bytes: DeclarationBytes,
pub decoded: document_graph_storage::Declarations,
}
/// Constructs the storage ops for one gesture's deltas, in delta order. Removal closures and
/// resource liveness are computed against the whole batch, since several removals in one gesture
/// can jointly orphan a resource that each alone would not. Op timestamps are placeholders,
/// re-stamped by the staging clock.
///
/// `metadata` addresses each delta's node by the identity the interface holds for it, so the ops
/// land on the same nodes a whole-document conversion of that interface would produce.
pub fn construct_batch(
deltas: &[EditorDelta],
working: &Registry,
resources: &ResourceRegistry,
metadata: &dyn NodeMetadataSource,
peer: document_graph_storage::PeerId,
) -> Result<ConstructedOps, ConversionError> {
let identities = IdentitiesOnly(metadata);
let context = ConversionContext {
resources,
identities: &identities,
resolver: PathResolver::new(Some(&identities), peer),
peer,
};
let mut batch = BatchRegistry::new(working);
let mut ops = Vec::new();
let mut declarations = BatchDeclarations::default();
let mut batch_removed_nodes = Vec::new();
// In delta order, so each delta reads what the ones before it did
for delta in deltas {
delta.construct(&context, &mut batch, &mut batch_removed_nodes, &mut ops, &mut declarations)?;
}
batch_removed_nodes.sort_by_key(|(id, _)| *id);
batch_removed_nodes.dedup_by_key(|(id, _)| *id);
construct_resource_removals(&batch_removed_nodes, &batch, &mut ops);
Ok(ConstructedOps { ops, declarations })
}
/// What every delta in a batch converts against, fixed for the whole batch.
struct ConversionContext<'a> {
resources: &'a ResourceRegistry,
identities: &'a dyn NodeMetadataSource,
resolver: PathResolver<'a>,
peer: document_graph_storage::PeerId,
}
impl EditorDelta {
fn construct(
&self,
context: &ConversionContext,
batch: &mut BatchRegistry,
batch_removed_nodes: &mut Vec<(document_graph_storage::NodeId, document_graph_storage::Node)>,
ops: &mut Vec<RegistryDelta>,
declarations: &mut BatchDeclarations,
) -> Result<(), ConversionError> {
match self {
EditorDelta::Graph(RuntimeDelta::AddNode { network_path, node_id, node }) => {
construct_structural_additions(network_path, *node_id, node, batch, context, ops, declarations)?;
}
EditorDelta::Graph(RuntimeDelta::ReplaceNode { network_path, node_id, node }) => {
// Only what the previous implementation owned goes; the node stays so the addition below
// updates it in place and its `ui::*` attributes survive the swap.
construct_removals_below(context.resolver.node_id(network_path, *node_id), batch, batch_removed_nodes, ops);
construct_structural_additions(network_path, *node_id, node, batch, context, ops, declarations)?;
}
EditorDelta::Graph(RuntimeDelta::RemoveNode { network_path, node_id }) => {
construct_removals(context.resolver.node_id(network_path, *node_id), batch, batch_removed_nodes, ops);
}
EditorDelta::Graph(RuntimeDelta::SetVisibility { network_path, node_id, visible }) => {
ops.push(RegistryDelta::ChangeNodeAttribute {
id: context.resolver.node_id(network_path, *node_id),
delta: AttributeDelta {
key: node_attr::VISIBLE.to_string(),
value: (!visible).then_some(serde_json::Value::Bool(false)),
},
});
}
EditorDelta::Graph(RuntimeDelta::SetInput {
network_path,
node_id,
input_index,
input,
}) => {
let new_input = context.resolver.convert_input_at(input, network_path)?;
construct_referenced_resource(Some(context.resolver.node_id(network_path, *node_id)), &new_input, context, batch, ops)?;
ops.push(RegistryDelta::ChangeNodeInput {
id: context.resolver.node_id(network_path, *node_id),
index: (*input_index).try_into().map_err(|_| ConversionError::IndexOverflow(*input_index))?,
new_input,
});
}
EditorDelta::Graph(RuntimeDelta::SetExport { network_path, export_index, input }) => {
let export = input.as_ref().map(|input| context.resolver.convert_input_at(input, network_path)).transpose()?;
if let Some(export) = export.as_ref() {
construct_referenced_resource(None, export, context, batch, ops)?;
}
ops.push(RegistryDelta::SetNetworkExport {
id: context.resolver.network_id(network_path),
index: (*export_index).try_into().map_err(|_| ConversionError::IndexOverflow(*export_index))?,
export,
});
}
EditorDelta::Graph(RuntimeDelta::SetCallArgument { network_path, node_id, call_argument }) => {
ops.push(RegistryDelta::ChangeNodeAttribute {
id: context.resolver.node_id(network_path, *node_id),
delta: document_graph_storage::from_runtime::encode_call_argument(call_argument)?,
});
}
EditorDelta::Graph(RuntimeDelta::SetContextFeatures {
network_path,
node_id,
context_features,
}) => {
ops.push(RegistryDelta::ChangeNodeAttribute {
id: context.resolver.node_id(network_path, *node_id),
delta: document_graph_storage::from_runtime::encode_context_features(context_features)?,
});
}
EditorDelta::NodeMetadataSnapshot { network_path, node_id, metadata } => {
construct_metadata_snapshot(network_path, *node_id, metadata, batch, &context.resolver, ops)?;
}
EditorDelta::Graph(RuntimeDelta::SetInputs { network_path, node_id, inputs }) => {
// The slots' `ui::*` attributes arrive with the paired input metadata delta
let inputs = inputs
.iter()
.map(|input| {
Ok(document_graph_storage::InputSlot {
input: context.resolver.convert_input_at(input, network_path)?,
timestamp: TimeStamp::ORIGIN,
attributes: convert_input_attributes(input)?,
})
})
.collect::<Result<Vec<_>, ConversionError>>()?;
for slot in &inputs {
construct_referenced_resource(Some(context.resolver.node_id(network_path, *node_id)), &slot.input, context, batch, ops)?;
}
ops.push(RegistryDelta::SetNodeInputs {
id: context.resolver.node_id(network_path, *node_id),
inputs,
});
}
EditorDelta::NodeMetadata { network_path, node_id, change } => {
ops.extend(node_metadata_ops(context.resolver.node_id(network_path, *node_id), change)?);
}
EditorDelta::NodeInputMetadata {
network_path,
node_id,
input_metadata,
} => {
let global_id = context.resolver.node_id(network_path, *node_id);
let source = InputMetadataSource(input_metadata);
let working_node = batch.node(global_id);
for input_index in 0..input_metadata.len() {
let mut encoded = Attributes::new();
encode_input_ui_attributes(&mut encoded, &source, network_path, *node_id, input_index, TimeStamp::ORIGIN)?;
let current = working_node.and_then(|node| node.inputs().get(input_index)).map(|slot| &slot.attributes);
for delta in ui_attribute_writes(current, &encoded) {
ops.push(RegistryDelta::ChangeNodeInputAttribute {
id: global_id,
index: input_index.try_into().map_err(|_| ConversionError::IndexOverflow(input_index))?,
delta,
});
}
}
}
EditorDelta::NetworkMetadata { network_path, change } => {
let delta = match change {
NetworkMetadataChange::Reference(reference) => AttributeDelta {
key: node_attr::ui::REFERENCE.to_string(),
value: reference.clone().map(serde_json::Value::String),
},
NetworkMetadataChange::PinnedOrder(order) => {
let stored: Vec<_> = order.iter().map(|node_id| context.resolver.node_id(network_path, *node_id)).collect();
AttributeDelta {
key: network_attr::PINNED_ORDER.to_string(),
value: (!stored.is_empty()).then(|| serialize_attribute(network_attr::PINNED_ORDER, &stored)).transpose()?,
}
}
};
ops.push(RegistryDelta::ChangeNetworkAttribute {
id: context.resolver.network_id(network_path),
delta,
});
}
}
Ok(())
}
}
fn serialize_attribute<T: serde::Serialize>(key: &str, value: &T) -> Result<serde_json::Value, ConversionError> {
serde_json::to_value(value).map_err(|error| ConversionError::SerializationError(format!("{key}: {error:?}")))
}
/// The attribute writes one metadata field makes, as the whole-document encoder would write them.
///
/// A field set back to its unset value clears the attribute, since absence is how that encoder spells
/// unset. Clearing rather than writing a sentinel keeps the two paths producing the same registry.
fn node_metadata_ops(global_id: document_graph_storage::NodeId, change: &NodeMetadataChange) -> Result<Vec<RegistryDelta>, ConversionError> {
let node_attribute = |key: &str, value: Option<serde_json::Value>| RegistryDelta::ChangeNodeAttribute {
id: global_id,
delta: AttributeDelta { key: key.to_string(), value },
};
let input_attribute = |key: &str, index: usize, value: Option<serde_json::Value>| {
Ok::<_, ConversionError>(RegistryDelta::ChangeNodeInputAttribute {
id: global_id,
index: index.try_into().map_err(|_| ConversionError::IndexOverflow(index))?,
delta: AttributeDelta { key: key.to_string(), value },
})
};
// The empty string is the runtime's own sentinel for an unset name
let flag = |value: bool| value.then_some(serde_json::Value::Bool(true));
let non_empty = |value: &str| (!value.is_empty()).then(|| serde_json::Value::String(value.to_string()));
Ok(match change {
NodeMetadataChange::NodeType(node_type) => {
let position = position_from_runtime(node_type);
vec![
node_attribute(node_attr::ui::POSITION, Some(serialize_attribute(node_attr::ui::POSITION, &position)?)),
node_attribute(node_attr::ui::IS_LAYER, flag(matches!(node_type, NodeTypePersistentMetadata::Layer(_)))),
]
}
NodeMetadataChange::DisplayName(display_name) => vec![node_attribute(node_attr::ui::DISPLAY_NAME, non_empty(display_name))],
NodeMetadataChange::Locked(locked) => vec![node_attribute(node_attr::ui::LOCKED, flag(*locked))],
NodeMetadataChange::Pinned(pinned) => vec![node_attribute(node_attr::ui::PINNED, flag(*pinned))],
NodeMetadataChange::OutputNames(output_names) => {
let value = (!output_names.is_empty()).then(|| serialize_attribute(node_attr::ui::OUTPUT_NAMES, output_names)).transpose()?;
vec![node_attribute(node_attr::ui::OUTPUT_NAMES, value)]
}
NodeMetadataChange::InputName { index, name } => vec![input_attribute(node_attr::input::ui::NAME, *index, non_empty(name))?],
NodeMetadataChange::WidgetOverride { index, widget_override } => {
let value = widget_override.as_deref().and_then(non_empty);
vec![input_attribute(node_attr::input::ui::WIDGET_OVERRIDE, *index, value)?]
}
})
}
/// Converts through the same encoders as a whole-document conversion, with identities only as the
/// source: ui attributes arrive via the gesture's paired `NodeMetadata` delta.
fn construct_structural_additions(
network_path: &[NodeId],
node_id: NodeId,
node: &graph_craft::document::DocumentNode,
batch: &mut BatchRegistry,
context: &ConversionContext,
ops: &mut Vec<RegistryDelta>,
declarations: &mut BatchDeclarations,
) -> Result<(), ConversionError> {
let mut scoped = ScopedConversion::new(context.identities, context.peer);
let mut scratch = Registry::default();
scoped.convert_node_at(&mut scratch, network_path, node_id, node, true)?;
let (bytes, decoded) = scoped.finish();
declarations.bytes.extend(bytes);
declarations.decoded.extend(decoded);
let mut networks: Vec<_> = scratch.networks.iter().map(|(id, network)| (*id, network.clone())).collect();
networks.sort_by_key(|(id, _)| *id);
for (id, network) in networks {
ops.push(RegistryDelta::AddNetwork { id, network: network.clone() });
batch.record_network(id, network);
}
// Recorded as well as emitted, so a later delta in this batch can read these nodes back
let mut nodes: Vec<_> = scratch.node_instances.iter().collect();
nodes.sort_by_key(|(id, _)| **id);
let added: Vec<_> = nodes.into_iter().map(|(id, node)| (*id, node.clone())).collect();
for (id, node) in added {
// A node the registry already holds is updated rather than rebuilt: rebuilding would clear the
// `ui::*` attributes it carries, and restating those would clobber whatever a concurrent peer
// wrote to its name, lock or pin.
match batch.node(id).is_some() {
true => {
ops.push(RegistryDelta::SetNodeImplementation {
id,
implementation: node.implementation().clone(),
});
ops.push(RegistryDelta::SetNodeInputs { id, inputs: node.inputs().to_vec() });
}
false => ops.push(RegistryDelta::AddNode { id, node: node.clone() }),
}
batch.record_addition(id, node);
}
let mut new_resources: Vec<_> = scratch
.resources
.iter()
.filter(|(id, _)| !batch.working.resources.contains_key(id))
.map(|(id, entry)| (*id, entry.clone()))
.collect();
new_resources.sort_by_key(|(id, _)| *id);
for (id, entry) in new_resources {
if batch.record_resource(id, entry.clone()) {
ops.push(RegistryDelta::AddResource { id, entry });
}
}
let mut tagged: Vec<ResourceId> = scratch.node_instances.values().flat_map(node_value_resource_refs).collect();
tagged.sort();
tagged.dedup();
for id in tagged {
if batch.resource(id).is_none()
&& !scratch.resources.contains_key(&id)
&& let Some(entry) = convert_resource_entry(context.resources, id, context.peer)?
{
batch.record_resource(id, entry.clone());
ops.push(RegistryDelta::AddResource { id, entry });
}
}
Ok(())
}
/// Stages the resource a value input references, so setting an input to an asset persists the entry
/// alongside the reference rather than leaving the registry pointing at something it does not hold.
fn construct_referenced_resource(
owner: Option<document_graph_storage::NodeId>,
input: &document_graph_storage::NodeInput,
context: &ConversionContext,
batch: &mut BatchRegistry,
ops: &mut Vec<RegistryDelta>,
) -> Result<(), ConversionError> {
let Some(id) = value_resource_ref(input) else { return Ok(()) };
if let Some(owner) = owner {
batch.record_input_resource(owner, id);
}
if batch.resource(id).is_some() {
return Ok(());
}
let Some(entry) = convert_resource_entry(context.resources, id, context.peer)? else {
return Ok(());
};
batch.record_resource(id, entry.clone());
ops.push(RegistryDelta::AddResource { id, entry });
Ok(())
}
fn construct_metadata_snapshot(
network_path: &[NodeId],
node_id: NodeId,
metadata: &DocumentNodePersistentMetadata,
batch: &BatchRegistry,
resolver: &PathResolver,
ops: &mut Vec<RegistryDelta>,
) -> Result<(), ConversionError> {
let source = MetadataCopySource {
anchor_path: network_path,
anchor_id: node_id,
metadata,
};
let mut pending = vec![(network_path.to_vec(), node_id, metadata)];
while let Some((path, id, node_metadata)) = pending.pop() {
let global_id = resolver.node_id(&path, id);
let working_node = batch.node(global_id);
let mut encoded = Attributes::new();
encode_node_ui_attributes(&mut encoded, &source, &path, id, TimeStamp::ORIGIN)?;
for delta in ui_attribute_writes(working_node.map(|node| node.attributes()), &encoded) {
ops.push(RegistryDelta::ChangeNodeAttribute { id: global_id, delta });
}
for input_index in 0..node_metadata.input_metadata.len() {
let mut encoded = Attributes::new();
encode_input_ui_attributes(&mut encoded, &source, &path, id, input_index, TimeStamp::ORIGIN)?;
let current = working_node.and_then(|node| node.inputs().get(input_index)).map(|slot| &slot.attributes);
for delta in ui_attribute_writes(current, &encoded) {
ops.push(RegistryDelta::ChangeNodeInputAttribute {
id: global_id,
index: input_index.try_into().map_err(|_| ConversionError::IndexOverflow(input_index))?,
delta,
});
}
}
if let Some(network_metadata) = &node_metadata.network_metadata {
let mut nested_path = path.clone();
nested_path.push(id);
let network_id = resolver.network_id(&nested_path);
let target = network_metadata.persistent_metadata.reference.clone().map(serde_json::Value::String);
// Read through the batch rather than the pre-batch registry: a `ReplaceNode` earlier in this
// batch rebuilds the network without a reference, so comparing against the old state would
// suppress the write and leave the rebuilt network missing it.
let current = batch
.network(network_id)
.and_then(|network| network.attributes.get(node_attr::ui::REFERENCE))
.map(|value| value.value.clone());
if current != target {
ops.push(RegistryDelta::ChangeNetworkAttribute {
id: network_id,
delta: AttributeDelta {
key: node_attr::ui::REFERENCE.to_string(),
value: target,
},
});
}
// Restated alongside the reference, since a rebuild clears the network's attributes and the
// order would otherwise be lost for every nested network the snapshot covers.
let pinned_order: Vec<_> = network_metadata
.persistent_metadata
.pinned_node_order
.iter()
.map(|pinned| resolver.node_id(&nested_path, *pinned))
.collect();
ops.push(RegistryDelta::ChangeNetworkAttribute {
id: network_id,
delta: AttributeDelta {
key: network_attr::PINNED_ORDER.to_string(),
value: (!pinned_order.is_empty()).then(|| serialize_attribute(network_attr::PINNED_ORDER, &pinned_order)).transpose()?,
},
});
for (child_id, child) in &network_metadata.persistent_metadata.node_metadata {
pending.push((nested_path.clone(), *child_id, &child.persistent_metadata));
}
}
}
Ok(())
}
/// Every `ui::` attribute of `encoded`, plus a clear for each `ui::` key of `current` that `encoded`
/// does not carry. Values are compared only to decide what to clear, never to skip a write.
///
/// Restating a value that already matches looks redundant but is load-bearing: `current` is the
/// registry as it stood before the batch, and these writes follow an op in the same batch that
/// rebuilt what they describe. A value the pre-batch state agrees with may already have been cleared
/// by that op, so skipping it would leave the attribute missing.
fn ui_attribute_writes(current: Option<&Attributes>, encoded: &Attributes) -> Vec<AttributeDelta> {
let owned = |key: &str| key.starts_with("ui::");
let mut deltas = Vec::new();
if let Some(current) = current {
for key in current.keys() {
if owned(key) && !encoded.contains_key(key) {
deltas.push(AttributeDelta { key: key.clone(), value: None });
}
}
}
for (key, value) in encoded {
deltas.push(AttributeDelta {
key: key.clone(),
value: Some(value.value.clone()),
});
}
deltas.sort_by(|a, b| a.key.cmp(&b.key));
deltas
}
/// Emits the removal of a node and everything nested under it, recording what was removed so the
/// batch's resource liveness accounts for all of it at the end.
fn construct_removals(
node_id: document_graph_storage::NodeId,
batch: &mut BatchRegistry,
batch_removed_nodes: &mut Vec<(document_graph_storage::NodeId, document_graph_storage::Node)>,
ops: &mut Vec<RegistryDelta>,
) {
construct_removals_with(node_id, true, batch, batch_removed_nodes, ops)
}
/// Removes everything the node's implementation owns while leaving the node itself, for a swap that
/// keeps the node in place.
fn construct_removals_below(
node_id: document_graph_storage::NodeId,
batch: &mut BatchRegistry,
batch_removed_nodes: &mut Vec<(document_graph_storage::NodeId, document_graph_storage::Node)>,
ops: &mut Vec<RegistryDelta>,
) {
construct_removals_with(node_id, false, batch, batch_removed_nodes, ops)
}
fn construct_removals_with(
node_id: document_graph_storage::NodeId,
include_node: bool,
batch: &mut BatchRegistry,
batch_removed_nodes: &mut Vec<(document_graph_storage::NodeId, document_graph_storage::Node)>,
ops: &mut Vec<RegistryDelta>,
) {
let (mut removed_nodes, mut removed_networks) = removal_closure(node_id, batch);
removed_nodes.sort();
removed_networks.sort();
for id in &removed_nodes {
if !include_node && *id == node_id {
continue;
}
let Some(snapshot) = batch.node(*id).cloned() else { continue };
ops.push(RegistryDelta::RemoveNode { id: *id, snapshot: snapshot.clone() });
// Kept by value: a replacement later in this batch re-adds the same ID with different content, so
// looking the node up again at the end would read what replaced it rather than what was removed.
batch_removed_nodes.push((*id, snapshot));
batch.record_removal(*id);
}
for id in &removed_networks {
let Some(snapshot) = batch.network(*id) else { continue };
ops.push(RegistryDelta::RemoveNetwork { id: *id, snapshot: snapshot.clone() });
}
}
/// Emits removals for resources referenced only by the batch's removed nodes, checked after every
/// removal is known.
fn construct_resource_removals(batch_removed_nodes: &[(document_graph_storage::NodeId, document_graph_storage::Node)], batch: &BatchRegistry, ops: &mut Vec<RegistryDelta>) {
// A node this batch wrote an input on and then removed orphans whatever that write referenced, which
// the stored node does not mention.
let mut candidates: Vec<ResourceId> = batch_removed_nodes
.iter()
.flat_map(|(id, _)| batch.input_resources.get(id).into_iter().flatten().copied())
.chain(batch_removed_nodes.iter().map(|(_, node)| node).flat_map(|node| {
let declaration = match node.implementation() {
Implementation::ProtoNode(declaration) => Some(*declaration),
Implementation::Network(_) => None,
};
declaration.into_iter().chain(node_value_resource_refs(node))
}))
.collect();
candidates.sort();
candidates.dedup();
if candidates.is_empty() {
return;
}
// Gathered in one pass so each candidate is a lookup rather than another scan of the whole registry
let mut still_referenced: HashSet<ResourceId> = HashSet::new();
for (id, node) in batch.live_nodes() {
if let Implementation::ProtoNode(declaration) = node.implementation() {
still_referenced.insert(*declaration);
}
still_referenced.extend(node_value_resource_refs(node));
// What this batch wrote onto a node that survives it is a live reference, even though the stored
// node still carries the input it had before.
still_referenced.extend(batch.input_resources.get(&id).into_iter().flatten().copied());
}
// The batch's own networks count too: one added earlier in it can export a resource the removal would
// otherwise see as orphaned.
for network in batch.working.networks.values().chain(batch.added_networks.values()) {
still_referenced.extend(network.exports.iter().filter_map(|slot| slot.target.as_ref().and_then(value_resource_ref)));
}
for candidate in candidates {
if !still_referenced.contains(&candidate)
&& let Some(entry) = batch.resource(candidate)
{
ops.push(RegistryDelta::RemoveResource {
id: candidate,
snapshot: entry.clone(),
});
}
}
}
/// The registry a delta is constructed against: what the batch started from, plus the nodes deltas
/// earlier in the same batch have added, since a delta can read back or remove a node an earlier one
/// added.
///
/// Nodes are also indexed by network, so a removal closure walks only the subtree it removes instead
/// of rescanning every node for each nested network it meets.
struct BatchRegistry<'a> {
working: &'a Registry,
added: HashMap<document_graph_storage::NodeId, document_graph_storage::Node>,
added_networks: HashMap<document_graph_storage::NetworkId, document_graph_storage::Network>,
added_resources: HashMap<ResourceId, document_graph_storage::ResourceEntry>,
by_network: HashMap<document_graph_storage::NetworkId, Vec<document_graph_storage::NodeId>>,
/// Nodes the batch has removed and not since re-added, so a lookup answers with the state the ops so
/// far have produced rather than the state the batch started from.
removed: HashSet<document_graph_storage::NodeId>,
/// Resources the batch's own input writes reference, keyed by the node written to. The stored node
/// still holds its pre-batch inputs, so liveness would otherwise miss both the reference these writes
/// create and the orphan they leave when that node is later removed.
input_resources: HashMap<document_graph_storage::NodeId, HashSet<ResourceId>>,
}
impl<'a> BatchRegistry<'a> {
fn new(working: &'a Registry) -> Self {
let mut by_network: HashMap<_, Vec<_>> = HashMap::new();
for (id, node) in &working.node_instances {
by_network.entry(node.network()).or_default().push(*id);
}
Self {
working,
added: HashMap::new(),
added_networks: HashMap::new(),
added_resources: HashMap::new(),
by_network,
removed: HashSet::new(),
input_resources: HashMap::new(),
}
}
/// Records that an input write on `owner` references `resource`.
fn record_input_resource(&mut self, owner: document_graph_storage::NodeId, resource: ResourceId) {
self.input_resources.entry(owner).or_default().insert(resource);
}
/// Records a node an earlier delta in this batch added, so a later one can read it back.
fn record_addition(&mut self, id: document_graph_storage::NodeId, node: document_graph_storage::Node) {
self.by_network.entry(node.network()).or_default().push(id);
self.removed.remove(&id);
self.added.insert(id, node);
}
/// Records a node this batch removed, so a later delta reading it back finds it gone.
fn record_removal(&mut self, id: document_graph_storage::NodeId) {
self.added.remove(&id);
self.removed.insert(id);
}
/// Records a network an earlier delta in this batch added, so removing the node that owns it finds
/// the network to remove alongside it.
fn record_network(&mut self, id: document_graph_storage::NetworkId, network: document_graph_storage::Network) {
self.added_networks.insert(id, network);
}
/// Records a resource this batch added. Returns whether it is new to the batch, so the caller emits
/// one addition for a resource several nodes reference.
fn record_resource(&mut self, id: ResourceId, entry: document_graph_storage::ResourceEntry) -> bool {
self.added_resources.insert(id, entry).is_none()
}
fn node(&self, id: document_graph_storage::NodeId) -> Option<&document_graph_storage::Node> {
if self.removed.contains(&id) {
return None;
}
self.added.get(&id).or_else(|| self.working.node_instances.get(&id))
}
/// Every node the batch leaves in place, which is what the working registry held plus what the batch
/// added, less what it removed.
fn live_nodes(&self) -> impl Iterator<Item = (document_graph_storage::NodeId, &document_graph_storage::Node)> {
self.working
.node_instances
.keys()
.chain(self.added.keys())
.copied()
.collect::<HashSet<_>>()
.into_iter()
.filter_map(|id| Some((id, self.node(id)?)))
}
fn network(&self, id: document_graph_storage::NetworkId) -> Option<&document_graph_storage::Network> {
self.added_networks.get(&id).or_else(|| self.working.networks.get(&id))
}
fn resource(&self, id: ResourceId) -> Option<&document_graph_storage::ResourceEntry> {
self.added_resources.get(&id).or_else(|| self.working.resources.get(&id))
}
fn children(&self, network_id: document_graph_storage::NetworkId) -> &[document_graph_storage::NodeId] {
self.by_network.get(&network_id).map_or(&[], Vec::as_slice)
}
}
/// The node together with everything nested under it, and the networks that nesting owns.
fn removal_closure(node_id: document_graph_storage::NodeId, batch: &BatchRegistry) -> (Vec<document_graph_storage::NodeId>, Vec<document_graph_storage::NetworkId>) {
let mut nodes = Vec::new();
let mut networks = Vec::new();
collect_removal_closure(node_id, batch, &mut nodes, &mut networks);
(nodes, networks)
}
fn collect_removal_closure(node_id: document_graph_storage::NodeId, batch: &BatchRegistry, nodes: &mut Vec<document_graph_storage::NodeId>, networks: &mut Vec<document_graph_storage::NetworkId>) {
let Some(node) = batch.node(node_id) else { return };
nodes.push(node_id);
if let &Implementation::Network(network_id) = node.implementation() {
networks.push(network_id);
for &child_id in batch.children(network_id) {
collect_removal_closure(child_id, batch, nodes, networks);
}
}
}
/// Narrows a metadata source to the node identities alone, so a scoped conversion addresses nodes the
/// way a whole-document conversion does without also re-encoding ui attributes the gesture's paired
/// `NodeMetadata` delta already carries.
struct IdentitiesOnly<'a>(&'a dyn NodeMetadataSource);
impl NodeMetadataSource for IdentitiesOnly<'_> {
fn storage_node_id(&self, network_path: &[NodeId], local_id: NodeId) -> Option<document_graph_storage::NodeId> {
self.0.storage_node_id(network_path, local_id)
}
}
/// Serves one node's input metadata for encoding a [`EditorDelta::NodeInputMetadata`] delta. Only the
/// per-input accessors answer, since the node-level ones are never reached: the delta encodes through
/// `encode_input_ui_attributes` alone.
struct InputMetadataSource<'a>(&'a [InputMetadata]);
impl InputMetadataSource<'_> {
fn persistent(&self, input_index: usize) -> Option<&InputPersistentMetadata> {
self.0.get(input_index).map(|metadata| &metadata.persistent_metadata)
}
}
impl NodeMetadataSource for InputMetadataSource<'_> {
fn input_name(&self, _network_path: &[NodeId], _local_id: NodeId, input_index: usize) -> Option<&str> {
Some(self.persistent(input_index)?.input_name.as_str())
}
fn input_description(&self, _network_path: &[NodeId], _local_id: NodeId, input_index: usize) -> Option<&str> {
Some(self.persistent(input_index)?.input_description.as_str())
}
fn widget_override(&self, _network_path: &[NodeId], _local_id: NodeId, input_index: usize) -> Option<&str> {
self.persistent(input_index)?.widget_override.as_deref()
}
fn input_data(&self, _network_path: &[NodeId], _local_id: NodeId, input_index: usize) -> HashMap<String, serde_json::Value> {
self.persistent(input_index).map(|metadata| metadata.input_data.clone()).unwrap_or_default()
}
}
/// Serves a metadata copy as the [`document_graph_storage::NodeMetadataSource`] for its own
/// encoding, resolving requested paths relative to the anchor node the copy was taken from.
struct MetadataCopySource<'a> {
anchor_path: &'a [NodeId],
anchor_id: NodeId,
metadata: &'a DocumentNodePersistentMetadata,
}
impl MetadataCopySource<'_> {
fn metadata_for(&self, metadata_path: &[NodeId], node_id: NodeId) -> Option<&DocumentNodePersistentMetadata> {
let relative = metadata_path.strip_prefix(self.anchor_path)?;
let (mut current, rest) = match relative.split_first() {
None => return (node_id == self.anchor_id).then_some(self.metadata),
Some((first, rest)) if *first == self.anchor_id => (self.metadata, rest),
Some(_) => return None,
};
for step in rest {
current = child_metadata(current, *step)?;
}
child_metadata(current, node_id)
}
}
fn child_metadata(metadata: &DocumentNodePersistentMetadata, child_id: NodeId) -> Option<&DocumentNodePersistentMetadata> {
metadata
.network_metadata
.as_ref()
.and_then(|network| network.persistent_metadata.node_metadata.get(&child_id))
.map(|child: &DocumentNodeMetadata| &child.persistent_metadata)
}
impl document_graph_storage::NodeMetadataSource for MetadataCopySource<'_> {
fn position(&self, metadata_path: &[NodeId], node_id: NodeId) -> Option<Position> {
match &self.metadata_for(metadata_path, node_id)?.node_type_metadata {
NodeTypePersistentMetadata::Layer(layer) => Some(match layer.position {
LayerPosition::Absolute(offset) => Position::Absolute([offset.x, offset.y]),
LayerPosition::Stack(offset) => Position::Stack(offset),
}),
NodeTypePersistentMetadata::Node(node) => Some(match *node.position() {
NodePosition::Absolute(offset) => Position::Absolute([offset.x, offset.y]),
NodePosition::Chain => Position::Chain,
}),
}
}
fn is_layer(&self, metadata_path: &[NodeId], node_id: NodeId) -> bool {
self.metadata_for(metadata_path, node_id)
.is_some_and(|metadata| matches!(metadata.node_type_metadata, NodeTypePersistentMetadata::Layer(_)))
}
fn display_name(&self, metadata_path: &[NodeId], node_id: NodeId) -> Option<&str> {
self.metadata_for(metadata_path, node_id).map(|metadata| metadata.display_name.as_str())
}
fn locked(&self, metadata_path: &[NodeId], node_id: NodeId) -> bool {
self.metadata_for(metadata_path, node_id).is_some_and(|metadata| metadata.locked)
}
fn pinned(&self, metadata_path: &[NodeId], node_id: NodeId) -> bool {
self.metadata_for(metadata_path, node_id).is_some_and(|metadata| metadata.pinned)
}
fn output_names(&self, metadata_path: &[NodeId], node_id: NodeId) -> Vec<String> {
self.metadata_for(metadata_path, node_id).map(|metadata| metadata.output_names.clone()).unwrap_or_default()
}
fn input_name(&self, metadata_path: &[NodeId], node_id: NodeId, input_index: usize) -> Option<&str> {
self.metadata_for(metadata_path, node_id)
.and_then(|metadata| metadata.input_metadata.get(input_index))
.map(|input| input.persistent_metadata.input_name.as_str())
}
fn input_description(&self, metadata_path: &[NodeId], node_id: NodeId, input_index: usize) -> Option<&str> {
self.metadata_for(metadata_path, node_id)
.and_then(|metadata| metadata.input_metadata.get(input_index))
.map(|input| input.persistent_metadata.input_description.as_str())
}
fn widget_override(&self, metadata_path: &[NodeId], node_id: NodeId, input_index: usize) -> Option<&str> {
self.metadata_for(metadata_path, node_id)
.and_then(|metadata| metadata.input_metadata.get(input_index))
.and_then(|input| input.persistent_metadata.widget_override.as_deref())
}
fn input_data(&self, metadata_path: &[NodeId], node_id: NodeId, input_index: usize) -> std::collections::HashMap<String, serde_json::Value> {
self.metadata_for(metadata_path, node_id)
.and_then(|metadata| metadata.input_metadata.get(input_index))
.map(|input| input.persistent_metadata.input_data.clone())
.unwrap_or_default()
}
fn reference(&self, network_path: &[NodeId]) -> Option<&str> {
let (owner_path, owner_id) = network_path.split_last().map(|(last, rest)| (rest, *last))?;
self.metadata_for(owner_path, owner_id)?
.network_metadata
.as_ref()
.and_then(|network| network.persistent_metadata.reference.as_deref())
}
}
@@ -0,0 +1,614 @@
use super::DocumentNodePersistentMetadata;
use super::InputConnector;
use super::editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange, construct_batch};
use super::storage_metadata::StorageMetadataView;
use crate::test_utils::test_prelude::*;
use document_graph_storage::delta::compute_deltas;
use document_graph_storage::{PeerId, Registry, RegistryDelta, Session};
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use graph_craft::runtime_delta::RuntimeDelta;
use graphene_std::uuid::NodeId;
const PEER: PeerId = PeerId(7);
fn rectangle_definition() -> DefinitionIdentifier {
DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER)
}
fn convert(editor: &EditorTestUtils) -> Registry {
let document = editor.active_document();
Registry::convert_from_runtime(
document.network_interface.document_network(),
&StorageMetadataView::new(&document.network_interface),
&document.resources.registry,
PEER,
)
.expect("conversion should succeed")
.registry
}
fn construct(editor: &EditorTestUtils, deltas: &[EditorDelta], working: &Registry) -> Vec<RegistryDelta> {
let document = editor.active_document();
construct_batch(deltas, working, &document.resources.registry, &StorageMetadataView::new(&document.network_interface), PEER)
.expect("construction should succeed")
.ops
}
fn node_metadata(editor: &EditorTestUtils, node_id: NodeId) -> DocumentNodePersistentMetadata {
editor
.active_document()
.network_interface
.node_metadata(&node_id, &[])
.expect("node metadata should exist")
.persistent_metadata
.clone()
}
fn metadata_change(node_id: NodeId, change: NodeMetadataChange) -> EditorDelta {
EditorDelta::NodeMetadata {
network_path: Vec::new(),
node_id,
change,
}
}
fn assert_same_stored_effect(working: &Registry, constructed: Vec<RegistryDelta>, diffed: Vec<RegistryDelta>, at: &str) {
let baseline = compute_deltas(&Registry::default(), working);
let mut from_construction = Session::with_peer(PEER);
from_construction.stage_computed_ops(baseline.clone()).expect("baseline should stage");
from_construction.stage_computed_ops(constructed).expect("constructed ops should stage");
let mut from_diff = Session::with_peer(PEER);
from_diff.stage_computed_ops(baseline).expect("baseline should stage");
from_diff.stage_computed_ops(diffed).expect("diffed ops should stage");
assert!(
from_construction.registry().value_equal(from_diff.registry()),
"Constructed ops must produce the same stored state as the whole-document diff: {at}\nresidual: {:#?}",
compute_deltas(from_construction.registry(), from_diff.registry())
);
}
#[tokio::test]
async fn set_input_value_constructs_the_exact_diff_op() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let node = editor.create_node_by_name(rectangle_definition()).await;
let working = convert(&editor);
let input = NodeInput::value(TaggedValue::Number(42.), false);
editor.active_document_mut().network_interface.set_input(&InputConnector::node_at_index(node, 1), input.clone(), &[]);
let delta = EditorDelta::Graph(RuntimeDelta::SetInput {
network_path: Vec::new(),
node_id: node,
input_index: 1,
input,
});
let constructed = construct(&editor, std::slice::from_ref(&delta), &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_eq!(constructed, diffed, "A value edit should construct exactly the diff's op");
}
#[tokio::test]
async fn wiring_and_export_edits_construct_the_exact_diff_ops() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let a = editor.create_node_by_name(rectangle_definition()).await;
let b = editor.create_node_by_name(rectangle_definition()).await;
let working = convert(&editor);
let wire = NodeInput::node(b, 0);
editor.active_document_mut().network_interface.set_input(&InputConnector::node_at_index(a, 1), wire.clone(), &[]);
let delta = EditorDelta::Graph(RuntimeDelta::SetInput {
network_path: Vec::new(),
node_id: a,
input_index: 1,
input: wire,
});
let constructed = construct(&editor, std::slice::from_ref(&delta), &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_eq!(constructed, diffed, "A wiring edit should construct exactly the diff's op");
let working = convert(&editor);
let export = NodeInput::node(a, 0);
editor.active_document_mut().network_interface.set_input(&InputConnector::Export(0), export.clone(), &[]);
let delta = EditorDelta::Graph(RuntimeDelta::SetExport {
network_path: Vec::new(),
export_index: 0,
input: Some(export),
});
let constructed = construct(&editor, std::slice::from_ref(&delta), &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_eq!(constructed, diffed, "An export edit should construct exactly the diff's op");
}
#[tokio::test]
async fn adding_a_node_as_structure_plus_metadata_matches_the_diff() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let working = convert(&editor);
let template = crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type(&rectangle_definition())
.expect("rectangle definition")
.default_node_template();
let node_id = NodeId(0xDE17A);
let (document_node, metadata) = template.clone().into_parts();
editor.active_document_mut().network_interface.insert_node(node_id, template, &[]);
let deltas = [
EditorDelta::Graph(RuntimeDelta::AddNode {
network_path: Vec::new(),
node_id,
node: Box::new(document_node),
}),
EditorDelta::NodeMetadataSnapshot {
network_path: Vec::new(),
node_id,
metadata: Box::new(metadata),
},
];
let constructed = construct(&editor, &deltas, &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_same_stored_effect(&working, constructed, diffed, "node addition");
}
#[tokio::test]
async fn per_field_metadata_edits_match_the_diff() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let node = editor.create_node_by_name(rectangle_definition()).await;
let working = convert(&editor);
{
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.set_display_name(&node, "Renamed".to_string(), &[]);
network_interface.set_visibility(&node, &[], false);
network_interface.set_locked(&node, &[], true);
network_interface.set_pinned(&node, &[], true);
network_interface.shift_node(&node, glam::IVec2::new(3, 5), &[]);
}
let metadata = node_metadata(&editor, node);
let deltas = [
metadata_change(node, NodeMetadataChange::DisplayName(metadata.display_name.clone())),
metadata_change(node, NodeMetadataChange::Locked(metadata.locked)),
metadata_change(node, NodeMetadataChange::Pinned(metadata.pinned)),
metadata_change(node, NodeMetadataChange::NodeType(metadata.node_type_metadata.clone())),
EditorDelta::Graph(RuntimeDelta::SetVisibility {
network_path: Vec::new(),
node_id: node,
visible: false,
}),
// Pinning a node also appends it to the network's display order, which is network state.
EditorDelta::NetworkMetadata {
network_path: Vec::new(),
change: NetworkMetadataChange::PinnedOrder(vec![node]),
},
];
let constructed = construct(&editor, &deltas, &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_same_stored_effect(&working, constructed, diffed, "per-field metadata edits");
}
/// The encoding spells "unset" as an absent attribute, so a per-field delta that sets a field back to
/// its unset value must clear the key rather than write a sentinel.
#[tokio::test]
async fn clearing_a_metadata_field_removes_the_attribute() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let node = editor.create_node_by_name(rectangle_definition()).await;
{
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.set_display_name(&node, "Renamed".to_string(), &[]);
network_interface.set_locked(&node, &[], true);
}
let working = convert(&editor);
{
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.set_display_name(&node, String::new(), &[]);
network_interface.set_locked(&node, &[], false);
}
let metadata = node_metadata(&editor, node);
let deltas = [
metadata_change(node, NodeMetadataChange::DisplayName(metadata.display_name.clone())),
metadata_change(node, NodeMetadataChange::Locked(metadata.locked)),
];
let constructed = construct(&editor, &deltas, &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_same_stored_effect(&working, constructed, diffed, "cleared metadata fields");
}
/// The deltas the interface emits for a real edit must store what a whole-document conversion of the
/// result would. Taking them from the interface rather than writing them by hand is what catches a
/// setter that forgets to emit, or emits the wrong field.
#[tokio::test]
async fn emitted_deltas_reproduce_the_diff() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let node = editor.create_node_by_name(rectangle_definition()).await;
let working = convert(&editor);
editor.active_document_mut().network_interface.discard_deltas();
{
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.set_display_name(&node, "Renamed".to_string(), &[]);
network_interface.set_locked(&node, &[], true);
network_interface.set_pinned(&node, &[], true);
network_interface.set_visibility(&node, &[], false);
network_interface.shift_node(&node, glam::IVec2::new(3, 5), &[]);
}
let emitted = editor.active_document_mut().network_interface.take_deltas();
assert!(!emitted.is_empty(), "the edits should have emitted deltas");
let constructed = construct(&editor, &emitted, &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_same_stored_effect(&working, constructed, diffed, "emitted deltas");
}
/// A write that changes nothing is not a write, so it must not emit. Otherwise a redundant setter call
/// would stamp a fresh timestamp and win against a concurrent peer that did change the field.
#[tokio::test]
async fn unchanged_writes_emit_nothing() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let node = editor.create_node_by_name(rectangle_definition()).await;
editor.active_document_mut().network_interface.set_display_name(&node, "Named".to_string(), &[]);
editor.active_document_mut().network_interface.discard_deltas();
{
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.set_display_name(&node, "Named".to_string(), &[]);
network_interface.set_locked(&node, &[], false);
network_interface.shift_node(&node, glam::IVec2::ZERO, &[]);
}
let emitted = editor.active_document_mut().network_interface.take_deltas();
assert!(emitted.is_empty(), "re-writing the same values should emit nothing, got {emitted:#?}");
}
/// Structural writes go through the store too, so inserting and deleting a node must be recorded
/// without the caller saying anything about it.
#[tokio::test]
async fn emitted_deltas_reproduce_the_diff_for_structural_edits() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let working = convert(&editor);
editor.active_document_mut().network_interface.discard_deltas();
let template = crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type(&rectangle_definition())
.expect("rectangle definition")
.default_node_template();
let node_id = NodeId(0xDE17A);
editor.active_document_mut().network_interface.insert_node(node_id, template, &[]);
let emitted = editor.active_document_mut().network_interface.take_deltas();
let constructed = construct(&editor, &emitted, &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_same_stored_effect(&working, constructed, diffed, "emitted node insertion");
let working = convert(&editor);
editor.active_document_mut().network_interface.discard_deltas();
editor.active_document_mut().network_interface.delete_nodes(vec![node_id], true, &[]);
let emitted = editor.active_document_mut().network_interface.take_deltas();
let constructed = construct(&editor, &emitted, &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_same_stored_effect(&working, constructed, diffed, "emitted node deletion");
}
/// Adding an import shifts every later input slot, which no index-addressed op can express. The store
/// restates the whole list instead, so this checks that restatement lands the same as the diff.
#[tokio::test]
async fn emitted_deltas_reproduce_the_diff_for_an_arity_change() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: crate::messages::portfolio::document::utility_types::misc::GroupFolderType::Layer,
})
.await;
let group = editor
.active_document()
.network_interface
.document_network()
.nodes
.iter()
.find(|(_, node)| matches!(node.implementation, graph_craft::document::DocumentNodeImplementation::Network(_)))
.map(|(id, _)| *id)
.expect("the group should be a network node");
let working = convert(&editor);
editor.active_document_mut().network_interface.discard_deltas();
editor
.active_document_mut()
.network_interface
.add_import(TaggedValue::Number(7.), true, -1, "Added", "An added import", &[group]);
let emitted = editor.active_document_mut().network_interface.take_deltas();
assert!(!emitted.is_empty(), "adding an import should have emitted deltas");
let constructed = construct(&editor, &emitted, &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_same_stored_effect(&working, constructed, diffed, "emitted import addition");
}
/// An arity change rebuilds the node's whole record, so anything written to that node earlier in the
/// same batch has to survive it. Renaming first and adding the import second is the order that catches
/// a rebuild sourced from the pre-batch registry rather than from what the batch has done so far.
#[tokio::test]
async fn an_arity_change_keeps_an_earlier_edit_to_the_same_node() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: crate::messages::portfolio::document::utility_types::misc::GroupFolderType::Layer,
})
.await;
let group = editor
.active_document()
.network_interface
.document_network()
.nodes
.iter()
.find(|(_, node)| matches!(node.implementation, graph_craft::document::DocumentNodeImplementation::Network(_)))
.map(|(id, _)| *id)
.expect("the group should be a network node");
let working = convert(&editor);
editor.active_document_mut().network_interface.discard_deltas();
editor.active_document_mut().network_interface.set_display_name(&group, "Renamed".to_string(), &[]);
editor
.active_document_mut()
.network_interface
.add_import(TaggedValue::Number(7.), true, -1, "Added", "An added import", &[group]);
let emitted = editor.active_document_mut().network_interface.take_deltas();
let constructed = construct(&editor, &emitted, &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_same_stored_effect(&working, constructed, diffed, "rename then arity change");
}
/// What an edit records must be enough to reproduce it: applying the recorded deltas to a clone of the
/// interface taken before the edit must yield the edited interface. A write recorded wrongly or not at
/// all surfaces here rather than as drift on another peer.
async fn assert_replay_reproduces(edit: impl FnOnce(&mut EditorTestUtils)) {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: crate::messages::portfolio::document::utility_types::misc::GroupFolderType::Layer,
})
.await;
editor.active_document_mut().network_interface.discard_deltas();
let before = editor.active_document().network_interface.clone();
edit(&mut editor);
let recorded = editor.active_document_mut().network_interface.take_deltas();
assert!(!recorded.is_empty(), "the edit should have recorded something to replay");
let mut replayed = before;
for delta in &recorded {
replayed.apply(delta);
}
assert_eq!(
replayed,
editor.active_document().network_interface,
"replaying {} recorded deltas did not reproduce the edited interface",
recorded.len()
);
}
fn only_group(editor: &EditorTestUtils) -> NodeId {
editor
.active_document()
.network_interface
.document_network()
.nodes
.iter()
.find(|(_, node)| matches!(node.implementation, graph_craft::document::DocumentNodeImplementation::Network(_)))
.map(|(id, _)| *id)
.expect("the group should be a network node")
}
#[tokio::test]
async fn replaying_metadata_edits_reproduces_the_interface() {
assert_replay_reproduces(|editor| {
let group = only_group(editor);
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.set_display_name(&group, "Renamed".to_string(), &[]);
network_interface.set_locked(&group, &[], true);
network_interface.set_pinned(&group, &[], true);
network_interface.set_visibility(&group, &[], false);
network_interface.shift_node(&group, glam::IVec2::new(3, 5), &[]);
})
.await;
}
#[tokio::test]
async fn replaying_an_arity_change_reproduces_the_interface() {
assert_replay_reproduces(|editor| {
let group = only_group(editor);
editor
.active_document_mut()
.network_interface
.add_import(TaggedValue::Number(7.), true, -1, "Added", "An added import", &[group]);
})
.await;
}
#[tokio::test]
async fn replaying_a_node_insertion_reproduces_the_interface() {
assert_replay_reproduces(|editor| {
let template = crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type(&rectangle_definition())
.expect("rectangle definition")
.default_node_template();
editor.active_document_mut().network_interface.insert_node(NodeId(0xDE17A), template, &[]);
})
.await;
}
/// A node added and removed inside one batch is never in the registry the batch started from, so the
/// removal has nothing to look up there. The pair has to cancel out rather than leaving the addition
/// staged on its own.
#[tokio::test]
async fn a_node_added_and_removed_in_one_batch_leaves_nothing_behind() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let working = convert(&editor);
editor.active_document_mut().network_interface.discard_deltas();
let template = crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type(&rectangle_definition())
.expect("rectangle definition")
.default_node_template();
let node_id = NodeId(0xDE17A);
editor.active_document_mut().network_interface.insert_node(node_id, template, &[]);
editor.active_document_mut().network_interface.delete_nodes(vec![node_id], true, &[]);
let emitted = editor.active_document_mut().network_interface.take_deltas();
let constructed = construct(&editor, &emitted, &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_same_stored_effect(&working, constructed, diffed, "add then remove in one batch");
}
#[tokio::test]
async fn removing_a_nested_network_node_matches_the_diff() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: crate::messages::portfolio::document::utility_types::misc::GroupFolderType::Layer,
})
.await;
let before: Vec<NodeId> = editor.active_document().network_interface.document_network().nodes.keys().copied().collect();
let working = convert(&editor);
let group = editor
.active_document()
.network_interface
.document_network()
.nodes
.iter()
.find(|(_, node)| matches!(node.implementation, graph_craft::document::DocumentNodeImplementation::Network(_)))
.map(|(id, _)| *id)
.expect("the group should be a network node");
editor.active_document_mut().network_interface.delete_nodes(vec![group], true, &[]);
let network = editor.active_document().network_interface.document_network().clone();
let mut deltas: Vec<EditorDelta> = before
.iter()
.filter(|id| !network.nodes.contains_key(id))
.map(|id| {
EditorDelta::Graph(RuntimeDelta::RemoveNode {
network_path: Vec::new(),
node_id: *id,
})
})
.collect();
for (index, export) in network.exports.iter().enumerate() {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetExport {
network_path: Vec::new(),
export_index: index,
input: Some(export.clone()),
}));
}
for (node_id, node) in &network.nodes {
for (index, input) in node.inputs.iter().enumerate() {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetInput {
network_path: Vec::new(),
node_id: *node_id,
input_index: index,
input: input.clone(),
}));
}
}
let constructed = construct(&editor, &deltas, &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_same_stored_effect(&working, constructed, diffed, "nested network removal");
}
/// A group carries a nested network, so adding and removing one inside a batch has to cancel out the
/// network as well as the nodes. The proto-node case above does not reach this, since a proto node has
/// no network of its own.
#[tokio::test]
async fn a_group_added_and_removed_in_one_batch_leaves_nothing_behind() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
let working = convert(&editor);
editor.active_document_mut().network_interface.discard_deltas();
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: crate::messages::portfolio::document::utility_types::misc::GroupFolderType::Layer,
})
.await;
let group = only_group(&editor);
editor.active_document_mut().network_interface.delete_nodes(vec![group], true, &[]);
let emitted = editor.active_document_mut().network_interface.take_deltas();
let constructed = construct(&editor, &emitted, &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_same_stored_effect(&working, constructed, diffed, "group added then removed in one batch");
}
/// Swapping a node's implementation must not restate the node's own metadata: the swap did not write it,
/// and asserting it would overwrite whatever a concurrent peer set for the node's name, lock or pin.
#[tokio::test]
async fn swapping_an_implementation_leaves_the_node_in_place() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await;
let working = convert(&editor);
let deltas = {
let interface = &mut editor.active_document_mut().network_interface;
interface.discard_deltas();
let Some(mut cursor) = interface.node_mut(super::NodeLocator::new(node, &[])) else {
panic!("the node should resolve")
};
cursor.replace_implementation(graph_craft::document::DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER), None);
interface.take_deltas()
};
let ops = construct(&editor, &deltas, &working);
assert!(
ops.iter().any(|op| matches!(op, RegistryDelta::SetNodeImplementation { .. })),
"the swap should update the implementation in place"
);
assert!(
!ops.iter().any(|op| matches!(op, RegistryDelta::RemoveNode { .. })),
"the node itself should not be rebuilt, since that would clear the attributes it carries"
);
assert!(
!deltas.iter().any(|delta| matches!(delta, EditorDelta::NodeMetadataSnapshot { node_id, .. } if *node_id == node)),
"the node's own metadata should not be restated by a swap that did not write it"
);
}
@@ -0,0 +1,181 @@
//! The shapes the node graph frontend is sent: one entry per visible port, carrying its type, its
//! name and what it connects to. Read-only projections of the graph, never a source of truth.
use super::*;
impl NodeNetworkInterface {
pub fn frontend_imports(&self, network_path: &[NodeId]) -> Vec<Option<FrontendGraphOutput>> {
match network_path.split_last() {
Some((node_id, encapsulating_network_path)) => {
let Some(node) = self.document_node(node_id, encapsulating_network_path) else {
log::error!("Could not get node {node_id} in network {encapsulating_network_path:?}");
return Vec::new();
};
let mut frontend_imports = (0..node.inputs.len())
.map(|import_index| self.frontend_output_from_connector(&OutputConnector::Import(import_index), network_path))
.collect::<Vec<_>>();
if frontend_imports.is_empty() {
frontend_imports.push(None);
}
frontend_imports
}
// In the document network display no imports
None => Vec::new(),
}
}
pub fn frontend_exports(&self, network_path: &[NodeId]) -> Vec<Option<FrontendGraphInput>> {
let Some(network) = self.nested_network(network_path) else { return Vec::new() };
let mut frontend_exports = ((0..network.exports.len()).map(|export_index| self.frontend_input_from_connector(&InputConnector::Export(export_index), network_path))).collect::<Vec<_>>();
if frontend_exports.is_empty() {
frontend_exports.push(None);
}
frontend_exports
}
/// Returns None if there is an error, it is a hidden primary export, or a hidden input
pub fn frontend_input_from_connector(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Option<FrontendGraphInput> {
// Return None if it is a hidden input
if self.input_from_connector(input_connector, network_path).is_some_and(|input| !input.is_exposed()) {
return None;
}
let input_type = self.input_type(input_connector, network_path);
let data_type = input_type.displayed_type();
let resolved_type = input_type.resolved_type_node_string();
let connected_to = self
.upstream_output_connector(input_connector, network_path)
.map(|output_connector| match output_connector {
OutputConnector::Node { node_id, output_index } => {
let name = self.display_name(&node_id, network_path);
format!("Connected to output #{output_index} of \"{name}\", ID: {node_id}.")
}
OutputConnector::Import(import_index) => format!("Connected to import #{import_index}."),
})
.unwrap_or("Connected to nothing.".to_string());
let (name, description) = match input_connector {
InputConnector::Node { node_id, input_index } => self.displayed_input_name_and_description(node_id, *input_index, network_path),
InputConnector::Export(export_index) => {
// Get export name from parent node metadata input, which must match the number of exports.
// Empty string means to use type, or "Export + index" if type is empty determined
let export_name = if network_path.is_empty() {
"Canvas".to_string()
} else {
self.encapsulating_node_metadata(network_path)
.and_then(|encapsulating_metadata| encapsulating_metadata.persistent_metadata.output_names.get(*export_index).cloned())
.unwrap_or_default()
};
let export_name = if !export_name.is_empty() {
export_name
} else if let Some(export_type_name) = input_type.compiled_nested_type().map(ToString::to_string) {
export_type_name
} else {
format!("Export #{}", export_index)
};
(export_name, String::new())
}
};
let valid_types = self.potential_valid_input_types(input_connector, network_path).iter().map(ToString::to_string).collect::<Vec<_>>();
let valid_types = {
// Dedupe while preserving order
let mut found = HashSet::new();
valid_types.into_iter().filter(|s| found.insert(s.clone())).collect::<Vec<_>>()
};
Some(FrontendGraphInput {
data_type,
resolved_type,
name,
description,
valid_types,
connected_to,
})
}
/// Returns None if there is an error, it is the document network, a hidden primary output or import
pub fn frontend_output_from_connector(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Option<FrontendGraphOutput> {
let output_type = self.output_type(output_connector, network_path);
let (name, description) = match output_connector {
OutputConnector::Node { node_id, output_index } => {
// Do not display the primary output port for a node if it is a network node with a hidden primary export
if *output_index == 0 && self.hidden_primary_output(node_id, network_path) {
return None;
};
// Get the output name from the interior network export name
let node_metadata = self.node_metadata(node_id, network_path)?;
let output_name = node_metadata.persistent_metadata.output_names.get(*output_index).cloned().unwrap_or_default();
let output_name = if !output_name.is_empty() { output_name } else { output_type.resolved_type_node_string() };
(output_name, String::new())
}
OutputConnector::Import(import_index) => {
// Get the import name from the encapsulating node input metadata
let Some((encapsulating_node_id, encapsulating_path)) = network_path.split_last() else {
// Return None if it is an import in the document network
return None;
};
// Return None if the primary input is hidden and this is the primary import
if *import_index == 0 && self.hidden_primary_import(network_path) {
return None;
};
let (import_name, description) = self.displayed_input_name_and_description(encapsulating_node_id, *import_index, encapsulating_path);
let import_name = if !import_name.is_empty() {
import_name
} else if let Some(import_type_name) = output_type.compiled_nested_type().map(ToString::to_string) {
import_type_name
} else {
format!("Import #{}", import_index)
};
(import_name, description)
}
};
let data_type = output_type.displayed_type();
let resolved_type = output_type.resolved_type_node_string();
let mut connected_to = self
.with_outward_wires(network_path, |outward_wires| outward_wires.get(output_connector).cloned())
.flatten()
.unwrap_or_default()
.iter()
.map(|input| match input {
&InputConnector::Node { node_id, input_index } => {
let name = self.display_name(&node_id, network_path);
format!("Connected to input #{input_index} of \"{name}\", ID: {node_id}.")
}
InputConnector::Export(export_index) => format!("Connected to export #{export_index}."),
})
.collect::<Vec<_>>();
if connected_to.is_empty() {
connected_to.push("Connected to nothing.".to_string());
}
Some(FrontendGraphOutput {
data_type,
resolved_type,
name,
description,
connected_to,
})
}
/// Returns the input name to display in the properties panel. If the name is empty then the type is used.
pub fn displayed_input_name_and_description(&self, node_id: &NodeId, input_index: usize, network_path: &[NodeId]) -> (String, String) {
let Some(input_metadata) = self.persistent_input_metadata(node_id, input_index, network_path) else {
log::warn!("input metadata not found in displayed_input_name_and_description");
return (String::new(), String::new());
};
let description = input_metadata.input_description.to_string();
let name = if input_metadata.input_name.is_empty() {
self.input_type(&InputConnector::node_at_index(*node_id, input_index), network_path).resolved_type_node_string()
} else {
input_metadata.input_name.to_string()
};
(name, description)
}
}
@@ -0,0 +1,348 @@
//! Geometry of the node graph: where a node's body, ports and handles sit in node graph space.
//!
//! Derived from the grid model in `layout`, never the other way round. These are pure computations;
//! the caller decides whether to cache the result.
use super::*;
impl NodeNetworkInterface {
/// The node body, its ports, and for a layer its visibility, lock, grip and name handles, all in node graph space.
pub(super) fn compute_node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<DocumentNodeClickTargets> {
let Some(node_position) = self.position(node_id, network_path) else {
log::error!("Could not get node position in compute_node_click_targets for node {node_id}");
return None;
};
let node_metadata = self.node_metadata(node_id, network_path)?;
let Some(document_node) = self.document_node(node_id, network_path) else {
log::error!("Could not get document node in compute_node_click_targets");
return None;
};
let node_top_left = node_position.as_dvec2() * GRID_SIZE as f64;
let mut port_click_targets = Ports::new();
let document_node_click_targets = if !node_metadata.persistent_metadata.is_layer() {
let mut input_row_count = 0;
for (input_index, input) in document_node.inputs.iter().enumerate() {
if input.is_exposed() {
port_click_targets.insert_node_input(input_index, input_row_count, node_top_left);
}
// Primary input row is always displayed, even if the input is not exposed
if input_index == 0 || input.is_exposed() {
input_row_count += 1;
}
}
let number_of_outputs = match &document_node.implementation {
DocumentNodeImplementation::Network(network) => network.exports.len(),
_ => 1,
};
// If the node has a hidden primary output, do not display the first output
let start_index = if self.hidden_primary_output(node_id, network_path) { 1 } else { 0 };
for output_index in start_index..number_of_outputs {
port_click_targets.insert_node_output(output_index, node_top_left);
}
let height = self.displayed_row_count(node_id, network_path) as u32 * GRID_SIZE;
let width = 5 * GRID_SIZE;
// Offset down by half a grid so the click target sits below the top connector strip.
let node_click_target_top_left = node_top_left + DVec2::new(0., HALF_GRID_SIZE as f64);
let node_click_target_bottom_right = node_click_target_top_left + DVec2::new(width as f64, height as f64);
let radius = 3.;
let path = rounded_rectangle_path(node_click_target_top_left, node_click_target_bottom_right, [radius; 4]);
let node_click_target = ClickTarget::new_with_path(path, 0.);
DocumentNodeClickTargets {
node_click_target,
port_click_targets,
node_type_metadata: NodeTypeClickTargets::Node,
}
} else {
port_click_targets.insert_layer_input(0, node_top_left);
if document_node.inputs.iter().filter(|input| input.is_exposed()).count() > 1 {
port_click_targets.insert_layer_input(1, node_top_left);
}
port_click_targets.insert_layer_output(node_top_left);
let layer_width_cells = self.layer_width(node_id, network_path).unwrap_or_else(|| {
log::error!("Could not get layer width in compute_node_click_targets");
0
});
let width = layer_width_cells * GRID_SIZE;
let height = LAYER_GRID_HEIGHT * GRID_SIZE;
let locked = self.is_locked(node_id, network_path);
// The layer is `2 * GRID_SIZE` tall, so its vertical center sits one grid unit below `node_top_left.y`.
// Visibility/lock buttons fill a 1-grid-cell square (so half-extents of HALF_GRID_SIZE each side of center).
const LAYER_VERTICAL_CENTER: f64 = GRID_SIZE as f64;
const ICON_HALF_EXTENT: f64 = HALF_GRID_SIZE as f64;
let visibility_offset = node_top_left + DVec2::new(width as f64, LAYER_VERTICAL_CENTER);
let path = rounded_rectangle_path(
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + visibility_offset,
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + visibility_offset,
[3.; 4],
);
let visibility_click_target = ClickTarget::new_with_path(path, 0.);
// Update lock button click target, positioned one grid unit to the left of the visibility button (only when locked)
let lock_click_target = if locked {
let lock_offset = node_top_left + DVec2::new(width as f64 - GRID_SIZE as f64, LAYER_VERTICAL_CENTER);
let path = rounded_rectangle_path(
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + lock_offset,
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + lock_offset,
[3.; 4],
);
Some(ClickTarget::new_with_path(path, 0.))
} else {
None
};
// The grip sits to the left of the leftmost icon, 8px wide but spanning the full layer-vertical-center band
const GRIP_WIDTH: f64 = 8.;
let icons_width = if locked { GRID_SIZE as f64 } else { 0. };
let grip_offset_right_edge = node_top_left + DVec2::new(width as f64 - ICON_HALF_EXTENT - icons_width, LAYER_VERTICAL_CENTER);
let path = rounded_rectangle_path(
DVec2::new(-GRIP_WIDTH, -ICON_HALF_EXTENT) + grip_offset_right_edge,
DVec2::new(0., ICON_HALF_EXTENT) + grip_offset_right_edge,
[0.; 4],
);
let grip_click_target = ClickTarget::new_with_path(path, 0.);
// The double-click rename target is sized to the text bounds, not the surrounding `.details` area,
// so the rest of the layer still drills into the subgraph on double-click
/// `.layer` margin-left (= 12), for chain layers the negative margin-left and positive padding-left cancel out, keeping content at this same offset
const LAYER_LEFT_MARGIN: f64 = HALF_GRID_SIZE as f64;
/// `.thumbnail` (70px) + its 1px side margins (= 72)
const THUMBNAIL_BLOCK_WIDTH: f64 = 3. * GRID_SIZE as f64;
/// `.details` margin-left
const DETAILS_LEFT_MARGIN: f64 = 8.;
const NAME_LEFT_OFFSET: f64 = LAYER_LEFT_MARGIN + THUMBNAIL_BLOCK_WIDTH + DETAILS_LEFT_MARGIN;
/// Distance from layer's right edge to visibility's left edge (= 12)
const VISIBILITY_INSET_FROM_LAYER_RIGHT: f64 = HALF_GRID_SIZE as f64;
const FONT_SIZE: f64 = 14.;
let display_name = self.display_name(node_id, network_path);
let name_click_target = if display_name.is_empty() {
None
} else {
let name_left = node_top_left.x + NAME_LEFT_OFFSET;
let icons_reserve = VISIBILITY_INSET_FROM_LAYER_RIGHT + icons_width + GRIP_WIDTH;
let name_right_max = node_top_left.x + width as f64 - icons_reserve;
let name_width = text_width(&display_name, FONT_SIZE);
let name_right = (name_left + name_width).min(name_right_max);
if name_right > name_left {
// The 1-grid-tall name strip is centered vertically in the 2-grid-tall layer.
let name_top = node_top_left.y + HALF_GRID_SIZE as f64;
let name_bottom = node_top_left.y + GRID_SIZE as f64 + HALF_GRID_SIZE as f64;
let path = rounded_rectangle_path(DVec2::new(name_left, name_top), DVec2::new(name_right, name_bottom), [3.; 4]);
Some(ClickTarget::new_with_path(path, 0.))
} else {
None
}
};
// The layer click target spans the layer and its chain background
let chain_width_grid_spaces = self.chain_width(node_id, network_path);
let node_bottom_right = node_top_left + DVec2::new(width as f64, height as f64);
let chain_top_left = node_top_left - DVec2::new((chain_width_grid_spaces * GRID_SIZE) as f64, 0.);
const CORNER_RADIUS: f64 = 10.;
let path = rounded_rectangle_path(chain_top_left, node_bottom_right, [CORNER_RADIUS; 4]);
let node_click_target = ClickTarget::new_with_path(path, 0.);
DocumentNodeClickTargets {
node_click_target,
port_click_targets,
node_type_metadata: NodeTypeClickTargets::Layer(Box::new(LayerClickTargets {
visibility_click_target,
lock_click_target,
grip_click_target,
name_click_target,
})),
}
};
Some(document_node_click_targets)
}
/// The add, remove and reorder handles that sit beside each import and export port.
pub(super) fn compute_modify_import_export(&self, network_path: &[NodeId]) -> Option<ModifyImportExportClickTarget> {
let mut reorder_imports_exports = Ports::new();
let mut remove_imports_exports = Ports::new();
if !network_path.is_empty() {
let ports_built = self.with_import_export_ports(network_path, |import_exports| {
for (import_index, import_click_target) in import_exports.output_ports() {
let Some(import_bounding_box) = import_click_target.bounding_box() else {
log::error!("Could not get export bounding box in compute_modify_import_export");
continue;
};
let reorder_import_center = (import_bounding_box[0] + import_bounding_box[1]) / 2. + DVec2::new(-12., 0.);
if *import_index == 0 {
let remove_import_center = reorder_import_center + DVec2::new(-4., 0.);
let remove_import = ClickTarget::new_with_path(rectangle_path(remove_import_center - DVec2::new(8., 8.), remove_import_center + DVec2::new(8., 8.)), 0.);
remove_imports_exports.insert_custom_output_port(*import_index, remove_import);
} else {
let remove_import_center = reorder_import_center + DVec2::new(-12., 0.);
let reorder_import = ClickTarget::new_with_path(rectangle_path(reorder_import_center - DVec2::new(3., 4.), reorder_import_center + DVec2::new(3., 4.)), 0.);
let remove_import = ClickTarget::new_with_path(rectangle_path(remove_import_center - DVec2::new(8., 8.), remove_import_center + DVec2::new(8., 8.)), 0.);
reorder_imports_exports.insert_custom_output_port(*import_index, reorder_import);
remove_imports_exports.insert_custom_output_port(*import_index, remove_import);
}
}
for (export_index, export_click_target) in import_exports.input_ports() {
let Some(export_bounding_box) = export_click_target.bounding_box() else {
log::error!("Could not get export bounding box in compute_modify_import_export");
continue;
};
let reorder_export_center = (export_bounding_box[0] + export_bounding_box[1]) / 2. + DVec2::new(12., 0.);
if *export_index == 0 {
let remove_export_center = reorder_export_center + DVec2::new(4., 0.);
let remove_export = ClickTarget::new_with_path(rectangle_path(remove_export_center - DVec2::new(8., 8.), remove_export_center + DVec2::new(8., 8.)), 0.);
remove_imports_exports.insert_custom_input_port(*export_index, remove_export);
} else {
let remove_export_center = reorder_export_center + DVec2::new(12., 0.);
let reorder_export = ClickTarget::new_with_path(rectangle_path(reorder_export_center - DVec2::new(3., 4.), reorder_export_center + DVec2::new(3., 4.)), 0.);
let remove_export = ClickTarget::new_with_path(rectangle_path(remove_export_center - DVec2::new(8., 8.), remove_export_center + DVec2::new(8., 8.)), 0.);
reorder_imports_exports.insert_custom_input_port(*export_index, reorder_export);
remove_imports_exports.insert_custom_input_port(*export_index, remove_export);
}
}
});
if ports_built.is_none() {
log::error!("Could not get import_export_ports in compute_modify_import_export");
return None;
}
}
Some(ModifyImportExportClickTarget {
remove_imports_exports,
reorder_imports_exports,
})
}
/// A port for each import and export of the network, placed down the left and right edges.
pub(super) fn compute_import_export_ports(&self, network_path: &[NodeId]) -> Option<Ports> {
let Some(import_export_position) = self.import_export_position(network_path) else {
log::error!("Could not get import_export_position");
return None;
};
let network = self.nested_network(network_path)?;
let mut import_export_ports = Ports::new();
if !network_path.is_empty() {
let import_start_index = if self.hidden_primary_import(network_path) { 1 } else { 0 };
for import_index in import_start_index..self.number_of_imports(network_path) {
import_export_ports.insert_output_port_at_center(import_index, import_export_position.0.as_dvec2() + DVec2::new(0., import_index as f64 * 24.));
}
}
let export_start_index = if self.hidden_primary_export(network_path) { 1 } else { 0 };
for export_index in export_start_index..network.exports.len() {
import_export_ports.insert_input_port_at_center(export_index, import_export_position.1.as_dvec2() + DVec2::new(0., export_index as f64 * 24.));
}
Some(import_export_ports)
}
/// The width of a layer in grid units, which covers its thumbnail, its name and its icons. Cached
/// because measuring the name's text is slow.
pub(super) fn compute_layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> u32 {
const GAP_WIDTH: f64 = 8.;
const FONT_SIZE: f64 = 14.;
let left_thumbnail_padding = GRID_SIZE as f64 / 2.;
let thumbnail_width = 3. * GRID_SIZE as f64;
let layer_text = self.display_name(node_id, network_path);
let text_width = text_width(&layer_text, FONT_SIZE);
let grip_padding = 4.;
let grip_width = 8.;
let lock_icon_width = if self.is_locked(node_id, network_path) { GRID_SIZE as f64 } else { 0. };
let icon_overhang_width = GRID_SIZE as f64 / 2.;
let layer_width_pixels = left_thumbnail_padding + thumbnail_width + GAP_WIDTH + text_width + grip_padding + grip_width + lock_icon_width + icon_overhang_width;
((layer_width_pixels / 24.).ceil() as u32).max(8)
}
pub fn import_export_position(&self, network_path: &[NodeId]) -> Option<(IVec2, IVec2)> {
let Some(all_nodes_bounding_box) = self.all_nodes_bounding_box(network_path) else {
log::error!("Could not get all nodes bounding box in import_export_position");
return None;
};
let Some(network) = self.nested_network(network_path) else {
log::error!("Could not get current network in import_export_position");
return None;
};
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in import_export_position");
return None;
};
let node_graph_to_viewport = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport;
let target_viewport_top_left = DVec2::new(IMPORTS_TO_LEFT_EDGE_PIXEL_GAP as f64, IMPORTS_TO_TOP_EDGE_PIXEL_GAP as f64);
let node_graph_pixel_offset_top_left = node_graph_to_viewport.inverse().transform_point2(target_viewport_top_left);
// A 5x5 grid offset from the top left corner
let node_graph_grid_space_offset_top_left = node_graph_to_viewport.inverse().transform_point2(DVec2::ZERO) + DVec2::new(5. * GRID_SIZE as f64, 4. * GRID_SIZE as f64);
// The inner bound of the import is the highest/furthest left of the two offsets
let top_left_inner_bound = DVec2::new(
node_graph_pixel_offset_top_left.x.min(node_graph_grid_space_offset_top_left.x),
node_graph_pixel_offset_top_left.y.min(node_graph_grid_space_offset_top_left.y),
);
let offset_from_top_left = if network
.exports
.first()
.is_some_and(|export| export.as_node().is_some_and(|export_node| self.is_layer(&export_node, network_path)))
{
DVec2::new(-4. * GRID_SIZE as f64, -2. * GRID_SIZE as f64)
} else {
DVec2::new(-4. * GRID_SIZE as f64, 0.)
};
let bounding_box_top_left = DVec2::new((all_nodes_bounding_box[0].x / 24. + 0.5).floor() * 24., (all_nodes_bounding_box[0].y / 24. + 0.5).floor() * 24.) + offset_from_top_left;
let import_top_left = DVec2::new(top_left_inner_bound.x.min(bounding_box_top_left.x), top_left_inner_bound.y.min(bounding_box_top_left.y));
let rounded_import_top_left = DVec2::new((import_top_left.x / 24.).round() * 24., (import_top_left.y / 24.).round() * 24.);
let viewport_width = network_metadata.persistent_metadata.navigation_metadata.node_graph_width;
let target_viewport_top_right = DVec2::new(viewport_width - EXPORTS_TO_RIGHT_EDGE_PIXEL_GAP as f64, EXPORTS_TO_TOP_EDGE_PIXEL_GAP as f64);
// An offset from the right edge in viewport pixels
let node_graph_pixel_offset_top_right = node_graph_to_viewport.inverse().transform_point2(target_viewport_top_right);
// A 5x5 grid offset from the right corner
let node_graph_grid_space_offset_top_right = node_graph_to_viewport.inverse().transform_point2(DVec2::new(viewport_width, 0.)) + DVec2::new(-5. * GRID_SIZE as f64, 4. * GRID_SIZE as f64);
// The inner bound of the export is the highest/furthest right of the two offsets.
// When zoomed out this keeps it a constant grid space away from the edge, but when zoomed in it prevents the exports from getting too far in
let top_right_inner_bound = DVec2::new(
node_graph_pixel_offset_top_right.x.max(node_graph_grid_space_offset_top_right.x),
node_graph_pixel_offset_top_right.y.min(node_graph_grid_space_offset_top_right.y),
);
let offset_from_top_right = if network
.exports
.first()
.is_some_and(|export| export.as_node().is_some_and(|export_node| self.is_layer(&export_node, network_path)))
{
DVec2::new(2. * GRID_SIZE as f64, -2. * GRID_SIZE as f64)
} else {
DVec2::new(4. * GRID_SIZE as f64, 0.)
};
let mut bounding_box_top_right = DVec2::new((all_nodes_bounding_box[1].x / 24. + 0.5).floor() * 24., (all_nodes_bounding_box[0].y / 24. + 0.5).floor() * 24.);
bounding_box_top_right += offset_from_top_right;
let export_top_right = DVec2::new(top_right_inner_bound.x.max(bounding_box_top_right.x), top_right_inner_bound.y.min(bounding_box_top_right.y));
let rounded_export_top_right = DVec2::new((export_top_right.x / 24.).round() * 24., (export_top_right.y / 24.).round() * 24.);
Some((rounded_import_top_left.as_ivec2(), rounded_export_top_right.as_ivec2()))
}
}
@@ -121,11 +121,11 @@ impl NodeNetworkInterface {
}
pub fn node_graph_ptz_mut(&mut self, network_path: &[NodeId]) -> Option<&mut PTZ> {
let Some(network_metadata) = self.network_metadata_mut(network_path) else {
let Some(navigation) = self.navigation_mut(network_path) else {
log::error!("Could not get nested network_metadata in node_graph_ptz_mut");
return None;
};
Some(&mut network_metadata.persistent_metadata.navigation_metadata.node_graph_ptz)
Some(&mut navigation.node_graph_ptz)
}
// TODO: Optimize getting click target intersections from click by using a spacial data structure like a quadtree instead of linear search
@@ -0,0 +1,35 @@
//! What a change feeds: each rule names a kind of edit and unloads everything derived from it.
//!
//! Declared here once rather than restated at each mutation site, so two edits of the same kind cannot
//! disagree about what they invalidate.
use super::*;
impl NodeNetworkInterface {
/// Unloads everything a node's position feeds: its own geometry, the geometry of every node placed
/// relative to it, and the network bounds. A chain node also sets the width of the layer encapsulating
/// its chain, so that layer reloads too.
pub(crate) fn invalidate_position(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
if self.is_chain(node_id, network_path)
&& let Some(downstream_layer) = self.downstream_layer_for_chain_node(node_id, network_path)
{
self.unload_node_click_targets(&downstream_layer, network_path);
}
self.unload_upstream_node_click_targets(vec![*node_id], network_path);
self.unload_all_nodes_bounding_box(network_path);
}
/// Unloads the network's import and export strip: the ports themselves and the handles beside them
/// for adding, removing and reordering.
pub(crate) fn invalidate_import_export(&mut self, network_path: &[NodeId]) {
self.unload_import_export_ports(network_path);
self.unload_modify_import_export(network_path);
}
/// Unloads what a node's name or lock state feeds: a layer's width, and the geometry sized from it.
pub(crate) fn invalidate_node_appearance(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
self.try_unload_layer_width(node_id, network_path);
self.unload_node_click_targets(node_id, network_path);
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -22,10 +22,6 @@ impl NodeNetworkInterface {
pub fn document_network(&self) -> &NodeNetwork {
self.network.network()
}
pub fn document_network_mut(&mut self) -> &mut NodeNetwork {
self.network.network_mut()
}
/// Gets the nested network based on network_path
pub fn nested_network(&self, network_path: &[NodeId]) -> Option<&NodeNetwork> {
let Some(network) = self.document_network().nested_network(network_path) else {
@@ -172,6 +168,11 @@ impl NodeNetworkInterface {
self.query(network_path, "has_primary_input", |view| view.has_primary_input(node_id)).unwrap_or_default()
}
/// Grid rows the node body spans, which is the greater of its input rows and its output count.
pub fn displayed_row_count(&self, node_id: &NodeId, network_path: &[NodeId]) -> usize {
self.query(network_path, "displayed_row_count", |view| view.displayed_row_count(node_id)).unwrap_or(1)
}
pub fn number_of_outputs(&self, node_id: &NodeId, network_path: &[NodeId]) -> usize {
self.query(network_path, "number_of_outputs", |view| view.number_of_outputs(node_id)).unwrap_or_default()
}
@@ -293,23 +294,6 @@ impl NodeNetworkInterface {
}
}
pub fn position(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<IVec2> {
self.try_load_node_click_targets(node_id, network_path);
let top_left_position = self.try_get_node_bounding_box(node_id, network_path).map(|mut bounding_box| {
if !self.is_layer(node_id, network_path) {
bounding_box[0] -= DVec2::new(0., 12.);
}
(bounding_box[0] / 24.).as_ivec2()
});
top_left_position.map(|position| {
if self.is_layer(node_id, network_path) {
position + IVec2::new(self.chain_width(node_id, network_path) as i32, 0)
} else {
position
}
})
}
pub fn collect_used_resources(&self, target: &mut HashSet<ResourceId>) {
visit_network_resources(self.document_network(), &mut |id| {
target.insert(id);
@@ -322,254 +306,6 @@ impl NodeNetworkInterface {
counts
}
pub fn frontend_imports(&self, network_path: &[NodeId]) -> Vec<Option<FrontendGraphOutput>> {
match network_path.split_last() {
Some((node_id, encapsulating_network_path)) => {
let Some(node) = self.document_node(node_id, encapsulating_network_path) else {
log::error!("Could not get node {node_id} in network {encapsulating_network_path:?}");
return Vec::new();
};
let mut frontend_imports = (0..node.inputs.len())
.map(|import_index| self.frontend_output_from_connector(&OutputConnector::Import(import_index), network_path))
.collect::<Vec<_>>();
if frontend_imports.is_empty() {
frontend_imports.push(None);
}
frontend_imports
}
// In the document network display no imports
None => Vec::new(),
}
}
pub fn frontend_exports(&self, network_path: &[NodeId]) -> Vec<Option<FrontendGraphInput>> {
let Some(network) = self.nested_network(network_path) else { return Vec::new() };
let mut frontend_exports = ((0..network.exports.len()).map(|export_index| self.frontend_input_from_connector(&InputConnector::Export(export_index), network_path))).collect::<Vec<_>>();
if frontend_exports.is_empty() {
frontend_exports.push(None);
}
frontend_exports
}
pub fn import_export_position(&self, network_path: &[NodeId]) -> Option<(IVec2, IVec2)> {
let Some(all_nodes_bounding_box) = self.all_nodes_bounding_box(network_path) else {
log::error!("Could not get all nodes bounding box in load_export_ports");
return None;
};
let Some(network) = self.nested_network(network_path) else {
log::error!("Could not get current network in load_export_ports");
return None;
};
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in load_export_ports");
return None;
};
let node_graph_to_viewport = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport;
let target_viewport_top_left = DVec2::new(IMPORTS_TO_LEFT_EDGE_PIXEL_GAP as f64, IMPORTS_TO_TOP_EDGE_PIXEL_GAP as f64);
let node_graph_pixel_offset_top_left = node_graph_to_viewport.inverse().transform_point2(target_viewport_top_left);
// A 5x5 grid offset from the top left corner
let node_graph_grid_space_offset_top_left = node_graph_to_viewport.inverse().transform_point2(DVec2::ZERO) + DVec2::new(5. * GRID_SIZE as f64, 4. * GRID_SIZE as f64);
// The inner bound of the import is the highest/furthest left of the two offsets
let top_left_inner_bound = DVec2::new(
node_graph_pixel_offset_top_left.x.min(node_graph_grid_space_offset_top_left.x),
node_graph_pixel_offset_top_left.y.min(node_graph_grid_space_offset_top_left.y),
);
let offset_from_top_left = if network
.exports
.first()
.is_some_and(|export| export.as_node().is_some_and(|export_node| self.is_layer(&export_node, network_path)))
{
DVec2::new(-4. * GRID_SIZE as f64, -2. * GRID_SIZE as f64)
} else {
DVec2::new(-4. * GRID_SIZE as f64, 0.)
};
let bounding_box_top_left = DVec2::new((all_nodes_bounding_box[0].x / 24. + 0.5).floor() * 24., (all_nodes_bounding_box[0].y / 24. + 0.5).floor() * 24.) + offset_from_top_left;
let import_top_left = DVec2::new(top_left_inner_bound.x.min(bounding_box_top_left.x), top_left_inner_bound.y.min(bounding_box_top_left.y));
let rounded_import_top_left = DVec2::new((import_top_left.x / 24.).round() * 24., (import_top_left.y / 24.).round() * 24.);
let viewport_width = network_metadata.persistent_metadata.navigation_metadata.node_graph_width;
let target_viewport_top_right = DVec2::new(viewport_width - EXPORTS_TO_RIGHT_EDGE_PIXEL_GAP as f64, EXPORTS_TO_TOP_EDGE_PIXEL_GAP as f64);
// An offset from the right edge in viewport pixels
let node_graph_pixel_offset_top_right = node_graph_to_viewport.inverse().transform_point2(target_viewport_top_right);
// A 5x5 grid offset from the right corner
let node_graph_grid_space_offset_top_right = node_graph_to_viewport.inverse().transform_point2(DVec2::new(viewport_width, 0.)) + DVec2::new(-5. * GRID_SIZE as f64, 4. * GRID_SIZE as f64);
// The inner bound of the export is the highest/furthest right of the two offsets.
// When zoomed out this keeps it a constant grid space away from the edge, but when zoomed in it prevents the exports from getting too far in
let top_right_inner_bound = DVec2::new(
node_graph_pixel_offset_top_right.x.max(node_graph_grid_space_offset_top_right.x),
node_graph_pixel_offset_top_right.y.min(node_graph_grid_space_offset_top_right.y),
);
let offset_from_top_right = if network
.exports
.first()
.is_some_and(|export| export.as_node().is_some_and(|export_node| self.is_layer(&export_node, network_path)))
{
DVec2::new(2. * GRID_SIZE as f64, -2. * GRID_SIZE as f64)
} else {
DVec2::new(4. * GRID_SIZE as f64, 0.)
};
let mut bounding_box_top_right = DVec2::new((all_nodes_bounding_box[1].x / 24. + 0.5).floor() * 24., (all_nodes_bounding_box[0].y / 24. + 0.5).floor() * 24.);
bounding_box_top_right += offset_from_top_right;
let export_top_right = DVec2::new(top_right_inner_bound.x.max(bounding_box_top_right.x), top_right_inner_bound.y.min(bounding_box_top_right.y));
let rounded_export_top_right = DVec2::new((export_top_right.x / 24.).round() * 24., (export_top_right.y / 24.).round() * 24.);
Some((rounded_import_top_left.as_ivec2(), rounded_export_top_right.as_ivec2()))
}
/// Returns None if there is an error, it is a hidden primary export, or a hidden input
pub fn frontend_input_from_connector(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Option<FrontendGraphInput> {
// Return None if it is a hidden input
if self.input_from_connector(input_connector, network_path).is_some_and(|input| !input.is_exposed()) {
return None;
}
let input_type = self.input_type(input_connector, network_path);
let data_type = input_type.displayed_type();
let resolved_type = input_type.resolved_type_node_string();
let connected_to = self
.upstream_output_connector(input_connector, network_path)
.map(|output_connector| match output_connector {
OutputConnector::Node { node_id, output_index } => {
let name = self.display_name(&node_id, network_path);
format!("Connected to output #{output_index} of \"{name}\", ID: {node_id}.")
}
OutputConnector::Import(import_index) => format!("Connected to import #{import_index}."),
})
.unwrap_or("Connected to nothing.".to_string());
let (name, description) = match input_connector {
InputConnector::Node { node_id, input_index } => self.displayed_input_name_and_description(node_id, *input_index, network_path),
InputConnector::Export(export_index) => {
// Get export name from parent node metadata input, which must match the number of exports.
// Empty string means to use type, or "Export + index" if type is empty determined
let export_name = if network_path.is_empty() {
"Canvas".to_string()
} else {
self.encapsulating_node_metadata(network_path)
.and_then(|encapsulating_metadata| encapsulating_metadata.persistent_metadata.output_names.get(*export_index).cloned())
.unwrap_or_default()
};
let export_name = if !export_name.is_empty() {
export_name
} else if let Some(export_type_name) = input_type.compiled_nested_type().map(ToString::to_string) {
export_type_name
} else {
format!("Export #{}", export_index)
};
(export_name, String::new())
}
};
let valid_types = self.potential_valid_input_types(input_connector, network_path).iter().map(ToString::to_string).collect::<Vec<_>>();
let valid_types = {
// Dedupe while preserving order
let mut found = HashSet::new();
valid_types.into_iter().filter(|s| found.insert(s.clone())).collect::<Vec<_>>()
};
Some(FrontendGraphInput {
data_type,
resolved_type,
name,
description,
valid_types,
connected_to,
})
}
/// Returns None if there is an error, it is the document network, a hidden primary output or import
pub fn frontend_output_from_connector(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Option<FrontendGraphOutput> {
let output_type = self.output_type(output_connector, network_path);
let (name, description) = match output_connector {
OutputConnector::Node { node_id, output_index } => {
// Do not display the primary output port for a node if it is a network node with a hidden primary export
if *output_index == 0 && self.hidden_primary_output(node_id, network_path) {
return None;
};
// Get the output name from the interior network export name
let node_metadata = self.node_metadata(node_id, network_path)?;
let output_name = node_metadata.persistent_metadata.output_names.get(*output_index).cloned().unwrap_or_default();
let output_name = if !output_name.is_empty() { output_name } else { output_type.resolved_type_node_string() };
(output_name, String::new())
}
OutputConnector::Import(import_index) => {
// Get the import name from the encapsulating node input metadata
let Some((encapsulating_node_id, encapsulating_path)) = network_path.split_last() else {
// Return None if it is an import in the document network
return None;
};
// Return None if the primary input is hidden and this is the primary import
if *import_index == 0 && self.hidden_primary_import(network_path) {
return None;
};
let (import_name, description) = self.displayed_input_name_and_description(encapsulating_node_id, *import_index, encapsulating_path);
let import_name = if !import_name.is_empty() {
import_name
} else if let Some(import_type_name) = output_type.compiled_nested_type().map(ToString::to_string) {
import_type_name
} else {
format!("Import #{}", import_index)
};
(import_name, description)
}
};
let data_type = output_type.displayed_type();
let resolved_type = output_type.resolved_type_node_string();
let mut connected_to = self
.with_outward_wires(network_path, |outward_wires| outward_wires.get(output_connector).cloned())
.flatten()
.unwrap_or_default()
.iter()
.map(|input| match input {
&InputConnector::Node { node_id, input_index } => {
let name = self.display_name(&node_id, network_path);
format!("Connected to input #{input_index} of \"{name}\", ID: {node_id}.")
}
InputConnector::Export(export_index) => format!("Connected to export #{export_index}."),
})
.collect::<Vec<_>>();
if connected_to.is_empty() {
connected_to.push("Connected to nothing.".to_string());
}
Some(FrontendGraphOutput {
data_type,
resolved_type,
name,
description,
connected_to,
})
}
pub fn height_from_click_target(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<u32> {
self.try_load_node_click_targets(node_id, network_path);
let mut node_height: Option<u32> = self
.try_get_node_bounding_box(node_id, network_path)
.map(|bounding_box| ((bounding_box[1].y - bounding_box[0].y) / 24.) as u32);
if !self.is_layer(node_id, network_path) {
node_height = node_height.map(|height| height + 1);
}
node_height
}
/// Returns whether every downstream path from the node's outputs stays within the dependent set defined by `classify`, meaning nothing else in the graph depends on this node.
/// Reaching an export or a dead end (a walked node with no outward wires) always escapes. O(nodes + wires) per call.
pub(crate) fn is_sole_dependent(&self, node_id: NodeId, network_path: &[NodeId], classify: impl Fn(NodeId, usize) -> SoleDependentStep) -> bool {
@@ -795,29 +531,11 @@ impl NodeNetworkInterface {
}
pub fn set_input_override(&mut self, node_id: &NodeId, index: usize, widget_override: Option<String>, network_path: &[NodeId]) {
let Some(metadata) = self
.node_metadata_mut(node_id, network_path)
.and_then(|node_metadata| node_metadata.persistent_metadata.input_metadata.get_mut(index))
else {
log::error!("Could not get input metadata for {node_id} index {index} in set_input_override");
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else {
log::error!("Could not get node {node_id} in set_input_override");
return;
};
metadata.persistent_metadata.widget_override = widget_override;
}
/// Returns the input name to display in the properties panel. If the name is empty then the type is used.
pub fn displayed_input_name_and_description(&self, node_id: &NodeId, input_index: usize, network_path: &[NodeId]) -> (String, String) {
let Some(input_metadata) = self.persistent_input_metadata(node_id, input_index, network_path) else {
log::warn!("input metadata not found in displayed_input_name_and_description");
return (String::new(), String::new());
};
let description = input_metadata.input_description.to_string();
let name = if input_metadata.input_name.is_empty() {
self.input_type(&InputConnector::node_at_index(*node_id, input_index), network_path).resolved_type_node_string()
} else {
input_metadata.input_name.to_string()
};
(name, description)
node.set_widget_override(index, widget_override);
}
/// Returns the display name of the node. If the display name is empty, it will return "Untitled Node" or "Untitled Layer" depending on the node type.
@@ -1184,61 +902,6 @@ impl NodeNetworkInterface {
nested_network_metadata.persistent_metadata.node_metadata.insert(node_id, node_metadata);
}
}
Self {
network: MemoNetwork::new(node_network),
network_metadata,
document_metadata: DocumentMetadata::default(),
resolved_types: ResolvedDocumentNodeTypes::default(),
transaction_status: TransactionStatus::Finished,
}
}
}
// Private mutable getters for use within the network interface
impl NodeNetworkInterface {
pub(crate) fn network_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetwork> {
self.document_network_mut().nested_network_mut(network_path)
}
pub(crate) fn network_metadata_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetworkMetadata> {
self.network_metadata.nested_metadata_mut(network_path)
}
pub(crate) fn node_metadata_mut(&mut self, node_id: &NodeId, network_path: &[NodeId]) -> Option<&mut DocumentNodeMetadata> {
let Some(network_metadata) = self.network_metadata_mut(network_path) else {
log::error!("Could not get nested network_metadata");
return None;
};
let Some(node_metadata) = network_metadata.persistent_metadata.node_metadata.get_mut(node_id) else {
log::error!("Could not get nested node_metadata for node {node_id} in network {network_path:?}");
return None;
};
Some(node_metadata)
}
/// Mutably get the network which the encapsulating node of the currently viewed network is part of. Will always be None in the document network.
pub(crate) fn encapsulating_network_metadata_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetworkMetadata> {
let mut encapsulating_path = network_path.to_vec();
encapsulating_path.pop()?;
let Some(parent_metadata) = self.network_metadata_mut(&encapsulating_path) else {
log::error!("Could not get parent network in encapsulating_node_metadata");
return None;
};
Some(parent_metadata)
}
/// Get the node metadata for the node which encapsulates the currently viewed network. Will always be None in the document network.
pub(crate) fn encapsulating_node_metadata_mut(&mut self, network_path: &[NodeId]) -> Option<&mut DocumentNodeMetadata> {
let mut encapsulating_path = network_path.to_vec();
let encapsulating_node_id = encapsulating_path.pop()?;
let Some(parent_metadata) = self.network_metadata_mut(&encapsulating_path) else {
log::error!("Could not get parent network in encapsulating_node_metadata");
return None;
};
let Some(encapsulating_node_metadata) = parent_metadata.persistent_metadata.node_metadata.get_mut(&encapsulating_node_id) else {
log::error!("Could not get encapsulating node metadata in encapsulating_node_metadata");
return None;
};
Some(encapsulating_node_metadata)
Self::from_trees(node_network, network_metadata)
}
}
@@ -13,7 +13,6 @@ use glam::IVec2;
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeNetwork};
use graphene_std::vector::style::RenderMode;
use super::memo_network::MemoNetwork;
use super::{
DocumentNodePersistentMetadata, DocumentNodeTransientMetadata, InputMetadata, InputPersistentMetadata, LayerPosition, NavigationMetadata, NodeNetworkInterface, NodeNetworkMetadata,
NodePersistentMetadata, NodePosition, NodeTypePersistentMetadata, PTZ, Previewing,
@@ -65,16 +64,7 @@ impl StorageMetadataView<'_> {
impl NodeMetadataSource for StorageMetadataView<'_> {
fn position(&self, network_path: &[NodeId], local_id: NodeId) -> Option<Position> {
match &self.persistent(network_path, local_id)?.node_type_metadata {
NodeTypePersistentMetadata::Layer(layer) => match layer.position {
LayerPosition::Absolute(v) => Some(Position::Absolute([v.x, v.y])),
LayerPosition::Stack(offset) => Some(Position::Stack(offset)),
},
NodeTypePersistentMetadata::Node(node) => match *node.position() {
NodePosition::Absolute(v) => Some(Position::Absolute([v.x, v.y])),
NodePosition::Chain => Some(Position::Chain),
},
}
Some(position_from_runtime(&self.persistent(network_path, local_id)?.node_type_metadata))
}
fn is_layer(&self, network_path: &[NodeId], local_id: NodeId) -> bool {
@@ -114,10 +104,21 @@ impl NodeMetadataSource for StorageMetadataView<'_> {
self.persistent(network_path, local_id).map(|p| p.output_names.clone()).unwrap_or_default()
}
fn storage_node_id(&self, network_path: &[NodeId], local_id: NodeId) -> Option<document_graph_storage::NodeId> {
self.persistent(network_path, local_id)?.storage_id.map(document_graph_storage::NodeId)
}
fn reference(&self, network_path: &[NodeId]) -> Option<&str> {
let network_metadata = self.interface.network_metadata.nested_metadata(network_path)?;
network_metadata.persistent_metadata.reference.as_deref()
}
fn pinned_order(&self, network_path: &[NodeId]) -> Vec<NodeId> {
self.interface
.network_metadata
.nested_metadata(network_path)
.map(|network_metadata| network_metadata.persistent_metadata.pinned_node_order.clone())
.unwrap_or_default()
}
}
impl DocumentSettings<'_> {
@@ -146,6 +147,20 @@ impl DocumentSettings<'_> {
}
}
/// The stored position of a node, which pairs with `is_layer` to reconstruct the runtime node type.
pub fn position_from_runtime(node_type: &NodeTypePersistentMetadata) -> Position {
match node_type {
NodeTypePersistentMetadata::Layer(layer) => match layer.position {
LayerPosition::Absolute(v) => Position::Absolute([v.x, v.y]),
LayerPosition::Stack(offset) => Position::Stack(offset),
},
NodeTypePersistentMetadata::Node(node) => match *node.position() {
NodePosition::Absolute(v) => Position::Absolute([v.x, v.y]),
NodePosition::Chain => Position::Chain,
},
}
}
/// Inverse of the position extraction in `NodeMetadataSource::position`.
/// `(Stack, !is_layer)` and `(Chain, is_layer)` shouldn't arise from a faithful round-trip; they fall back to a default of the matching variant.
pub fn position_to_runtime(position: Position, is_layer: bool) -> NodeTypePersistentMetadata {
@@ -164,21 +179,13 @@ pub fn position_to_runtime(position: Position, is_layer: bool) -> NodeTypePersis
}
/// Builds a `NodeNetworkInterface` from a `NodeNetwork` plus the metadata vecs `Registry::to_runtime_with_full_metadata` emits.
///
/// Sets private fields directly (rather than via public setters) because we're constructing a fresh self-consistent snapshot;
/// the setters' transient-cache invalidation isn't needed.
pub fn build_interface_from_storage(network: NodeNetwork, node_entries: Vec<NodeMetadataEntry>, network_entries: Vec<NetworkMetadataEntry>) -> Result<NodeNetworkInterface, InterfaceRebuildError> {
let mut network_metadata = NodeNetworkMetadata::default();
seed_metadata_tree(&network, &mut network_metadata);
apply_entries_into_tree(&network, &mut network_metadata, node_entries)?;
apply_network_entries_into_tree(&mut network_metadata, network_entries);
let interface = NodeNetworkInterface {
network: MemoNetwork::new(network),
network_metadata,
..Default::default()
};
Ok(interface)
Ok(NodeNetworkInterface::from_trees(network, network_metadata))
}
/// Build the runtime-`network_path` -> stable-`NetworkId` map from the `NetworkMetadataEntry`s that
@@ -249,30 +256,31 @@ pub fn apply_network_view_settings(
) {
for (network_path, network_id) in network_ids {
let Some(settings) = network_view_settings.get(network_id) else { continue };
let Some(network_metadata) = interface.network_metadata.nested_metadata_mut(network_path) else {
let Some(navigation) = interface.navigation_mut(network_path) else {
continue;
};
let persistent = &mut network_metadata.persistent_metadata;
if let Some(value) = settings.get(session::network::NAV_PTZ)
&& let Ok(ptz) = serde_json::from_value::<PTZ>(value.clone())
{
persistent.navigation_metadata.node_graph_ptz = ptz;
navigation.node_graph_ptz = ptz;
}
if let Some(value) = settings.get(session::network::NAV_TRANSFORM)
&& let Ok(transform) = serde_json::from_value(value.clone())
{
persistent.navigation_metadata.node_graph_to_viewport = transform;
navigation.node_graph_to_viewport = transform;
}
if let Some(value) = settings.get(session::network::NAV_WIDTH)
&& let Ok(width) = serde_json::from_value(value.clone())
{
persistent.navigation_metadata.node_graph_width = width;
navigation.node_graph_width = width;
}
if let Some(value) = settings.get(session::network::PREVIEWING)
&& let Ok(previewing) = serde_json::from_value::<Previewing>(value.clone())
&& let Some(mut network) = interface.network_mut(network_path)
{
persistent.previewing = previewing;
network.set_previewing(previewing);
}
}
}
@@ -288,6 +296,7 @@ fn apply_network_entries_into_tree(metadata: &mut NodeNetworkMetadata, entries:
if let Some(reference) = entry.reference {
network_metadata.persistent_metadata.reference = Some(reference);
}
network_metadata.persistent_metadata.pinned_node_order = entry.pinned_order;
}
}
@@ -329,6 +338,10 @@ fn apply_entries_into_tree(network: &NodeNetwork, metadata: &mut NodeNetworkMeta
let persistent = &mut document_node_metadata.persistent_metadata;
// Pins the node to the identity storage holds for it, so the next conversion reuses it rather
// than re-deriving one from the node's location.
persistent.storage_id = Some(entry.storage_id.0);
if let Some(position) = entry.position {
persistent.node_type_metadata = position_to_runtime(position, entry.is_layer);
} else if entry.is_layer {
@@ -0,0 +1,140 @@
//! Every route to a mutable reference inside the two trees, gathered here so the whole mutable
//! surface can be read in one place.
//!
//! Two tiers of visibility carry the rule. `pub(super)` reaches only the rest of `store` and hands
//! out the raw trees, so an unrecorded write to the document cannot be spelled outside this module.
//! `pub(in super::super)` reaches the rest of the network interface, and hands out only state the
//! registry never holds: transient caches, and this peer's view state.
use super::*;
impl NodeNetworkInterface {
// ===== Raw trees, reachable only from the store =====
/// The root of the graph tree.
fn document_network_mut(&mut self) -> &mut NodeNetwork {
self.network.get_mut().network_mut()
}
/// The graph of the network at `network_path`, written only by the store's primitives.
pub(super) fn network_graph_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetwork> {
self.document_network_mut().nested_network_mut(network_path)
}
/// The metadata tree at `network_path`.
fn network_metadata_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetworkMetadata> {
self.network_metadata.get_mut().nested_metadata_mut(network_path)
}
/// The metadata of the node that encapsulates the network at `network_path`, or `None` for the
/// document network, which no node encapsulates.
pub(super) fn encapsulating_node_metadata_mut(&mut self, network_path: &[NodeId]) -> Option<&mut DocumentNodeMetadata> {
let mut encapsulating_path = network_path.to_vec();
let encapsulating_node_id = encapsulating_path.pop()?;
self.network_metadata_mut(&encapsulating_path)?.persistent_metadata.node_metadata.get_mut(&encapsulating_node_id)
}
/// Rewrites the whole graph in place, for a document arriving in an older shape than the current one.
///
/// Nothing is recorded: a migration produces the document the peer should have had rather than
/// changing the one they have.
pub(in super::super) fn migrate_graph(&mut self, migrate: impl FnOnce(&mut NodeNetwork)) {
migrate(self.document_network_mut());
}
// ===== Recorded writes =====
/// The persistent metadata of a network, or `None` if the network is missing.
pub(crate) fn network_mut<'a>(&'a mut self, network_path: &'a [NodeId]) -> Option<NetworkMut<'a>> {
let metadata = &mut self.network_metadata.get_mut().nested_metadata_mut(network_path)?.persistent_metadata;
Some(NetworkMut::new(metadata, &mut self.deltas, network_path))
}
/// Both halves of a node, or `None` if either is missing.
pub(crate) fn node_mut<'a>(&'a mut self, locator: NodeLocator<'a>) -> Option<NodeMut<'a>> {
let node = self.network.get_mut().network_mut().nested_network_mut(locator.network_path)?.nodes.get_mut(&locator.node_id)?;
let metadata = self
.network_metadata
.get_mut()
.nested_metadata_mut(locator.network_path)?
.persistent_metadata
.node_metadata
.get_mut(&locator.node_id)?;
Some(NodeMut::new(node, &mut metadata.persistent_metadata, &mut self.deltas, locator))
}
// ===== Unrecorded state, reachable from the whole network interface =====
/// The transient caches of a network, which are not part of the document and so record nothing.
pub(in super::super) fn network_transient_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetworkTransientMetadata> {
Some(&mut self.network_metadata_mut(network_path)?.transient_metadata)
}
/// The transient caches of one node.
pub(in super::super) fn node_transient_mut(&mut self, node_id: &NodeId, network_path: &[NodeId]) -> Option<&mut DocumentNodeTransientMetadata> {
let network_metadata = self.network_metadata_mut(network_path)?;
Some(&mut network_metadata.persistent_metadata.node_metadata.get_mut(node_id)?.transient_metadata)
}
/// The transient caches of the network that the network at `network_path` sits inside.
pub(in super::super) fn encapsulating_network_transient_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetworkTransientMetadata> {
let mut encapsulating_path = network_path.to_vec();
encapsulating_path.pop()?;
self.network_transient_mut(&encapsulating_path)
}
/// The selection undo and redo stacks. Per-peer state that is not recorded and does not reach storage.
pub(in super::super) fn selection_history_mut(&mut self, network_path: &[NodeId]) -> Option<SelectionHistoryMut<'_>> {
let persistent = &mut self.network_metadata_mut(network_path)?.persistent_metadata;
Some(SelectionHistoryMut {
undo: &mut persistent.selection_undo_history,
redo: &mut persistent.selection_redo_history,
})
}
/// Where the node graph is panned and zoomed to. This write is not recorded.
pub(in super::super) fn navigation_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NavigationMetadata> {
Some(&mut self.network_metadata_mut(network_path)?.persistent_metadata.navigation_metadata)
}
/// Visits every network at every nesting level with its view state, for restoring what the peer was
/// looking at onto an interface rebuilt from storage.
pub(in super::super) fn for_each_network_view_state_mut(&mut self, mut visit: impl FnMut(&[NodeId], NetworkViewStateMut)) {
let mut stack = vec![Vec::new()];
while let Some(network_path) = stack.pop() {
let Some(network_metadata) = self.network_metadata_mut(&network_path) else { continue };
let persistent = &mut network_metadata.persistent_metadata;
stack.extend(
persistent
.node_metadata
.iter()
.filter(|(_, node_metadata)| node_metadata.persistent_metadata.network_metadata.is_some())
.map(|(node_id, _)| [network_path.as_slice(), &[*node_id]].concat()),
);
visit(
&network_path,
NetworkViewStateMut {
navigation: &mut persistent.navigation_metadata,
previewing: &mut persistent.previewing,
selection: SelectionHistoryMut {
undo: &mut persistent.selection_undo_history,
redo: &mut persistent.selection_redo_history,
},
nodes: &persistent.node_metadata,
},
);
}
}
}
/// One network's per-peer view state: what a rebuild restores, and what the registry never records.
pub(crate) struct NetworkViewStateMut<'a> {
pub(crate) navigation: &'a mut NavigationMetadata,
pub(crate) previewing: &'a mut Previewing,
pub(crate) selection: SelectionHistoryMut<'a>,
/// The network's nodes, for a view field that may only name one that still exists.
pub(crate) nodes: &'a HashMap<NodeId, DocumentNodeMetadata>,
}
@@ -0,0 +1,521 @@
//! The recorded-write cursors: the only handles through which a node or a network is edited.
//!
//! Each setter writes its field and records a delta naming exactly what it wrote, so a write cannot
//! reach the document without also reaching the delta buffer.
use super::*;
use graph_craft::runtime_delta::RuntimeDelta;
/// A network's selection undo and redo stacks, borrowed together since every operation on one is
/// paired with one on the other.
pub(crate) struct SelectionHistoryMut<'a> {
pub(crate) undo: &'a mut VecDeque<SelectedNodes>,
pub(crate) redo: &'a mut VecDeque<SelectedNodes>,
}
/// Addresses one node: the network it lives in, and its ID within that network.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct NodeLocator<'a> {
pub node_id: NodeId,
pub network_path: &'a [NodeId],
}
impl<'a> NodeLocator<'a> {
pub fn new(node_id: NodeId, network_path: &'a [NodeId]) -> Self {
Self { node_id, network_path }
}
/// The path of the network this node owns, if it implements one.
pub fn owned_network_path(&self) -> Vec<NodeId> {
[self.network_path, &[self.node_id]].concat()
}
}
/// The graph and metadata halves of one node, resolved together so the two parallel trees are never
/// reached separately and cannot drift apart.
///
/// Holds the halves directly rather than the interface, so a write cannot reach back out to query the
/// graph or unload a cache: what a write invalidates is declared, not performed here.
pub(crate) struct NodeMut<'a> {
pub(super) node: &'a mut DocumentNode,
pub(super) metadata: &'a mut DocumentNodePersistentMetadata,
deltas: NodeDeltas<'a>,
}
impl<'a> NodeMut<'a> {
pub(super) fn new(node: &'a mut DocumentNode, metadata: &'a mut DocumentNodePersistentMetadata, deltas: &'a mut Vec<EditorDelta>, locator: NodeLocator<'a>) -> Self {
Self {
node,
metadata,
deltas: NodeDeltas { deltas, locator },
}
}
}
/// Where a node's writes record what they changed, carrying the node's address so each setter names
/// what it wrote without its caller repeating it.
struct NodeDeltas<'a> {
pub(super) deltas: &'a mut Vec<EditorDelta>,
locator: NodeLocator<'a>,
}
impl NodeDeltas<'_> {
fn metadata(&mut self, change: NodeMetadataChange) {
self.deltas.push(EditorDelta::NodeMetadata {
network_path: self.locator.network_path.to_vec(),
node_id: self.locator.node_id,
change,
});
}
/// Records a change to the network this node owns, addressed by the node's path extended with its ID.
fn owned_network(&mut self, change: NetworkMetadataChange) {
self.deltas.push(EditorDelta::NetworkMetadata {
network_path: self.locator.owned_network_path(),
change,
});
}
fn graph(&mut self, delta: RuntimeDelta) {
self.deltas.push(EditorDelta::Graph(delta));
}
fn input_metadata(&mut self, input_metadata: Vec<InputMetadata>) {
self.deltas.push(EditorDelta::NodeInputMetadata {
network_path: self.locator.network_path.to_vec(),
node_id: self.locator.node_id,
input_metadata,
});
}
fn snapshot(&mut self, metadata: Box<DocumentNodePersistentMetadata>) {
self.deltas.push(EditorDelta::NodeMetadataSnapshot {
network_path: self.locator.network_path.to_vec(),
node_id: self.locator.node_id,
metadata,
});
}
/// Records a snapshot for a node inside the network this one owns, for metadata that arrived with a
/// new nested network rather than describing this node.
fn snapshot_owned(&mut self, node_id: NodeId, metadata: Box<DocumentNodePersistentMetadata>) {
self.deltas.push(EditorDelta::NodeMetadataSnapshot {
network_path: self.locator.owned_network_path(),
node_id,
metadata,
});
}
fn network_path(&self) -> Vec<NodeId> {
self.locator.network_path.to_vec()
}
fn node_id(&self) -> NodeId {
self.locator.node_id
}
}
impl NodeMut<'_> {
/// Places the node at an absolute grid position, keeping whether it is displayed as a layer or a node.
pub(crate) fn set_absolute_position(&mut self, position: IVec2) -> bool {
let node_type = match self.metadata.node_type_metadata {
NodeTypePersistentMetadata::Layer(_) => NodeTypePersistentMetadata::layer(position),
NodeTypePersistentMetadata::Node(_) => NodeTypePersistentMetadata::node(position),
};
self.set_node_type(node_type)
}
/// Offsets a node that is absolutely positioned, leaving a stack or chain node where it is.
pub(crate) fn shift_absolute_position(&mut self, shift: IVec2) -> bool {
let shifted = match self.metadata.node_type_metadata {
NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
position: LayerPosition::Absolute(position),
}) => NodeTypePersistentMetadata::layer(position + shift),
NodeTypePersistentMetadata::Node(ref node) => match node.position {
NodePosition::Absolute(position) => NodeTypePersistentMetadata::node(position + shift),
NodePosition::Chain => return false,
},
NodeTypePersistentMetadata::Layer(_) => return false,
};
self.set_node_type(shifted)
}
/// Stacks a layer `y_offset` below the sibling it feeds. Nodes are never stacked.
pub(crate) fn set_stack_position(&mut self, y_offset: u32) -> bool {
if !self.metadata.is_layer() {
return false;
}
self.set_node_type(NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
position: LayerPosition::Stack(y_offset),
}))
}
/// Chains a node to the left of the layer it feeds. Layers are never chained.
pub(crate) fn set_chain_position(&mut self) -> bool {
if self.metadata.is_layer() {
return false;
}
self.set_node_type(NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Chain)))
}
/// Whether the node is displayed as a layer, which decides the kinds of position it can hold.
pub(crate) fn is_layer(&self) -> bool {
self.metadata.is_layer()
}
/// Whether the node is rendered, which the compiler reads to replace it with a passthrough.
pub(crate) fn set_visible(&mut self, visible: bool) -> bool {
let changed = self.node.visible != visible;
self.node.visible = visible;
if changed {
let delta = RuntimeDelta::SetVisibility {
network_path: self.deltas.network_path(),
node_id: self.deltas.node_id(),
visible,
};
self.deltas.graph(delta);
}
changed
}
/// The type of argument the node can be evaluated with.
pub(crate) fn set_call_argument(&mut self, call_argument: Type) -> bool {
let changed = self.node.call_argument != call_argument;
self.node.call_argument = call_argument;
if changed {
let delta = RuntimeDelta::SetCallArgument {
network_path: self.deltas.network_path(),
node_id: self.deltas.node_id(),
call_argument: self.node.call_argument.clone(),
};
self.deltas.graph(delta);
}
changed
}
/// The Extract and Inject annotations the node declares for the Context.
pub(crate) fn set_context_features(&mut self, context_features: ContextDependencies) -> bool {
let changed = self.node.context_features != context_features;
self.node.context_features = context_features;
if changed {
let delta = RuntimeDelta::SetContextFeatures {
network_path: self.deltas.network_path(),
node_id: self.deltas.node_id(),
context_features: self.node.context_features,
};
self.deltas.graph(delta);
}
changed
}
/// The user-chosen name for this instance, empty when it has none.
pub(crate) fn set_display_name(&mut self, display_name: String) -> bool {
let changed = self.metadata.display_name != display_name;
self.metadata.display_name = display_name;
if changed {
let change = NodeMetadataChange::DisplayName(self.metadata.display_name.clone());
self.deltas.metadata(change);
}
changed
}
pub(crate) fn set_locked(&mut self, locked: bool) -> bool {
let changed = self.metadata.locked != locked;
self.metadata.locked = locked;
if changed {
self.deltas.metadata(NodeMetadataChange::Locked(locked));
}
changed
}
pub(crate) fn set_pinned(&mut self, pinned: bool) -> bool {
let changed = self.metadata.pinned != pinned;
self.metadata.pinned = pinned;
if changed {
self.deltas.metadata(NodeMetadataChange::Pinned(pinned));
}
changed
}
/// Whether the node is displayed as a layer or a node, together with its position.
pub(crate) fn set_node_type(&mut self, node_type: NodeTypePersistentMetadata) -> bool {
let changed = self.metadata.node_type_metadata != node_type;
self.metadata.node_type_metadata = node_type;
if changed {
let change = NodeMetadataChange::NodeType(self.metadata.node_type_metadata.clone());
self.deltas.metadata(change);
}
changed
}
/// The definition this node's nested network was instantiated from. Only network nodes carry one.
pub(crate) fn set_reference(&mut self, reference: Option<String>) -> bool {
let Some(network_metadata) = self.metadata.network_metadata.as_mut() else { return false };
let changed = network_metadata.persistent_metadata.reference != reference;
network_metadata.persistent_metadata.reference = reference;
if changed {
let change = NetworkMetadataChange::Reference(network_metadata.persistent_metadata.reference.clone());
self.deltas.owned_network(change);
}
changed
}
pub(crate) fn set_input_name(&mut self, input_index: usize, input_name: String) -> bool {
let Some(input_metadata) = self.metadata.input_metadata.get_mut(input_index) else { return false };
let changed = input_metadata.persistent_metadata.input_name != input_name;
input_metadata.persistent_metadata.input_name = input_name;
if changed {
let change = NodeMetadataChange::InputName {
index: input_index,
name: input_metadata.persistent_metadata.input_name.clone(),
};
self.deltas.metadata(change);
}
changed
}
/// The identifier of the widget override the properties panel uses for this input, or `None` for the
/// widget generated from its type.
pub(crate) fn set_widget_override(&mut self, input_index: usize, widget_override: Option<String>) -> bool {
let Some(input_metadata) = self.metadata.input_metadata.get_mut(input_index) else { return false };
let changed = input_metadata.persistent_metadata.widget_override != widget_override;
input_metadata.persistent_metadata.widget_override = widget_override;
if changed {
let change = NodeMetadataChange::WidgetOverride {
index: input_index,
widget_override: input_metadata.persistent_metadata.widget_override.clone(),
};
self.deltas.metadata(change);
}
changed
}
pub(crate) fn set_output_name(&mut self, output_index: usize, output_name: String) -> bool {
let Some(existing) = self.metadata.output_names.get_mut(output_index) else { return false };
let changed = *existing != output_name;
*existing = output_name;
if changed {
let change = NodeMetadataChange::OutputNames(self.metadata.output_names.clone());
self.deltas.metadata(change);
}
changed
}
/// The encapsulating node's names for every one of the network's exports, replaced together since
/// they are stored as one array.
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
pub(crate) fn set_output_names(&mut self, output_names: Vec<String>) -> bool {
let changed = self.metadata.output_names != output_names;
self.metadata.output_names = output_names;
if changed {
let change = NodeMetadataChange::OutputNames(self.metadata.output_names.clone());
self.deltas.metadata(change);
}
changed
}
/// The metadata array the node's inputs index, one entry per input.
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
pub(crate) fn input_metadata(&self) -> &[InputMetadata] {
&self.metadata.input_metadata
}
/// Grows `output_names` to one entry per export, which an older document may be missing.
pub(crate) fn resize_output_names(&mut self, number_of_exports: usize) {
if self.metadata.output_names.len() == number_of_exports {
return;
}
self.metadata.output_names.resize(number_of_exports, String::new());
let change = NodeMetadataChange::OutputNames(self.metadata.output_names.clone());
self.deltas.metadata(change);
}
/// Appends input metadata until there is one entry per input, filling from `defaults` where it has an
/// entry for the added index. Restores the parallel-array invariant for an older document.
pub(crate) fn pad_input_metadata(&mut self, number_of_inputs: usize, defaults: impl Fn(usize) -> Option<InputMetadata>) {
if self.metadata.input_metadata.len() >= number_of_inputs {
return;
}
for added_input_index in self.metadata.input_metadata.len()..number_of_inputs {
self.metadata.input_metadata.push(defaults(added_input_index).unwrap_or_default());
}
self.emit_input_metadata();
}
/// Swaps in a new implementation together with the nested network metadata that belongs to it.
///
/// Replaces the node and everything nested under it, since the nested network goes with the
/// implementation.
pub(crate) fn replace_implementation(&mut self, implementation: DocumentNodeImplementation, network_metadata: Option<NodeNetworkMetadata>) {
self.node.implementation = implementation;
self.metadata.network_metadata = network_metadata;
let delta = RuntimeDelta::ReplaceNode {
network_path: self.deltas.network_path(),
node_id: self.deltas.node_id(),
node: Box::new(self.node.clone()),
};
self.deltas.graph(delta);
// Only what the new implementation brought with it. A swap leaves the node's own metadata alone,
// and restating it would assert values this peer did not write, clobbering a concurrent rename.
let owned: Vec<_> = self
.metadata
.network_metadata
.iter()
.flat_map(|network_metadata| &network_metadata.persistent_metadata.node_metadata)
.map(|(child_id, child)| (*child_id, Box::new(child.persistent_metadata.clone())))
.collect();
for (child_id, metadata) in owned {
self.deltas.snapshot_owned(child_id, metadata);
}
}
/// Replaces the node's whole persistent metadata, including that of everything nested under it,
/// which is the write a metadata snapshot describes.
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
pub(crate) fn replace_metadata(&mut self, metadata: DocumentNodePersistentMetadata) {
*self.metadata = metadata;
let snapshot = Box::new(self.metadata.clone());
self.deltas.snapshot(snapshot);
}
/// Replaces the metadata array the node's inputs index, leaving the inputs themselves alone.
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
pub(crate) fn set_input_metadata(&mut self, input_metadata: Vec<InputMetadata>) {
self.metadata.input_metadata = input_metadata;
self.emit_input_metadata();
}
/// Swaps in new inputs together with their metadata, returning the inputs replaced.
pub(crate) fn replace_inputs(&mut self, inputs: Vec<NodeInput>, input_metadata: Vec<InputMetadata>) -> Vec<NodeInput> {
self.metadata.input_metadata = input_metadata;
let previous = std::mem::replace(&mut self.node.inputs, inputs);
self.emit_inputs();
previous
}
/// Records the node's input list and the metadata array indexed by it, which change together
/// whenever the number or order of slots does.
pub(super) fn emit_inputs(&mut self) {
let delta = RuntimeDelta::SetInputs {
network_path: self.deltas.network_path(),
node_id: self.deltas.node_id(),
inputs: self.node.inputs.clone(),
};
self.deltas.graph(delta);
self.emit_input_metadata();
}
fn emit_input_metadata(&mut self) {
let input_metadata = self.metadata.input_metadata.clone();
self.deltas.input_metadata(input_metadata);
}
}
/// The persistent metadata of one network, resolved once so a run of writes walks the tree a single time.
///
/// Metadata only: the graph half of a network is its export slots, which are addressed through
/// [`NodeNetworkInterface::set_input_slot`] like any other input.
pub(crate) struct NetworkMut<'a> {
pub(super) metadata: &'a mut NodeNetworkPersistentMetadata,
pub(super) deltas: &'a mut Vec<EditorDelta>,
pub(super) network_path: &'a [NodeId],
}
impl<'a> NetworkMut<'a> {
pub(super) fn new(metadata: &'a mut NodeNetworkPersistentMetadata, deltas: &'a mut Vec<EditorDelta>, network_path: &'a [NodeId]) -> Self {
Self { metadata, deltas, network_path }
}
}
impl NetworkMut<'_> {
/// Which node the network renders instead of its export. This write is not recorded.
pub(crate) fn set_previewing(&mut self, previewing: Previewing) -> bool {
let changed = self.metadata.previewing != previewing;
self.metadata.previewing = previewing;
changed
}
/// The definition this network was instantiated from.
pub(crate) fn set_reference(&mut self, reference: Option<String>) -> bool {
let changed = self.metadata.reference != reference;
self.metadata.reference = reference;
if changed {
let change = NetworkMetadataChange::Reference(self.metadata.reference.clone());
self.emit(change);
}
changed
}
/// The display order of pinned nodes in the Properties panel.
pub(crate) fn set_pinned_order(&mut self, pinned_node_order: Vec<NodeId>) -> bool {
let changed = self.metadata.pinned_node_order != pinned_node_order;
self.metadata.pinned_node_order = pinned_node_order;
if changed {
let change = NetworkMetadataChange::PinnedOrder(self.metadata.pinned_node_order.clone());
self.emit(change);
}
changed
}
/// Appends a newly pinned node to the display order, or drops one that is no longer pinned.
pub(crate) fn record_pinned(&mut self, node_id: NodeId, pinned: bool) -> bool {
let order = &mut self.metadata.pinned_node_order;
let changed = match pinned {
true if !order.contains(&node_id) => {
order.push(node_id);
true
}
true => false,
false => {
let before = order.len();
order.retain(|id| *id != node_id);
order.len() != before
}
};
if changed {
let change = NetworkMetadataChange::PinnedOrder(self.metadata.pinned_node_order.clone());
self.emit(change);
}
changed
}
/// Drops every node the order names that is no longer in the network.
pub(crate) fn retain_pinned(&mut self, surviving: impl Fn(&NodeId) -> bool) -> bool {
let before = self.metadata.pinned_node_order.len();
self.metadata.pinned_node_order.retain(&surviving);
let changed = self.metadata.pinned_node_order.len() != before;
if changed {
let change = NetworkMetadataChange::PinnedOrder(self.metadata.pinned_node_order.clone());
self.emit(change);
}
changed
}
fn emit(&mut self, change: NetworkMetadataChange) {
self.deltas.push(EditorDelta::NetworkMetadata {
network_path: self.network_path.to_vec(),
change,
});
}
/// The transform from node graph space to viewport space.
pub(crate) fn set_navigation_transform(&mut self, transform: DAffine2) -> bool {
let changed = self.metadata.navigation_metadata.node_graph_to_viewport != transform;
self.metadata.navigation_metadata.node_graph_to_viewport = transform;
changed
}
/// The width of the node graph in viewport space.
pub(crate) fn set_navigation_width(&mut self, node_graph_width: f64) -> bool {
let changed = self.metadata.navigation_metadata.node_graph_width != node_graph_width;
self.metadata.navigation_metadata.node_graph_width = node_graph_width;
changed
}
}
@@ -0,0 +1,365 @@
use super::*;
use graph_craft::runtime_delta::RuntimeDelta;
mod accessors;
mod cursor;
pub use cursor::NodeLocator;
pub(crate) use cursor::{NetworkMut, NodeMut, SelectionHistoryMut};
/// Holds one of the two parallel trees so that only this module can write it.
///
/// `Deref` passes reads straight through, so a query reads the tree as though the interface held it
/// directly. There is deliberately no `DerefMut` and the field is private to this module, so the only
/// route to a `&mut` is the store API below, and a write that skips it does not compile rather than
/// silently going unrecorded.
///
/// Transparent to serde, so wrapping a field does not change the document format.
#[derive(Debug, Default, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
pub struct Guarded<T>(T);
impl<T> std::ops::Deref for Guarded<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
impl<T> Guarded<T> {
fn new(value: T) -> Self {
Self(value)
}
fn get_mut(&mut self) -> &mut T {
&mut self.0
}
}
// The store: the only writer of the node graph and its parallel metadata tree, keeping the two halves
// in step by construction.
impl NodeNetworkInterface {
/// Builds an interface around a freshly-assembled pair of trees, for a document arriving from
/// storage or from an older format rather than being edited into existence. Nothing is recorded: the
/// trees are the document, not a set of changes to it.
pub(super) fn from_trees(network: NodeNetwork, network_metadata: NodeNetworkMetadata) -> Self {
Self {
network: Guarded::new(MemoNetwork::new(network)),
network_metadata: Guarded::new(network_metadata),
..Default::default()
}
}
/// Inserts an input and its metadata at `index`, clamped to the end. Returns whether the node was found.
pub(crate) fn insert_input_slot(&mut self, locator: NodeLocator, index: usize, input: NodeInput, metadata: InputMetadata) -> bool {
let Some(mut node) = self.node_mut(locator) else {
log::error!("Could not get node {} in insert_input_slot", locator.node_id);
return false;
};
let index = index.min(node.node.inputs.len());
node.node.inputs.insert(index, input);
node.metadata.input_metadata.insert(index.min(node.metadata.input_metadata.len()), metadata);
node.emit_inputs();
true
}
/// Removes the input at `index` together with its metadata, returning both.
pub(crate) fn remove_input_slot(&mut self, locator: NodeLocator, index: usize) -> Option<(NodeInput, InputMetadata)> {
let Some(mut node) = self.node_mut(locator) else {
log::error!("Could not get node {} in remove_input_slot", locator.node_id);
return None;
};
if index >= node.node.inputs.len() {
log::error!("Input index {index} out of bounds in remove_input_slot for node {}", locator.node_id);
return None;
}
let input = node.node.inputs.remove(index);
let metadata = (index < node.metadata.input_metadata.len()).then(|| node.metadata.input_metadata.remove(index));
node.emit_inputs();
Some((input, metadata.unwrap_or_default()))
}
/// Moves the input at `from` to `to`, carrying its metadata with it.
///
/// Records the removal and the insertion separately, so the list is briefly one slot short. Both
/// land in the same batch, where the second supersedes the first.
pub(crate) fn move_input_slot(&mut self, locator: NodeLocator, from: usize, to: usize) -> bool {
let Some((input, metadata)) = self.remove_input_slot(locator, from) else { return false };
self.insert_input_slot(locator, to, input, metadata)
}
/// Inserts an export at `index`, clamped to the end, along with the name the encapsulating node shows
/// for it. The document network has no encapsulating node, so it carries no name.
pub(crate) fn insert_export_slot(&mut self, network_path: &[NodeId], index: usize, export: NodeInput, output_name: String) -> bool {
let Some(network) = self.network_graph_mut(network_path) else {
log::error!("Could not get nested network in insert_export_slot");
return false;
};
let index = index.min(network.exports.len());
network.exports.insert(index, export);
if let Some(encapsulating_node_metadata) = self.encapsulating_node_metadata_mut(network_path) {
let output_names = &mut encapsulating_node_metadata.persistent_metadata.output_names;
output_names.insert(index.min(output_names.len()), output_name);
}
self.emit_exports_from(network_path, index, None);
true
}
/// Removes the export at `index` together with the encapsulating node's name for it.
pub(crate) fn remove_export_slot(&mut self, network_path: &[NodeId], index: usize) -> Option<NodeInput> {
let Some(network) = self.network_graph_mut(network_path) else {
log::error!("Could not get nested network in remove_export_slot");
return None;
};
if index >= network.exports.len() {
log::error!("Export index {index} out of bounds in remove_export_slot");
return None;
}
let export = network.exports.remove(index);
// The list shrank by one, so what was the last index now has no slot and has to be cleared.
let vacated = network.exports.len();
if let Some(encapsulating_node_metadata) = self.encapsulating_node_metadata_mut(network_path) {
let output_names = &mut encapsulating_node_metadata.persistent_metadata.output_names;
if index < output_names.len() {
output_names.remove(index);
}
}
self.emit_exports_from(network_path, index, Some(vacated));
Some(export)
}
/// Records every export slot from `index` on, plus a clear for `vacated` when the list shrank.
///
/// Export slots are addressed by index, so inserting or removing one changes the meaning of every
/// later slot and each has to be restated. The encapsulating node's names for them ride along as one
/// whole-array metadata write.
fn emit_exports_from(&mut self, network_path: &[NodeId], index: usize, vacated: Option<usize>) {
let Some(network) = self.network.network().nested_network(network_path) else { return };
let exports: Vec<_> = network.exports.iter().skip(index).cloned().collect();
for (offset, export) in exports.into_iter().enumerate() {
self.deltas.push(EditorDelta::Graph(RuntimeDelta::SetExport {
network_path: network_path.to_vec(),
export_index: index + offset,
input: Some(export),
}));
}
if let Some(vacated) = vacated {
self.deltas.push(EditorDelta::Graph(RuntimeDelta::SetExport {
network_path: network_path.to_vec(),
export_index: vacated,
input: None,
}));
}
let Some((&node_id, parent_path)) = network_path.split_last() else { return };
let Some(metadata) = self.encapsulating_node_metadata(network_path) else { return };
let change = NodeMetadataChange::OutputNames(metadata.persistent_metadata.output_names.clone());
self.deltas.push(EditorDelta::NodeMetadata {
network_path: parent_path.to_vec(),
node_id,
change,
});
}
/// Moves the export at `from` to `to`, carrying the encapsulating node's name for it.
pub(crate) fn move_export_slot(&mut self, network_path: &[NodeId], from: usize, to: usize) -> bool {
let name = self
.encapsulating_node_metadata(network_path)
.and_then(|metadata| metadata.persistent_metadata.output_names.get(from).cloned())
.unwrap_or_default();
let Some(export) = self.remove_export_slot(network_path, from) else { return false };
self.insert_export_slot(network_path, to, export, name)
}
/// Writes the input at `connector`, returning the input it replaced.
pub(crate) fn set_input_slot(&mut self, connector: &InputConnector, network_path: &[NodeId], input: NodeInput) -> Option<NodeInput> {
let Some(network) = self.network_graph_mut(network_path) else {
log::error!("Could not get nested network in set_input_slot");
return None;
};
let Some(slot) = input_slot_mut(network, connector) else {
log::error!("Could not get input {connector:?} in set_input_slot");
return None;
};
if *slot == input {
return Some(input);
}
let previous = std::mem::replace(slot, input.clone());
self.deltas.push(input_write_delta(connector, network_path, input));
Some(previous)
}
/// Edits the value at `connector` in place, recording the value the edit leaves behind.
///
/// For a change expressed as an operation on the existing value rather than as a replacement of it,
/// which avoids copying the value out and back. The recorded delta still carries the whole result,
/// since the storage op is a whole-value write.
pub(crate) fn edit_input_value(&mut self, connector: &InputConnector, network_path: &[NodeId], edit: impl FnOnce(&mut TaggedValue) -> bool) -> bool {
let Some(network) = self.network_graph_mut(network_path) else {
log::error!("Could not get nested network in edit_input_value");
return false;
};
let Some(slot) = input_slot_mut(network, connector) else {
log::error!("Could not get input {connector:?} in edit_input_value");
return false;
};
let Some(mut value) = slot.as_value_mut() else {
log::error!("Input {connector:?} is not a value in edit_input_value");
return false;
};
// The edit reports whether it changed anything, rather than this comparing before and after.
// Comparing the values would mean copying one out, which is the copy this method exists to avoid,
// and comparing their memoized hashes would let a collision silently drop a real edit.
let changed = edit(&mut value);
drop(value);
// An edit that changes nothing still carries a timestamp, which would let it supersede a concurrent
// peer's real edit to the same input.
if !changed {
return true;
}
let input = slot.clone();
self.deltas.push(input_write_delta(connector, network_path, input));
true
}
/// Inserts a node and its metadata, returning the entry it replaced.
pub(crate) fn insert_node_entry(&mut self, locator: NodeLocator, template: NodeTemplate) -> Option<NodeTemplate> {
if !self.network_pair_exists(locator.network_path) {
log::error!("Could not get network {:?} in insert_node_entry", locator.network_path);
return None;
}
let (document_node, persistent_metadata) = template.into_parts();
let node = Box::new(document_node.clone());
let metadata = Box::new(persistent_metadata.clone());
let previous_node = self
.network
.get_mut()
.network_mut()
.nested_network_mut(locator.network_path)?
.nodes
.insert(locator.node_id, document_node);
let previous_metadata = self.network_metadata.get_mut().nested_metadata_mut(locator.network_path)?.persistent_metadata.node_metadata.insert(
locator.node_id,
DocumentNodeMetadata {
persistent_metadata,
transient_metadata: DocumentNodeTransientMetadata::default(),
},
);
// Overwriting an existing entry replaces the node and everything nested under it, which is what
// distinguishes the two from the storage side.
let network_path = locator.network_path.to_vec();
let node_id = locator.node_id;
self.deltas.push(EditorDelta::Graph(match previous_node.is_some() {
true => RuntimeDelta::ReplaceNode {
network_path: network_path.clone(),
node_id,
node,
},
false => RuntimeDelta::AddNode {
network_path: network_path.clone(),
node_id,
node,
},
}));
self.deltas.push(EditorDelta::NodeMetadataSnapshot { network_path, node_id, metadata });
previous_node
.zip(previous_metadata)
.map(|(node, metadata)| NodeTemplate::from_parts(node, metadata.persistent_metadata))
}
/// Removes a node and its metadata, returning them joined as a template.
pub(crate) fn remove_node_entry(&mut self, locator: NodeLocator) -> Option<NodeTemplate> {
if !self.network_pair_exists(locator.network_path) {
log::error!("Could not get network {:?} in remove_node_entry", locator.network_path);
return None;
}
let node = self.network.get_mut().network_mut().nested_network_mut(locator.network_path)?.nodes.remove(&locator.node_id);
let metadata = self
.network_metadata
.get_mut()
.nested_metadata_mut(locator.network_path)?
.persistent_metadata
.node_metadata
.remove(&locator.node_id);
if node.is_some() {
self.deltas.push(EditorDelta::Graph(RuntimeDelta::RemoveNode {
network_path: locator.network_path.to_vec(),
node_id: locator.node_id,
}));
}
node.zip(metadata).map(|(node, metadata)| NodeTemplate::from_parts(node, metadata.persistent_metadata))
}
/// Whether both trees hold the network, checked before a write so a missing one cannot leave the two
/// halves out of step.
fn network_pair_exists(&self, network_path: &[NodeId]) -> bool {
self.network.network().nested_network(network_path).is_some() && self.network_metadata.nested_metadata(network_path).is_some()
}
/// Takes what the writes since the last drain changed, in write order, leaving the buffer empty.
pub(crate) fn take_deltas(&mut self) -> Vec<EditorDelta> {
std::mem::take(&mut self.deltas)
}
/// Drops what the writes since the last drain changed, for writes that are not edits to the document.
pub(crate) fn discard_deltas(&mut self) {
self.deltas.clear();
}
/// Drops the network's link to the definition it was instantiated from, which no longer describes it
/// once its signature is edited.
pub(crate) fn clear_encapsulating_reference(&mut self, network_path: &[NodeId]) {
if let Some(mut network) = self.network_mut(network_path) {
network.set_reference(None);
}
}
}
/// The slot `connector` addresses, whether it is a node's input or one of the network's exports.
fn input_slot_mut<'a>(network: &'a mut NodeNetwork, connector: &InputConnector) -> Option<&'a mut NodeInput> {
match connector {
InputConnector::Node { node_id, input_index } => network.nodes.get_mut(node_id).and_then(|node| node.inputs.get_mut(*input_index)),
InputConnector::Export(export_index) => network.exports.get_mut(*export_index),
}
}
/// What a whole-value write to `connector` records, which is a different delta for an input than for
/// an export.
fn input_write_delta(connector: &InputConnector, network_path: &[NodeId], input: NodeInput) -> EditorDelta {
EditorDelta::Graph(match connector {
InputConnector::Node { node_id, input_index } => RuntimeDelta::SetInput {
network_path: network_path.to_vec(),
node_id: *node_id,
input_index: *input_index,
input,
},
InputConnector::Export(export_index) => RuntimeDelta::SetExport {
network_path: network_path.to_vec(),
export_index: *export_index,
input: Some(input),
},
})
}
@@ -103,6 +103,10 @@ pub struct NodeNetworkTemplate {
impl NodeTemplate {
/// Joins a [`DocumentNode`] and its persistent metadata into the unified template shape. Missing nested metadata is filled with defaults.
///
/// A template names no node, so the storage identity is dropped here and left unset by
/// [`Self::into_parts`]: a node inserted from a template is addressed by its location until storage
/// names it.
pub fn from_parts(document_node: DocumentNode, persistent_node_metadata: DocumentNodePersistentMetadata) -> Self {
let DocumentNode {
inputs,
@@ -114,6 +118,7 @@ impl NodeTemplate {
original_location: _,
} = document_node;
let DocumentNodePersistentMetadata {
storage_id: _,
display_name,
input_metadata,
output_names,
@@ -196,6 +201,7 @@ impl NodeTemplate {
original_location: Default::default(),
};
let persistent_node_metadata = DocumentNodePersistentMetadata {
storage_id: None,
display_name,
input_metadata,
output_names,
@@ -93,6 +93,9 @@ pub enum ImportOrExport {
pub const PRIMARY_INPUT_INDEX: usize = 0;
/// The secondary input (index 1) of a layer-shaped node: the horizontal wire from the left, carrying the node chain or child stack that the layer renders.
pub const LAYER_SECONDARY_INPUT_INDEX: usize = 1;
/// The height in grid cells of a node displayed as a layer, which is fixed regardless of its inputs.
pub const LAYER_GRID_HEIGHT: u32 = 2;
/// The primary output (index 0) of a node, which most nodes expose as their only output.
pub const PRIMARY_OUTPUT_INDEX: usize = 0;
@@ -442,6 +445,24 @@ impl<T> TransientCache<T> {
*self.0.borrow_mut() = None;
}
/// Computes and stores the value with `load` if it is not already loaded.
///
/// `load` runs with no borrow held, so it is free to read other cache slots.
pub(crate) fn ensure_loaded(&self, load: impl FnOnce() -> Option<T>) {
let already_loaded = self.0.borrow().is_some();
if already_loaded {
return;
}
let Some(value) = load() else { return };
self.store(value);
}
/// Runs `read` on the cached value, computing it with `load` first if it is not loaded.
pub(crate) fn with_loaded_or<R>(&self, load: impl FnOnce() -> Option<T>, read: impl FnOnce(&T) -> R) -> Option<R> {
self.ensure_loaded(load);
self.with_loaded(read)
}
/// Runs `read` on the cached value if it is loaded.
pub(crate) fn with_loaded<R>(&self, read: impl FnOnce(&T) -> R) -> Option<R> {
self.0.borrow().as_ref().map(read)
@@ -655,6 +676,11 @@ impl InputPersistentMetadata {
#[derive(Default, Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DocumentNodePersistentMetadata {
/// The identity storage holds for this node, pinned when the interface is built from a document so
/// a conversion back reuses it instead of re-deriving one. Absent for a node storage has not named,
/// which falls back to a hash of its location.
#[serde(default)]
pub storage_id: Option<u64>,
/// A name chosen by the user for this instance of the node. Empty indicates no given name, in which case the implementation name is displayed to the user in italics.
#[serde(default)]
pub display_name: String,
@@ -225,6 +225,22 @@ impl<'a, 'p> NetworkView<'a, 'p> {
Ok(self.node(node_id)?.inputs.iter().filter(|input| input.is_exposed()).count())
}
/// Input rows the node displays: every exposed input, plus the primary input, whose row is shown even when it is not exposed.
pub fn input_row_count(&self, node_id: &NodeId) -> Result<usize, NetworkError> {
Ok(self
.node(node_id)?
.inputs
.iter()
.enumerate()
.filter(|(input_index, input)| *input_index == 0 || input.is_exposed())
.count())
}
/// Grid rows the node body spans, which is the greater of its input rows and its output count.
pub fn displayed_row_count(&self, node_id: &NodeId) -> Result<usize, NetworkError> {
Ok(self.input_row_count(node_id)?.max(self.number_of_outputs(node_id)?).max(1))
}
pub fn number_of_outputs(&self, node_id: &NodeId) -> Result<usize, NetworkError> {
Ok(match self.implementation(node_id)? {
DocumentNodeImplementation::Network(nested_network) => nested_network.exports.len(),
@@ -32,7 +32,7 @@ const TEXT_REPLACEMENTS: &[(&str, &str)] = &[
"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>",
),
("graphene_core::transform::Footprint", "graphene_core::transform::Footprint"),
("\"OptionalF64\":", "\"F64\":"),
("\"OptionalF64\":", "\"Number\":"),
("\"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
@@ -339,10 +339,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphene_math_nodes::LogicalOrNode",
],
},
NodeReplacement {
node: graphene_std::math_nodes::math::IDENTIFIER,
aliases: &["graphene_math_nodes::MathNode", "graphene_core::ops::MathNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::max::IDENTIFIER,
aliases: &["graphene_math_nodes::MaxNode", "graphene_core::ops::MaxNode"],
@@ -420,12 +416,17 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
aliases: &["graphene_math_nodes::ToF64Node", "graphene_core::ops::ToF64Node", "math_nodes::ToF64Node", "math_nodes::AsF64Node"],
},
NodeReplacement {
node: graphene_std::math_nodes::as_u_32::IDENTIFIER,
aliases: &["graphene_math_nodes::ToU32Node", "graphene_core::ops::ToU32Node", "math_nodes::ToU32Node"],
},
NodeReplacement {
node: graphene_std::math_nodes::as_u_64::IDENTIFIER,
aliases: &["graphene_math_nodes::ToU64Node", "graphene_core::ops::ToU64Node", "math_nodes::ToU64Node"],
node: graphene_std::math_nodes::as_integer::IDENTIFIER,
aliases: &[
"graphene_math_nodes::ToU32Node",
"graphene_core::ops::ToU32Node",
"math_nodes::ToU32Node",
"math_nodes::AsU32Node",
"graphene_math_nodes::ToU64Node",
"graphene_core::ops::ToU64Node",
"math_nodes::ToU64Node",
"math_nodes::AsU64Node",
],
},
// 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.
@@ -1143,7 +1144,7 @@ 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();
document.network_interface.normalize_stored_types();
let network = document.network_interface.document_network().clone();
@@ -1204,8 +1205,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
if *old_inputs_count == 6 {
match old_inputs.get(2) {
Some(NodeInput::Value { tagged_value, exposed }) => {
if let TaggedValue::F64(radians) = *tagged_value.clone().into_inner() {
let degrees = NodeInput::value(TaggedValue::F64(radians.to_degrees()), *exposed);
if let TaggedValue::Number(radians) = *tagged_value.clone().into_inner() {
let degrees = NodeInput::value(TaggedValue::Number(radians.to_degrees()), *exposed);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 2), degrees, network_path);
}
}
@@ -1214,9 +1215,9 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
// (which represented radians in the legacy format) reaches the now-degrees Rotation input correctly.
if let Some(multiply_node) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::multiply::IDENTIFIER)) {
let mut multiply_template = multiply_node.default_node_template();
multiply_template.inputs[1] = NodeInput::value(TaggedValue::F64(180. / PI), false);
multiply_template.inputs[1] = NodeInput::value(TaggedValue::Number(180. / PI), false);
let multiply_node_id = NodeId::new();
if let Some(transform_position) = document.network_interface.position_from_downstream_node(node_id, network_path) {
if let Some(transform_position) = document.network_interface.position(node_id, network_path) {
let multiply_position = transform_position + IVec2::new(-7, 1);
document.network_interface.insert_node(multiply_node_id, multiply_template, network_path);
document.network_interface.shift_absolute_node_position(&multiply_node_id, multiply_position, network_path);
@@ -1264,6 +1265,132 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
}
}
// The old "Math" node evaluated an expression over "A" and "B". A lexable static expression not reading a wired `B` becomes "Math f(x)"
// with `A` as `x` and a constant `B` inlined. Anything else becomes "Extend" feeding "Math f(…)", which reads the pair as `a` and `b`.
let math_nodes: Vec<(NodeId, Vec<NodeId>, Vec<NodeInput>)> = document
.network_interface
.document_network()
.recursive_nodes()
.filter_map(|(node_id, node, path)| {
let DocumentNodeImplementation::ProtoNode(protonode_id) = &node.implementation else { return None };
let name = protonode_id.as_str().split('<').next().unwrap_or_default();
let is_old_math = matches!(name, "math_nodes::MathNode" | "graphene_math_nodes::MathNode" | "graphene_core::ops::MathNode");
(is_old_math && node.inputs.len() >= 3).then(|| (*node_id, path, node.inputs.clone()))
})
.collect();
for (node_id, network_path, old_inputs) in &math_nodes {
// Pre-load `outward_wires` so the chain-break check inside `set_input` resolves wires from cache, as in the Transform pass above
let _ = document.network_interface.outward_wires(network_path);
let (operand_a, expression, operand_b) = (&old_inputs[0], &old_inputs[1], &old_inputs[2]);
// Lex a static expression once, learning both whether it lexes at all and whether it references `B`
let static_expression = match expression.as_value() {
Some(TaggedValue::String(expression)) => Some(expression.clone()),
_ => None,
};
let mut references_b = false;
let lexable = static_expression
.as_deref()
.and_then(|source| {
math_parser::lexer::rename_identifiers(source, |name| {
references_b |= name.eq_ignore_ascii_case("b");
None
})
})
.is_some();
// The rewritten "Math f(x)" expression, or `None` when only the Extend + "Math f(…)" form can preserve the node's meaning
let inline_b_constant = match operand_b.as_value() {
Some(TaggedValue::Number(constant)) => Some(*constant),
_ => None,
};
let fx_expression = match &static_expression {
Some(source) if lexable && !references_b => math_parser::lexer::rename_identifiers(source, |name| name.eq_ignore_ascii_case("a").then(|| "x".to_string())),
Some(source) if lexable && let Some(constant) = inline_b_constant => math_parser::lexer::rename_identifiers(source, |name| {
if name.eq_ignore_ascii_case("a") {
Some("x".to_string())
} else if name.eq_ignore_ascii_case("b") {
Some(format!("({constant:?})"))
} else {
None
}
}),
_ => None,
};
if let Some(fx_expression) = fx_expression {
// "Math f(x)": forward the old `A` input and the rewritten expression; the old `B` input is dropped
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::math_fx::IDENTIFIER)) else {
continue;
};
let mut node_template = definition.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
if document.network_interface.replace_inputs(node_id, network_path, &mut node_template).is_none() {
continue;
}
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), operand_a.clone(), network_path);
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::String(fx_expression), false), network_path);
} else {
// "Extend" joins the two operands into the list "Math f(…)" reads; an unwired constant operand becomes a one-item list value
let as_list_input = |input: &NodeInput| match input.as_value() {
Some(TaggedValue::Number(value)) => NodeInput::value(TaggedValue::Numbers(vec![*value]), input.is_exposed()),
_ => input.clone(),
};
let Some(extend_definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::graphic::extend::IDENTIFIER)) else {
continue;
};
let extend_template = extend_definition.default_node_template();
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::math_f::IDENTIFIER)) else {
continue;
};
let mut node_template = definition.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
if document.network_interface.replace_inputs(node_id, network_path, &mut node_template).is_none() {
continue;
}
// Wire inputs cannot ride along on an inserted template, so the Extend node's operands are set after insertion
let extend_node_id = NodeId::new();
let math_position = document.network_interface.position(node_id, network_path);
document.network_interface.insert_node(extend_node_id, extend_template, network_path);
if let Some(math_position) = math_position {
document
.network_interface
.shift_absolute_node_position(&extend_node_id, math_position + IVec2::new(-7, 1), network_path);
}
document
.network_interface
.set_input(&InputConnector::node_at_index(extend_node_id, 0), as_list_input(operand_a), network_path);
document
.network_interface
.set_input(&InputConnector::node_at_index(extend_node_id, 1), as_list_input(operand_b), network_path);
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 0), NodeInput::node(extend_node_id, 0), network_path);
// A static expression is rewritten to the exact-lowercase positional spellings, escaping the old node's
// constants `e` and `i` behind the `\` prefix that always reaches the builtin; a wired or unlexable one forwards untouched
let positional_expression = match (&static_expression, lexable) {
(Some(source), true) => math_parser::lexer::rename_identifiers(source, |name| {
if name.eq_ignore_ascii_case("a") || name.eq_ignore_ascii_case("b") {
return Some(name.to_ascii_lowercase());
}
matches!(name, "e" | "i").then(|| format!("\\{name}"))
})
.map(|rewritten| NodeInput::value(TaggedValue::String(rewritten), false)),
_ => None,
};
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 1), positional_expression.unwrap_or_else(|| expression.clone()), network_path);
}
}
// Record which old text nodes are chain-positioned now, before `migrate_node`'s staged input-count migrations run, since those set
// the upstream chain to absolute; the split below re-chains exactly the nodes that were originally part of a layer chain.
let text_nodes_in_chain: std::collections::HashSet<NodeId> = document
@@ -1370,14 +1497,66 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
document.network_interface.shift_absolute_node_position(&converter_id, text_position + IVec2::new(7, 0), network_path);
}
}
// Parameters that historically accepted fractional numbers are now integers (the polygon and star "Sides", the index,
// shift amount, and slice bound parameters of the list, string, and regex nodes, the "Path is Closed" index, and the
// "Blend" count), so a stored F64 truncates as those slots' own casts and Floor node did, preserving what documents drew
let narrowed_integer_inputs: &[(DefinitionIdentifier, &[usize])] = &[
(DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::regular_polygon::IDENTIFIER), &[1]),
(DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::star::IDENTIFIER), &[1]),
(DefinitionIdentifier::ProtoNode(graphene_std::vector::index_points::IDENTIFIER), &[1]),
(DefinitionIdentifier::ProtoNode(graphene_std::graphic::item_at_index::IDENTIFIER), &[1]),
(DefinitionIdentifier::ProtoNode(graphene_std::graphic::remove_at_index::IDENTIFIER), &[1]),
(DefinitionIdentifier::ProtoNode(graphene_std::graphic::shift::IDENTIFIER), &[1]),
(DefinitionIdentifier::ProtoNode(graphene_std::graphic::list_indices::IDENTIFIER), &[1]),
(DefinitionIdentifier::ProtoNode(graphene_std::graphic::list_slice::IDENTIFIER), &[1, 2]),
(DefinitionIdentifier::ProtoNode(graphene_std::text_nodes::string_slice::IDENTIFIER), &[1, 2]),
(DefinitionIdentifier::ProtoNode(graphene_std::text_nodes::regex::regex_find::IDENTIFIER), &[2]),
(DefinitionIdentifier::Network("Regex Find".into()), &[2]),
(DefinitionIdentifier::ProtoNode(graphene_std::vector::path_is_closed::IDENTIFIER), &[1]),
(DefinitionIdentifier::Network("Blend".into()), &[1]),
];
let fractional_value_inputs: Vec<(NodeId, Vec<NodeId>, usize, i64, bool)> = document
.network_interface
.document_network()
.recursive_nodes()
.flat_map(|(node_id, node, path)| {
let Some(reference) = document.network_interface.reference(node_id, &path) else {
return Vec::new();
};
let Some((_, indices)) = narrowed_integer_inputs.iter().find(|(identifier, _)| reference == *identifier) else {
return Vec::new();
};
indices
.iter()
.filter_map(|&index| {
let NodeInput::Value { tagged_value, exposed } = node.inputs.get(index)? else { return None };
let TaggedValue::Number(value) = &**tagged_value else { return None };
Some((*node_id, path.clone(), index, *value as i64, *exposed))
})
.collect::<Vec<_>>()
})
.collect();
for (node_id, network_path, index, integer, exposed) in fractional_value_inputs {
document
.network_interface
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::value(TaggedValue::Integer(integer), exposed), &network_path);
}
// Bringing an old document up to date is not a set of edits on it, it is how the document arrives.
// The upgrades run through the ordinary mutators, so the store records them; dropping what they
// recorded leaves the opened document as the baseline rather than as a pile of changes to itself.
document.network_interface.discard_deltas();
document.require_whole_document_stage();
}
/// 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 lengths = match &*tagged_value.clone().into_inner() {
TaggedValue::F64Array(lengths) => lengths.clone(),
TaggedValue::F64(length) => vec![*length],
TaggedValue::Numbers(lengths) => lengths.clone(),
TaggedValue::Number(length) => vec![*length],
TaggedValue::String(text) => graphene_std::core_types::misc::parse_f64_list(text),
_ => return None,
};
@@ -1388,8 +1567,8 @@ fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> {
fn migrate_corner_radius_input(input: &NodeInput) -> Option<NodeInput> {
let NodeInput::Value { tagged_value, exposed } = input else { return None };
let values = match &*tagged_value.clone().into_inner() {
TaggedValue::F64Array(values) => values.clone(),
TaggedValue::F64(value) => vec![*value],
TaggedValue::Numbers(values) => values.clone(),
TaggedValue::Number(value) => vec![*value],
_ => return None,
};
Some(NodeInput::value(TaggedValue::BoxCorners(values), *exposed))
@@ -1425,6 +1604,29 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
}
// Rebuild the Blend subgraph that still floors its Count import, since the now-integer Count enters through As Number instead
if let DocumentNodeImplementation::Network(inner) = &node.implementation
&& document.network_interface.reference(node_id, network_path) == Some(DefinitionIdentifier::Network("Blend".into()))
&& inner.nodes.values().any(|n| {
matches!(&n.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::math_nodes::floor::IDENTIFIER)
&& n.inputs.iter().any(|input| matches!(input, NodeInput::Import { import_index: 1, .. }))
}) && let Some(node_definition) = resolve_network_node_type("Blend")
{
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
}
// Rebuild the Regex Find subgraph that still imports its Match Index as a decimal, since that index is now an integer
if let DocumentNodeImplementation::Network(inner) = &node.implementation
&& document.network_interface.reference(node_id, network_path) == Some(DefinitionIdentifier::Network("Regex Find".into()))
&& inner.nodes.values().any(|n| {
n.inputs
.iter()
.any(|input| matches!(input, NodeInput::Import { import_type, import_index: 2 } if *import_type == item!(f64)))
}) && let Some(node_definition) = resolve_network_node_type("Regex Find")
{
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
}
// Upgrade old nodes to use `Context` instead of `()` or `Footprint` as their call argument
if node.call_argument == graph_craft::concrete!(()) || node.call_argument == graph_craft::concrete!(graphene_std::transform::Footprint) {
document.network_interface.set_call_argument(node_id, network_path, graph_craft::concrete!(graphene_std::Context));
@@ -1435,6 +1637,20 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
let mut inputs_count = node.inputs.len();
// The expression nodes gained an output-type input, a type witness the Properties panel edits. A node from before it
// takes the definition's default choice, Number, which is the output type every such node had.
let expression_node_identifiers = [graphene_std::math_nodes::math_fx::IDENTIFIER, graphene_std::math_nodes::math_f::IDENTIFIER];
if expression_node_identifiers.iter().any(|identifier| reference == DefinitionIdentifier::ProtoNode(identifier.clone())) && inputs_count == 2 {
let definition = resolve_document_node_type(&reference)?;
let mut template = definition.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut template)?;
for (index, input) in old_inputs.into_iter().enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
}
inputs_count = 3;
}
// Split the legacy combined "Blending" node into a chain of separate Blend Mode, Opacity (now also covers fill), and Clip nodes.
// `NODE_REPLACEMENTS` rewrites the old `Blending` proto identifier (and its older aliases) to `blend_mode::IDENTIFIER`, so a leftover
// 5-input shape on a Blend Mode node identifies an old Blending node that still needs structural splitting. Sub-nodes whose values
@@ -1454,8 +1670,8 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
// A sub-node is kept if its input is exposed/wired (so the user can drive it from the graph) OR if its value differs from the default
let keep_blend_mode = blend_mode_input.is_exposed() || !matches!(blend_mode_input.as_value(), Some(TaggedValue::BlendMode(BlendMode::Normal)));
let keep_opacity = opacity_input.is_exposed() || !matches!(opacity_input.as_value(), Some(TaggedValue::F64(v)) if (*v - 100.).abs() < f64::EPSILON);
let keep_fill = fill_input.is_exposed() || !matches!(fill_input.as_value(), Some(TaggedValue::F64(v)) if (*v - 100.).abs() < f64::EPSILON);
let keep_opacity = opacity_input.is_exposed() || !matches!(opacity_input.as_value(), Some(TaggedValue::Number(v)) if (*v - 100.).abs() < f64::EPSILON);
let keep_fill = fill_input.is_exposed() || !matches!(fill_input.as_value(), Some(TaggedValue::Number(v)) if (*v - 100.).abs() < f64::EPSILON);
let keep_clip = clip_input.is_exposed() || !matches!(clip_input.as_value(), Some(TaggedValue::Bool(false)));
// Find the downstream connection so we can chain new nodes between this node and downstream
@@ -1601,7 +1817,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
.set_input(&InputConnector::node_at_index(*node_id, 3), NodeInput::value(TaggedValue::Bool(false), false), network_path);
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 4), NodeInput::value(TaggedValue::F64(100.), false), network_path);
.set_input(&InputConnector::node_at_index(*node_id, 4), NodeInput::value(TaggedValue::Number(100.), false), network_path);
inputs_count = 5;
}
@@ -1947,9 +2163,9 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut template)?;
// Line height and character spacing were hardcoded to 1 in the era before they became inputs
let hardcoded_to_one = || NodeInput::value(TaggedValue::F64(1.), false);
let hardcoded_to_one = || NodeInput::value(TaggedValue::Number(1.), false);
// Zero is how an absent `Option<f64>` maximum reads to the split below
let unset_maximum = || NodeInput::value(TaggedValue::F64(0.), false);
let unset_maximum = || NodeInput::value(TaggedValue::Number(0.), false);
let upgraded_inputs = [
old_inputs[0].clone(),
@@ -1963,7 +2179,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
old_inputs
.get(8)
.cloned()
.unwrap_or_else(|| NodeInput::value(TaggedValue::F64(TypesettingConfig::default().letter_tilt), false)),
.unwrap_or_else(|| NodeInput::value(TaggedValue::Number(TypesettingConfig::default().letter_tilt), false)),
NodeInput::value(TaggedValue::TextAlign(TextAlign::default()), false),
old_inputs.get(9).cloned().unwrap_or_else(|| NodeInput::value(TaggedValue::Bool(false), false)),
];
@@ -1990,7 +2206,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
// The old `Option<f64>` maximum becomes a bool plus a value, with zero standing in for the absent option.
// A wired maximum has no value to read, so it keeps its connection and counts as present.
let split_maximum = |input: &NodeInput| match input.as_value() {
Some(&TaggedValue::F64(maximum)) => (maximum != 0., NodeInput::value(TaggedValue::F64(if maximum == 0. { 100. } else { maximum }), false)),
Some(&TaggedValue::Number(maximum)) => (maximum != 0., NodeInput::value(TaggedValue::Number(if maximum == 0. { 100. } else { maximum }), false)),
_ => (true, input.clone()),
};
@@ -2113,7 +2329,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
);
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 2), NodeInput::value(TaggedValue::F64(old_offset), false), network_path);
.set_input(&InputConnector::node_at_index(*node_id, 2), NodeInput::value(TaggedValue::Number(old_offset), false), network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 3), old_inputs[2].clone(), network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 4), old_inputs[3].clone(), network_path);
}
@@ -2246,18 +2462,18 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
let mut node_template = resolve_document_node_type(&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)?;
let output_level = |index: usize, default: f32| match old_inputs.get(index).and_then(|input| input.as_value()) {
Some(TaggedValue::F32(percent)) => percent / 100.,
let output_level = |index: usize, default: f64| match old_inputs.get(index).and_then(|input| input.as_value()) {
Some(TaggedValue::Number(percent)) => percent / 100.,
_ => default,
};
let (output_minimums, output_maximums) = (output_level(4, 0.), output_level(5, 1.));
for (index, input) in old_inputs.iter().take(6).enumerate() {
let input = match (index, input.as_value()) {
(2, Some(TaggedValue::F32(percent))) => {
(2, Some(TaggedValue::Number(percent))) => {
// The old node's midtones-to-gamma mapping, from https://stackoverflow.com/questions/39510072/algorithm-for-adjustment-of-image-levels
let midtones = output_minimums + (output_maximums - output_minimums) * percent / 100.;
let gamma = if midtones < 0.5 { 1. + 9. * (1. - midtones * 2.) } else { ((1. - midtones) * 2.).max(0.01) };
NodeInput::value(TaggedValue::F32(gamma.clamp(0.01, 9.99)), input.is_exposed())
NodeInput::value(TaggedValue::Number(gamma.clamp(0.01, 9.99)), input.is_exposed())
}
_ => input.clone(),
};
@@ -2312,7 +2528,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::F64(0.), false), network_path);
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Number(0.), false), network_path);
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 2), NodeInput::value(TaggedValue::Bool(false), false), network_path);
@@ -2367,7 +2583,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
let new_spacing_value = NodeInput::value(TaggedValue::PointSpacingType(graphene_std::vector::misc::PointSpacingType::Separation), false);
let new_quantity_value = NodeInput::value(TaggedValue::U32(100), false);
let new_quantity_value = NodeInput::value(TaggedValue::Integer(100), false);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), new_spacing_value, network_path);
@@ -2386,9 +2602,9 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
.input_from_connector(&InputConnector::Node { node_id: *node_id, input_index: 3 }, network_path)?;
if let NodeInput::Value { tagged_value, exposed } = quantity_value
&& let TaggedValue::F64(value) = **tagged_value
&& let TaggedValue::Number(value) = **tagged_value
{
let new_quantity_value = NodeInput::value(TaggedValue::U32(value as u32), *exposed);
let new_quantity_value = NodeInput::value(TaggedValue::Integer(value as i64), *exposed);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 3), new_quantity_value, network_path);
}
}
@@ -2402,12 +2618,12 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut new_node_template)?;
// The two six-input layouts differ only in where the DVec2 "angles" and the u32 "columns"/"rows" sit:
// Legacy: [primary, grid_type, spacing, angles (DVec2), columns (u32), rows (u32)]
// Modern: [primary, grid_type, spacing, columns (u32), rows (u32), angles (DVec2)]
// So a DVec2 "angles" at index 3, or a u32 "rows" at index 5, marks the legacy order. Checking both slots classifies
// Legacy: [primary, grid_type, spacing, angles (DVec2), columns (int), rows (int)]
// Modern: [primary, grid_type, spacing, columns (int), rows (int), angles (DVec2)]
// So a DVec2 "angles" at index 3, or anything but angles at index 5, marks the legacy order. Checking both slots classifies
// correctly even when one of them is a wired or imported connection rather than a literal value.
let index_3_is_angles = matches!(old_inputs.get(3), Some(NodeInput::Value { tagged_value, .. }) if matches!(**tagged_value, TaggedValue::DVec2(_)));
let index_5_is_rows = matches!(old_inputs.get(5), Some(NodeInput::Value { tagged_value, .. }) if matches!(**tagged_value, TaggedValue::U32(_)));
let index_5_is_rows = matches!(old_inputs.get(5), Some(NodeInput::Value { tagged_value, .. }) if !matches!(**tagged_value, TaggedValue::DVec2(_)));
let legacy_angles_layout = index_3_is_angles || index_5_is_rows;
if legacy_angles_layout {
@@ -2436,7 +2652,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
node_path.push(*node_id);
document.network_interface.add_import(TaggedValue::None, false, 0, "Primary", "", &node_path);
document.network_interface.add_import(TaggedValue::U32(0), false, 1, "Loop Level", "TODO", &node_path);
document.network_interface.add_import(TaggedValue::Integer(0), false, 1, "Loop Level", "TODO", &node_path);
}
// Drop the placeholder primary input the "Read Vector" node used to carry, since it reads its value from the context
@@ -2483,7 +2699,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
.set_input(&InputConnector::node_at_index(*node_id, 0), NodeInput::value(TaggedValue::None, false), network_path);
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::F64(1.), false), network_path);
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Number(1.), false), network_path);
}
// Upgrade the "Read Position" node to add the "Loop Level" input
@@ -2497,7 +2713,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
.set_input(&InputConnector::node_at_index(*node_id, 0), NodeInput::value(TaggedValue::None, false), network_path);
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::U32(0), false), network_path);
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Integer(0), false), network_path);
}
// Migrate from the old source/target v1 "Morph" node to the new `List<Vector>`-based v2 "Morph" node.
@@ -2527,7 +2743,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
let merge_node_id = NodeId::new();
// Decide on the placement position of the new Merge node
let Some(morph_position) = document.network_interface.position_from_downstream_node(node_id, network_path) else {
let Some(morph_position) = document.network_interface.position(node_id, network_path) else {
log::error!("Could not get position for morph node {node_id}");
return None;
};
@@ -2568,7 +2784,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
// Reconnect content (input 0) and leave path (input 4) as default
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
let Some(morph_position) = document.network_interface.position_from_downstream_node(node_id, network_path) else {
let Some(morph_position) = document.network_interface.position(node_id, network_path) else {
log::error!("Could not get position for morph node {node_id}");
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[1].clone(), network_path);
return None;
@@ -2590,7 +2806,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
return None;
};
let mut subtract_template = subtract_def.default_node_template();
subtract_template.inputs[1] = NodeInput::value(TaggedValue::F64(1.), false);
subtract_template.inputs[1] = NodeInput::value(TaggedValue::Number(1.), false);
let subtract_id = NodeId::new();
// Create Divide node: old_progression / (N-1) → new progression
@@ -3066,12 +3282,12 @@ mod tests {
NodeInput::scope("editor-api"),
NodeInput::value(TaggedValue::String("Lorem".into()), false),
NodeInput::value(TaggedValue::Font(Font::new("Lato".to_string(), "Regular (400)".to_string())), false),
NodeInput::value(TaggedValue::F64(48.), false),
NodeInput::value(TaggedValue::F64(1.5), false),
NodeInput::value(TaggedValue::F64(2.), false),
NodeInput::value(TaggedValue::F64(0.), false),
NodeInput::value(TaggedValue::F64(0.), false),
NodeInput::value(TaggedValue::F64(10.), false),
NodeInput::value(TaggedValue::Number(48.), false),
NodeInput::value(TaggedValue::Number(1.5), false),
NodeInput::value(TaggedValue::Number(2.), false),
NodeInput::value(TaggedValue::Number(0.), false),
NodeInput::value(TaggedValue::Number(0.), false),
NodeInput::value(TaggedValue::Number(10.), false),
NodeInput::value(TaggedValue::Bool(false), false),
];
@@ -3117,29 +3333,281 @@ mod tests {
);
let input_value = |index: usize| text_node.inputs.get(index).and_then(|input| input.as_value()).cloned();
assert_eq!(input_value(graphene_std::text::text::SizeInput::INDEX), Some(TaggedValue::F64(48.)), "shape {shape} lost its size");
assert_eq!(input_value(graphene_std::text::text::SizeInput::INDEX), Some(TaggedValue::Number(48.)), "shape {shape} lost its size");
if shape >= 6 {
assert_eq!(
input_value(graphene_std::text::text::LineHeightInput::INDEX),
Some(TaggedValue::F64(1.5)),
Some(TaggedValue::Number(1.5)),
"shape {shape} lost its line height"
);
assert_eq!(
input_value(graphene_std::text::text::LetterSpacingInput::INDEX),
Some(TaggedValue::F64(2.)),
Some(TaggedValue::Number(2.)),
"shape {shape} lost its letter spacing"
);
}
if shape >= 9 {
assert_eq!(
input_value(graphene_std::text::text::LetterTiltInput::INDEX),
Some(TaggedValue::F64(10.)),
Some(TaggedValue::Number(10.)),
"shape {shape} lost its letter tilt"
);
}
}
}
// An expression node saved before the output-type witness input had only its value and expression inputs
#[test]
fn expression_nodes_gain_the_output_type_witness() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
let node_id = NodeId(1);
let mut document = DocumentMessageHandler::default();
document.network_interface.insert_node(
node_id,
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::math_fx::IDENTIFIER),
inputs: vec![NodeInput::value(TaggedValue::Number(4.), false), NodeInput::value(TaggedValue::String("x^2".into()), false)],
..Default::default()
},
&[],
);
document_migration_upgrades(&mut document, false);
// The old inputs stay in place and the witness defaults to Number, the output type every such node had
let node = &document.network_interface.document_network().nodes[&node_id];
let value_at = |index: usize| node.inputs.get(index).and_then(|input| input.as_value()).cloned();
assert_eq!(node.inputs.len(), 3);
assert_eq!(value_at(0), Some(TaggedValue::Number(4.)));
assert_eq!(value_at(1), Some(TaggedValue::String("x^2".into())));
assert_eq!(value_at(2), Some(TaggedValue::Number(0.)));
}
// The old Math node's expression decides its replacement: a static string that never reads `B` becomes "Math f(x)",
// while a wired `B` or an uninspectable expression becomes "Extend" feeding "Math f(…)"
#[test]
fn old_math_nodes_split_into_the_expression_node_pair() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
let math_id = NodeId(1);
let (source_a_id, source_b_id, source_expression_id) = (NodeId(2), NodeId(3), NodeId(4));
// Builds a document holding one old Math node with the given inputs, plus three source nodes to wire from
let build_document = |identifier: &'static str, inputs: Vec<NodeInput>| {
let mut document = DocumentMessageHandler::default();
for source_id in [source_a_id, source_b_id, source_expression_id] {
document.network_interface.insert_node(
source_id,
NodeTemplate {
inputs: vec![NodeInput::value(TaggedValue::None, false)],
..Default::default()
},
&[],
);
}
document.network_interface.insert_node(
math_id,
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
inputs: vec![NodeInput::value(TaggedValue::None, false); 3],
..Default::default()
},
&[],
);
for (index, input) in inputs.into_iter().enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(math_id, index), input, &[]);
}
document
};
let implementation_of = |document: &DocumentMessageHandler, node_id: NodeId| match &document.network_interface.document_network().nodes[&node_id].implementation {
DocumentNodeImplementation::ProtoNode(identifier) => identifier.clone(),
other => panic!("expected a proto node implementation, got {other:?}"),
};
let find_extend = |document: &DocumentMessageHandler| {
document
.network_interface
.document_network()
.nodes
.iter()
.find(|(_, node)| matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::graphic::extend::IDENTIFIER))
.map(|(extend_id, _)| *extend_id)
.expect("an Extend node should be spliced in")
};
// A static expression that never reads `B` becomes "Math f(x)" with `A` renamed to `x` and the `B` input dropped
{
let inputs = vec![
NodeInput::node(source_a_id, 0),
NodeInput::value(TaggedValue::String("2 - 0.2A".into()), false),
NodeInput::value(TaggedValue::Number(0.), false),
];
let mut document = build_document("math_nodes::MathNode", inputs);
document_migration_upgrades(&mut document, false);
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_fx::IDENTIFIER);
let node = &document.network_interface.document_network().nodes[&math_id];
assert_eq!(
node.inputs.len(),
3,
"the old `B` input should be dropped, leaving the value, the expression, and the output-type witness"
);
assert_eq!(node.inputs.first(), Some(&NodeInput::node(source_a_id, 0)));
assert_eq!(node.inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::String("2 - 0.2x".into())));
assert_eq!(node.inputs.get(2).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::Number(0.)));
}
// A constant `B` inlines into the rewritten string as a parenthesized literal; an alias spelling of the old identifier also matches
{
let inputs = vec![
NodeInput::node(source_a_id, 0),
NodeInput::value(TaggedValue::String("sqrt(A + B) - B^2".into()), false),
NodeInput::value(TaggedValue::Number(3.), false),
];
let mut document = build_document("graphene_core::ops::MathNode", inputs);
document_migration_upgrades(&mut document, false);
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_fx::IDENTIFIER);
let node = &document.network_interface.document_network().nodes[&math_id];
assert_eq!(
node.inputs.get(1).and_then(|input| input.as_value()).cloned(),
Some(TaggedValue::String("sqrt(x + (3.0)) - (3.0)^2".into()))
);
}
// A wired `B` keeps both wires by joining them through a spliced Extend node, with the expression rewritten to the
// lowercase positional spellings and the old constants escaped behind the `\` prefix that still reaches them
{
let inputs = vec![
NodeInput::node(source_a_id, 0),
NodeInput::value(TaggedValue::String("A * B + e".into()), false),
NodeInput::node(source_b_id, 0),
];
let mut document = build_document("math_nodes::MathNode", inputs);
document_migration_upgrades(&mut document, false);
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_f::IDENTIFIER);
let extend_id = find_extend(&document);
let network = document.network_interface.document_network();
assert_eq!(network.nodes[&math_id].inputs.first(), Some(&NodeInput::node(extend_id, 0)));
assert_eq!(
network.nodes[&math_id].inputs.get(1).and_then(|input| input.as_value()).cloned(),
Some(TaggedValue::String("a * b + \\e".into()))
);
assert_eq!(network.nodes[&extend_id].inputs.first(), Some(&NodeInput::node(source_a_id, 0)));
assert_eq!(network.nodes[&extend_id].inputs.get(1), Some(&NodeInput::node(source_b_id, 0)));
}
// A wired expression cannot be inspected, so it splices too, wrapping unwired constant operands as one-item list values
{
let inputs = vec![
NodeInput::value(TaggedValue::Number(2.), true),
NodeInput::node(source_expression_id, 0),
NodeInput::value(TaggedValue::Number(5.), false),
];
let mut document = build_document("math_nodes::MathNode", inputs);
document_migration_upgrades(&mut document, false);
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_f::IDENTIFIER);
let extend_id = find_extend(&document);
let network = document.network_interface.document_network();
assert_eq!(network.nodes[&math_id].inputs.get(1), Some(&NodeInput::node(source_expression_id, 0)));
assert_eq!(network.nodes[&extend_id].inputs.first(), Some(&NodeInput::value(TaggedValue::Numbers(vec![2.]), true)));
assert_eq!(network.nodes[&extend_id].inputs.get(1), Some(&NodeInput::value(TaggedValue::Numbers(vec![5.]), false)));
}
}
// The Blend network's Count is now an integer, so an old instance rounds its stored F64 count and swaps the Floor its
// subgraph used to whole-number the count for the As Number that brings the integer into the network's decimal math
#[test]
fn blend_count_narrows_to_i64_and_its_subgraph_is_rebuilt() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplateImplementation;
let node_id = NodeId(1);
let mut document = DocumentMessageHandler::default();
let mut node_template = resolve_network_node_type("Blend").expect("Blend should exist").default_node_template();
node_template.inputs[1] = NodeInput::value(TaggedValue::Number(6.9), false);
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
panic!("Blend should be a network node")
};
let count_conversion = network_template.nodes.get_mut(&NodeId(3)).expect("Blend should have a count conversion node");
count_conversion.implementation = NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::floor::IDENTIFIER);
count_conversion.inputs = vec![NodeInput::import(item!(f64), 1)];
document.network_interface.insert_node(node_id, node_template, &[]);
document_migration_upgrades(&mut document, false);
let node = &document.network_interface.document_network().nodes[&node_id];
assert_eq!(
node.inputs.get(1).and_then(|input| input.as_value()).cloned(),
Some(TaggedValue::Integer(6)),
"the count truncates as the retired Floor did, so the document keeps drawing six"
);
let DocumentNodeImplementation::Network(inner) = &node.implementation else {
panic!("Blend should stay a network node")
};
assert_eq!(
inner.nodes[&NodeId(3)].implementation,
DocumentNodeImplementation::ProtoNode(graphene_std::math_nodes::as_number::IDENTIFIER)
);
}
// The rebuild above is keyed on the retired Floor that took the Count import, since the subgraph keeps another Floor
// for its subpath index and a current Blend would otherwise lose any edit made inside it on every load
#[test]
fn current_blend_subgraph_survives_migration() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplateImplementation;
let node_id = NodeId(1);
let mut document = DocumentMessageHandler::default();
let mut node_template = resolve_network_node_type("Blend").expect("Blend should exist").default_node_template();
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
panic!("Blend should be a network node")
};
let edited_subtract = network_template.nodes.get_mut(&NodeId(5)).expect("Blend should have an open-path denominator node");
edited_subtract.inputs[1] = NodeInput::value(TaggedValue::Number(42.), false);
document.network_interface.insert_node(node_id, node_template, &[]);
document_migration_upgrades(&mut document, false);
let DocumentNodeImplementation::Network(inner) = &document.network_interface.document_network().nodes[&node_id].implementation else {
panic!("Blend should stay a network node")
};
assert_eq!(inner.nodes[&NodeId(5)].inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::Number(42.)));
}
// Regex Find's Match Index is now an integer, so an old instance rounds its stored F64 index and rebuilds the subgraph
// that fed the decimal index to its two item-at-index nodes
#[test]
fn regex_find_match_index_narrows_to_i64_and_its_subgraph_is_rebuilt() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplateImplementation;
let node_id = NodeId(1);
let mut document = DocumentMessageHandler::default();
let mut node_template = resolve_network_node_type("Regex Find").expect("Regex Find should exist").default_node_template();
node_template.inputs[2] = NodeInput::value(TaggedValue::Number(1.6), false);
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
panic!("Regex Find should be a network node")
};
network_template.nodes.get_mut(&NodeId(0)).expect("Regex Find should have a find node").inputs[2] = NodeInput::import(item!(f64), 2);
network_template.nodes.get_mut(&NodeId(1)).expect("Regex Find should have an item-at-index node").inputs[1] = NodeInput::value(TaggedValue::Number(0.), false);
document.network_interface.insert_node(node_id, node_template, &[]);
document_migration_upgrades(&mut document, false);
let node = &document.network_interface.document_network().nodes[&node_id];
assert_eq!(
node.inputs.get(2).and_then(|input| input.as_value()).cloned(),
Some(TaggedValue::Integer(1)),
"the match index truncates as the retired cast did"
);
let DocumentNodeImplementation::Network(inner) = &node.implementation else {
panic!("Regex Find should stay a network node")
};
assert_eq!(inner.nodes[&NodeId(0)].inputs.get(2), Some(&NodeInput::import(item!(i64), 2)));
assert_eq!(inner.nodes[&NodeId(1)].inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::Integer(0)));
}
#[test]
fn every_legacy_image_shape_stores_its_resource_as_secondary_input() {
use graphene_std::raster::Image;
@@ -90,7 +90,7 @@ pub(super) async fn open_gdd_document(
/// Core of the `.gdd` open: archive -> working copy -> `Gdd` -> runtime interface. The registry build is
/// authoritative; the embedded legacy blob is the soak oracle and the fallback if the build fails.
/// Returns `None` only if neither the build nor the legacy fallback worked.
async fn build_document_from_gdd(path: Option<&std::path::Path>, content: &[u8], store_handle: &ResourcesHandle, document_id: DocumentId, validate: bool) -> Option<DocumentMessageHandler> {
async fn build_document_from_gdd(path: Option<&std::path::Path>, content: &[u8], store_handle: &impl ResourceStorage, document_id: DocumentId, validate: bool) -> Option<DocumentMessageHandler> {
let (container, _exists) = match build_per_document_container(path).await {
Ok(result) => result,
Err(error) => {
@@ -164,7 +164,7 @@ async fn build_document_from_gdd(path: Option<&std::path::Path>, content: &[u8],
);
}
}
return Some(DocumentMessageHandler::from_storage(interface, gdd, declarations, store_handle.storage(), String::new(), None));
return Some(DocumentMessageHandler::from_storage(interface, gdd, declarations, String::new(), None));
}
log::warn!("Opening .gdd for {document_id:?}: registry build failed, falling back to embedded legacy document");
-1
View File
@@ -8,7 +8,6 @@ pub mod failed_documents;
pub mod fonts;
pub mod ingest;
pub mod persistent_state;
pub mod sync;
pub mod utility_types;
pub mod workspace;
@@ -1,6 +1,5 @@
use super::document::utility_types::document_metadata::LayerNodeIdentifier;
use super::persistent_state::PersistentStateMessage;
use super::sync::SyncMessage;
use crate::messages::frontend::utility_types::{ExportBounds, FileType, PersistedState};
use crate::messages::prelude::*;
use std::path::PathBuf;
@@ -21,8 +20,6 @@ pub enum PortfolioMessage {
#[child]
PersistentState(PersistentStateMessage),
#[child]
Sync(SyncMessage),
#[child]
Workspace(WorkspaceMessage),
// Messages
@@ -59,7 +56,7 @@ pub enum PortfolioMessage {
reopened: bool,
#[serde(skip, default)]
#[derivative(Debug = "ignore", PartialEq = "ignore", Clone(clone_with = "clone_to_none"))]
mounted: Option<(document_format::GddV1, document_graph_storage::Declarations)>,
mounted: Option<Box<(document_format::GddV1, document_graph_storage::Declarations)>>,
},
DestroyAllDocuments,
EditorPreferences,
@@ -53,7 +53,6 @@ pub struct PortfolioMessageHandler {
persistent_state: PersistentStateMessageHandler,
pub fonts: FontsMessageHandler,
ingest: IngestMessageHandler,
sync: SyncMessageHandler,
pub executor: NodeGraphExecutor,
pub selection_mode: SelectionMode,
pub reset_node_definitions_on_open: bool,
@@ -119,14 +118,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
};
self.ingest.process_message(message, responses, context);
}
PortfolioMessage::Sync(message) => {
let context = SyncMessageContext {
documents: &mut self.documents,
active_document_id: self.active_document_id,
resource_storage,
};
self.sync.process_message(message, responses, context);
}
PortfolioMessage::Workspace(message) => {
let context = WorkspaceMessageContext {
has_active_document: self.active_document_id.is_some(),
@@ -323,16 +314,16 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
// Document was closed before its working copy finished mounting.
return;
};
let Some((gdd, declarations)) = mounted else {
let Some(mounted) = mounted else {
log::error!("DocumentStorageMounted for {document_id:?} arrived without its payload");
return;
};
document.set_storage(gdd, declarations, resource_storage.resources_mut().storage());
let (gdd, declarations) = *mounted;
document.set_storage(gdd, declarations);
if !reopened {
document.commit_storage_snapshot(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
document.retire_storage_interaction();
}
responses.add(SyncMessage::StorageMounted { document_id });
}
PortfolioMessage::DestroyAllDocuments => {
// Empty the list of internal document data
@@ -651,7 +642,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
document.network_interface.validate_input_metadata(node_id, node, &path);
document.network_interface.validate_output_names(node_id, node, &path);
}
// Ensure layers are positioned as stacks if they are upstream siblings of another layer
document.network_interface.load_structure();
let all_layers = LayerNodeIdentifier::ROOT_PARENT.descendants(document.network_interface.document_metadata()).collect::<Vec<_>>();
@@ -682,6 +672,12 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
}
}
// Everything above is how the document arrives rather than an edit to it, so what those fix-ups
// recorded must not ride along in the first real commit. They still have to reach storage, so
// the next commit converts the whole document instead of staging the batch that follows them.
document.network_interface.discard_deltas();
document.require_whole_document_stage();
// Set the save state of the document based on what's given to us by the caller to this message
document.set_auto_save_state(document_is_auto_saved);
document.set_save_state(document_is_saved);
@@ -1329,7 +1325,7 @@ impl PortfolioMessageHandler {
Message::Portfolio(PortfolioMessage::DocumentStorageMounted {
document_id,
reopened,
mounted: Some((gdd, declarations)),
mounted: Some(Box::new((gdd, declarations))),
})
};
future.into()
@@ -1,7 +0,0 @@
mod sync_message;
mod sync_message_handler;
#[doc(inline)]
pub use sync_message::{SyncMessage, SyncMessageDiscriminant};
#[doc(inline)]
pub use sync_message_handler::{SyncMessageContext, SyncMessageHandler};
@@ -1,27 +0,0 @@
use crate::messages::prelude::*;
use graph_craft::application_io::resource::ResourceHash;
use peer_transport::TransportPeerId;
#[impl_message(Message, PortfolioMessage, Sync)]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum SyncMessage {
/// Host the active document and hand the frontend a link for others to join.
Share,
/// Open a new document that follows the session behind `token`.
Join { token: String },
/// Leave the active document's session.
Leave,
/// Per frame: apply what peers sent and answer their requests.
Poll,
/// A document's working copy mounted; attaches it to a pending join.
StorageMounted { document_id: DocumentId },
/// The transport loop of a document's session ended.
Disconnected { document_id: DocumentId },
/// A resource a peer asked for was read from the byte store.
ResourceLoaded {
document_id: DocumentId,
to: TransportPeerId,
hash: ResourceHash,
bytes: Vec<u8>,
},
}
@@ -1,219 +0,0 @@
use crate::application::generate_uuid;
use crate::messages::portfolio::document::DocumentMessageHandler;
use crate::messages::portfolio::document::utility_types::network_interface::TransactionStatus;
use crate::messages::prelude::*;
use crate::messages::resource_storage::ResourcesHandle;
use document_graph_storage::UserId;
use graph_craft::application_io::resource::LoadResource;
use peer_transport::{DEFAULT_SIGNALING_SERVER, Event, Room, SessionToken, SyncTarget};
use std::collections::HashSet;
#[derive(ExtractField)]
pub struct SyncMessageContext<'a> {
pub documents: &'a mut HashMap<DocumentId, DocumentMessageHandler>,
pub active_document_id: Option<DocumentId>,
pub resource_storage: &'a ResourceStorageMessageHandler,
}
/// Drives every document's collaborative session: attaches transports, polls them once per frame,
/// and turns remote changes into interface rebuilds.
#[derive(Debug, Default, ExtractField)]
pub struct SyncMessageHandler {
pending_join: Option<SessionToken>,
polling: bool,
/// Documents whose registry changed remotely since their interface was last rebuilt.
dirty: HashSet<DocumentId>,
blocked_reason: HashMap<DocumentId, String>,
}
#[message_handler_data]
impl MessageHandler<SyncMessage, SyncMessageContext<'_>> for SyncMessageHandler {
fn process_message(&mut self, message: SyncMessage, responses: &mut VecDeque<Message>, context: SyncMessageContext) {
let SyncMessageContext {
documents,
active_document_id,
resource_storage,
} = context;
match message {
SyncMessage::Share => {
let Some(document) = active_document_id.and_then(|id| documents.get_mut(&id)) else { return };
let Some(gdd) = document.storage_mut() else {
log::warn!("Cannot share a document before its working copy is mounted");
return;
};
if gdd.role().is_some() {
return;
}
let token = SessionToken(random_token_bytes());
let (room, driver) = Room::connect(&token.signaling_url(DEFAULT_SIGNALING_SERVER));
let user = UserId(gdd.session().peer().0);
gdd.share(room, user);
let document_id = active_document_id.expect("checked above");
responses.add(driver_future(document_id, driver));
responses.add(FrontendMessage::TriggerSessionLinkCopy { token: token.to_string() });
responses.add(DialogMessage::DisplayDialogError {
title: "Live session started".into(),
description: format!("A link to join was copied to the clipboard.\n\nSession {token}"),
});
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
self.start_polling(responses);
}
SyncMessage::Join { token } => {
let token = match token.parse::<SessionToken>() {
Ok(token) => token,
Err(error) => {
log::warn!("Ignoring session link: {error}");
return;
}
};
self.pending_join = Some(token);
responses.add(PortfolioMessage::NewDocumentWithName { name: "Shared session".into() });
}
SyncMessage::StorageMounted { document_id } => {
let Some(token) = self.pending_join.take() else { return };
let Some(gdd) = documents.get_mut(&document_id).and_then(|document| document.storage_mut()) else {
return;
};
let (room, driver) = Room::connect(&token.signaling_url(DEFAULT_SIGNALING_SERVER));
let user = UserId(gdd.session().peer().0);
gdd.join(room, user);
responses.add(driver_future(document_id, driver));
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
self.start_polling(responses);
}
SyncMessage::Leave => {
let Some(gdd) = active_document_id.and_then(|id| documents.get_mut(&id)).and_then(|document| document.storage_mut()) else {
return;
};
gdd.leave();
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
}
SyncMessage::Disconnected { document_id } => {
if let Some(gdd) = documents.get_mut(&document_id).and_then(|document| document.storage_mut()) {
gdd.leave();
}
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
}
SyncMessage::Poll => {
let resources = resource_storage.resources_mut();
for (&document_id, document) in documents.iter_mut() {
let Some(gdd) = document.storage_mut() else { continue };
if gdd.role().is_none() {
continue;
}
let events = gdd.poll_peers();
for event in events {
match event {
Event::Synced | Event::Changed => {
self.dirty.insert(document_id);
document.runtime_stale = true;
}
Event::ResourceRequested { from, hash } => {
log::debug!("Peer asked for resource {hash}");
responses.add(load_resource_future(document_id, from, hash, resources.clone()));
}
// The replica already put the bytes in the byte store; only the decoded form is missing.
Event::ResourceReceived { hash, bytes } => {
log::debug!("Received resource {hash} ({} bytes)", bytes.len());
document.cache_declaration_bytes(hash, &bytes);
self.dirty.insert(document_id);
}
Event::PeerJoined { .. } | Event::PeerLeft { .. } => responses.add(PortfolioMessage::UpdateOpenDocumentsList),
}
}
}
// Rebuild only once every referenced resource is in the app cache, and never underneath an
// open transaction, whose un-staged edits the swap would discard.
for document_id in self.dirty.clone() {
let Some(document) = documents.get_mut(&document_id) else {
self.dirty.remove(&document_id);
continue;
};
let Some(gdd) = document.storage() else { continue };
let missing = SyncTarget::missing_resources(gdd).len();
let transaction = document.network_interface.transaction_status();
if missing > 0 || transaction != TransactionStatus::Finished {
let reason = format!("missing {missing} transaction {transaction:?}");
if self.blocked_reason.get(&document_id) != Some(&reason) {
log::debug!("Sync rebuild for {document_id:?} waiting: {reason}");
self.blocked_reason.insert(document_id, reason);
}
continue;
}
self.blocked_reason.remove(&document_id);
self.dirty.remove(&document_id);
document.apply_remote_changes(responses);
// The swapped-in registry names resources this peer may still have to fetch or resolve.
responses.add(PortfolioMessage::ResolveDocumentResources { document_id });
}
}
SyncMessage::ResourceLoaded { document_id, to, hash, bytes } => {
log::debug!("Sending resource {hash} ({} bytes)", bytes.len());
let Some(gdd) = documents.get_mut(&document_id).and_then(|document| document.storage_mut()) else {
return;
};
if let Err(error) = gdd.send_resource(to, hash, bytes) {
log::warn!("Failed to send resource {hash} to a peer: {error}");
}
}
}
}
advertise_actions!(SyncMessageDiscriminant; Share, Leave);
}
impl SyncMessageHandler {
fn start_polling(&mut self, responses: &mut VecDeque<Message>) {
if self.polling {
return;
}
self.polling = true;
responses.add(BroadcastMessage::SubscribeEvent {
on: EventMessage::AnimationFrame,
send: Box::new(SyncMessage::Poll.into()),
});
}
}
fn driver_future(document_id: DocumentId, driver: peer_transport::MessageLoopFuture) -> Message {
let future = async move {
if let Err(error) = driver.await {
log::warn!("Session transport for {document_id:?} ended: {error}");
}
Message::Portfolio(PortfolioMessage::Sync(SyncMessage::Disconnected { document_id }))
};
future.into()
}
fn load_resource_future(document_id: DocumentId, to: peer_transport::TransportPeerId, hash: graph_craft::application_io::resource::ResourceHash, resources: ResourcesHandle) -> Message {
let future = async move {
match resources.load(hash).await {
Some(resource) => Message::Portfolio(PortfolioMessage::Sync(SyncMessage::ResourceLoaded {
document_id,
to,
hash,
bytes: resource.as_ref().to_vec(),
})),
None => {
log::warn!("A peer asked for resource {hash} which is not in the byte store");
Message::NoOp
}
}
};
future.into()
}
fn random_token_bytes() -> [u8; 16] {
let mut bytes = [0; 16];
bytes[..8].copy_from_slice(&generate_uuid().to_le_bytes());
bytes[8..].copy_from_slice(&generate_uuid().to_le_bytes());
bytes
}
-1
View File
@@ -35,7 +35,6 @@ pub use crate::messages::portfolio::failed_documents::{FailedDocumentsMessage, F
pub use crate::messages::portfolio::fonts::{FontsMessage, FontsMessageContext, FontsMessageDiscriminant, FontsMessageHandler};
pub use crate::messages::portfolio::ingest::{IngestMessage, IngestMessageContext, IngestMessageDiscriminant, IngestMessageHandler};
pub use crate::messages::portfolio::persistent_state::{PersistentStateMessage, PersistentStateMessageContext, PersistentStateMessageDiscriminant, PersistentStateMessageHandler};
pub use crate::messages::portfolio::sync::{SyncMessage, SyncMessageContext, SyncMessageDiscriminant, SyncMessageHandler};
pub use crate::messages::portfolio::workspace::{WorkspaceMessage, WorkspaceMessageContext, WorkspaceMessageDiscriminant, WorkspaceMessageHandler};
pub use crate::messages::portfolio::{PortfolioMessage, PortfolioMessageContext, PortfolioMessageDiscriminant, PortfolioMessageHandler};
pub use crate::messages::preferences::{PreferencesMessage, PreferencesMessageDiscriminant, PreferencesMessageHandler};
@@ -7,17 +7,6 @@ pub struct ResourcesHandle {
inner: Arc<dyn ResourceStorage>,
}
impl ResourcesHandle {
pub fn new(inner: Arc<dyn ResourceStorage>) -> Self {
Self { inner }
}
/// The shared store behind this handle, for a consumer that needs to keep it alive itself.
pub fn storage(&self) -> Arc<dyn ResourceStorage> {
self.inner.clone()
}
}
impl LoadResource for ResourcesHandle {
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
self.inner.load(hash)
@@ -173,7 +173,7 @@ impl RadiusHandle {
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, radius_parameter),
input: NodeInput::value(TaggedValue::F64(current_radius + net_delta), false),
input: NodeInput::value(TaggedValue::Number(current_radius + net_delta), false),
});
responses.add(NodeGraphMessage::RunDocumentGraph);
}
@@ -124,7 +124,7 @@ impl RowColumnGizmo {
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, self.gizmo_type.parameter()),
input: NodeInput::value(TaggedValue::U32((self.initial_dimension() as i32 + dimensions_to_add).max(1) as u32), false),
input: NodeInput::value(TaggedValue::Integer((self.initial_dimension() as i32 + dimensions_to_add).max(1) as i64), false),
});
responses.add(GraphOperationMessage::TransformChange {
@@ -209,7 +209,7 @@ impl NumberOfPointsDial {
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, sides_parameter),
input: NodeInput::value(TaggedValue::U32(new_point_count as u32), false),
input: NodeInput::value(TaggedValue::Integer(new_point_count as i64), false),
});
responses.add(NodeGraphMessage::RunDocumentGraph);
}
@@ -343,13 +343,13 @@ impl PointRadiusHandle {
return snap_radii;
};
let (Some(&TaggedValue::F64(radius_1)), Some(&TaggedValue::F64(radius_2))) = (parameters.value(star::Radius1Input), parameters.value(star::Radius2Input)) else {
let (Some(&TaggedValue::Number(radius_1)), Some(&TaggedValue::Number(radius_2))) = (parameters.value(star::Radius1Input), parameters.value(star::Radius2Input)) else {
return snap_radii;
};
let other_radius = if *radius_parameter == ParameterRef::from(star::Radius2Input) { radius_1 } else { radius_2 };
let Some(&TaggedValue::U32(sides)) = parameters.value(star::SidesInput) else {
let Some(&TaggedValue::Integer(sides)) = parameters.value(star::SidesInput) else {
return snap_radii;
};
@@ -452,7 +452,7 @@ impl PointRadiusHandle {
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, radius_parameter),
input: NodeInput::value(TaggedValue::F64(original_radius + net_delta), false),
input: NodeInput::value(TaggedValue::Number(original_radius + net_delta), false),
});
responses.add(NodeGraphMessage::RunDocumentGraph);
}
@@ -462,7 +462,7 @@ impl PointRadiusHandle {
return;
};
let (Some(&TaggedValue::F64(radius_1)), Some(&TaggedValue::F64(radius_2))) = (parameters.value(star::Radius1Input), parameters.value(star::Radius2Input)) else {
let (Some(&TaggedValue::Number(radius_1)), Some(&TaggedValue::Number(radius_2))) = (parameters.value(star::Radius1Input), parameters.value(star::Radius2Input)) else {
return;
};
Loaded 100 of 187 files, more files were not shown because too many files have changed in this diff. Show more