Compare commits

..
Author SHA1 Message Date
Dennis Kobert 3902163e03 Resolve a batch of node positions in one downstream walk instead of one per node 2026-09-23 13:07:14 +00:00
Dennis Kobert 99824a70a9 Preview a node by redirecting the graph that is evaluated, not the document 2026-09-23 12:15:44 +00:00
Dennis Kobert c25410185c Answer the cycle question without writing the network 2026-09-23 11:31:05 +00:00
Dennis Kobert 93665c5e9d Give cache invalidation and per-peer view state their own accessors 2026-09-23 10:46:12 +00:00
Dennis Kobert ccb02ddf8d Make writing either parallel tree outside the store a compile error 2026-09-23 10:21:28 +00:00
Dennis Kobert 305cd02332 Stage what the store recorded instead of converting and diffing the whole document 2026-09-23 09:59:11 +00:00
Dennis Kobert 3394695fb9 Replay a recorded delta back into the interface without recording it again 2026-09-23 08:51:29 +00:00
Dennis Kobert 47f56b481c Store previewing and pinned order in the registry and stop rebuilding nodes to change their inputs 2026-09-23 08:13:16 +00:00
Dennis Kobert bdab64eb29 Record input arity and node entry writes, and route node type changes through the store 2026-09-23 07:29:09 +00:00
Dennis Kobert 0fe91cc0fd Record what each store write changed at the point of the write 2026-09-23 06:49:32 +00:00
Dennis Kobert 06672ddb39 Give each metadata field its own delta instead of diffing a wholesale copy 2026-09-23 06:27:06 +00:00
Dennis Kobert e060233d7c Record the interface restructure state and the open emission fork alongside the delta design 2026-09-22 21:00:23 +00:00
Dennis Kobert 70e0c51fae Index nodes by network and resource references once instead of rescanning the registry per removal 2026-09-22 20:52:57 +00:00
Dennis Kobert 3e46541ea0 Split shifting nodes into its selection, ordering, direction and settling phases 2026-09-22 20:48:21 +00:00
Dennis Kobert 526e760792 Name the phases of moving a layer into a stack and drop a measurement nothing read 2026-09-22 20:18:37 +00:00
Dennis Kobert 4749e2518f Name the policies set_input and the slot reorders were carrying inline 2026-09-22 19:39:54 +00:00
Dennis Kobert 07acbfad9f Carry a node's storage identity through the rebuild so it survives a document round trip 2026-09-22 18:58:09 +00:00
Dennis Kobert aca1805fcf Resolve node identities through one place, preferring a stored identity over a location hash
No node stores an identity yet, so every path still hashes and nothing changes. Minting needs
to land in one step across from_runtime, to_runtime, PathResolver and the rebuild, since a
node whose identity survives one path but not another silently changes id.
2026-09-22 15:50:21 +00:00
Dennis Kobert 35b9153f27 Name the invalidation rules and lift the frontend projections out of the query layer 2026-09-22 15:13:25 +00:00
Dennis Kobert 93ca25ebe5 Separate node graph geometry from the caches that store it 2026-09-22 14:58:54 +00:00
Dennis Kobert 6ef640c288 Turn each cache loader into a pure computation the slot stores itself 2026-09-22 14:49:01 +00:00
Dennis Kobert 0f21bbc337 Load transient caches through one load-on-miss helper instead of a per-slot ceremony 2026-09-22 14:24:03 +00:00
Dennis Kobert fee15b9048 Clear the workspace clippy warnings and shrink the message enum by boxing the mounted working copy 2026-09-22 14:12:17 +00:00
Dennis Kobert 6c52714194 Declare what a position change invalidates once instead of at each layout writer 2026-09-22 12:40:49 +00:00
Dennis Kobert f5f1b09eec Write node fields through a resolved cursor and close the raw tree accessors 2026-09-22 12:40:49 +00:00
Dennis Kobert 5528af9617 Write inputs and node entries through the store instead of the two trees directly 2026-09-22 12:40:49 +00:00
Dennis Kobert 1863e9ea67 Route import and export signature edits through paired store primitives 2026-09-22 12:40:48 +00:00
Dennis Kobert ea17f690a2 Derive node positions from layout metadata instead of click target geometry 2026-09-22 12:40:48 +00:00
Keavon Chambers 6d3951b26f Record the runtime delta design context and the storage-driven undo follow-up plan 2026-09-22 11:56:12 +00:00
Keavon Chambers 225c2cde98 Document the runtime delta modules where understanding needs it 2026-09-22 11:56:12 +00:00
Keavon Chambers 3799e55491 Adopt batch-scoped delta construction with shared removal and resource context, and carry visibility as a structural delta 2026-09-22 11:56:12 +00:00
Keavon Chambers 74a80b61bd Rework the runtime delta experiment to the agreed shape: graph-craft structural deltas, an editor metadata wrapper, and diff-derived metadata ops 2026-09-22 11:56:12 +00:00
Keavon Chambers 951005e5cf Expose scoped conversion, path ID derivation, and computed-op staging from the storage layer 2026-09-22 11:19:19 +00:00
279 changed files with 7378 additions and 17631 deletions

No files matched your search

+5 -6
View File
@@ -1,7 +1,7 @@
{ pkgs, ... }:
let
toolchain = pkgs.rust-bin.nightly."2026-07-03".default.override {
toolchain = pkgs.rust-bin.nightly."2026-04-11".default.override {
extensions = [
"rust-src"
"rust-analyzer"
@@ -32,12 +32,11 @@ let
(finalAttrs: {
pname = "rustc_codegen_spirv";
version = "0.10.0-alpha.1";
src = pkgs.fetchgit {
url = "https://github.com/Rust-GPU/rust-gpu";
rev = "2fff75a21a1909945ac85f5818843dd9960004d7";
sha256 = "sha256-clUt4jUh4D9EmoXZFgur1RrMYob4X5jti2e2hvBnAx8=";
src = pkgs.fetchCrate {
inherit (finalAttrs) pname version;
sha256 = "sha256-zJEpExkPgYzwo7fR4ge4GxJNj7H5yo4bJ4eTOw36+7c=";
};
cargoHash = "sha256-9dGb+RDYpJKaIhkMPkZAx1M1VGE3gMfCD2T84i1VtV8=";
cargoHash = "sha256-J1rtbfGqrL2NJ7Bu2pYfDwCdUmnECB/kzxrpYluA0kY=";
cargoBuildFlags = [
"-p"
"rustc_codegen_spirv"
Generated
+154 -163
View File
File diff suppressed because it is too large. Load diff
+6 -11
View File
@@ -53,7 +53,7 @@ default-members = [
resolver = "2"
[workspace.package]
rust-version = "1.98"
rust-version = "1.88"
edition = "2024"
authors = ["Graphite Authors <[email protected]>"]
homepage = "https://graphite.art"
@@ -114,7 +114,7 @@ rustc-hash = "2.0"
bytemuck = { version = "1.13", features = ["derive", "min_const_generics"] }
serde = { version = "1.0", features = ["derive", "rc"] }
serde_json = "1.0"
postcard = { version = "1.1", default-features = false, features = ["use-std"] }
rmp-serde = "1.3"
serde_bytes = "0.11"
serde-wasm-bindgen = "0.6"
reqwest = { version = "0.13", features = ["blocking", "json"] }
@@ -172,6 +172,7 @@ tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt", "rt-mult
kurbo = { version = "0.13", features = ["serde"] }
vello = "0.10"
vello_encoding = "0.10"
resvg = "0.47"
usvg = "0.47"
simplecss = "0.2"
parley = { version = "0.9", default-features = false, features = ["std"] }
@@ -181,12 +182,10 @@ color = "0.3"
# Linebender ecosystem (END)
rand = { version = "0.9", default-features = false, features = ["std_rng"] }
rand_chacha = "0.9"
glam = { version = "0.33", default-features = false, features = [
glam = { version = "0.32.1", default-features = false, features = [
"nostd-libm",
"scalar-math",
"bytemuck",
"debug-glam-assert",
"all-types",
] }
base64 = "0.22"
blake3 = "1.5"
@@ -240,12 +239,8 @@ rfd = "0.17"
open = "5.3"
spin = "0.10"
clap = "4.5"
# Ensure these are kept in sync with .nix/deps/rust-gpu.nix
# Git commit required for glam=0.33 support (TODO: use release when new version is published. Last publish was Apr 17)
spirv-std = { git = "https://github.com/Rust-GPU/rust-gpu.git", rev = "2fff75a21a1909945ac85f5818843dd9960004d7", features = ["bytemuck"] }
cargo-gpu-install = { git = "https://github.com/Rust-GPU/rust-gpu.git", rev = "2fff75a21a1909945ac85f5818843dd9960004d7", default-features = false }
spirv-std = { version = "0.10.0-alpha.1", features = ["bytemuck"] }
cargo-gpu-install = { version = "0.10.0-alpha.1", default-features = false }
qrcodegen = "1.8"
lzma-rust2 = { version = "0.16", default-features = false, features = ["std", "encoder", "optimization", "xz"] }
scraper = "0.25"
+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::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
{"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
+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]]]},"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
{"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
+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
-6
View File
@@ -5,15 +5,9 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[[bin]]
name = "graphite"
path = "src/main.rs"
-6
View File
@@ -5,15 +5,9 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[dependencies]
cef-dll-sys = { workspace = true }
-3
View File
@@ -7,9 +7,6 @@ mod mac;
#[cfg(target_os = "windows")]
mod win;
// Avoid incorrect warnings about an unused dependency (this crate sets `DEP_CEF_DLL_WRAPPER_CEF_DIR` which is used in `build.rs`)
use cef_dll_sys as _;
fn main() {
#[cfg(target_os = "linux")]
linux::main().unwrap();
-3
View File
@@ -5,9 +5,6 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
-6
View File
@@ -5,15 +5,9 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[[bin]]
name = "graphite"
path = "src/main.rs"
-6
View File
@@ -5,15 +5,9 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[features]
main = ["dep:graphite-desktop"]
helper = ["dep:graphite-desktop-ui"]
-6
View File
@@ -5,15 +5,9 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[[bin]]
name = "graphite"
path = "src/main.rs"
+15 -8
View File
@@ -25,7 +25,7 @@ use crate::render::{RenderError, RenderState};
use crate::ui::{InputEvent, UiCommand, UiInstance};
use crate::window::Window;
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, IngestAction, Preferences};
use crate::wrapper::{DesktopWrapper, FolderStore, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
use crate::wrapper::{DesktopWrapper, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
pub(crate) struct App {
render_state: Option<RenderState>,
@@ -99,13 +99,7 @@ impl App {
let wake = Arc::new(move || {
wake_scheduler.schedule(AppEvent::DesktopWrapperMessage(DesktopWrapperMessage::Wake));
});
let desktop_wrapper = DesktopWrapper::new(
rand::rng().random(),
Arc::new(resource_storage),
Arc::new(FolderStore::new(dirs::app_autosave_documents_dir())),
wgpu_context.clone(),
wake,
);
let desktop_wrapper = DesktopWrapper::new(rand::rng().random(), Arc::new(resource_storage), dirs::app_autosave_documents_dir(), wgpu_context.clone(), wake);
Self {
render_state: None,
@@ -313,6 +307,19 @@ impl App {
DesktopFrontendMessage::PersistenceReadState => {
responses.push(DesktopWrapperMessage::LoadPersistedState { state: persist::read_state() });
}
DesktopFrontendMessage::PersistenceReadDocument { id } => {
if let Some(document) = persist::read_document_content(&id) {
responses.push(DesktopWrapperMessage::LoadDocumentContent { id, document });
} else {
tracing::error!("Failed to read document content for {id:?}");
}
}
DesktopFrontendMessage::PersistenceWriteDocument { id, document_serialized_content } => {
persist::write_document_content(id, document_serialized_content);
}
DesktopFrontendMessage::PersistenceDeleteDocument { id } => {
persist::delete_document(&id);
}
DesktopFrontendMessage::PersistenceWritePreferences { preferences } => {
preferences::write(preferences);
}
+52 -50
View File
@@ -1,9 +1,6 @@
use crate::wrapper::messages::PersistedState;
use crate::wrapper::messages::{DocumentId, PersistedState};
pub(crate) fn read_state() -> PersistedState {
if let Err(error) = migrate_documents() {
tracing::error!("Autosave migration failed: {error}");
}
let path = state_file_path();
let data = match std::fs::read_to_string(&path) {
Ok(d) => d,
@@ -16,13 +13,16 @@ pub(crate) fn read_state() -> PersistedState {
return PersistedState::default();
}
};
match ron::from_str(&data) {
let loaded = match ron::from_str(&data) {
Ok(d) => d,
Err(e) => {
tracing::error!("Failed to deserialize persistent data: {e}");
PersistedState::default()
return PersistedState::default();
}
}
};
garbage_collect_document_files(&loaded);
loaded
}
pub(crate) fn write_state(state: PersistedState) {
@@ -37,6 +37,47 @@ pub(crate) fn write_state(state: PersistedState) {
if let Err(e) = std::fs::write(state_file_path(), data) {
tracing::error!("Failed to write persistent data to disk: {e}");
}
garbage_collect_document_files(state);
}
pub(crate) fn write_document_content(id: DocumentId, document_content: String) {
if let Err(e) = std::fs::write(document_content_path(&id), document_content) {
tracing::error!("Failed to write document {id:?} to disk: {e}");
}
}
pub(crate) fn read_document_content(id: &DocumentId) -> Option<String> {
std::fs::read_to_string(document_content_path(id)).ok()
}
pub(crate) fn delete_document(id: &DocumentId) {
if let Err(e) = std::fs::remove_file(document_content_path(id)) {
tracing::error!("Failed to delete document {id:?} from disk: {e}");
}
}
fn garbage_collect_document_files(state: &PersistedState) {
let valid_paths: std::collections::HashSet<_> = state.documents.iter().map(|doc| document_content_path(&doc.id)).collect();
let directory = crate::dirs::app_autosave_documents_dir();
let entries = match std::fs::read_dir(&directory) {
Ok(entries) => entries,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,
Err(e) => {
tracing::error!("Failed to read autosave documents directory: {e}");
return;
}
};
for entry in entries.flatten() {
let path = entry.path();
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}");
}
}
}
fn state_file_path() -> std::path::PathBuf {
@@ -45,47 +86,8 @@ fn state_file_path() -> std::path::PathBuf {
path
}
// TODO: Remove this migration code
fn migrate_documents() -> std::io::Result<()> {
let root = crate::dirs::app_autosave_documents_dir();
let entries = match std::fs::read_dir(&root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(error),
};
for entry in entries {
let entry = match entry {
Ok(entry) => entry,
Err(error) => {
tracing::error!("Skipping an unreadable autosave entry: {error}");
continue;
}
};
if let Err(error) = migrate_document(&root, &entry) {
tracing::error!("Autosave migration of {} failed: {error}", entry.path().display());
}
}
Ok(())
}
fn migrate_document(root: &std::path::Path, entry: &std::fs::DirEntry) -> std::io::Result<()> {
let path = entry.path();
if !entry.file_type()?.is_file() || path.extension().and_then(|s| s.to_str()) != Some(graphite_desktop_wrapper::FILE_EXTENSION) {
return Ok(());
}
let Some(id) = path.file_stem().and_then(|s| s.to_str()).and_then(|s| u64::from_str_radix(s, 16).ok()) else {
return Ok(());
};
let destination = root.join(format!("{id:016x}"));
if !destination.join("legacy.graphite").exists() && !destination.join("manifest.json").exists() {
std::fs::create_dir_all(&destination)?;
let staging = destination.join("legacy.graphite.migrating");
std::fs::copy(&path, &staging)?;
std::fs::rename(staging, destination.join("legacy.graphite"))?;
}
let backup = path.with_extension(format!("{}.migrated", graphite_desktop_wrapper::FILE_EXTENSION));
if backup.exists() {
return Ok(());
}
std::fs::rename(path, backup)
fn document_content_path(id: &DocumentId) -> std::path::PathBuf {
let mut path = crate::dirs::app_autosave_documents_dir();
path.push(format!("{:x}.{}", id.0, graphite_desktop_wrapper::FILE_EXTENSION));
path
}
-6
View File
@@ -5,15 +5,9 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[features]
default = []
embedded_resources = ["dep:graphite-desktop-embedded-resources"]
-6
View File
@@ -5,15 +5,9 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[features]
gpu = ["graphite-editor/gpu", "graphene-std/shader-nodes"]
@@ -44,6 +44,10 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
let message = FrontendMessage::UpdateFullscreen { fullscreen };
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::LoadDocumentContent { id, document } => {
let message = PersistentStateMessage::LoadDocument { document_id: id, document };
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::LoadPersistedState { state } => {
let message = PersistentStateMessage::LoadState { state };
dispatcher.queue_editor_message(message);
@@ -69,6 +69,18 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
FrontendMessage::TriggerPersistenceWriteState { state } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceWriteState { state });
}
FrontendMessage::TriggerPersistenceReadDocument { document_id } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceReadDocument { id: document_id });
}
FrontendMessage::TriggerPersistenceDeleteDocument { document_id } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceDeleteDocument { id: document_id });
}
FrontendMessage::TriggerPersistenceWriteDocument { document_id, document } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceWriteDocument {
id: document_id,
document_serialized_content: document,
});
}
FrontendMessage::TriggerOpenLaunchDocuments => {
dispatcher.respond(DesktopFrontendMessage::OpenLaunchDocuments);
}
+2 -3
View File
@@ -10,7 +10,6 @@ use std::sync::Arc;
pub use graph_craft::application_io::resource::MmapResourceStorage;
pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
pub use graphite_editor::document_store::{DocumentStore, FolderStore};
pub use wgpu_executor::Texture;
pub use wgpu_executor::WgpuBackends;
pub use wgpu_executor::WgpuContext;
@@ -33,7 +32,7 @@ pub struct DesktopWrapper {
}
impl DesktopWrapper {
pub fn new(uuid_random_seed: u64, resource_storage: Arc<dyn ResourceStorage>, document_store: Arc<dyn DocumentStore>, wgpu_context: WgpuContext, schedule_wake: Wake) -> Self {
pub fn new(uuid_random_seed: u64, resource_storage: Arc<dyn ResourceStorage>, working_copy_root: std::path::PathBuf, wgpu_context: WgpuContext, schedule_wake: Wake) -> Self {
#[cfg(target_os = "windows")]
let host = Host::Windows;
#[cfg(target_os = "macos")]
@@ -44,7 +43,7 @@ impl DesktopWrapper {
let application_io = PlatformApplicationIo::new_with_context(wgpu_context);
Self {
editor: Editor::new(env, uuid_random_seed, resource_storage, document_store, application_io, schedule_wake),
editor: Editor::new(env, uuid_random_seed, resource_storage, Some(working_copy_root), application_io, schedule_wake),
}
}
+1 -1
View File
@@ -47,7 +47,7 @@ impl<'a> DesktopWrapperMessageDispatcher<'a> {
if let Err(e) = self.editor.poll_node_graph_evaluation(&mut responses)
&& e != "No active document"
{
tracing::error!("Error polling node graph: {}", e);
tracing::error!("Error poling node graph: {}", e);
}
while let Some(message) = responses.pop_front() {
self.queue_editor_message(message);
+11
View File
@@ -44,6 +44,13 @@ pub enum DesktopFrontendMessage {
enabled: bool,
},
UpdateOverlays(vello::Scene),
PersistenceWriteDocument {
id: DocumentId,
document_serialized_content: String,
},
PersistenceDeleteDocument {
id: DocumentId,
},
PersistenceWritePreferences {
preferences: Preferences,
},
@@ -52,6 +59,9 @@ pub enum DesktopFrontendMessage {
state: PersistedState,
},
PersistenceReadState,
PersistenceReadDocument {
id: DocumentId,
},
UpdateMenu {
entries: Vec<MenuItem>,
},
@@ -82,6 +92,7 @@ pub enum DesktopWrapperMessage {
PollNodeGraphEvaluation,
UpdateMaximized { maximized: bool },
UpdateFullscreen { fullscreen: bool },
LoadDocumentContent { id: DocumentId, document: String },
LoadPersistedState { state: PersistedState },
LoadPreferences { preferences: Preferences },
MenuEvent { id: String },
-7
View File
@@ -5,15 +5,9 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[features]
default = []
zip = ["dep:zip"]
@@ -40,7 +34,6 @@ web-sys = { workspace = true, features = [
"FileSystemFileHandle",
"FileSystemGetFileOptions",
"FileSystemGetDirectoryOptions",
"FileSystemRemoveOptions",
"FileSystemHandle",
"FileSystemHandleKind",
"FileSystemWritableFileStream",
@@ -6,7 +6,6 @@ use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
#[derive(Clone)]
pub struct FolderBackend {
root: PathBuf,
}
+3 -3
View File
@@ -2,11 +2,11 @@
use crate::{ByteHolder, Container, ContainerError, Result, validate_path, validate_prefix, with_trailing_slash};
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Mutex};
use std::sync::Mutex;
#[derive(Clone, Default)]
#[derive(Default)]
pub struct MemoryBackend {
files: Arc<Mutex<HashMap<String, Vec<u8>>>>,
files: Mutex<HashMap<String, Vec<u8>>>,
}
impl MemoryBackend {
+11 -67
View File
@@ -3,7 +3,6 @@
use crate::{AsyncContainer, ByteHolder, ContainerError, Result, validate_path, validate_prefix, with_trailing_slash};
use futures::channel::oneshot;
use js_sys::Uint8Array;
use std::cell::Cell;
use std::collections::{HashSet, VecDeque};
use std::sync::{Arc, Mutex};
use wasm_bindgen::JsCast;
@@ -41,33 +40,6 @@ struct Inner {
worker_active: bool,
}
thread_local! {
static LAST_WRITE_FAILURE_ALERT: Cell<Option<f64>> = const { Cell::new(None) };
}
fn report_write_error(operation: &str, path: &str, error: &JsValue) {
if is_not_found(error) {
log::warn!("OPFS {operation} on {path} dropped: the container no longer exists");
return;
}
log::error!("OPFS {operation} failure on {path}:\n{error:?}");
let now = js_sys::Date::now();
// Debounce alerts to avoid spamming the user
if LAST_WRITE_FAILURE_ALERT.get().is_some_and(|last| now - last < 60. * 1000.) {
return;
}
LAST_WRITE_FAILURE_ALERT.set(Some(now));
if let Some(window) = web_sys::window() {
let message = format!(
"Autosave is not working. Save your documents manually to avoid losing changes.\n\n\
Please report it at https://github.com/GraphiteEditor/Graphite/issues/new and include this error:\n\n\
{operation} {path}: {error:?}"
);
let _ = window.alert_with_message(&message);
}
}
#[derive(Clone)]
pub struct OpfsBackend {
inner: Arc<Mutex<Inner>>,
}
@@ -105,6 +77,8 @@ impl OpfsBackend {
guard.queue.push_back(Mutation::Barrier(sender));
kick_worker(&self.inner, &mut guard);
}
// The sender is only dropped without sending if the worker is torn down mid-drain; either way
// there is nothing left to wait for, so a receive error is treated as "already flushed".
let _ = receiver.await;
}
}
@@ -265,12 +239,12 @@ async fn drain_queue(inner: Arc<Mutex<Inner>>) {
match mutation {
Mutation::Write { path, bytes } => {
if let Err(error) = write_file(&directory, &path, &bytes).await {
report_write_error("write", &path, &error);
log::error!("OPFS background write for {path} failed: {error:?}");
}
}
Mutation::Append { path, bytes } => {
if let Err(error) = append_file(&directory, &path, &bytes).await {
report_write_error("append", &path, &error);
log::error!("OPFS background append for {path} failed: {error:?}");
}
}
Mutation::Delete { path } => {
@@ -278,7 +252,7 @@ async fn drain_queue(inner: Arc<Mutex<Inner>>) {
if let Err(error) = remove_file(&directory, &path).await
&& !is_not_found(&error)
{
report_write_error("delete", &path, &error);
log::error!("OPFS background delete for {path} failed: {error:?}");
}
}
// A receive error on the waiter side just means the reader gave up; nothing to apply.
@@ -289,11 +263,16 @@ async fn drain_queue(inner: Arc<Mutex<Inner>>) {
}
}
fn js_err(error: JsValue) -> ContainerError {
ContainerError::Backend(format!("{error:?}"))
}
/// Resolve `directory_path` (a `/`-separated relative path) under the OPFS root, creating each
/// segment. OPFS rejects directory names containing `/`, so a multi-segment path like
/// `documents/<id>` must be descended one segment at a time rather than passed whole.
async fn open_directory(directory_path: &str) -> std::result::Result<FileSystemDirectoryHandle, JsValue> {
let mut current = opfs_root().await?;
let storage = web_sys::window().ok_or_else(|| JsValue::from_str("no window"))?.navigator().storage();
let mut current: FileSystemDirectoryHandle = JsFuture::from(storage.get_directory()).await?.dyn_into()?;
for segment in directory_path.split('/').filter(|segment| !segment.is_empty()) {
let options = FileSystemGetDirectoryOptions::new();
@@ -304,37 +283,6 @@ async fn open_directory(directory_path: &str) -> std::result::Result<FileSystemD
Ok(current)
}
/// List the subdirectories directly under `directory_path`.
pub async fn list_directories(directory_path: &str) -> Result<Vec<String>> {
crate::validate_prefix(directory_path)?;
let root = opfs_root().await.map_err(js_err)?;
list_entries(&root, directory_path, EntryKind::Directory).await.map_err(|error| list_error(directory_path, error))
}
/// Remove `directory_path` recursively.
pub async fn remove_directory(directory_path: &str) -> Result<()> {
validate_path(directory_path)?;
let root = opfs_root().await.map_err(js_err)?;
let removed = async {
let (parent, name) = descend(&root, directory_path, false).await?;
let options = web_sys::FileSystemRemoveOptions::new();
options.set_recursive(true);
JsFuture::from(parent.remove_entry_with_options(name, &options)).await
}
.await;
match removed {
Ok(_) => Ok(()),
Err(error) if is_not_found(&error) => Ok(()),
Err(error) => Err(js_err(error)),
}
}
async fn opfs_root() -> std::result::Result<FileSystemDirectoryHandle, JsValue> {
let storage = web_sys::window().ok_or_else(|| JsValue::from_str("no window"))?.navigator().storage();
JsFuture::from(storage.get_directory()).await?.dyn_into()
}
/// Descend the `/`-separated path against `root` and return the directory handle plus the final segment.
async fn descend<'a>(root: &FileSystemDirectoryHandle, relative: &'a str, create_dirs: bool) -> std::result::Result<(FileSystemDirectoryHandle, &'a str), JsValue> {
let mut current = root.clone();
@@ -525,7 +473,3 @@ fn list_error(prefix: &str, error: JsValue) -> ContainerError {
js_err(error)
}
}
fn js_err(error: JsValue) -> ContainerError {
ContainerError::Backend(format!("{error:?}"))
}
-2
View File
@@ -12,7 +12,6 @@
pub mod archive;
pub mod backends;
pub mod store;
pub enum ByteHolder {
/// Bytes synthesized in memory (decompressed from an archive, produced by serialization).
@@ -351,7 +350,6 @@ impl<C: Container + ?Sized> AsyncContainer for C {
/// `AsyncContainer::read` returns `impl Future`, so `dyn AsyncContainer` is not object-safe.
/// `AnyContainer` is the workaround: `Gdd` holds one of these by value, and the `AsyncContainer`
/// impl forwards to the active variant.
#[derive(Clone)]
pub enum AnyContainer {
Memory(backends::memory::MemoryBackend),
#[cfg(not(target_family = "wasm"))]
-145
View File
@@ -1,145 +0,0 @@
use crate::backends::memory::MemoryBackend;
use crate::{AnyContainer, Result};
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Mutex;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DocumentKey(pub u64);
#[cfg(not(target_family = "wasm"))]
pub type StoreFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T>> + Send + 'a>>;
#[cfg(target_family = "wasm")]
pub type StoreFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T>> + 'a>>;
pub trait DocumentStore: Send + Sync {
fn list(&self) -> StoreFuture<'_, Vec<DocumentKey>>;
fn open(&self, key: DocumentKey) -> StoreFuture<'_, AnyContainer>;
fn remove(&self, key: DocumentKey) -> StoreFuture<'_, ()>;
}
fn directory_name(key: DocumentKey) -> String {
format!("{:016x}", key.0)
}
fn parse_directory_name(name: &str) -> Option<DocumentKey> {
(name.len() == 16 && name.bytes().all(|byte| byte.is_ascii_hexdigit()))
.then(|| u64::from_str_radix(name, 16).ok().map(DocumentKey))
.flatten()
}
#[derive(Default)]
pub struct MemoryStore {
documents: Mutex<HashMap<DocumentKey, MemoryBackend>>,
}
impl DocumentStore for MemoryStore {
fn list(&self) -> StoreFuture<'_, Vec<DocumentKey>> {
let mut keys: Vec<_> = self.documents.lock().unwrap().keys().copied().collect();
keys.sort();
Box::pin(async move { Ok(keys) })
}
fn open(&self, key: DocumentKey) -> StoreFuture<'_, AnyContainer> {
let backend = self.documents.lock().unwrap().entry(key).or_default().clone();
Box::pin(async move { Ok(AnyContainer::Memory(backend)) })
}
fn remove(&self, key: DocumentKey) -> StoreFuture<'_, ()> {
self.documents.lock().unwrap().remove(&key);
Box::pin(async { Ok(()) })
}
}
#[cfg(not(target_family = "wasm"))]
pub struct FolderStore {
root: std::path::PathBuf,
}
#[cfg(not(target_family = "wasm"))]
impl FolderStore {
pub fn new(root: impl Into<std::path::PathBuf>) -> Self {
Self { root: root.into() }
}
}
#[cfg(not(target_family = "wasm"))]
impl DocumentStore for FolderStore {
fn list(&self) -> StoreFuture<'_, Vec<DocumentKey>> {
Box::pin(async {
let entries = match std::fs::read_dir(&self.root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(error) => return Err(error.into()),
};
let mut keys: Vec<_> = entries
.filter_map(|entry| entry.ok())
.filter(|entry| entry.file_type().is_ok_and(|file_type| file_type.is_dir()))
.filter_map(|entry| parse_directory_name(&entry.file_name().to_string_lossy()))
.collect();
keys.sort();
Ok(keys)
})
}
fn open(&self, key: DocumentKey) -> StoreFuture<'_, AnyContainer> {
Box::pin(async move {
let backend = crate::backends::folder::FolderBackend::create(self.root.join(directory_name(key)))?;
Ok(AnyContainer::Folder(backend))
})
}
fn remove(&self, key: DocumentKey) -> StoreFuture<'_, ()> {
Box::pin(async move {
match std::fs::remove_dir_all(self.root.join(directory_name(key))) {
Ok(()) => Ok(()),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error.into()),
}
})
}
}
#[cfg(target_family = "wasm")]
pub struct OpfsStore {
root: String,
}
#[cfg(target_family = "wasm")]
impl OpfsStore {
pub fn new(root: impl Into<String>) -> Self {
Self {
root: root.into().trim_matches('/').to_string(),
}
}
fn document_path(&self, key: DocumentKey) -> String {
let name = directory_name(key);
if self.root.is_empty() { name } else { format!("{}/{name}", self.root) }
}
}
#[cfg(target_family = "wasm")]
impl DocumentStore for OpfsStore {
fn list(&self) -> StoreFuture<'_, Vec<DocumentKey>> {
Box::pin(async {
let paths = crate::backends::opfs::list_directories(&self.root).await?;
let mut keys: Vec<_> = paths.iter().filter_map(|path| parse_directory_name(path.rsplit('/').next()?)).collect();
keys.sort();
Ok(keys)
})
}
fn open(&self, key: DocumentKey) -> StoreFuture<'_, AnyContainer> {
Box::pin(async move {
let backend = crate::backends::opfs::OpfsBackend::open(&self.document_path(key)).await?;
Ok(AnyContainer::Opfs(backend))
})
}
fn remove(&self, key: DocumentKey) -> StoreFuture<'_, ()> {
Box::pin(async move { crate::backends::opfs::remove_directory(&self.document_path(key)).await })
}
}
-12
View File
@@ -176,15 +176,3 @@ fn folder_backend_write_sized_fills_via_mmap() {
let read_back = backend.read("resources/sized").unwrap();
assert_eq!(read_back.as_slice(), payload);
}
#[test]
fn memory_backend_clones_share_the_store() {
let backend = MemoryBackend::new();
let clone = backend.clone();
backend.write("file", b"through the original").unwrap();
assert_eq!(clone.read("file").unwrap().as_slice(), b"through the original");
clone.remove("file").unwrap();
assert!(!backend.exists("file"));
}
+1 -7
View File
@@ -5,15 +5,9 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[features]
# Runtime bridge: the editor <-> storage conversion methods (stage/commit from a `NodeNetwork`,
# `network_ids`, `declarations`). Off lets a standalone migration tool build without `graph-craft`
@@ -33,7 +27,7 @@ graphene-resource = { workspace = true }
core-types = { workspace = true, optional = true }
serde = { workspace = true }
serde_json = { workspace = true }
postcard = { workspace = true }
rmp-serde = { workspace = true }
futures = { workspace = true }
thiserror = "2.0"
log = { workspace = true }
+51 -33
View File
@@ -8,16 +8,18 @@ pub enum Codec {
Json,
/// Newline-delimited compact JSON, one value per line.
JsonLines,
/// A single postcard blob. `append` to a non-empty buffer errors.
Postcard,
/// Length-prefixed postcard frames: `[u32 big-endian length][postcard bytes]` per value.
PostcardFrames,
/// A single MessagePack blob. `append` to a non-empty buffer errors.
MessagePack,
/// Length-prefixed MessagePack frames: `[u32 big-endian length][MessagePack bytes]` per value.
MessagePackFrames,
}
#[derive(Debug, thiserror::Error)]
pub enum CodecError {
#[error("postcard error: {0}")]
Postcard(#[from] postcard::Error),
#[error("MessagePack encode error: {0}")]
MessagePackEncode(#[from] rmp_serde::encode::Error),
#[error("MessagePack decode error: {0}")]
MessagePackDecode(#[from] rmp_serde::decode::Error),
#[error("JSON error: {0}")]
Json(#[from] serde_json::Error),
#[error("frame length {0} exceeds u32")]
@@ -39,8 +41,8 @@ impl Codec {
match self {
Codec::Json => "json",
Codec::JsonLines => "jsonl",
Codec::Postcard => "bin",
Codec::PostcardFrames => "frames",
Codec::MessagePack => "bin",
Codec::MessagePackFrames => "frames",
}
}
@@ -60,15 +62,15 @@ impl Codec {
output.push(b'\n');
Ok(())
}
Codec::Postcard => {
Codec::MessagePack => {
if !output.is_empty() {
return Err(CodecError::SingleValueAlreadyWritten);
}
postcard::to_io(value, &mut *output)?;
rmp_serde::encode::write(output, value)?;
Ok(())
}
Codec::PostcardFrames => {
let payload = postcard::to_stdvec(value)?;
Codec::MessagePackFrames => {
let payload = rmp_serde::to_vec(value)?;
let length = u32::try_from(payload.len()).map_err(|_| CodecError::FrameTooLarge(payload.len()))?;
output.extend_from_slice(&length.to_be_bytes());
output.extend_from_slice(&payload);
@@ -89,11 +91,11 @@ impl Codec {
remaining: bytes,
_marker: std::marker::PhantomData,
}),
Codec::Postcard => {
let single = postcard::from_bytes::<T>(bytes).map_err(CodecError::from);
Codec::MessagePack => {
let single = rmp_serde::from_slice::<T>(bytes).map_err(CodecError::from);
Box::new(std::iter::once(single))
}
Codec::PostcardFrames => Box::new(PostcardFrameIter {
Codec::MessagePackFrames => Box::new(MessagePackFrameIter {
remaining: bytes,
_marker: std::marker::PhantomData,
}),
@@ -151,12 +153,12 @@ impl<T: DeserializeOwned> Iterator for JsonLineIter<'_, T> {
}
}
struct PostcardFrameIter<'a, T> {
struct MessagePackFrameIter<'a, T> {
remaining: &'a [u8],
_marker: std::marker::PhantomData<fn() -> T>,
}
impl<T: DeserializeOwned> Iterator for PostcardFrameIter<'_, T> {
impl<T: DeserializeOwned> Iterator for MessagePackFrameIter<'_, T> {
type Item = Result<T, CodecError>;
fn next(&mut self) -> Option<Self::Item> {
@@ -181,7 +183,7 @@ impl<T: DeserializeOwned> Iterator for PostcardFrameIter<'_, T> {
let (frame, after) = tail.split_at(length);
self.remaining = after;
Some(postcard::from_bytes(frame).map_err(CodecError::from))
Some(rmp_serde::from_slice(frame).map_err(CodecError::from))
}
}
@@ -222,20 +224,31 @@ mod tests {
}
#[test]
fn postcard_round_trip_single() {
fn message_pack_round_trip_single() {
let frame = Frame { id: 99, label: "blob".into() };
let bytes = Codec::Postcard.write_single(&frame).unwrap();
let decoded: Frame = Codec::Postcard.read_single(&bytes).unwrap();
let bytes = Codec::MessagePack.write_single(&frame).unwrap();
let decoded: Frame = Codec::MessagePack.read_single(&bytes).unwrap();
assert_eq!(decoded, frame);
}
#[test]
fn postcard_append_to_non_empty_errors() {
fn message_pack_append_to_non_empty_errors() {
let mut buffer = vec![0xAB];
let result = Codec::Postcard.append(&mut buffer, &Frame { id: 1, label: "x".into() });
let result = Codec::MessagePack.append(&mut buffer, &Frame { id: 1, label: "x".into() });
assert!(matches!(result, Err(CodecError::SingleValueAlreadyWritten)), "got {result:?}");
}
/// A type-erased `serde_json::Value` round-trips through the binary codec: the property postcard
/// could not satisfy (it raises `WontImplement` on self-describing values), which is why the
/// resource/attribute deltas that carry `serde_json::Value` bodies need a self-describing codec.
#[test]
fn message_pack_round_trips_serde_json_value() {
let value = serde_json::json!({ "kind": "embedded", "priority": 1.5, "tags": ["a", "b"] });
let bytes = Codec::MessagePack.write_single(&value).unwrap();
let decoded: serde_json::Value = Codec::MessagePack.read_single(&bytes).unwrap();
assert_eq!(decoded, value);
}
#[test]
fn json_lines_round_trip_and_skip_blanks() {
let frames = [Frame { id: 1, label: "alpha".into() }, Frame { id: 2, label: "beta".into() }];
@@ -250,13 +263,13 @@ mod tests {
}
#[test]
fn postcard_frames_round_trip() {
fn message_pack_frames_round_trip() {
let frames = frames();
let mut buffer = Vec::new();
for frame in &frames {
Codec::PostcardFrames.append(&mut buffer, frame).unwrap();
Codec::MessagePackFrames.append(&mut buffer, frame).unwrap();
}
let decoded: Vec<Frame> = Codec::PostcardFrames.iter(&buffer).collect::<Result<_, _>>().unwrap();
let decoded: Vec<Frame> = Codec::MessagePackFrames.iter(&buffer).collect::<Result<_, _>>().unwrap();
assert_eq!(decoded, frames);
}
@@ -264,27 +277,27 @@ mod tests {
/// deterministically (declared length exceeds the bytes that actually made it to disk) rather
/// than decoding a partial value into a plausible-but-wrong one.
#[test]
fn postcard_frames_detect_truncation() {
fn message_pack_frames_detect_truncation() {
let mut buffer = Vec::new();
Codec::PostcardFrames.append(&mut buffer, &Frame { id: 7, label: "ok".into() }).unwrap();
Codec::MessagePackFrames.append(&mut buffer, &Frame { id: 7, label: "ok".into() }).unwrap();
buffer.truncate(buffer.len() - 1);
let last = Codec::PostcardFrames.iter::<Frame>(&buffer).last().unwrap();
let last = Codec::MessagePackFrames.iter::<Frame>(&buffer).last().unwrap();
assert!(matches!(last, Err(CodecError::TruncatedFrame { .. })), "got {last:?}");
}
/// A buffer whose first record's length prefix itself is incomplete (fewer than 4 bytes) is
/// reported as a truncated prefix rather than mis-read as a zero-length frame.
#[test]
fn postcard_frames_detect_truncated_length_prefix() {
fn message_pack_frames_detect_truncated_length_prefix() {
let buffer = vec![0x00, 0x00];
let last = Codec::PostcardFrames.iter::<Frame>(&buffer).last().unwrap();
let last = Codec::MessagePackFrames.iter::<Frame>(&buffer).last().unwrap();
assert!(matches!(last, Err(CodecError::TruncatedLengthPrefix(2))), "got {last:?}");
}
#[test]
fn write_single_then_read_with_iter_yields_one() {
let frame = Frame { id: 5, label: "one".into() };
for codec in [Codec::Json, Codec::JsonLines, Codec::Postcard, Codec::PostcardFrames] {
for codec in [Codec::Json, Codec::JsonLines, Codec::MessagePack, Codec::MessagePackFrames] {
let bytes = codec.write_single(&frame).unwrap();
let collected: Vec<Frame> = codec.iter(&bytes).collect::<Result<_, _>>().unwrap();
assert_eq!(collected, vec![Frame { id: 5, label: "one".into() }], "codec {codec:?}");
@@ -302,7 +315,12 @@ mod tests {
#[test]
fn extensions_are_distinct() {
let exts = [Codec::Json.extension(), Codec::JsonLines.extension(), Codec::Postcard.extension(), Codec::PostcardFrames.extension()];
let exts = [
Codec::Json.extension(),
Codec::JsonLines.extension(),
Codec::MessagePack.extension(),
Codec::MessagePackFrames.extension(),
];
let unique: std::collections::HashSet<_> = exts.iter().collect();
assert_eq!(unique.len(), exts.len(), "extensions collide: {exts:?}");
}
-3
View File
@@ -35,9 +35,6 @@ pub enum Error {
#[cfg(feature = "conversion")]
#[error("commit error: {0}")]
Commit(#[from] CommitError),
/// The container has no manifest, cannot be opened.
#[error("container has no manifest")]
MissingManifest,
/// The manifest's `format` field is not the `.gdd` magic, so this is not a `.gdd` document.
#[error("not a .gdd document (manifest format = {found:?}, expected {expected:?})")]
WrongFormat { found: String, expected: &'static str },
-4
View File
@@ -146,14 +146,10 @@ impl<L: Layout> Gdd<L> {
// Carry the per-peer cursor + view settings so a `.gdd` reopened elsewhere restores the viewport.
let session_state = SessionState {
peer_id: self.session.peer(),
user_id: self.session.user(),
head_rev: self.session.head_rev(),
last_broadcast_rev: self.session.last_broadcast_rev(),
redo_stack: self.session.redo_stack().to_vec(),
next_node_counter: self.session.next_node_counter(),
last_hot_sequence: self.session.last_hot_sequence(),
settled: self.session.settled_marks().clone(),
clock: self.session.clock_counter(),
view_settings: self.view_settings.clone(),
network_view_settings: self.network_view_settings.clone(),
};
+59 -49
View File
@@ -6,6 +6,7 @@
//!
//! See the "On-disk container" section of `node-graph/rfcs/document-format.md` for the format spec.
use std::sync::Arc;
// `Path` and `FolderBackend` are only used by the native-only path-based open/create, so they're
// gated off wasm to avoid unused-import warnings.
#[cfg(not(target_family = "wasm"))]
@@ -13,10 +14,10 @@ use std::path::Path;
#[cfg(not(target_family = "wasm"))]
use document_container::backends::folder::FolderBackend;
use document_container::{AnyContainer, AsyncContainer, ByteHolder};
use document_container::{AnyContainer, AsyncContainer, ByteHolder, ContainerError};
#[cfg(feature = "conversion")]
use document_graph_storage::{CommitError, NodeMetadataSource};
use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session, UserId};
use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session};
#[cfg(feature = "conversion")]
use graphene_resource::LoadResource;
use graphene_resource::ResourceHash;
@@ -48,28 +49,30 @@ pub type GddV1 = Gdd<GddV1Layout>;
pub const MANIFEST_CODEC: Codec = Codec::Json;
/// Working-copy codecs. The working copy lives in appdata, not under VCS — these defaults
/// optimize for size and write cost. JSON/JSONL is opt-in via `ExportFormat::Folder` for users who
/// want a diffable on-disk representation. Recorded in the manifest at create time and read back on
/// open (see [`manifest::PayloadCodecs`]), so the persist path never probes the filesystem.
/// optimize for size and write cost. MessagePack is self-describing, so it round-trips the
/// type-erased `serde_json::Value` bodies that resource and attribute deltas carry (a non-self-
/// describing format like postcard cannot). JSON/JSONL is opt-in via `ExportFormat::Folder` for
/// users who want a diffable on-disk representation. Recorded in the manifest at create time and
/// read back on open (see [`manifest::PayloadCodecs`]), so the persist path never probes the filesystem.
pub const DEFAULT_SESSION_CODEC: Codec = Codec::Json;
pub const DEFAULT_REGISTRY_CODEC: Codec = Codec::Postcard;
pub const DEFAULT_HISTORY_CODEC: Codec = Codec::PostcardFrames;
pub const DEFAULT_HOT_LOG_CODEC: Codec = Codec::PostcardFrames;
pub const DEFAULT_REGISTRY_CODEC: Codec = Codec::MessagePack;
pub const DEFAULT_HISTORY_CODEC: Codec = Codec::MessagePackFrames;
pub const DEFAULT_HOT_LOG_CODEC: Codec = Codec::MessagePackFrames;
/// Editor-facing handle. Owns the `Session` and the working-copy container; mutations are mirrored
/// to disk continuously (every retirement appends to the history file and re-snapshots the registry).
///
/// The per-edit persist path (`commit_from_runtime`, `apply_hot_op`, `retire`) is synchronous and
/// read-free: the manifest is cached in memory (so payload codecs need no disk read), and writes go
/// through the container's sync write surface. Only `open` / `export` are async, since they
/// through the container's sync write surface. Only `open` / `create` / `export` are async, since they
/// read.
/// `Clone` shares the working-copy container (`AnyContainer` is a handle) so a cloned handle reads and writes
/// `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.
#[derive(Clone)]
pub struct Gdd<L: Layout = GddV1Layout> {
pub(crate) session: Session,
pub(crate) working: AnyContainer,
pub(crate) working: Arc<AnyContainer>,
pub(crate) layout: L,
/// In-memory copy of the manifest, kept authoritative since `Gdd` is its sole writer. Holds the
/// per-payload codecs so the persist path never probes the filesystem, keeping it fully read-free
@@ -77,10 +80,10 @@ pub struct Gdd<L: Layout = GddV1Layout> {
pub(crate) manifest: Manifest,
/// Per-peer view settings (PTZ, rulers, etc.), persisted in `session.json` not the registry, so
/// they stay out of the CRDT/history. Opaque to the storage layer; the editor owns the keys/values.
pub(crate) view_settings: std::collections::BTreeMap<String, document_graph_storage::Value>,
pub(crate) view_settings: std::collections::BTreeMap<String, serde_json::Value>,
/// 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, document_graph_storage::Value>>,
pub(crate) network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, serde_json::Value>>,
}
/// Native folder-backed convenience constructors. On wasm the editor builds an OPFS-backed
@@ -98,10 +101,10 @@ impl<L: Layout + Default> Gdd<L> {
/// Create a fresh, empty working copy at `path` bound to `peer`. Writes a default manifest
/// and session state; the caller fills in editor metadata via [`Gdd::update_manifest`].
pub fn create(path: &Path, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
pub async fn create(path: &Path, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
let working = AnyContainer::Folder(FolderBackend::create(path)?);
let layout = L::default();
Self::create_in(working, layout, peer, document_uuid, editor_version, stdlib_version)
Self::create_in(working, layout, peer, document_uuid, editor_version, stdlib_version).await
}
}
@@ -121,14 +124,10 @@ impl<L: Layout> Gdd<L> {
/// Backend-agnostic open. Splits out so tests can supply a [`document_container::backends::memory::MemoryBackend`].
///
/// # Errors
/// [`Error::MissingManifest`] if the container holds no manifest, [`Error::WrongFormat`] / [`Error::UnsupportedVersion`]
/// if it fails validation, plus the usual [`Error::Read`] / [`Error::Codec`] / [`Error::Crdt`] if a payload is malformed.
/// [`Error::WrongFormat`] / [`Error::UnsupportedVersion`] if the manifest fails validation, plus
/// the usual [`Error::Read`] / [`Error::Codec`] / [`Error::Crdt`] if a payload is malformed.
pub async fn open_in(working: AnyContainer, layout: L) -> Result<Self, Error> {
let manifest: Manifest = match io::read_single(&working, layout.manifest_basename(), MANIFEST_CODEC).await {
Ok(manifest) => manifest,
Err(io::ReadError::NotFound { .. }) => return Err(Error::MissingManifest),
Err(error) => return Err(error.into()),
};
let manifest: Manifest = io::read_single(&working, layout.manifest_basename(), MANIFEST_CODEC).await?;
validate_manifest(&manifest)?;
let codecs = manifest.codecs;
@@ -141,19 +140,18 @@ impl<L: Layout> Gdd<L> {
let has_history = io::exists(&working, layout.history_basename(), codecs.history).await;
let peer = session_state.peer_id;
let user = session_state.user_id;
let mut session = match (has_registry, has_history) {
(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, user, registry, history, session_state.head_rev, session_state.redo_stack, session_state.next_node_counter)
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.
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
Session::bootstrap_from_registry(peer, user, registry)?
Session::bootstrap_from_registry(peer, registry)?
}
(false, _) => Session::replay_from_history(peer, user, load_history(&working, &layout, codecs.history).await?, session_state.next_node_counter)?,
(false, _) => Session::replay_from_history(peer, load_history(&working, &layout, codecs.history).await?, session_state.next_node_counter)?,
};
// Restore the published frontier (silent/published undo boundary) regardless of which load arm ran.
@@ -161,15 +159,11 @@ impl<L: Layout> Gdd<L> {
session.publish_up_to(rev);
}
session.restore_hot_sequence(session_state.last_hot_sequence);
session.restore_clock(session_state.clock);
// Before the hot log replays, so a settled op in it is dropped rather than staged again.
session.absorb_settled_marks(&session_state.settled);
replay_hot_log(&working, &layout, codecs.hot_log, &mut session).await?;
Ok(Self {
session,
working,
working: Arc::new(working),
layout,
manifest,
view_settings: session_state.view_settings,
@@ -179,15 +173,11 @@ impl<L: Layout> Gdd<L> {
/// Backend-agnostic create. Records the working-copy default codecs (see `DEFAULT_*_CODEC`) in
/// the manifest and writes each payload with its recorded codec.
pub fn create_in(working: AnyContainer, layout: L, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
pub async fn create_in(working: AnyContainer, layout: L, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
let manifest = Manifest::new(document_uuid, editor_version, stdlib_version);
let codecs = manifest.codecs;
io::write_single(&working, layout.manifest_basename(), MANIFEST_CODEC, &manifest)?;
let session_state = SessionState {
peer_id: peer,
user_id: UserId(peer.0),
..Default::default()
};
let session_state = SessionState { peer_id: peer, ..Default::default() };
io::write_single(&working, layout.session_basename(), codecs.session, &session_state)?;
let session = Session::with_peer(peer);
@@ -195,7 +185,7 @@ impl<L: Layout> Gdd<L> {
Ok(Self {
session,
working,
working: Arc::new(working),
layout,
manifest,
view_settings: std::collections::BTreeMap::new(),
@@ -266,13 +256,13 @@ impl<L: Layout> Gdd<L> {
/// The per-peer view settings read from `session.json` (PTZ, rulers, overlays, snapping, collapse).
/// Opaque `ui::doc::*` blobs; the editor decodes them. Empty for a fresh document.
pub fn view_settings(&self) -> &std::collections::BTreeMap<String, document_graph_storage::Value> {
pub fn view_settings(&self) -> &std::collections::BTreeMap<String, serde_json::Value> {
&self.view_settings
}
/// The per-network view settings read from `session.json` (node-graph nav + previewing), keyed by
/// [`NetworkId`](document_graph_storage::NetworkId). Opaque `ui::nav::*` / `ui::previewing` blobs the editor decodes.
pub fn network_view_settings(&self) -> &std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, document_graph_storage::Value>> {
pub fn network_view_settings(&self) -> &std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, serde_json::Value>> {
&self.network_view_settings
}
@@ -295,20 +285,31 @@ impl<L: Layout> Gdd<L> {
}
/// Drop the session and return the working-copy container + layout.
/// Intended for test code that needs to reopen against the same container; panics if the container
/// is still shared by a `Gdd` clone (tests don't clone before calling this).
pub fn into_storage(self) -> (AnyContainer, L) {
(self.working, self.layout)
let working = Arc::try_unwrap(self.working).unwrap_or_else(|_| panic!("into_storage called while the working-copy container is still shared by a Gdd clone"));
(working, self.layout)
}
/// Resolve every proto-node declaration referenced by the registry or its history into a
/// [`document_graph_storage::Declarations`] map, loading each `ProtoNode`'s bytes from `byte_store`
/// (the global cache in the editor, the working-copy container for standalone). Covers history so
/// the map can serve any undo/redo target. Cold-path (mount / open); async because resource loads are.
/// Resolve the proto-node declarations referenced by the registry into a [`document_graph_storage::Declarations`]
/// map, loading each `ProtoNode`'s bytes from `byte_store` (the global cache in the editor, the
/// working-copy container for standalone). Only resources referenced by `Implementation::ProtoNode`
/// are visited, so image/font resources are skipped. Cold-path (open / `to_runtime`); async
/// because resource loads are.
#[cfg(feature = "conversion")]
pub async fn declarations(&self, byte_store: &dyn LoadResource) -> document_graph_storage::Declarations {
use document_graph_storage::Implementation;
let registry = self.session.registry();
let mut declarations = document_graph_storage::Declarations::new();
for (id, hash) in self.session.all_declaration_resources() {
let Some(hash) = hash else {
for node in registry.node_instances.values() {
let Implementation::ProtoNode(id) = node.implementation() else { continue };
if declarations.contains_key(id) {
continue;
}
let Some(hash) = registry.resources.get(id).and_then(|entry| entry.hash) else {
log::error!("Declaration resource {id} has no resolved hash; cannot load ProtoNode");
continue;
};
@@ -318,7 +319,7 @@ impl<L: Layout> Gdd<L> {
};
match document_graph_storage::decode_declaration(resource.as_ref()) {
Ok(proto) => {
declarations.insert(id, proto);
declarations.insert(*id, proto);
}
Err(error) => log::error!("Failed to deserialize ProtoNode for {id}: {error}"),
}
@@ -327,7 +328,16 @@ impl<L: Layout> Gdd<L> {
declarations
}
/// Read the embedded legacy `.graphite` document, if present.
/// Store the legacy `.graphite` document bytes verbatim inside the working copy (dual-write soak).
/// Synchronous (hot-path safe via `write_non_blocking`): called at the autosave boundary alongside
/// the registry snapshot. The bytes are opaque to `Gdd` — it never deserializes them.
// TODO: Add feature gate for legacy embedding
pub fn store_legacy_document(&self, bytes: &[u8]) -> Result<(), ContainerError> {
self.working.write_non_blocking(self.layout.legacy_path(), bytes)
}
/// Read back the embedded legacy `.graphite` document, if present. The compare-on-open oracle and
/// the recovery fallback both go through here. `None` when no legacy blob was ever written.
pub async fn read_legacy_document(&self) -> Option<ByteHolder> {
self.working.read(self.layout.legacy_path()).await.ok()
}
+14 -16
View File
@@ -6,7 +6,7 @@
use document_container::AsyncContainer;
#[cfg(feature = "conversion")]
use document_graph_storage::NodeMetadataSource;
use document_graph_storage::{HotOp, Rev, TimeStamp, Value};
use document_graph_storage::{HotOp, Rev, TimeStamp};
#[cfg(feature = "conversion")]
use graphene_resource::ResourceStorage;
@@ -47,7 +47,7 @@ impl<L: Layout> Gdd<L> {
/// declaration bytes. The working registry reflects the edit immediately, but nothing enters durable
/// retired history until [`retire_pending_interaction`](Self::retire_pending_interaction). Staging on
/// every edit while retiring only at interaction boundaries lets several edits coalesce into one retired
/// interaction. Returns the decoded declarations the snapshot references, for the caller's cache.
/// interaction.
///
/// # Errors
/// [`Error::Commit`] if the runtime diff is rejected by the session. On an [`Error::Container`] /
@@ -60,8 +60,8 @@ impl<L: Layout> Gdd<L> {
metadata: &M,
resources: &graphene_resource::ResourceRegistry,
byte_store: &dyn ResourceStorage,
) -> Result<document_graph_storage::Declarations, Error> {
let (hot_ops, conversion) = self.session.stage_from_runtime(network, metadata, resources)?;
) -> Result<(), Error> {
let (hot_ops, declaration_bytes) = self.session.stage_from_runtime(network, metadata, resources)?;
for hot_op in &hot_ops {
self.append_hot_frame(hot_op)?;
@@ -70,10 +70,10 @@ impl<L: Layout> Gdd<L> {
// 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
// identical bytes on every commit is an idempotent no-op.
for bytes in conversion.declaration_bytes.values() {
for bytes in declaration_bytes.values() {
byte_store.store(bytes);
}
Ok(conversion.declarations)
Ok(())
}
/// Stage ops the caller built from what the editor recorded, rather than deriving them by converting
@@ -173,7 +173,7 @@ impl<L: Layout> Gdd<L> {
/// Unlike the per-interaction marker written inline at retire, this targets an already-written delta, so
/// the whole history file is rewritten in topological order. O(history) — fine for occasional user
/// labeling, not for per-interaction marking (which uses the inline path). No-op if `rev` is unknown.
pub fn annotate_delta(&mut self, rev: Rev, key: &str, value: Value) -> Result<(), Error> {
pub fn annotate_delta(&mut self, rev: Rev, key: &str, value: serde_json::Value) -> Result<(), Error> {
if self.session.annotate_delta(rev, key, value) {
self.rewrite_history()?;
}
@@ -194,14 +194,10 @@ impl<L: Layout> Gdd<L> {
fn persist_session_state(&mut self) -> Result<(), Error> {
let state = SessionState {
peer_id: self.session.peer(),
user_id: self.session.user(),
head_rev: self.session.head_rev(),
last_broadcast_rev: self.session.last_broadcast_rev(),
redo_stack: self.session.redo_stack().to_vec(),
next_node_counter: self.session.next_node_counter(),
last_hot_sequence: self.session.last_hot_sequence(),
settled: self.session.settled_marks().clone(),
clock: self.session.clock_counter(),
view_settings: self.view_settings.clone(),
network_view_settings: self.network_view_settings.clone(),
};
@@ -209,16 +205,18 @@ impl<L: Layout> Gdd<L> {
Ok(())
}
/// Re-snapshot the retired registry to `registry.bin`. `Session::load` trusts it to match the persisted `head`
/// and replays the hot log on top, so it must hold no hot op, and any cursor move must re-persist it.
/// Re-snapshot the materialized working registry to `registry.bin`. `Session::load` trusts the stored
/// 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`).
fn persist_registry_snapshot(&mut self) -> Result<(), Error> {
io::write_single(&self.working, self.layout.registry_basename(), self.manifest.codecs.registry, self.session.retired_registry())?;
io::write_single(&self.working, self.layout.registry_basename(), self.manifest.codecs.registry, self.session.registry())?;
Ok(())
}
/// Replace the per-peer view settings and persist them to `session.json`. Called by the editor when
/// the viewport or a document-level toggle changes; never enters the registry, history, or CRDT.
pub fn set_view_settings(&mut self, view_settings: std::collections::BTreeMap<String, document_graph_storage::Value>) -> Result<(), Error> {
pub fn set_view_settings(&mut self, view_settings: std::collections::BTreeMap<String, serde_json::Value>) -> Result<(), Error> {
self.view_settings = view_settings;
self.persist_session_state()
}
@@ -234,7 +232,7 @@ impl<L: Layout> Gdd<L> {
/// enters the registry, history, or CRDT.
pub fn set_network_view_settings(
&mut self,
network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, document_graph_storage::Value>>,
network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, serde_json::Value>>,
) -> Result<(), Error> {
self.network_view_settings = network_view_settings;
self.persist_session_state()
+3 -2
View File
@@ -4,6 +4,7 @@
#[cfg(not(target_family = "wasm"))]
use std::path::Path;
use std::sync::Arc;
use document_container::{AnyContainer, AsyncContainer, ByteHolder, ContainerError};
use graphene_resource::ResourceFuture;
@@ -38,7 +39,7 @@ impl<L: Layout> Gdd<L> {
#[cfg(not(target_family = "wasm"))]
pub fn add_resource_from_path(&mut self, id: document_graph_storage::ResourceId, hash: ResourceHash, src: &Path) -> Result<(), Error> {
let dest_path = self.layout.resource_path(&hash);
if let AnyContainer::Folder(folder) = &self.working {
if let AnyContainer::Folder(folder) = self.working.as_ref() {
let full = folder.root().join(&dest_path);
if let Some(parent) = full.parent() {
std::fs::create_dir_all(parent).map_err(ContainerError::Io)?;
@@ -101,7 +102,7 @@ impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
}
}
pub struct ResourceProxy<T: Layout>(AnyContainer, T);
pub struct ResourceProxy<T: Layout>(Arc<AnyContainer>, T);
impl<L: Layout + Send + Sync> LoadResource for ResourceProxy<L> {
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
+6 -22
View File
@@ -4,7 +4,7 @@
//!
//! Lives in `session.json`. Rewritten on retirement.
use document_graph_storage::{HotSequence, NetworkId, PeerId, Rev, SettledHotOps, UserId, Value};
use document_graph_storage::{NetworkId, PeerId, Rev};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
@@ -15,17 +15,13 @@ pub struct SessionState {
/// tiebreaking and minting peer-scoped IDs.
#[serde(default)]
pub peer_id: PeerId,
/// The person using this device, which the peer registers as, so authorship and undo follow the person
/// across the peer ids they accumulate.
#[serde(default)]
pub user_id: UserId,
/// Local-chain cursor. Points at the most recently applied retired delta, or `None` on an empty
/// document (no commits yet).
#[serde(default)]
pub head_rev: Option<Rev>,
/// Published frontier: the latest retired commit broadcast to a peer. Commits after it are silently
/// rewritable on undo; commits at or before it are published. `None` until broadcast transport lands.
#[serde(default)]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_broadcast_rev: Option<Rev>,
/// Revs the user has undone past, so redo survives a reopen. (The legacy `VecDeque` redo history
/// is not persisted, so within the shadow phase this is strictly more capable than the live editor.)
@@ -35,24 +31,12 @@ pub struct SessionState {
/// collide on minted IDs.
#[serde(default)]
pub next_node_counter: u64,
/// The sequence of the last hot op this peer authored, feeding [`document_graph_storage::HotOp::sequence`], so a
/// reopen never reuses a spent sequence.
#[serde(default)]
pub last_hot_sequence: HotSequence,
/// 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)]
pub view_settings: BTreeMap<String, Value>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub view_settings: BTreeMap<String, serde_json::Value>,
/// Per-network view settings (node-graph nav + previewing), keyed by the stable storage [`NetworkId`].
/// Per-peer like [`view_settings`](Self::view_settings); opaque `ui::nav::*` / `ui::previewing` blobs.
#[serde(default)]
pub network_view_settings: BTreeMap<NetworkId, BTreeMap<String, Value>>,
/// Which hot ops are retired, so a late copy a peer re-sends after a reopen is dropped rather than retired a second
/// time. About one sequence per author; runs only for ops in flight when saved.
#[serde(default)]
pub settled: SettledHotOps,
/// The Lamport counter, so a reopen never mints a stamp already spent, even one no op in history or the hot log
/// carries any more.
#[serde(default)]
pub clock: u64,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub network_view_settings: BTreeMap<NetworkId, BTreeMap<String, serde_json::Value>>,
}
+70 -45
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, HotSequence, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp};
use document_graph_storage::{HotOp, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp};
fn empty_container() -> AnyContainer {
AnyContainer::Memory(MemoryBackend::new())
@@ -44,7 +44,7 @@ fn create_in_round_trips_empty_document() {
futures::executor::block_on(async {
let container = empty_container();
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()) {
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()).await {
Ok(gdd) => gdd,
Err(error) => panic!("create_in failed: {error:?}"),
};
@@ -82,7 +82,9 @@ fn open_in_rejects_wrong_format_magic() {
#[test]
fn manifest_returns_what_create_in_wrote() {
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(13), 0xC0FFEE, "ed-1.2".into(), "std-0.7".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(13), 0xC0FFEE, "ed-1.2".into(), "std-0.7".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
assert_eq!(gdd.session().peer(), PeerId(13));
@@ -97,7 +99,9 @@ fn manifest_returns_what_create_in_wrote() {
#[test]
fn update_manifest_changes_visible_after_reopen() {
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
gdd.update_manifest(|m| m.editor_version = "ed-NEW".into())
.unwrap_or_else(|error| panic!("update_manifest failed: {error:?}"));
@@ -112,7 +116,9 @@ fn update_manifest_changes_visible_after_reopen() {
#[test]
fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
// AddNetwork on the root network. Idempotent at apply, so two hot ops applied in sequence
// produces one network in the registry.
@@ -122,7 +128,6 @@ fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
sequence: HotSequence(1),
};
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
@@ -138,7 +143,9 @@ fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
#[test]
fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
// Two hot ops: one with low timestamp (will retire), one with high (will stay).
let early = HotOp {
@@ -147,7 +154,6 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
sequence: HotSequence(1),
};
let late = HotOp {
op: RegistryDelta::AddNetwork {
@@ -155,7 +161,6 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 10, peer: PeerId(5) },
sequence: HotSequence(2),
};
gdd.apply_hot_op(early).unwrap();
gdd.apply_hot_op(late).unwrap();
@@ -184,7 +189,9 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
#[test]
fn last_broadcast_rev_persists_across_reopen() {
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
// Retire one op so there is a real retired rev to mark as published.
let op = HotOp {
@@ -193,7 +200,6 @@ fn last_broadcast_rev_persists_across_reopen() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
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:?}"));
@@ -214,7 +220,9 @@ fn export_folder_round_trips_through_open() {
use document_format::{ExportFormat, ExportOptions};
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("export");
@@ -223,7 +231,7 @@ fn export_folder_round_trips_through_open() {
.await
.unwrap_or_else(|error| panic!("export failed: {error:?}"));
// Payloads keep the working-copy codecs: registry is postcard (`.bin`), manifest is JSON.
// Payloads keep the working-copy codecs: registry is MessagePack (`.bin`), manifest is JSON.
assert!(dest.join("registry.bin").exists());
assert!(dest.join("manifest.json").exists());
assert!(dest.join("session.json").exists());
@@ -242,7 +250,9 @@ fn export_zip_round_trips_via_deserialize() {
use document_format::{ExportFormat, ExportOptions};
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(4), 0xCD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(4), 0xCD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("doc.gdd.zip");
@@ -267,7 +277,9 @@ fn export_rejects_invalid_options() {
use document_format::{ExportFormat, ExportOptions};
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xEF, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("nope");
@@ -290,7 +302,9 @@ fn resource_round_trip_add_read_remove() {
use graphene_resource::{ResourceHash, ResourceId};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(99), 0xCAFE, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(99), 0xCAFE, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let payload = b"deadbeef cafe babe";
let hash = ResourceHash::from(&payload[..]);
@@ -320,7 +334,9 @@ fn resource_survives_reopen() {
use graphene_resource::{ResourceHash, ResourceId};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(7), 0xC0DE, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(7), 0xC0DE, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let payload = b"persistent bytes";
let hash = ResourceHash::from(&payload[..]);
@@ -349,7 +365,9 @@ fn resource_from_path_uses_fs_copy_on_folder_backend() {
// Need a folder-backed working copy to exercise the fs::copy path.
let working_dir = tempfile::tempdir().unwrap();
let working = AnyContainer::Folder(FolderBackend::create(working_dir.path()).unwrap());
let mut gdd = GddV1::create_in(working, GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(working, GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
// Source file outside the working copy.
let payload = b"external resource bytes";
@@ -373,7 +391,9 @@ fn export_carries_resources() {
use graphene_resource::{ResourceHash, ResourceId};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(2), 0xBC, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(2), 0xBC, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let payload = b"exported resource";
let hash = ResourceHash::from(&payload[..]);
@@ -396,12 +416,14 @@ fn export_carries_resources() {
#[test]
fn embed_all_resources_materializes_link_only_resource() {
use document_format::{ExportFormat, ExportOptions};
use document_graph_storage::{NoMetadata, to_value};
use document_graph_storage::NoMetadata;
use graph_craft::application_io::resource::ResourceStorage;
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(8), 0xF00D, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(8), 0xF00D, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
// A resource whose only source is a URL, resolved to a hash. The bytes live solely in the
// byte store; the working copy never holds them.
@@ -448,8 +470,8 @@ fn embed_all_resources_materializes_link_only_resource() {
let entry = reopened.registry().resources.get(&id).expect("resource entry survived export");
assert_eq!(entry.hash, Some(hash));
let embedded = to_value(&DataSource::Embedded).unwrap();
let url = to_value(&DataSource::Url("https://example.com/r.bin".parse().unwrap())).unwrap();
let embedded = serde_json::to_value(DataSource::Embedded).unwrap();
let url = serde_json::to_value(DataSource::Url("https://example.com/r.bin".parse().unwrap())).unwrap();
let chain: Vec<_> = entry.sources.iter().map(|(_, value)| value.source.clone()).collect();
assert_eq!(chain, vec![embedded, url], "Embedded leads the chain, URL kept as fallback");
});
@@ -466,7 +488,9 @@ fn export_materializes_embedded_resource_from_byte_store() {
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), 0xBEEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), 0xBEEF, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
// An Embedded resource whose bytes live only in the byte store, not the working copy.
let payload = b"embedded bytes in the cache";
@@ -507,7 +531,9 @@ fn export_round_trips_unretired_hot_ops() {
use graphene_resource::{DataSource, ResourceId, ResourceRegistry};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xF15E, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xF15E, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let payload = b"hot resource bytes";
let hash = graphene_resource::ResourceHash::from(&payload[..]);
@@ -560,12 +586,14 @@ fn open_in_rejects_future_format_version() {
#[test]
fn create_in_records_default_codecs_in_manifest() {
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let codecs = gdd.manifest().codecs;
assert_eq!(codecs.registry, Codec::Postcard);
assert_eq!(codecs.history, Codec::PostcardFrames);
assert_eq!(codecs.hot_log, Codec::PostcardFrames);
assert_eq!(codecs.registry, Codec::MessagePack);
assert_eq!(codecs.history, Codec::MessagePackFrames);
assert_eq!(codecs.hot_log, Codec::MessagePackFrames);
assert_eq!(codecs.session, Codec::Json);
});
}
@@ -581,7 +609,9 @@ fn first_commit_registers_peer_and_survives_reopen() {
use graphene_resource::ResourceRegistry;
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(21), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(21), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let network = NodeNetwork {
exports: vec![NodeInput::node(core_types::uuid::NodeId(0), 0)],
@@ -600,19 +630,11 @@ fn first_commit_registers_peer_and_survives_reopen() {
gdd.commit_from_runtime(&network, &NoMetadata, &ResourceRegistry::new(), &HashMapResourceStorage::new())
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
assert_eq!(
gdd.registry().peer_users.get(&PeerId(21)).map(|registration| registration.user),
Some(UserId(21)),
"first commit registers the peer"
);
assert_eq!(gdd.registry().peer_users.get(&PeerId(21)), Some(&UserId(21)), "first commit registers the peer");
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
assert_eq!(
reopened.registry().peer_users.get(&PeerId(21)).map(|registration| registration.user),
Some(UserId(21)),
"registration survives reopen"
);
assert_eq!(reopened.registry().peer_users.get(&PeerId(21)), Some(&UserId(21)), "registration survives reopen");
});
}
@@ -623,7 +645,9 @@ fn persist_path_writes_at_manifest_declared_codec_paths() {
futures::executor::block_on(async {
use document_container::AsyncContainer;
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let hot_op = HotOp {
op: RegistryDelta::AddNetwork {
@@ -631,13 +655,12 @@ fn persist_path_writes_at_manifest_declared_codec_paths() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
sequence: HotSequence(1),
};
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
let (working, layout) = gdd.into_storage();
// Defaults: hot log is PostcardFrames (.frames), manifest is always JSON.
assert!(working.exists(&io::path_for(layout.hot_log_basename(), Codec::PostcardFrames)).await);
// Defaults: hot log is MessagePackFrames (.frames), manifest is always JSON.
assert!(working.exists(&io::path_for(layout.hot_log_basename(), Codec::MessagePackFrames)).await);
assert!(working.exists(&io::path_for(layout.manifest_basename(), Codec::Json)).await);
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
@@ -675,7 +698,9 @@ fn declarations_round_trip_through_byte_store() {
..Default::default()
};
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
// Commit: declaration bytes flow into the byte store, not the Gdd container.
let byte_store = HashMapResourceStorage::new();
-108
View File
@@ -1,108 +0,0 @@
// Staging a whole document after a recorded batch, and what a reopen must carry over.
#![cfg(feature = "conversion")]
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use document_graph_storage::{NoMetadata, PeerId, Registry};
use graph_craft::application_io::resource::HashMapResourceStorage;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeNetwork};
use graph_craft::{ProtoNodeIdentifier, concrete};
use graphene_resource::ResourceRegistry;
fn network_with_one_node() -> NodeNetwork {
let node = DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::identity::IdentityNode")),
call_argument: concrete!(()),
..Default::default()
};
NodeNetwork {
nodes: [(NodeId(1), node)].into_iter().collect(),
..Default::default()
}
}
/// A whole-document stage after a recorded batch stages nothing new: restating the batch would fail on the node it added.
#[test]
fn a_whole_document_stage_after_a_recorded_batch_stages_nothing_new() {
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(21), 1, "ed".into(), "std".into()).unwrap();
let store = HashMapResourceStorage::new();
let resources = ResourceRegistry::new();
gdd.stage_runtime_snapshot(&NodeNetwork::default(), &NoMetadata, &resources, &store)
.expect("first whole-document stage");
let target = Registry::convert_from_runtime(&network_with_one_node(), &NoMetadata, &resources, PeerId(21)).unwrap();
let ops = document_graph_storage::delta::compute_deltas(gdd.registry(), &target.registry);
gdd.stage_constructed_ops(ops, &target.declaration_bytes, &store).expect("recorded batch");
let hot_before = gdd.session().hot_log().len();
gdd.stage_runtime_snapshot(&network_with_one_node(), &NoMetadata, &resources, &store)
.expect("the runtime already matches what was staged");
assert_eq!(gdd.session().hot_log().len(), hot_before, "nothing new to stage");
}
/// `registry.bin` is the retired snapshot the hot log replays onto, so an op still hot at save time must stay out of it.
#[test]
fn a_reopen_keeps_unretired_hot_ops_out_of_the_retired_snapshot() {
use document_graph_storage::{AttributeDelta, HotOp, HotSequence, RegistryDelta, TimeStamp, Value};
let set = |value: u32, counter: u64| HotOp {
op: RegistryDelta::ChangeDocumentAttribute {
delta: AttributeDelta {
key: "k".into(),
value: Some(Value::from(serde_json::json!(value))),
},
},
timestamp: TimeStamp { counter, peer: PeerId(22) },
sequence: HotSequence(counter),
};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(22), 1, "ed".into(), "std".into()).unwrap();
gdd.apply_hot_op(set(1, 1)).unwrap();
gdd.apply_hot_op(set(2, 2)).unwrap();
gdd.retire(TimeStamp { counter: 1, peer: PeerId(22) }).unwrap();
let retired = gdd.session().retired_registry().clone();
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.unwrap();
assert!(reopened.session().retired_registry().value_equal(&retired), "the hot op leaked into the retired snapshot");
assert_eq!(reopened.session().hot_log().len(), 1);
});
}
/// A reopen continues this peer's clock and run of hot op sequences, with ops still hot and after they all retired,
/// since a reused sequence would let a peer's settled marks drop the new op.
#[test]
fn a_reopen_continues_the_hot_op_sequence() {
use document_graph_storage::{AttributeDelta, RegistryDelta, Value};
let set = |value: u32| RegistryDelta::ChangeDocumentAttribute {
delta: AttributeDelta {
key: "k".into(),
value: Some(Value::from(serde_json::json!(value))),
},
};
// Stages one op and returns the sequence it got.
fn stage(gdd: &mut GddV1, op: RegistryDelta) -> u64 {
gdd.stage_constructed_ops(vec![op], &Default::default(), &HashMapResourceStorage::new()).unwrap();
gdd.session().hot_log().last().unwrap().sequence.0
}
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(23), 1, "ed".into(), "std".into()).unwrap();
stage(&mut gdd, set(1));
let up_to = gdd.session().hot_log().last().unwrap().timestamp;
gdd.retire(up_to).unwrap();
let last = stage(&mut gdd, set(2));
let (working, layout) = gdd.into_storage();
let mut reopened = GddV1::open_in(working, layout).await.unwrap();
assert_eq!(stage(&mut reopened, set(3)), last + 1);
let up_to = reopened.session().hot_log().last().unwrap().timestamp;
reopened.retire(up_to).unwrap();
let last = reopened.session().last_hot_sequence().0;
let clock = reopened.session().clock_counter();
let (working, layout) = reopened.into_storage();
let mut reopened = GddV1::open_in(working, layout).await.unwrap();
assert_eq!(reopened.session().clock_counter(), clock, "the clock carries over");
assert_eq!(stage(&mut reopened, set(4)), last + 1);
});
}
+1 -7
View File
@@ -5,15 +5,9 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[features]
conversion = ["dep:graph-craft", "dep:core-types"]
default = ["conversion"]
@@ -28,7 +22,7 @@ serde = { workspace = true }
serde_json = { workspace = true }
blake3 = { workspace = true }
rustc-hash = { workspace = true }
postcard = { workspace = true }
rmp-serde = { workspace = true }
[dev-dependencies]
graph-craft = { workspace = true, features = ["loading"] }
+16 -37
View File
@@ -1,4 +1,4 @@
use crate::{TimeStamp, Value, ValueError, from_value, to_value};
use crate::TimeStamp;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
@@ -8,54 +8,33 @@ use std::collections::BTreeMap;
/// keys live on `Node.inputs_attributes[i]`; per-network keys live on `Network.attributes`.
pub mod attr;
/// A type-erased attribute value paired with the timestamp at which it was last set. A deleted key
/// stays as a stamped tombstone, so an older write loses in either arrival order; readers see it as absent.
/// A type-erased attribute value paired with the timestamp at which it was last set.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AttributeValue {
pub value: Value,
pub struct Value {
pub value: serde_json::Value,
pub timestamp: TimeStamp,
// No skipping: the registry is positional on disk.
#[serde(default)]
pub deleted: bool,
}
impl AttributeValue {
pub fn new(value: Value, timestamp: TimeStamp) -> Self {
Self { value, timestamp, deleted: false }
}
/// The tombstone of a key deleted at `timestamp`.
pub fn deleted(timestamp: TimeStamp) -> Self {
Self {
value: Value::None,
timestamp,
deleted: true,
}
impl Value {
pub fn new(value: serde_json::Value, timestamp: TimeStamp) -> Self {
Self { value, timestamp }
}
}
/// Attribute maps. Each entity carries an `attributes_timestamp`: when its map was last written whole, by an
/// addition or a whole-list input write. A key absent from the map is deleted as of that stamp, so an older
/// write is dropped and an older tombstone is redundant.
pub type Attributes = BTreeMap<String, AttributeValue>;
/// The live entries of an attribute map: every key that is not a tombstone.
pub fn live(attributes: &Attributes) -> impl Iterator<Item = (&String, &AttributeValue)> {
attributes.iter().filter(|(_, value)| !value.deleted)
}
pub type Attributes = BTreeMap<String, Value>;
/// Write helpers for `Attributes`.
pub trait AttributesWrite {
/// Inserts `value` under `key`.
fn set(&mut self, key: &str, value: Value, timestamp: TimeStamp);
/// Inserts a JSON value under `key`.
fn set(&mut self, key: &str, value: serde_json::Value, timestamp: TimeStamp);
/// Serializes `value` and inserts it under `key`.
fn set_serialized<T: serde::Serialize>(&mut self, key: &str, value: &T, timestamp: TimeStamp) -> Result<(), ValueError> {
self.set(key, to_value(value)?, timestamp);
fn set_serialized<T: serde::Serialize>(&mut self, key: &str, value: &T, timestamp: TimeStamp) -> Result<(), serde_json::Error> {
self.set(key, serde_json::to_value(value)?, timestamp);
Ok(())
}
/// Inserts only when `value != default`, so the read side falls back to the same default.
fn set_if_not_default<T: serde::Serialize + PartialEq>(&mut self, key: &str, value: &T, default: &T, timestamp: TimeStamp) -> Result<(), ValueError> {
fn set_if_not_default<T: serde::Serialize + PartialEq>(&mut self, key: &str, value: &T, default: &T, timestamp: TimeStamp) -> Result<(), serde_json::Error> {
if value != default {
self.set_serialized(key, value, timestamp)?;
}
@@ -64,8 +43,8 @@ pub trait AttributesWrite {
}
impl AttributesWrite for Attributes {
fn set(&mut self, key: &str, value: Value, timestamp: TimeStamp) {
self.insert(key.to_string(), AttributeValue::new(value, timestamp));
fn set(&mut self, key: &str, value: serde_json::Value, timestamp: TimeStamp) {
self.insert(key.to_string(), Value { value, timestamp });
}
}
@@ -87,6 +66,6 @@ pub trait AttributesRead {
impl AttributesRead for Attributes {
fn get_typed<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
self.get(key).filter(|v| !v.deleted).and_then(|v| from_value(&v.value).ok())
self.get(key).and_then(|v| serde_json::from_value(v.value.clone()).ok())
}
}
@@ -31,7 +31,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";
+47 -78
View File
@@ -1,15 +1,13 @@
use crate::{
AttributeValue, Attributes, AttributesWrite, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, Prior, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId,
Value, attr, compute_rev,
};
use crate::{Attributes, AttributesWrite, 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};
/// Content-addressed delta: `id` is `blake3_128(parents, author, timestamp, delta_type)`.
///
/// `reverse` is state-dependent undo bookkeeping (what the op overwrote, captured as it applied), so it's
/// serialized for storage but excluded from the identity hash: two peers applying the same forward delta to
/// different local states would otherwise compute different Revs for the same logical op.
/// `reverse` is state-dependent undo bookkeeping (it captures pre-state at the moment the forward
/// op was applied), so it's serialized for storage but excluded from the identity hash — two peers
/// observing the same forward delta against different local states would otherwise compute
/// different Revs for the same logical op.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Delta {
pub id: Rev,
@@ -18,22 +16,16 @@ pub struct Delta {
pub author: PeerId,
pub timestamp: TimeStamp,
pub kind: RegistryDelta,
/// What every slot `kind` wrote held before it, stamps included, in write order. See [`Prior`].
pub reverse: Vec<Prior>,
pub reverse: RegistryDelta,
/// Local, mutable annotations on this commit (interaction-end marker, future commit messages / labels).
/// Deliberately excluded from `compute_rev`: relabeling a commit must not change its content-addressed
/// identity, and two peers annotating the same op differently must still dedup to one `Rev`.
#[serde(default)]
#[serde(default, skip_serializing_if = "Attributes::is_empty")]
pub attributes: Attributes,
/// When the delta entered history, in Unix milliseconds by the clock of the peer that retired it; display only,
/// and outside the rev like `attributes`. Zero means unrecorded, saving the tag byte an `Option` costs per delta;
/// read it through [`retired_at`](Self::retired_at). Last, since the history codec is positional.
#[serde(default)]
pub(crate) retired_at_ms: u64,
}
impl Delta {
pub fn new(parent: Option<Rev>, author: PeerId, timestamp: TimeStamp, kind: RegistryDelta, reverse: Vec<Prior>) -> Self {
pub fn new(parent: Option<Rev>, author: PeerId, timestamp: TimeStamp, kind: RegistryDelta, reverse: RegistryDelta) -> Self {
let id = compute_rev(parent, author, timestamp, &kind);
Self {
id,
@@ -43,7 +35,6 @@ impl Delta {
kind,
reverse,
attributes: Attributes::default(),
retired_at_ms: 0,
}
}
@@ -61,10 +52,9 @@ impl Delta {
parent,
author,
timestamp,
reverse: Vec::new(),
reverse: kind.clone(),
kind,
attributes: Attributes::default(),
retired_at_ms: 0,
}
}
@@ -79,16 +69,11 @@ impl Delta {
/// Mark this delta as the last op of a user interaction, so the undo cursor treats it as a checkpoint.
pub fn mark_interaction_end(&mut self, timestamp: TimeStamp) {
self.attributes.set(attr::delta::INTERACTION_END, Value::Bool(true), timestamp);
self.attributes.set(attr::delta::INTERACTION_END, serde_json::Value::Bool(true), timestamp);
}
pub fn is_interaction_end(&self) -> bool {
self.attributes.get(attr::delta::INTERACTION_END).is_some_and(|marker| marker.value == Value::Bool(true))
}
/// When the delta entered history in wall-clock milliseconds, if the peer that retired it recorded it.
pub fn retired_at(&self) -> Option<u64> {
(self.retired_at_ms != 0).then_some(self.retired_at_ms)
self.attributes.get(attr::delta::INTERACTION_END).is_some_and(|marker| marker.value == serde_json::Value::Bool(true))
}
/// The content-addressed `Rev` this delta's identity fields hash to. Equals `id` for a delta built
@@ -113,7 +98,8 @@ pub enum RegistryDelta {
id: NodeId,
node: Node,
},
/// `snapshot` is the node as removed, which folds in like any write so a removal of a node never seen still lands.
/// `snapshot` lets the reverse `AddNode` rebuild without reading the (already-removed) node from
/// the registry, mirroring `RemoveNetwork`.
RemoveNode {
id: NodeId,
snapshot: Node,
@@ -133,15 +119,6 @@ pub enum RegistryDelta {
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,
@@ -166,12 +143,13 @@ pub enum RegistryDelta {
id: NetworkId,
network: Network,
},
/// `snapshot` is the network as removed; see [`RemoveNode`](Self::RemoveNode).
/// `snapshot` lets the reverse delta rebuild without re-walking history.
RemoveNetwork {
id: NetworkId,
snapshot: Network,
},
/// Register a whole resource entry at once, the way `AddNetwork` pairs with `RemoveNetwork`.
/// Register a whole resource entry at once. Overwrites any existing entry for `id`; the reverse
/// of `RemoveResource`, the way `AddNetwork` pairs with `RemoveNetwork`.
AddResource {
id: ResourceId,
entry: ResourceEntry,
@@ -193,15 +171,16 @@ pub enum RegistryDelta {
AddSource {
id: ResourceId,
key: SourceKey,
source: Value,
source: serde_json::Value,
},
/// Remove one entry from a resource's source chain. LWW against the entry's timestamp.
RemoveSource {
id: ResourceId,
key: SourceKey,
},
/// Registers a device's `PeerId` to the `UserId` behind it. LWW per peer, so a device that changes person
/// registers again and the newest registration wins wherever it lands.
/// Append-only registration of a device's `PeerId` against its owning `UserId`.
/// First write wins; conflicting re-registration errors. Duplicate identical registration
/// is a no-op. Not LWW — the mapping is forever.
RegisterPeer {
peer: PeerId,
user: UserId,
@@ -216,52 +195,42 @@ pub enum RegistryDelta {
Merge {
extra_parents: Vec<Rev>,
},
/// The last op of its author's transaction. Changes nothing, and retirement drops it.
EndTransaction,
// Allow for future delta types without a model change
Other(Value),
Other(serde_json::Value),
}
/// `value: None` means remove. The timestamp comes from the wrapping `Delta`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AttributeDelta {
pub key: String,
pub value: Option<Value>,
pub value: Option<serde_json::Value>,
}
/// Lands a single-key write. `floor` is the map's `attributes_timestamp`; see [`Attributes`]. A deletion
/// leaves a tombstone.
pub(crate) fn apply_attribute_delta(delta: AttributeDelta, timestamp: TimeStamp, attributes: &mut Attributes, floor: TimeStamp) {
pub(crate) fn reverse_attribute_delta(delta: &AttributeDelta, attributes: &Attributes) -> AttributeDelta {
AttributeDelta {
key: delta.key.clone(),
value: attributes.get(&delta.key).map(|previous| previous.value.clone()),
}
}
pub(crate) fn apply_attribute_delta(delta: AttributeDelta, timestamp: TimeStamp, force: bool, attributes: &mut Attributes) {
let AttributeDelta { key, value } = delta;
let decided = attributes.get(&key).map_or(floor, |existing| existing.timestamp);
if timestamp <= decided {
return;
}
let entry = match value {
Some(value) => AttributeValue::new(value, timestamp),
None => AttributeValue::deleted(timestamp),
};
attributes.insert(key, entry);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_missing_retirement_time_costs_what_a_zero_costs_and_round_trips() {
let base = Delta::new(None, PeerId(1), TimeStamp { counter: 1, peer: PeerId(1) }, RegistryDelta::EndTransaction, Vec::new());
let mut stamped = base.clone();
stamped.retired_at_ms = 1_790_000_000_000;
let bare_base = postcard::to_allocvec(&base).expect("encode");
let bare_stamped = postcard::to_allocvec(&stamped).expect("encode");
// Only the integer's varint differs: one byte for zero, six for today's milliseconds, no tag byte in either.
assert_eq!(bare_stamped.len() - bare_base.len(), postcard::to_allocvec(&1_790_000_000_000u64).unwrap().len() - 1);
let decoded: Delta = postcard::from_bytes(&bare_stamped).expect("decode");
assert_eq!(decoded.retired_at(), Some(1_790_000_000_000));
let decoded: Delta = postcard::from_bytes(&bare_base).expect("decode");
assert_eq!(decoded.retired_at(), None);
match value {
Some(value) => match attributes.entry(key) {
std::collections::btree_map::Entry::Occupied(mut entry) => {
if force || timestamp > entry.get().timestamp {
entry.insert(Value { value, timestamp });
}
}
std::collections::btree_map::Entry::Vacant(entry) => {
entry.insert(Value { value, timestamp });
}
},
None => {
let should_remove = force || attributes.get(&key).is_none_or(|existing| timestamp > existing.timestamp);
if should_remove {
attributes.remove(&key);
}
}
}
}
+18 -18
View File
@@ -166,14 +166,14 @@ fn diff_resource_entry(id: ResourceId, from: &ResourceEntry, to: &ResourceEntry,
deltas.push(RegistryDelta::SetResourceHash { id, hash: to.hash });
}
for (key, _) in from.live_sources() {
for (key, _) in &from.sources {
if to.source(key).is_none() {
deltas.push(RegistryDelta::RemoveSource { id, key: *key });
}
}
// Compare source bodies only; the per-source timestamp is derived from the diff, not part of it.
for (key, to_source) in to.live_sources() {
for (key, to_source) in &to.sources {
if from.source(key).is_none_or(|from_source| from_source.source != to_source.source) {
deltas.push(RegistryDelta::AddSource {
id,
@@ -196,15 +196,15 @@ fn nodes_have_same_implementation(a: &Node, b: &Node) -> bool {
fn compute_attribute_deltas(from: &crate::Attributes, to: &crate::Attributes) -> Vec<AttributeDelta> {
let mut deltas = Vec::new();
for (key, _) in crate::attributes::live(from) {
if to.get(key).is_none_or(|value| value.deleted) {
for key in from.keys() {
if !to.contains_key(key) {
deltas.push(AttributeDelta { key: key.clone(), value: None });
}
}
// Compare by `value` only; the per-entry `timestamp` is derived from the diff, not part of it.
for (key, to_value) in crate::attributes::live(to) {
if from.get(key).is_none_or(|from_value| from_value.deleted || from_value.value != to_value.value) {
for (key, to_value) in to {
if from.get(key).is_none_or(|from_value| from_value.value != to_value.value) {
deltas.push(AttributeDelta {
key: key.clone(),
value: Some(to_value.value.clone()),
@@ -218,7 +218,7 @@ fn compute_attribute_deltas(from: &crate::Attributes, to: &crate::Attributes) ->
#[cfg(test)]
mod tests {
use super::*;
use crate::{Attributes, ExportSlot, Network, Node, NodeInput, TimeStamp, Value};
use crate::{Attributes, ExportSlot, Network, Node, NodeInput, TimeStamp};
#[test]
fn test_compute_deltas_empty() {
@@ -287,7 +287,6 @@ mod tests {
input: NodeInput::Import { index: 0 },
timestamp: TimeStamp::ORIGIN,
attributes: Attributes::new(),
attributes_timestamp: TimeStamp::ORIGIN,
});
let deltas = compute_deltas(&from, &to);
@@ -305,7 +304,11 @@ mod tests {
from.networks.insert(NetworkId(0), Network::default());
let mut to = from.clone();
to.networks.get_mut(&NetworkId(0)).unwrap().attributes.set("ui::nav::width", Value::Float(640.), TimeStamp::ORIGIN);
to.networks
.get_mut(&NetworkId(0))
.unwrap()
.attributes
.set("ui::nav::width", serde_json::json!(640.0), TimeStamp::ORIGIN);
let deltas = compute_deltas(&from, &to);
assert_eq!(deltas.len(), 1, "a changed per-network attribute must emit one delta");
@@ -338,10 +341,9 @@ mod tests {
let stamp = |counter: u64| TimeStamp { counter, peer: crate::PeerId(0) };
node.attributes.insert(
"test".to_string(),
crate::AttributeValue {
value: Value::Str("old".into()),
crate::Value {
value: serde_json::json!("old"),
timestamp: stamp(0),
deleted: false,
},
);
from.node_instances.insert(NodeId(42), node);
@@ -349,10 +351,9 @@ mod tests {
let mut to = from.clone();
to.node_instances.get_mut(&NodeId(42)).unwrap().attributes.insert(
"test".to_string(),
crate::AttributeValue {
value: Value::Str("new".into()),
crate::Value {
value: serde_json::json!("new"),
timestamp: stamp(1),
deleted: false,
},
);
@@ -375,10 +376,9 @@ mod tests {
let mut to = from.clone();
to.attributes.insert(
"doc::test_attribute".to_string(),
crate::AttributeValue {
value: Value::Str("value".into()),
crate::Value {
value: serde_json::json!("value"),
timestamp: stamp(1),
deleted: false,
},
);
+315 -543
View File
@@ -1,29 +1,23 @@
use std::collections::btree_map::Entry;
use std::collections::{HashMap, HashSet};
use std::hash::Hash;
use crate::{
Attributes, CrdtError, Delta, ExportSlot, History, HotOp, HotSequence, Implementation, InputSlot, LamportClock, MAX_EXPORT_SLOTS, MAX_INPUT_SLOTS, Network, NetworkId, Node, NodeId, NodeInput,
PeerId, PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, Rev, SettledHotOps, SourceValue, TimeStamp, Tombstone, UserId, apply_attribute_delta,
CrdtError, Delta, ExportSlot, History, HotOp, LamportClock, MAX_EXPORT_SLOTS, NetworkId, NodeId, NodeInput, PeerId, Registry, RegistryDelta, ResourceEntry, Rev, SourceValue, TimeStamp,
apply_attribute_delta, reverse_attribute_delta,
};
#[derive(Clone, Debug)]
pub struct Document {
/// Working registry: retired state with the current hot ops applied on top. This is what live
/// reads and `registry()` observe.
/// reads and `registry()` observe, and what undo/redo force-apply against.
pub(crate) working_registry: Registry,
/// 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>,
/// The stamps of the hot log's ops, so a re-announced op is recognised without a scan.
pub(crate) hot_timestamps: HashSet<TimeStamp>,
/// Which hot ops are retired into history, so a late copy is dropped;
/// retired deltas keep no link back to their hot ops.
pub(crate) settled: SettledHotOps,
/// 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. It equals the working registry whenever the hot log is
/// empty.
/// hot-polluted working state) and advances it, stamping fields at the fresh `T_retire`. Kept equal
/// to `registry` *by value* whenever the hot log is empty (undo/redo resync it after moving the
/// cursor), but field timestamps can differ: retirement bumps the snapshot's to `T_retire` while the
/// working registry keeps the staging-time timestamps. Benign while the local monotonic clock makes
/// new edits win
pub(crate) retired_snapshot: Registry,
/// User's cursor in their local history chain. `None` on an empty document (no commits yet).
pub(crate) head: Option<Rev>,
@@ -34,129 +28,97 @@ pub struct Document {
pub(crate) redo_stack: Vec<Rev>,
pub(crate) clock: LamportClock,
pub(crate) peer: PeerId,
/// The person behind this peer; what `RegisterPeer` records for it.
pub(crate) user: UserId,
/// Latest retired commit on the local chain that a peer holds. Commits after it can be undone silently; commits up
/// to it are published and stay. `None` means nothing published yet.
/// Latest retired commit on the local chain that has been broadcast to at least one peer.
/// Commits after this can be rewritten silently; commits at or before this are published
/// and require forward reverse-delta ops to undo. `None` means nothing broadcast yet.
pub(crate) last_broadcast_rev: Option<Rev>,
/// Shared-monotonic counter feeding `next_node_id`. Bumped on every mint regardless of which
/// peer is calling; collision avoidance comes from hashing `(self.peer, counter)`, so two peers
/// 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) last_hot_sequence: HotSequence,
}
impl Document {
/// An empty document for `peer`, at the origin of its clock.
pub(crate) fn empty(peer: PeerId, user: UserId) -> Self {
Self {
working_registry: Registry::default(),
retired_snapshot: Registry::default(),
history: History::new(),
hot_log: Vec::new(),
hot_timestamps: HashSet::new(),
settled: SettledHotOps::default(),
head: None,
redo_stack: Vec::new(),
clock: LamportClock::new(peer),
peer,
user,
last_broadcast_rev: None,
next_node_counter: 0,
last_hot_sequence: HotSequence::NONE,
}
}
/// Mint a fresh `NodeId` scoped to this document's peer. The 64-bit ID is `blake3(peer, counter)`
/// truncated; the counter is shared across peers and persisted with the document.
pub fn next_node_id(&mut self) -> NodeId {
self.next_node_counter += 1;
let mut hasher = blake3::Hasher::new();
postcard::to_io(&(self.peer, self.next_node_counter), &mut hasher).expect("(PeerId, counter) must serialize");
let digest = hasher.finalize();
let bytes = rmp_serde::to_vec(&(self.peer, self.next_node_counter)).expect("(PeerId, counter) must serialize");
let digest = blake3::hash(&bytes);
let mut truncated = [0u8; 8];
truncated.copy_from_slice(&digest.as_bytes()[..8]);
NodeId(u64::from_le_bytes(truncated))
}
/// Put back what a delta overwrote in the retired snapshot (silent-zone undo), leaving it as folding history up
/// to the delta's parent would. The working registry follows: it is the same registry when nothing is hot.
pub(crate) fn revert_delta(&mut self, delta: &Delta) {
crate::prior::restore(&mut self.retired_snapshot, &delta.reverse);
if self.hot_log.is_empty() {
crate::prior::restore(&mut self.working_registry, &delta.reverse);
}
pub(crate) fn restore_node_from_history(&mut self, target: RegistryTarget, node_id: NodeId) -> Result<(), CrdtError> {
let delta = self
.find_in_ancestry(|d| matches!(d.reverse, RegistryDelta::AddNode { id, .. } if id == node_id))
.ok_or(CrdtError::NodeNotInHistory(node_id))?;
self.revert_delta(target, delta)
}
/// Apply a locally staged op: LWW into the registry, append to the hot log, leave history and `head`
/// alone. Skips the retirement check, so staging never silently drops local work; outside callers use
/// [`Session::apply_hot_op`](crate::Session::apply_hot_op).
pub(crate) fn apply_hot_op(&mut self, hot_op: HotOp, mode: ApplyMode) -> Result<(), CrdtError> {
self.apply_op_with(RegistryTarget::Working, hot_op.op.clone(), hot_op.timestamp, mode)?;
self.hot_timestamps.insert(hot_op.timestamp);
pub(crate) fn restore_network_from_history(&mut self, target: RegistryTarget, network_id: NetworkId) -> Result<(), CrdtError> {
// Find the Delta whose forward op removed this network. Its `reverse` is `AddNetwork`,
// which is what we want to re-apply.
let delta = self
.find_in_ancestry(|d| matches!(d.reverse, RegistryDelta::AddNetwork { id, .. } if id == network_id))
.ok_or(CrdtError::NetworkNotInHistory(network_id))?;
self.revert_delta(target, delta)
}
/// Search every delta reachable from `head` (following all parents, including a merge's
/// `extra_parents`) for the first matching `predicate`, breadth-first. Resurrection needs full
/// ancestry reachability, so a node added only on a merged-in branch is still found.
fn find_in_ancestry(&self, predicate: impl Fn(&Delta) -> bool) -> Option<Delta> {
let mut queue: std::collections::VecDeque<Rev> = self.head.into_iter().collect();
let mut seen: std::collections::HashSet<Rev> = self.head.into_iter().collect();
while let Some(rev) = queue.pop_front() {
let Some(delta) = self.history.get(rev) else { continue };
if predicate(delta) {
return Some(delta.clone());
}
for parent in delta.all_parents() {
if seen.insert(parent) {
queue.push_back(parent);
}
}
}
None
}
/// Apply a delta's `reverse` as the new forward op (silent-zone undo). Force-applied: structural
/// ops are idempotent, and LWW arms assign the reverse value unconditionally even though it carries
/// the same timestamp as the forward op it undoes.
pub(crate) fn revert_delta(&mut self, target: RegistryTarget, mut delta: Delta) -> Result<(), CrdtError> {
for parent in delta.all_parents() {
if !self.history.contains(parent) {
return Err(CrdtError::NotFoundInHistory(parent));
}
}
std::mem::swap(&mut delta.kind, &mut delta.reverse);
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> {
self.apply_op(hot_op.op.clone(), hot_op.timestamp)?;
self.hot_log.push(hot_op);
Ok(())
}
/// Replay a hot op recovered from persisted state or received from a peer. Replaying one already
/// reflected in the registry changes nothing.
/// Replay a hot op recovered from persisted state. Idempotent on structural ops so that
/// 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> {
// Re-adding a settled op would leave a hot log entry no retirement will ever name.
if self.settled.covers(hot_op.id()) {
return Ok(());
}
// A re-announcement of a held op must not become a second copy.
if self.hot_timestamps.contains(&hot_op.timestamp) {
return Ok(());
}
// Our own ops raise the sequence counter too, should the persisted one lag behind the hot log.
if hot_op.timestamp.peer == self.peer {
self.last_hot_sequence = self.last_hot_sequence.max(hot_op.sequence);
}
self.apply_op_idempotent(hot_op.op.clone(), hot_op.timestamp)?;
self.hot_timestamps.insert(hot_op.timestamp);
self.hot_log.push(hot_op);
Ok(())
}
/// Take on a peer's marks as well as this peer's. Returns whether a hot op was dropped.
pub(crate) fn absorb_settled(&mut self, remote: &SettledHotOps) -> bool {
self.settled.absorb(remote);
self.drop_settled_hot_ops()
}
/// Bring the stamp index back in line after the hot log was filtered as a whole.
pub(crate) fn resync_hot_timestamps(&mut self) {
self.hot_timestamps = self.hot_log.iter().map(|hot_op| hot_op.timestamp).collect();
}
/// Re-derive the working registry as the retired snapshot plus every hot op, for a change that cannot
/// be applied in place. O(N + L), for rare paths only.
pub(crate) fn rebuild_working(&mut self) {
self.working_registry = self.retired_snapshot.clone();
for hot_op in std::mem::take(&mut self.hot_log) {
// Nothing is deferred, so this cannot fail on a referent; don't strand the op over anything else.
let _ = self.apply_op_idempotent(hot_op.op.clone(), hot_op.timestamp);
self.hot_log.push(hot_op);
}
}
/// Drop settled hot ops and re-derive the working registry without them; their effect comes back with their deltas.
fn drop_settled_hot_ops(&mut self) -> bool {
let before = self.hot_log.len();
let settled = &self.settled;
self.hot_log.retain(|hot_op| !settled.covers(hot_op.id()));
let dropped = self.hot_log.len() != before;
if dropped {
self.resync_hot_timestamps();
self.rebuild_working();
}
dropped
}
/// Apply a retired commit and record it in history.
/// Apply a retired commit. Idempotent on structural ops (AddNode/AddNetwork on existing
/// targets, Remove on missing ones) since hot ops already produced the structural state.
/// The point is to bump field timestamps to T_retire via the LWW arms.
pub fn apply_delta(&mut self, delta: Delta) -> Result<(), CrdtError> {
for parent in delta.all_parents() {
if !self.history.contains(parent) {
@@ -176,503 +138,312 @@ impl Document {
}
}
pub(crate) fn registry_ref(&self, target: RegistryTarget) -> &Registry {
fn registry_ref(&self, target: RegistryTarget) -> &Registry {
match target {
RegistryTarget::Working => &self.working_registry,
RegistryTarget::Snapshot => &self.retired_snapshot,
}
}
/// A fresh local edit against the working registry; see [`ApplyMode::Live`].
#[cfg(test)]
/// New local/remote op against the working registry: add ops error on duplicate targets and
/// `Change*` ops error on a missing target, while remove ops no-op when the target is already
/// absent; LWW arms keep the newer-timestamp value (strict `>`). The common entry point for edits.
pub(crate) fn apply_op(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Live)
}
/// An op from a peer or from persisted state, against the working registry.
/// Replay/retire against the working registry: structural ops skip duplicate/missing targets (the
/// state is already present from hot ops or a prior snapshot); LWW arms still gate on strict `>`.
pub(crate) fn apply_op_idempotent(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Idempotent)
}
/// Applies one op. Every field of the registry is last-writer-wins on a timestamp, whether an entity
/// exists included, so the registry folds to the same values whatever order the ops land in:
///
/// - An addition writes every field of the entity at its stamp, and is evidence it exists from then.
/// - A removal is evidence the entity does not exist from its stamp. Its content stays as a tombstone,
/// and the removal's snapshot folds in like any other write.
/// - A write, or a reference from another entity's op, is evidence the entity exists at its stamp, so it
/// revives an older removal; an older write lands on the tombstone, for a later revival to see.
/// - A write to an entity never seen lands on a placeholder until its addition arrives; see [`write()`].
/// Silent-zone undo/redo rewind against the working registry: structural ops are idempotent, and
/// LWW arms assign unconditionally. We own the single-writer chain here, so the precomputed reverse
/// (undo) or forward (redo) value is authoritative even though its timestamp ties what it replaces.
pub(crate) fn force_apply_op(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Force)
}
pub(crate) fn apply_op_with(&mut self, target: RegistryTarget, op: RegistryDelta, timestamp: TimeStamp, mode: ApplyMode) -> Result<(), CrdtError> {
// Advance the local clock past every observed op, including ones that subsequently no-op or
// error. Observation is about causality knowledge, not about whether the op took effect.
self.clock.observe(timestamp);
let live = mode == ApplyMode::Live;
// Structural ops skip (rather than error) on duplicate/missing targets when not a fresh edit;
// LWW arms assign unconditionally only under `Force`.
let idempotent = mode != ApplyMode::Live;
let force = mode == ApplyMode::Force;
// Resurrect any concurrently-removed targets the op references before binding the registry
// (resurrection re-borrows `self` via history), so the mutation below holds one `registry` ref.
self.ensure_referenced_exist(target, &op)?;
let registry = self.registry_mut(target);
match op {
RegistryDelta::AddNode { id, node } => {
if live && registry.node_instances.contains_key(&id) {
if registry.node_instances.contains_key(&id) {
if idempotent {
// Hot ops already created this node; skip rather than error.
return Ok(());
}
return Err(CrdtError::NodeAlreadyExists(id));
}
write_network(registry, node.network, timestamp, mode, |_| Ok(()))?;
add(&mut registry.node_instances, &mut registry.removed_nodes, id, node, timestamp);
registry.node_instances.insert(id, node);
}
RegistryDelta::RemoveNode { id, snapshot } => {
remove(&mut registry.node_instances, &mut registry.removed_nodes, id, snapshot, timestamp);
RegistryDelta::RemoveNode { id, .. } => {
registry.node_instances.remove(&id);
}
RegistryDelta::SetNodeInputs { id, mut inputs } => {
inputs.iter_mut().for_each(|slot| stamp_slot(slot, timestamp));
let referenced: Vec<NodeId> = inputs
.iter()
.filter_map(|slot| match slot.input {
NodeInput::Node { id, .. } => Some(id),
_ => None,
})
.collect();
ensure_seen(registry, &referenced, mode)?;
write_node(registry, id, timestamp, mode, |node| {
merge_inputs(node, inputs, timestamp);
Ok(())
})?;
for referenced in referenced {
write_node(registry, referenced, timestamp, mode, |_| Ok(()))?;
}
RegistryDelta::SetNodeInputs { id, inputs } => {
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
node.inputs = inputs;
}
RegistryDelta::ChangeNodeInput { id, index, new_input } => {
let referenced = match new_input {
NodeInput::Node { id, .. } => Some(id),
_ => None,
};
ensure_seen(registry, referenced.as_slice(), mode)?;
write_node(registry, id, timestamp, mode, |node| {
let Some(input) = slot_for_write(node, index as usize, timestamp, mode)? else { return Ok(()) };
if timestamp > input.timestamp {
input.input = new_input;
input.timestamp = timestamp;
}
Ok(())
})?;
if let Some(referenced) = referenced {
write_node(registry, referenced, timestamp, mode, |_| Ok(()))?;
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))?;
if force || timestamp > input.timestamp {
input.input = new_input;
input.timestamp = timestamp;
}
}
RegistryDelta::SetNodeImplementation { id, implementation } => {
ensure_seen(registry, &[id], mode)?;
if let Implementation::Network(network) = implementation {
write_network(registry, network, timestamp, mode, |_| Ok(()))?;
}
write_node(registry, id, timestamp, mode, |node| {
if timestamp > node.implementation_timestamp {
node.implementation = implementation;
node.implementation_timestamp = timestamp;
}
Ok(())
})?;
}
RegistryDelta::ChangeNodeAttribute { id, delta } => {
write_node(registry, id, timestamp, mode, |node| {
apply_attribute_delta(delta, timestamp, &mut node.attributes, node.attributes_timestamp);
Ok(())
})?;
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
apply_attribute_delta(delta, timestamp, force, &mut node.attributes);
}
RegistryDelta::ChangeNodeInputAttribute { id, index, delta } => {
write_node(registry, id, timestamp, mode, |node| {
let Some(input) = slot_for_write(node, index as usize, timestamp, mode)? else { return Ok(()) };
apply_attribute_delta(delta, timestamp, &mut input.attributes, input.attributes_timestamp);
Ok(())
})?;
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))?;
apply_attribute_delta(delta, timestamp, force, &mut input.attributes);
}
RegistryDelta::SetNetworkExport { id, index, export } => {
let referenced = match export {
Some(NodeInput::Node { id, .. }) => Some(id),
_ => None,
};
ensure_seen(registry, referenced.as_slice(), mode)?;
write_network(registry, id, timestamp, mode, |net| {
let slot_idx = index as usize;
if slot_idx >= net.exports.len() {
if slot_idx >= MAX_EXPORT_SLOTS {
return Err(CrdtError::ExportSlotOutOfBounds(index));
}
net.exports.resize(slot_idx + 1, ExportSlot::default());
}
let net = registry.networks.get_mut(&id).ok_or(CrdtError::NetworkDoesNotExist(id))?;
let slot_idx = index as usize;
let existing = &mut net.exports[slot_idx];
if timestamp > existing.timestamp {
existing.target = export;
existing.timestamp = timestamp;
if slot_idx >= net.exports.len() {
if slot_idx >= MAX_EXPORT_SLOTS {
return Err(CrdtError::ExportSlotOutOfBounds(index));
}
Ok(())
})?;
if let Some(referenced) = referenced {
write_node(registry, referenced, timestamp, mode, |_| Ok(()))?;
net.exports.resize(
slot_idx + 1,
ExportSlot {
target: None,
timestamp: TimeStamp::ORIGIN,
},
);
}
let existing = &mut net.exports[slot_idx];
if force || timestamp > existing.timestamp {
existing.target = export;
existing.timestamp = timestamp;
}
}
RegistryDelta::AddNetwork { id, network } => {
if live && registry.networks.contains_key(&id) {
RegistryDelta::AddNetwork { id, network: contents } => {
if registry.networks.contains_key(&id) {
if idempotent {
return Ok(());
}
return Err(CrdtError::NetworkAlreadyExists(id));
}
add(&mut registry.networks, &mut registry.removed_networks, id, network, timestamp);
registry.networks.insert(id, contents);
}
RegistryDelta::RemoveNetwork { id, snapshot } => {
remove(&mut registry.networks, &mut registry.removed_networks, id, snapshot, timestamp);
RegistryDelta::RemoveNetwork { id, .. } => {
registry.networks.remove(&id);
}
RegistryDelta::ChangeNetworkAttribute { id, delta } => {
write_network(registry, id, timestamp, mode, |net| {
apply_attribute_delta(delta, timestamp, &mut net.attributes, net.attributes_timestamp);
Ok(())
})?;
let net = registry.networks.get_mut(&id).ok_or(CrdtError::NetworkDoesNotExist(id))?;
apply_attribute_delta(delta, timestamp, force, &mut net.attributes);
}
RegistryDelta::SetResourceHash { id, hash } => {
upsert_resource(registry, id, timestamp, |entry| {
if timestamp > entry.hash_timestamp {
entry.hash = hash;
entry.hash_timestamp = timestamp;
}
});
}
RegistryDelta::AddSource { id, key, source } => {
upsert_resource(registry, id, timestamp, |entry| {
let value = SourceValue { source, timestamp, deleted: false };
entry.set_source(key, value);
});
}
RegistryDelta::RemoveSource { id, key } => {
// An upsert, so a removal for an entry never seen leaves a tombstone its addition loses to.
upsert_resource(registry, id, timestamp, |entry| {
entry.remove_source(&key, timestamp);
});
}
RegistryDelta::AddResource { id, entry } => {
add(&mut registry.resources, &mut registry.removed_resources, id, entry, timestamp);
}
RegistryDelta::RemoveResource { id, snapshot } => {
remove(&mut registry.resources, &mut registry.removed_resources, id, snapshot, timestamp);
}
RegistryDelta::RegisterPeer { peer, user } => {
// The newest registration of a device wins, whatever order they land in.
if registry.peer_users.get(&peer).is_none_or(|existing| timestamp > existing.at) {
registry.peer_users.insert(peer, PeerRegistration { user, at: timestamp });
let entry = registry.resources.entry(id).or_default();
if force || timestamp > entry.hash_timestamp {
entry.hash = hash;
entry.hash_timestamp = timestamp;
}
}
RegistryDelta::AddSource { id, key, source } => {
let entry = registry.resources.entry(id).or_default();
let value = SourceValue { source, timestamp };
if force { entry.force_set_source(key, value) } else { entry.set_source(key, value) }
}
RegistryDelta::RemoveSource { id, key } => {
if let Some(entry) = registry.resources.get_mut(&id) {
if force {
entry.force_remove_source(&key);
} else {
entry.remove_source(&key, timestamp);
}
}
}
RegistryDelta::AddResource { id, entry } => {
registry.resources.insert(id, entry);
}
RegistryDelta::RemoveResource { id, .. } => {
registry.resources.remove(&id);
}
RegistryDelta::RegisterPeer { peer, user } => match registry.peer_users.get(&peer) {
Some(existing) if *existing != user => return Err(CrdtError::PeerRegistrationConflict(peer)),
Some(_) => {}
None => {
registry.peer_users.insert(peer, user);
}
},
RegistryDelta::ChangeDocumentAttribute { delta } => {
apply_attribute_delta(delta, timestamp, &mut registry.attributes, TimeStamp::ORIGIN);
apply_attribute_delta(delta, timestamp, force, &mut registry.attributes);
}
// Merge is a structural sync point only; it mutates no registry state.
RegistryDelta::Merge { .. } | RegistryDelta::EndTransaction | RegistryDelta::Other(_) => {}
RegistryDelta::Merge { .. } | RegistryDelta::Other(_) => {}
}
Ok(())
}
}
/// An entity whose existence and every field are last-writer-wins on a timestamp.
pub(crate) trait Presence: Sized {
/// The newest stamp of an addition or a write: the latest evidence the entity exists.
fn presence(&self) -> TimeStamp;
fn set_presence(&mut self, at: TimeStamp);
/// Stamps every field at `at`, the way an addition writes all of them.
fn stamp_all(&mut self, at: TimeStamp);
/// Folds `other` in, keeping whichever value of each field is newer.
fn merge(&mut self, other: Self);
/// Dead content for an entity nothing has added yet, for writes to land on until an addition comes.
/// Every field is at the origin, so the addition's values win.
fn placeholder() -> Self;
}
impl Presence for Node {
fn presence(&self) -> TimeStamp {
self.presence
}
fn set_presence(&mut self, at: TimeStamp) {
self.presence = at;
}
fn placeholder() -> Self {
Node::new(crate::ROOT_NETWORK, Implementation::ProtoNode(ResourceId::from(0)), 0)
}
fn stamp_all(&mut self, at: TimeStamp) {
self.presence = at;
self.added = at;
self.inputs_timestamp = at;
self.implementation_timestamp = at;
self.inputs.iter_mut().for_each(|slot| stamp_slot(slot, at));
stamp_attributes(&mut self.attributes, &mut self.attributes_timestamp, at);
}
fn merge(&mut self, other: Self) {
if other.added > self.added {
self.network = other.network;
self.added = other.added;
}
if other.implementation_timestamp > self.implementation_timestamp {
self.implementation = other.implementation;
self.implementation_timestamp = other.implementation_timestamp;
}
merge_inputs(self, other.inputs, other.inputs_timestamp);
merge_attributes(&mut self.attributes, &mut self.attributes_timestamp, other.attributes, other.attributes_timestamp);
self.presence = self.presence.max(other.presence);
}
}
impl Presence for Network {
fn presence(&self) -> TimeStamp {
self.presence
}
fn set_presence(&mut self, at: TimeStamp) {
self.presence = at;
}
fn placeholder() -> Self {
Network::default()
}
fn stamp_all(&mut self, at: TimeStamp) {
self.presence = at;
self.exports.iter_mut().for_each(|slot| slot.timestamp = at);
stamp_attributes(&mut self.attributes, &mut self.attributes_timestamp, at);
}
fn merge(&mut self, other: Self) {
let len = self.exports.len().max(other.exports.len());
self.exports.resize_with(len, ExportSlot::default);
for (slot, incoming) in self.exports.iter_mut().zip(other.exports) {
if incoming.timestamp > slot.timestamp {
*slot = incoming;
/// Resurrect (from history) any nodes/networks an op references that were concurrently removed, so
/// the op applies against a consistent registry. Cascading: a node's owning network is restored
/// before the node. No-op for ops that reference nothing absent.
fn ensure_referenced_exist(&mut self, target: RegistryTarget, op: &RegistryDelta) -> Result<(), CrdtError> {
match op {
RegistryDelta::AddNode { node, .. } => self.ensure_network_exists(target, node.network())?,
RegistryDelta::ChangeNodeInput { id, new_input, .. } => {
if let NodeInput::Node { id: referenced, .. } = new_input {
self.ensure_node_exists(target, *referenced)?;
}
self.ensure_node_exists(target, *id)?;
}
}
merge_attributes(&mut self.attributes, &mut self.attributes_timestamp, other.attributes, other.attributes_timestamp);
self.presence = self.presence.max(other.presence);
}
}
impl Presence for ResourceEntry {
fn presence(&self) -> TimeStamp {
self.presence
}
fn set_presence(&mut self, at: TimeStamp) {
self.presence = at;
}
fn placeholder() -> Self {
ResourceEntry::default()
}
fn stamp_all(&mut self, at: TimeStamp) {
self.presence = at;
self.hash_timestamp = at;
self.stamp_sources(at);
}
fn merge(&mut self, other: Self) {
if other.hash_timestamp > self.hash_timestamp {
self.hash = other.hash;
self.hash_timestamp = other.hash_timestamp;
}
self.merge_sources(other.sources, other.sources_timestamp);
self.presence = self.presence.max(other.presence);
}
}
fn stamp_slot(slot: &mut InputSlot, at: TimeStamp) {
slot.timestamp = at;
stamp_attributes(&mut slot.attributes, &mut slot.attributes_timestamp, at);
}
/// Writes the map whole at `at`: the floor deletes every other key without a tombstone per key.
fn stamp_attributes(attributes: &mut Attributes, floor: &mut TimeStamp, at: TimeStamp) {
attributes.retain(|_, value| !value.deleted);
attributes.values_mut().for_each(|value| value.timestamp = at);
*floor = at;
}
/// Folds `other` in key by key. A key only one map holds is dead when the other map's floor is newer, since
/// that map was written whole after it; an entry stamped exactly at a floor was written by that whole-map
/// write and survives. Where both hold a key, the newer entry wins.
fn merge_attributes(attributes: &mut Attributes, floor: &mut TimeStamp, other: Attributes, other_floor: TimeStamp) {
attributes.retain(|_, value| value.timestamp >= other_floor);
for (key, value) in other {
match attributes.entry(key) {
Entry::Occupied(entry) if value.timestamp > entry.get().timestamp => *entry.into_mut() = value,
Entry::Vacant(entry) if value.timestamp >= *floor => {
entry.insert(value);
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::ChangeNodeAttribute { id, .. } | RegistryDelta::ChangeNodeInputAttribute { id, .. } => self.ensure_node_exists(target, *id)?,
RegistryDelta::SetNetworkExport {
id: network, export: export_target, ..
} => {
if let Some(NodeInput::Node { id: referenced, .. }) = export_target {
self.ensure_node_exists(target, *referenced)?;
}
self.ensure_network_exists(target, *network)?;
}
RegistryDelta::ChangeNetworkAttribute { id: network, .. } => self.ensure_network_exists(target, *network)?,
_ => {}
}
Ok(())
}
*floor = (*floor).max(other_floor);
}
/// Folds an input list stamped `at` into the node's. The newer list decides the slot count, except that a
/// slot written after that shape still exists, with the gap up to it filled by unset slots stamped by the
/// shape. A slot both lists hold keeps its newer value, and its attributes fold key by key. A whole-list
/// write and a per-slot write thus land the same in either order.
fn merge_inputs(node: &mut Node, other: Vec<InputSlot>, at: TimeStamp) {
let (mut newer, shape, older) = if at > node.inputs_timestamp {
(other, at, std::mem::take(&mut node.inputs))
} else {
(std::mem::take(&mut node.inputs), node.inputs_timestamp, other)
};
for (index, incoming) in older.into_iter().enumerate() {
if index >= newer.len() {
if slot_newest(&incoming) <= shape {
continue;
fn ensure_node_exists(&mut self, target: RegistryTarget, node_id: NodeId) -> Result<(), CrdtError> {
if !self.registry_ref(target).node_instances.contains_key(&node_id) {
self.restore_node_from_history(target, node_id)?;
}
Ok(())
}
fn ensure_network_exists(&mut self, target: RegistryTarget, network_id: NetworkId) -> Result<(), CrdtError> {
if !self.registry_ref(target).networks.contains_key(&network_id) {
self.restore_network_from_history(target, network_id)?;
}
Ok(())
}
/// Compute the inverse of `delta` against the registry named by `target`. Retirement passes
/// [`RegistryTarget::Snapshot`] so LWW reverses (export target, inputs, attributes, resource hash)
/// capture the true pre-op value rather than the hot-polluted working state.
pub(crate) fn compute_reverse_delta(&self, target: RegistryTarget, delta: &RegistryDelta) -> Result<RegistryDelta, CrdtError> {
let registry = self.registry_ref(target);
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() }
}
newer.resize_with(index + 1, || InputSlot::unset(shape));
}
let slot = &mut newer[index];
if incoming.timestamp > slot.timestamp {
slot.input = incoming.input;
slot.timestamp = incoming.timestamp;
}
merge_attributes(&mut slot.attributes, &mut slot.attributes_timestamp, incoming.attributes, incoming.attributes_timestamp);
}
node.inputs = newer;
node.inputs_timestamp = shape;
}
/// The newest write the slot carries, its attributes included.
fn slot_newest(slot: &InputSlot) -> TimeStamp {
slot.attributes
.values()
.map(|value| value.timestamp)
.fold(slot.timestamp.max(slot.attributes_timestamp), TimeStamp::max)
}
/// The slot at `index` for a write at `at`. A slot past the end comes into being when the write is newer
/// than the list's shape, as in [`merge_inputs`], and is `None` when the shape is newer. For a fresh local
/// edit the index is out of bounds.
fn slot_for_write(node: &mut Node, index: usize, at: TimeStamp, mode: ApplyMode) -> Result<Option<&mut InputSlot>, CrdtError> {
if index >= node.inputs.len() {
if index >= MAX_INPUT_SLOTS || mode == ApplyMode::Live {
return Err(CrdtError::InputIndexOutOfBounds(index));
}
if at <= node.inputs_timestamp {
return Ok(None);
}
let shape = node.inputs_timestamp;
node.inputs.resize_with(index + 1, || InputSlot::unset(shape));
}
Ok(node.inputs.get_mut(index))
}
/// The entity's content wherever it sits: live, or held by its tombstone.
fn content_mut<'a, K: Hash + Eq + Copy, T>(live: &'a mut HashMap<K, T>, dead: &'a mut HashMap<K, Tombstone<T>>, id: K) -> Option<&'a mut T> {
live.get_mut(&id).or_else(|| dead.get_mut(&id).map(|mark| &mut mark.content))
}
/// Brings a removed entity back when its presence has grown past its removal. A placeholder stays dead
/// whatever its presence.
fn settle<K: Hash + Eq + Copy, T: Presence>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K) {
if dead.get(&id).is_some_and(|mark| !mark.placeholder && mark.content.presence() > mark.at) {
let mark = dead.remove(&id).expect("checked above");
live.insert(id, mark.content);
}
}
/// Folds `content` into whatever is held under `id`, or holds it as new. Content comes from an addition or
/// a removal's snapshot, so it proves the entity was added and a placeholder holding it stops being one.
fn fold<K: Hash + Eq + Copy, T: Presence>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, content: T) {
if let Some(mark) = dead.get_mut(&id).filter(|mark| mark.placeholder) {
// The placeholder holds only early writes: they land on the real content as if the addition came first.
let early = std::mem::replace(&mut mark.content, content);
mark.content.merge(early);
mark.placeholder = false;
} else if let Some(existing) = content_mut(live, dead, id) {
existing.merge(content);
} else {
live.insert(id, content);
}
settle(live, dead, id);
}
/// An addition at `at`: every field of `content` is written at `at`, and the entity exists from then
/// unless a newer removal holds it dead.
fn add<K: Hash + Eq + Copy, T: Presence>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, mut content: T, at: TimeStamp) {
content.stamp_all(at);
fold(live, dead, id, content);
}
/// A removal at `at`: the entity is dead from then unless a newer addition or write holds it live. The
/// snapshot folds in first, so a removal of an entity never seen still lands and its addition loses when
/// it arrives.
fn remove<K: Hash + Eq + Copy, T: Presence>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, snapshot: T, at: TimeStamp) {
fold(live, dead, id, snapshot);
if let Some(mark) = dead.get_mut(&id) {
mark.at = mark.at.max(at);
} else if live.get(&id).is_some_and(|content| at > content.presence()) {
let content = live.remove(&id).expect("checked above");
dead.insert(id, Tombstone { content, at, placeholder: false });
}
}
/// A write at `at` to the entity under `id`, applied by `write` to its content wherever it sits. The
/// write is evidence the entity exists at `at`, so it revives an older removal. A write to an entity
/// never seen lands on a placeholder tombstone that stays dead until an addition folds into it, so ops
/// land the same in any order and nothing is deferred. For a fresh local edit the entity is `missing()`.
fn write<K: Hash + Eq + Copy, T: Presence>(
live: &mut HashMap<K, T>,
dead: &mut HashMap<K, Tombstone<T>>,
id: K,
at: TimeStamp,
mode: ApplyMode,
missing: impl FnOnce() -> CrdtError,
write: impl FnOnce(&mut T) -> Result<(), CrdtError>,
) -> Result<(), CrdtError> {
let unseen = !live.contains_key(&id) && !dead.contains_key(&id);
if unseen {
if mode == ApplyMode::Live {
return Err(missing());
}
dead.insert(
id,
Tombstone {
content: T::placeholder(),
at: TimeStamp::ORIGIN,
placeholder: true,
&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))?;
RegistryDelta::ChangeNodeInput {
id,
index: input_idx,
new_input: slot.input.clone(),
}
}
&RegistryDelta::ChangeNodeAttribute { id, ref delta } => {
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
RegistryDelta::ChangeNodeAttribute {
id,
delta: reverse_attribute_delta(delta, node.attributes()),
}
}
&RegistryDelta::ChangeNodeInputAttribute { id, index, ref delta } => {
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
let input = node.inputs().get(index as usize).ok_or(CrdtError::InputIndexOutOfBounds(index as usize))?;
RegistryDelta::ChangeNodeInputAttribute {
id,
index,
delta: reverse_attribute_delta(delta, &input.attributes),
}
}
&RegistryDelta::SetNetworkExport { id, index, .. } => {
// If the network is absent the forward op will resurrect it; the reverse is "set the export to None"
// since pre-forward there was no export to point at.
let export_target = registry.networks.get(&id).and_then(|net| net.exports.get(index as usize)).and_then(|s| s.target.clone());
RegistryDelta::SetNetworkExport { id, index, export: export_target }
}
RegistryDelta::AddNetwork { id, network } => RegistryDelta::RemoveNetwork { id: *id, snapshot: network.clone() },
&RegistryDelta::RemoveNetwork { id, ref snapshot } => RegistryDelta::AddNetwork { id, network: snapshot.clone() },
&RegistryDelta::ChangeNetworkAttribute { id, ref delta } => {
let current = registry.networks.get(&id).map(|net| &net.attributes).ok_or(CrdtError::NetworkDoesNotExist(id))?;
RegistryDelta::ChangeNetworkAttribute {
id,
delta: reverse_attribute_delta(delta, current),
}
}
RegistryDelta::ChangeDocumentAttribute { delta } => RegistryDelta::ChangeDocumentAttribute {
delta: reverse_attribute_delta(delta, &registry.attributes),
},
);
}
let content = content_mut(live, dead, id).expect("held above");
if let Err(error) = write(content) {
// A rejected op changes nothing, so the placeholder made for it goes too.
if unseen {
dead.remove(&id);
}
return Err(error);
}
content.set_presence(content.presence().max(at));
settle(live, dead, id);
Ok(())
}
/// A fresh local edit cannot name a node never seen. Checked before an op's first write, so a refused op changes nothing.
fn ensure_seen(registry: &Registry, ids: &[NodeId], mode: ApplyMode) -> Result<(), CrdtError> {
let unseen = |id: &&NodeId| !registry.node_instances.contains_key(id) && !registry.removed_nodes.contains_key(id);
match ids.iter().find(unseen) {
Some(&id) if mode == ApplyMode::Live => Err(CrdtError::TargetNodeDoesNotExist(id)),
_ => Ok(()),
}
}
/// [`write()`] to a node; with a no-op `f`, records a reference to it.
fn write_node(registry: &mut Registry, id: NodeId, at: TimeStamp, mode: ApplyMode, f: impl FnOnce(&mut Node) -> Result<(), CrdtError>) -> Result<(), CrdtError> {
write(&mut registry.node_instances, &mut registry.removed_nodes, id, at, mode, || CrdtError::TargetNodeDoesNotExist(id), f)
}
fn write_network(registry: &mut Registry, id: NetworkId, at: TimeStamp, mode: ApplyMode, f: impl FnOnce(&mut Network) -> Result<(), CrdtError>) -> Result<(), CrdtError> {
write(&mut registry.networks, &mut registry.removed_networks, id, at, mode, || CrdtError::NetworkDoesNotExist(id), f)
}
/// Like [`write()`] for a resource, except that an entry never seen is created first, since single-field
/// resource ops are upserts. Every other field starts at the origin, so a later addition fills them in.
fn upsert_resource(registry: &mut Registry, id: ResourceId, at: TimeStamp, f: impl FnOnce(&mut ResourceEntry)) {
if !registry.resources.contains_key(&id) && !registry.removed_resources.contains_key(&id) {
registry.resources.insert(
id,
ResourceEntry {
presence: at,
..ResourceEntry::default()
// Registrations are append-only and not user-undoable; reverse is the same op,
// which applies as a no-op on the already-registered PeerId.
&RegistryDelta::RegisterPeer { peer, user } => RegistryDelta::RegisterPeer { peer, user },
&RegistryDelta::SetResourceHash { id, .. } => RegistryDelta::SetResourceHash {
id,
hash: registry.resources.get(&id).and_then(|entry| entry.hash),
},
);
&RegistryDelta::AddSource { id, key, .. } => match registry.resources.get(&id).and_then(|entry| entry.source(&key)) {
// The slot already held a source: undo restores it.
Some(existing) => RegistryDelta::AddSource {
id,
key,
source: existing.source.clone(),
},
// The slot was empty: undo removes what this op added.
None => RegistryDelta::RemoveSource { id, key },
},
&RegistryDelta::RemoveSource { id, key } => match registry.resources.get(&id).and_then(|entry| entry.source(&key)) {
Some(existing) => RegistryDelta::AddSource {
id,
key,
source: existing.source.clone(),
},
// Nothing to restore; reverse is a no-op removal.
None => RegistryDelta::RemoveSource { id, key },
},
&RegistryDelta::AddResource { id, .. } => match registry.resources.get(&id) {
// Overwrote an existing entry: undo restores it.
Some(existing) => RegistryDelta::AddResource { id, entry: existing.clone() },
// Created a new entry: undo removes what this op added (snapshot is empty since there was nothing prior).
None => RegistryDelta::RemoveResource {
id,
snapshot: ResourceEntry::default(),
},
},
&RegistryDelta::RemoveResource { id, .. } => {
let snapshot = registry.resources.get(&id).cloned().unwrap_or_default();
RegistryDelta::AddResource { id, entry: snapshot }
}
RegistryDelta::Merge { extra_parents } => RegistryDelta::Merge { extra_parents: extra_parents.clone() },
&RegistryDelta::Other(_) => RegistryDelta::Other(serde_json::Value::Null),
})
}
let entry = content_mut(&mut registry.resources, &mut registry.removed_resources, id).expect("held above");
f(entry);
entry.set_presence(entry.presence().max(at));
settle(&mut registry.resources, &mut registry.removed_resources, id);
}
/// Which of a [`Document`]'s two registries an apply targets: the working copy (retired state plus
@@ -684,12 +455,13 @@ pub(crate) enum RegistryTarget {
Snapshot,
}
/// How [`Document::apply_op_with`] treats what it finds.
/// How [`Document::apply_op_with`] resolves structural collisions and LWW timestamp ties.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum ApplyMode {
/// A fresh local edit: adding what exists, or writing to what was never seen, is an error, since a local
/// edit cannot mean either.
/// Fresh local/remote edit: structural ops error on duplicate/missing targets; LWW uses strict `>`.
Live,
/// An op from a peer or from persisted state: every arm is a timestamp comparison.
/// Replay/retire: structural ops skip duplicate/missing targets; LWW still uses strict `>`.
Idempotent,
/// Silent-zone undo/redo rewind: structural ops are idempotent and LWW arms assign unconditionally.
Force,
}
+66 -80
View File
@@ -10,12 +10,9 @@ use serde::Serialize;
use crate::attr::*;
use crate::metadata_source::{NoMetadata, NodeMetadataSource};
use crate::{
AttributesWrite, ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ProtoNode, ROOT_NETWORK, Registry, ResourceHash, ResourceId, TimeStamp, Value,
ValueError, from_value, to_value,
};
use crate::{AttributesWrite, ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ProtoNode, ROOT_NETWORK, Registry, ResourceHash, ResourceId, TimeStamp};
fn map_serialization_error(key: &str) -> impl FnOnce(ValueError) -> ConversionError + '_ {
fn map_serialization_error(key: &str) -> impl FnOnce(serde_json::Error) -> ConversionError + '_ {
move |e| ConversionError::SerializationError(format!("{key}: {e:?}"))
}
@@ -43,7 +40,7 @@ impl NodePath {
}
fn to_global_id(&self, peer: PeerId) -> NodeId {
let bytes = postcard::to_stdvec(&(peer, self)).expect("NodePath must serialize");
let bytes = rmp_serde::to_vec(&(peer, self)).expect("NodePath must serialize");
let digest = blake3::hash(&bytes);
let mut truncated = [0u8; 8];
truncated.copy_from_slice(&digest.as_bytes()[..8]);
@@ -55,7 +52,7 @@ impl NodePath {
/// depending on traversal order. A domain tag keeps it from colliding with this node's own
/// `to_global_id`. The root network is `ROOT_NETWORK` and never goes through here.
fn owned_network_id(&self, peer: PeerId) -> NetworkId {
let bytes = postcard::to_stdvec(&("network", peer, self)).expect("NodePath must serialize");
let bytes = rmp_serde::to_vec(&("network", peer, self)).expect("NodePath must serialize");
let digest = blake3::hash(&bytes);
let mut truncated = [0u8; 8];
truncated.copy_from_slice(&digest.as_bytes()[..8]);
@@ -120,29 +117,45 @@ impl TryFrom<&NodeNetwork> for Registry {
pub type DeclarationBytes = HashMap<ResourceHash, Vec<u8>>;
/// A `from_runtime` conversion result: the reference-only [`Registry`] plus the proto-node
/// declarations it extracted, as bytes keyed by content hash (for the caller's byte store) and as
/// decoded [`ProtoNode`]s keyed by id (for the caller's declaration cache).
/// declaration *bytes* it extracted, keyed by content hash. `document-graph-storage` doesn't own a byte
/// store, so the caller (the `Gdd`) persists these into its content store; the registry only holds
/// the `ResourceId`/`ResourceHash` references.
pub struct RuntimeConversion {
pub registry: Registry,
pub declaration_bytes: DeclarationBytes,
pub declarations: crate::Declarations,
/// Each network's runtime `metadata_path` mapped to its stable storage `NetworkId`, for associating
/// per-network, per-peer view state (`session.json`) without re-deriving ids.
pub network_ids: HashMap<Vec<RuntimeNodeId>, NetworkId>,
}
/// Encode a [`ProtoNode`] declaration to its content-addressed bytes: through the self-describing
/// [`Value`] (so serde aliases keep working and the on-disk shape stays migratable), then postcard.
/// Paired with [`decode_declaration`].
impl RuntimeConversion {
/// Rebuild the [`Declarations`](crate::Declarations) map (`ResourceId` → [`ProtoNode`]) from the
/// extracted bytes, for callers that keep the bytes in hand instead of routing them through a
/// byte store (tests, the round-trip CLI). Editor/`Gdd` paths persist the bytes and resolve via
/// their byte store instead.
pub fn declarations(&self) -> Result<crate::Declarations, ConversionError> {
self.declaration_bytes
.iter()
.map(|(hash, bytes)| {
let proto = decode_declaration(bytes).map_err(|error| ConversionError::SerializationError(format!("declaration {hash}: {error}")))?;
Ok((ResourceId::from_hash(hash), proto))
})
.collect()
}
}
/// Encode a [`ProtoNode`] declaration to its content-addressed bytes: through a self-describing
/// `serde_json::Value` (so serde aliases keep working and the on-disk shape stays migratable), then
/// rmp-serialized (which encodes the intermediate `Value` compactly). Paired with [`decode_declaration`].
pub fn encode_declaration(proto: &ProtoNode) -> Result<Vec<u8>, String> {
let value = to_value(proto).map_err(|error| error.to_string())?;
postcard::to_stdvec(&value).map_err(|error| error.to_string())
let value = serde_json::to_value(proto).map_err(|error| error.to_string())?;
rmp_serde::to_vec(&value).map_err(|error| error.to_string())
}
/// Decode a [`ProtoNode`] declaration from the bytes [`encode_declaration`] produced.
pub fn decode_declaration(bytes: &[u8]) -> Result<ProtoNode, String> {
let value: Value = postcard::from_bytes(bytes).map_err(|error| error.to_string())?;
from_value(&value).map_err(|error| error.to_string())
let value: serde_json::Value = rmp_serde::from_slice(bytes).map_err(|error| error.to_string())?;
serde_json::from_value(value).map_err(|error| error.to_string())
}
impl Registry {
@@ -164,7 +177,6 @@ impl Registry {
let mut ctx = ConversionContext {
declaration_ids: HashMap::new(),
declaration_bytes: HashMap::new(),
declarations: HashMap::new(),
network_ids: HashMap::new(),
metadata,
peer,
@@ -183,7 +195,6 @@ impl Registry {
Ok(RuntimeConversion {
registry,
declaration_bytes: ctx.declaration_bytes,
declarations: ctx.declarations,
network_ids: ctx.network_ids,
})
}
@@ -192,7 +203,7 @@ impl Registry {
/// Snapshot the runtime [`ResourceRegistry`](graphene_resource::ResourceRegistry) into the storage
/// [`ResourceStore`](crate::ResourceStore). Each source's chain position becomes a fractional
/// [`Priority`](crate::Priority) (index-as-priority preserves order); the `DataSource` body is
/// stored type-erased as [`Value`] so its on-disk shape can migrate freely. All
/// stored type-erased as `serde_json::Value` so its on-disk shape can migrate freely. All
/// timestamps are `ORIGIN`, since this is a bootstrap snapshot, not an edit.
fn convert_resources(resources: &graphene_resource::ResourceRegistry, referenced: &std::collections::HashSet<ResourceId>, peer: PeerId, registry: &mut Registry) -> Result<(), ConversionError> {
for id in resources.ids() {
@@ -220,14 +231,12 @@ pub fn convert_resource_entry(resources: &graphene_resource::ResourceRegistry, i
priority: crate::Priority::new(position as f64).expect("enumerate index is finite"),
peer,
};
let body = to_value(source).map_err(|error| ConversionError::SerializationError(error.to_string()))?;
// Built rather than written: the chain is put in place as converted, floor and all at the origin.
entry.force_set_source(
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,
deleted: false,
},
);
}
@@ -280,8 +289,6 @@ struct ConversionContext<'m, M: NodeMetadataSource + ?Sized> {
declaration_ids: HashMap<String, ResourceId>,
/// Extracted declaration content keyed by hash, handed back for the caller's byte store.
declaration_bytes: DeclarationBytes,
/// The same declarations decoded, keyed by id, handed back for the caller's declaration cache.
declarations: crate::Declarations,
/// Maps each network's runtime `metadata_path` to its stable storage `NetworkId`, so the caller can
/// associate per-network, per-peer view state (in `session.json`) with networks without re-deriving ids.
network_ids: HashMap<Vec<RuntimeNodeId>, NetworkId>,
@@ -322,7 +329,7 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
runtime_node_id: *runtime_node_id,
};
let mut node = convert_node(doc_node, location, registry, ctx, true)?;
node.attributes.set(node::ORIGINAL_NODE_ID, Value::Int(runtime_node_id.0.into()), TimeStamp::ORIGIN);
node.attributes.set(node::ORIGINAL_NODE_ID, serde_json::json!(runtime_node_id.0), TimeStamp::ORIGIN);
registry.node_instances.insert(global_id, node);
}
@@ -338,18 +345,10 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
.collect::<Result<Vec<_>, ConversionError>>()?;
let mut attributes = crate::Attributes::new();
write_ui_network_attributes(&mut attributes, node_network, metadata_path, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
write_ui_network_attributes(&mut attributes, ctx.metadata, 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 {
presence: TimeStamp::ORIGIN,
exports,
attributes,
attributes_timestamp: TimeStamp::ORIGIN,
},
);
registry.networks.insert(network_id, Network { exports, attributes });
ctx.network_ids.insert(metadata_path.to_vec(), network_id);
Ok(())
@@ -427,7 +426,6 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
input: convert_input(input, parent_path, network_id, ctx.ids(metadata_path))?,
timestamp,
attributes: input_attrs,
attributes_timestamp: timestamp,
});
}
@@ -460,14 +458,9 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
write_ui_attributes(&mut attributes, ctx.metadata, metadata_path, runtime_node_id, timestamp)?;
Ok(Node {
presence: timestamp,
added: timestamp,
inputs_timestamp: timestamp,
implementation,
implementation_timestamp: timestamp,
inputs,
attributes,
attributes_timestamp: timestamp,
network: network_id,
})
}
@@ -484,7 +477,11 @@ pub fn encode_context_features(context_features: &ContextDependencies) -> Result
}
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(to_value(value).map_err(map_serialization_error(key))?) };
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 })
}
@@ -532,14 +529,14 @@ fn write_ui_attributes<M: NodeMetadataSource + ?Sized>(
(node::ui::PINNED, metadata.pinned(metadata_path, runtime_node_id)),
] {
if value {
attributes.set(key, Value::Bool(true), timestamp);
attributes.set(key, serde_json::Value::Bool(true), timestamp);
}
}
if let Some(name) = metadata.display_name(metadata_path, runtime_node_id)
&& !name.is_empty()
{
attributes.set(node::ui::DISPLAY_NAME, Value::Str(name.to_string()), timestamp);
attributes.set(node::ui::DISPLAY_NAME, serde_json::Value::String(name.to_string()), timestamp);
}
// One whole-vec attribute; per-slot LWW would be overkill for rename-on-output.
@@ -557,25 +554,20 @@ fn write_ui_attributes<M: NodeMetadataSource + ?Sized>(
/// 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,
metadata: &M,
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, Value::Str(reference.to_string()), timestamp);
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();
let pinned_order = metadata.pinned_order(network_path);
if !pinned_order.is_empty() {
let stored: Vec<NodeId> = pinned_order.into_iter().map(to_storage_id).collect();
attributes
@@ -598,7 +590,7 @@ fn write_ui_input_attributes<M: NodeMetadataSource + ?Sized>(
) -> Result<(), ConversionError> {
let non_empty_string = |key: &'static str, value: Option<&str>, attributes: &mut crate::Attributes| {
if let Some(value) = value.filter(|s| !s.is_empty()) {
attributes.set(key, Value::Str(value.to_string()), timestamp);
attributes.set(key, serde_json::Value::String(value.to_string()), timestamp);
}
};
@@ -620,7 +612,7 @@ fn convert_input<M: NodeMetadataSource + ?Sized>(input: &GraphCraftNodeInput, pa
index: (*output_index).try_into().map_err(|_| ConversionError::IndexOverflow(*output_index))?,
},
GraphCraftNodeInput::Value { tagged_value, exposed } => {
let value = to_value(&**tagged_value).map_err(|e| ConversionError::SerializationError(format!("{e:?}")))?;
let value = serde_json::to_value(&**tagged_value).map_err(|e| ConversionError::SerializationError(format!("{e:?}")))?;
NodeInput::Value { value, exposed: *exposed }
}
GraphCraftNodeInput::Scope(s) => NodeInput::Scope(s.clone()),
@@ -634,7 +626,7 @@ fn convert_input<M: NodeMetadataSource + ?Sized>(input: &GraphCraftNodeInput, pa
}
/// The non-ui attributes a slot carries, derived from the input itself: the declared type of an
/// import, and a reflection node's metadata.
/// import, and a reflection node.s metadata. Public for staging paths that rebuild a node.s slots.
pub fn convert_input_attributes(input: &GraphCraftNodeInput) -> Result<crate::Attributes, ConversionError> {
let mut attributes = crate::Attributes::new();
let timestamp = TimeStamp::ORIGIN;
@@ -685,7 +677,6 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
register_declaration_resource(registry, id, hash, ctx.peer);
ctx.declaration_bytes.insert(hash, bytes);
ctx.declarations.insert(id, proto);
ctx.declaration_ids.insert(identifier_str, id);
Implementation::ProtoNode(id)
@@ -779,7 +770,6 @@ impl<'m> ScopedConversion<'m> {
ctx: ConversionContext {
declaration_ids: HashMap::new(),
declaration_bytes: HashMap::new(),
declarations: HashMap::new(),
network_ids: HashMap::new(),
metadata,
peer,
@@ -801,7 +791,7 @@ impl<'m> ScopedConversion<'m> {
};
let mut node = convert_node(doc_node, location, registry, &mut self.ctx, recurse)?;
node.attributes.set(node::ORIGINAL_NODE_ID, Value::Int(local_id.0.into()), TimeStamp::ORIGIN);
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(())
}
@@ -824,25 +814,24 @@ impl<'m> ScopedConversion<'m> {
.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_ui_network_attributes(
&mut attributes,
self.ctx.metadata,
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 {
presence: TimeStamp::ORIGIN,
exports,
attributes,
attributes_timestamp: 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 extracted proto-node declaration bytes, for the caller to persist into its byte store.
pub fn finish(self) -> DeclarationBytes {
self.ctx.declaration_bytes
}
}
@@ -858,10 +847,7 @@ pub fn node_value_resource_refs(node: &Node) -> impl Iterator<Item = ResourceId>
/// 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::Object(fields), .. } => match fields.as_slice() {
[(key, id)] if key == "Resource" => from_value(id).ok(),
_ => None,
},
NodeInput::Value { value, .. } => value.get("Resource").and_then(|id| serde_json::from_value(id.clone()).ok()),
_ => None,
}
}
@@ -873,8 +859,8 @@ mod resource_ref_shape {
#[test]
fn resource_ref_shape_matches_serde() {
let id = ResourceId::from_hash(&ResourceHash::from(b"shape test".as_slice()));
let value = to_value(&TaggedValue::Resource(id)).expect("TaggedValue::Resource serializes");
let parsed = value_resource_ref(&NodeInput::Value { value, exposed: false });
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");
}
}
+62 -43
View File
@@ -3,26 +3,21 @@
//! [`History`] owns the deltas in topological order (every parent precedes its children) plus an
//! index from [`Rev`] to position for O(1) lookup. The order is a valid replay order, so it is what
//! gets serialized to the on-disk history file and what [`crate::Session::replay_from_history`]
//! consumes. Appending a commit keeps the order; deltas arriving out of it are put back by
//! a canonical sort.
//! consumes. Retired commits have a single writer in every regime (solo editing, or leader-ordered
//! collaboration where the leader serializes retired commits), so appending preserves the order by
//! construction. The only operation that introduces out-of-order deltas is [`merge`](History::merge),
//! which re-sorts the combined set into the canonical order to restore the invariant.
use std::collections::{HashMap, HashSet};
use std::collections::HashMap;
use crate::{AttributesWrite, CrdtError, Delta, RegistryDelta, ResourceHash, Rev, TimeStamp, Value};
use crate::{AttributesWrite, CrdtError, Delta, Rev, TimeStamp};
/// Every mutator maintains the indexes, so the tips and named hashes are probes, not scans of a growing history.
#[derive(Clone, Debug, Default)]
pub struct History {
/// Deltas in topological order. Mutated only via [`push`](Self::push).
deltas: Vec<Delta>,
/// `Rev` to its position in `deltas`. Kept in sync with `deltas` by every mutator.
index: HashMap<Rev, usize>,
/// Every rev some delta names as a parent.
referenced: HashSet<Rev>,
/// Deltas no other delta names as a parent.
tips: HashSet<Rev>,
/// Content hashes the deltas name, from resource additions and removals.
resource_hashes: HashSet<ResourceHash>,
}
impl History {
@@ -32,9 +27,8 @@ impl History {
/// Build from deltas already in topological order (the on-disk load path), indexing them in place.
pub fn from_ordered(deltas: Vec<Delta>) -> Self {
let mut history = Self::default();
deltas.into_iter().for_each(|delta| history.push(delta));
history
let index = deltas.iter().enumerate().map(|(position, delta)| (delta.id, position)).collect();
Self { deltas, index }
}
pub fn get(&self, rev: Rev) -> Option<&Delta> {
@@ -45,11 +39,6 @@ impl History {
self.index.contains_key(&rev)
}
/// The content hashes named by any resource addition or removal in history.
pub fn resource_hashes(&self) -> &HashSet<ResourceHash> {
&self.resource_hashes
}
pub fn len(&self) -> usize {
self.deltas.len()
}
@@ -62,22 +51,10 @@ impl History {
/// (idempotent re-apply) overwrites the existing entry in place rather than appending, so the
/// order and index are unchanged.
pub fn push(&mut self, delta: Delta) {
match &delta.kind {
RegistryDelta::AddResource { entry, .. } => self.resource_hashes.extend(entry.hash),
RegistryDelta::RemoveResource { snapshot, .. } => self.resource_hashes.extend(snapshot.hash),
_ => {}
}
if let Some(&position) = self.index.get(&delta.id) {
self.deltas[position] = delta;
return;
}
for parent in delta.all_parents() {
self.referenced.insert(parent);
self.tips.remove(&parent);
}
if !self.referenced.contains(&delta.id) {
self.tips.insert(delta.id);
}
self.index.insert(delta.id, self.deltas.len());
self.deltas.push(delta);
}
@@ -87,24 +64,66 @@ impl History {
self.deltas.iter()
}
/// `roots` and everything reachable from them through all parent links. Unknown roots are skipped.
pub(crate) fn ancestors(&self, roots: impl IntoIterator<Item = Rev>) -> HashSet<Rev> {
let mut seen = HashSet::new();
let mut stack: Vec<Rev> = roots.into_iter().filter(|rev| self.contains(*rev)).collect();
while let Some(rev) = stack.pop() {
if seen.insert(rev)
&& let Some(delta) = self.get(rev)
{
stack.extend(delta.all_parents());
/// Absorb `incoming` (dedup by `Rev`) and canonically re-sort the whole combined history.
///
/// The sort is deterministic (topological, ties broken by `Rev`), 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. Callers update the registry separately
/// (LWW apply is commutative, so the registry converges regardless of order).
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) {
for delta in incoming {
self.push(delta);
}
self.canonical_sort();
}
/// 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).
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());
let mut children: HashMap<Rev, Vec<Rev>> = HashMap::new();
for delta in &self.deltas {
let in_history_parents = delta.all_parents().filter(|parent| self.index.contains_key(parent)).count();
pending_parents.insert(delta.id, in_history_parents);
for parent in delta.all_parents() {
if self.index.contains_key(&parent) {
children.entry(parent).or_default().push(delta.id);
}
}
}
// Ready set as a min-heap on `Rev` (via `Reverse`) so ties resolve deterministically.
let mut ready: std::collections::BinaryHeap<std::cmp::Reverse<Rev>> = pending_parents.iter().filter(|(_, count)| **count == 0).map(|(rev, _)| std::cmp::Reverse(*rev)).collect();
let mut order: Vec<Rev> = Vec::with_capacity(self.deltas.len());
while let Some(std::cmp::Reverse(rev)) = ready.pop() {
order.push(rev);
for child in children.get(&rev).into_iter().flatten() {
let count = pending_parents.get_mut(child).expect("child is in history");
*count -= 1;
if *count == 0 {
ready.push(std::cmp::Reverse(*child));
}
}
}
// `order` is a permutation of the existing revs, so reorder `deltas` to match and rebuild the index.
let mut by_rev: HashMap<Rev, Delta> = self.deltas.drain(..).map(|delta| (delta.id, delta)).collect();
self.index.clear();
for (position, rev) in order.iter().enumerate() {
if let Some(delta) = by_rev.remove(rev) {
self.index.insert(*rev, position);
self.deltas.push(delta);
}
}
seen
}
/// The current tips: revs that no other delta lists as a parent (the divergent heads). A linear
/// history has exactly one tip; concurrent branches have several. Sorted ascending for determinism.
pub fn tips(&self) -> Vec<Rev> {
let mut tips: Vec<Rev> = self.tips.iter().copied().collect();
let referenced: std::collections::HashSet<Rev> = self.deltas.iter().flat_map(|delta| delta.all_parents()).collect();
let mut tips: Vec<Rev> = self.deltas.iter().map(|delta| delta.id).filter(|rev| !referenced.contains(rev)).collect();
tips.sort_unstable();
tips
}
@@ -123,7 +142,7 @@ impl History {
/// Set a local annotation attribute (e.g. a commit message) on a retired delta in place. Excluded
/// from the delta's `Rev`, so identity and the index are unchanged. Returns whether the delta was found.
pub fn annotate(&mut self, rev: Rev, key: &str, value: Value, timestamp: TimeStamp) -> bool {
pub fn annotate(&mut self, rev: Rev, key: &str, value: serde_json::Value, timestamp: TimeStamp) -> bool {
match self.index.get(&rev) {
Some(&position) => {
self.deltas[position].attributes.set(key, value, timestamp);
+2 -4
View File
@@ -56,8 +56,6 @@ pub const ROOT_NETWORK: NetworkId = NetworkId(0);
/// Upper bound on a network's export slot count, guarding `SetExport` against a malicious or corrupted
/// slot index forcing an unbounded `exports` allocation.
pub(crate) const MAX_EXPORT_SLOTS: usize = 1 << 16;
/// A per-slot write can bring a slot past the end of the list into being, so it is capped the same way.
pub(crate) const MAX_INPUT_SLOTS: usize = 1 << 16;
/// Per-device identity. Stable per `(device, document)`. Used for CRDT tiebreaking and `NodeId`
/// scoping. Globally unique across all peers ever in a document.
@@ -121,9 +119,9 @@ pub(crate) fn compute_rev(parent: Option<Rev>, author: PeerId, timestamp: TimeSt
let mut parents: Vec<Rev> = parent.into_iter().chain(extra_parents.iter().copied()).collect();
parents.sort_unstable();
parents.dedup();
postcard::to_stdvec(&("merge", parents)).expect("Merge identity fields must serialize")
rmp_serde::to_vec(&("merge", parents)).expect("Merge identity fields must serialize")
}
_ => postcard::to_stdvec(&(parent, author, timestamp, delta_type)).expect("Delta identity fields must serialize"),
_ => rmp_serde::to_vec(&(parent, author, timestamp, delta_type)).expect("Delta identity fields must serialize"),
};
hasher.update(&bytes);
let digest = hasher.finalize();
-5
View File
@@ -7,11 +7,9 @@ pub mod document;
pub mod history;
pub mod ids;
pub mod model;
mod prior;
pub mod registry;
pub mod resources;
pub mod session;
pub mod value;
#[cfg(any(feature = "conversion", test))]
pub mod from_runtime;
@@ -26,11 +24,9 @@ pub use document::*;
pub use history::History;
pub use ids::*;
pub use model::*;
pub use prior::{NetworkField, NodeField, Prior};
pub use registry::*;
pub use resources::*;
pub use session::*;
pub use value::{Value, ValueError, from_value, to_value};
#[cfg(any(feature = "conversion", test))]
pub use from_runtime::{
@@ -44,7 +40,6 @@ pub use to_runtime::Declarations;
#[cfg(test)]
mod tests {
mod bookkeeping;
mod crdt;
mod round_trip;
}
+6 -10
View File
@@ -8,8 +8,6 @@ use std::collections::HashMap;
use core_types::uuid::NodeId as RuntimeNodeId;
use crate::Value;
/// 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)]
@@ -40,9 +38,10 @@ pub struct NetworkMetadataEntry {
/// Stable storage id of this network. Lets the editor associate per-network, per-peer view state
/// (the node-graph nav, in `session.json`) with a network across reparenting.
pub network_id: crate::NetworkId,
/// Matches the runtime's `NodeNetworkPersistentMetadata::reference`: the definition lineage tag.
/// Matches the runtime's `NodeNetworkPersistentMetadata::reference` — definition lineage tag.
pub reference: Option<String>,
/// The display order of the network's pinned nodes.
/// The display order of the network's pinned nodes. Shared for the same reason the pinned flag is:
/// a shared set with per-peer ordering could never reconcile.
pub pinned_order: Vec<RuntimeNodeId>,
}
@@ -54,11 +53,11 @@ pub struct InputMetadataEntry {
pub input_description: Option<String>,
pub widget_override: Option<String>,
/// Reassembled from `ui::input_data::<sub_key>` attributes.
pub input_data: HashMap<String, Value>,
pub input_data: HashMap<String, serde_json::Value>,
}
/// Editor-side metadata source. Methods default to "no data" so implementors only override what
/// they carry. Returns are type-erased as [`Value`] where the underlying types live editor-side (PTZ, etc.).
/// they carry. Returns are JSON-shaped where the underlying types live editor-side (PTZ, etc.).
pub trait NodeMetadataSource {
fn position(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId) -> Option<Position> {
None
@@ -90,7 +89,7 @@ pub trait NodeMetadataSource {
None
}
/// Returns owned to stay object-safe. Each entry is stored as `ui::input_data::<key>` for per-key LWW.
fn input_data(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId, _input_index: usize) -> HashMap<String, Value> {
fn input_data(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId, _input_index: usize) -> HashMap<String, serde_json::Value> {
HashMap::new()
}
@@ -99,12 +98,9 @@ pub trait NodeMetadataSource {
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()
+9 -78
View File
@@ -1,30 +1,12 @@
use crate::{Attributes, NetworkId, NodeId, ResourceId, TimeStamp, Value, attributes_value_equal};
use crate::{Attributes, NetworkId, NodeId, ResourceId, TimeStamp, attributes_value_equal};
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Node {
/// The latest addition or write, so a concurrent removal resolves by last-writer-wins rather than
/// arrival order. See [`Registry::removed_nodes`](crate::Registry::removed_nodes).
#[serde(default)]
pub(crate) presence: TimeStamp,
/// When the node was last added, which decides its network between concurrent additions of one id.
#[serde(default)]
pub(crate) added: TimeStamp,
/// When the input list last changed shape, so whole-list and per-slot writes resolve the same in either
/// order: the list follows the newer write, and a slot both lists held keeps its newer value.
#[serde(default)]
pub(crate) inputs_timestamp: TimeStamp,
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,
/// When `attributes` was last written whole; see [`Attributes`].
#[serde(default)]
pub(crate) attributes_timestamp: TimeStamp,
pub(crate) network: NetworkId,
}
@@ -61,26 +43,14 @@ impl Node {
attributes_value_equal(&self.attributes, &other.attributes)
}
/// A node in `network` whose `inputs` slots are unset, for a caller that fills them in with
/// `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 {
Self {
presence: TimeStamp::ORIGIN,
added: TimeStamp::ORIGIN,
inputs_timestamp: TimeStamp::ORIGIN,
implementation,
implementation_timestamp: TimeStamp::ORIGIN,
inputs: vec![InputSlot::unset(TimeStamp::ORIGIN); inputs],
attributes: Attributes::new(),
attributes_timestamp: TimeStamp::ORIGIN,
network,
}
}
#[cfg(test)]
pub(crate) fn dummy() -> Self {
Self::new(crate::ROOT_NETWORK, Implementation::ProtoNode(ResourceId::new()), 0)
Self {
implementation: Implementation::ProtoNode(ResourceId::new()),
inputs: vec![],
attributes: Attributes::new(),
network: crate::ROOT_NETWORK,
}
}
}
@@ -91,26 +61,6 @@ pub struct InputSlot {
pub input: NodeInput,
pub timestamp: TimeStamp,
pub attributes: Attributes,
/// When `attributes` was last written whole; see [`Attributes`].
#[serde(default)]
pub attributes_timestamp: TimeStamp,
}
impl InputSlot {
/// A slot holding nothing, stamped `at`.
pub fn unset(at: TimeStamp) -> 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`.
Self {
input: NodeInput::Value {
value: Value::Str("None".to_string()),
exposed: false,
},
timestamp: at,
attributes: Attributes::new(),
attributes_timestamp: at,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -120,7 +70,7 @@ pub enum NodeInput {
index: u32,
},
Value {
value: Value,
value: serde_json::Value,
exposed: bool,
},
Scope(Cow<'static, str>),
@@ -142,16 +92,10 @@ pub enum Implementation {
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Network {
/// The latest addition or write; see [`Node::presence`](crate::Node).
#[serde(default)]
pub(crate) presence: TimeStamp,
pub exports: Vec<ExportSlot>,
/// Per-network `ui::*` state (navigation, previewing). Separate from `Node.attributes` so
/// view-state edits LWW independently.
pub attributes: Attributes,
/// When `attributes` was last written whole; see [`Attributes`].
#[serde(default)]
pub attributes_timestamp: TimeStamp,
}
impl Network {
@@ -176,7 +120,7 @@ impl Network {
/// One positional export slot. `target == None` marks an empty/removed slot. Timestamp drives LWW
/// on concurrent `SetExport` ops.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ExportSlot {
pub target: Option<NodeInput>,
pub timestamp: TimeStamp,
@@ -210,19 +154,6 @@ 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 = crate::from_value(value).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]
-304
View File
@@ -1,304 +0,0 @@
use crate::{
AttributeValue, ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, TimeStamp,
Tombstone,
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::hash::Hash;
/// What a slot held before a delta wrote it, with its own stamps. Undo puts these back as they were, bypassing
/// LWW, so the registry is again exactly what folding history up to the delta's parent gives. Never sent or
/// applied as an op.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Prior {
/// The whole entity, live or tombstoned. `None, None` means it didn't exist, so undoing an addition leaves no
/// tombstone behind.
Node {
id: NodeId,
live: Option<Node>,
removed: Option<Tombstone<Node>>,
},
Network {
id: NetworkId,
live: Option<Network>,
removed: Option<Tombstone<Network>>,
},
Resource {
id: ResourceId,
live: Option<ResourceEntry>,
removed: Option<Tombstone<ResourceEntry>>,
},
/// One field of a live node, and the node's presence, which every write moves.
NodeField {
id: NodeId,
presence: TimeStamp,
field: NodeField,
},
/// One field of a live network, and its presence.
NetworkField {
id: NetworkId,
presence: TimeStamp,
field: NetworkField,
},
DocumentAttribute {
key: String,
previous: Option<AttributeValue>,
},
PeerUser {
peer: PeerId,
previous: Option<PeerRegistration>,
},
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NodeField {
/// Only the presence moved, by a reference from another entity's op.
Presence,
Attribute {
key: String,
previous: Option<AttributeValue>,
},
Input {
index: u32,
previous: InputSlot,
},
InputAttribute {
index: u32,
key: String,
previous: Option<AttributeValue>,
},
Inputs {
previous: Vec<InputSlot>,
inputs_timestamp: TimeStamp,
},
Implementation {
previous: Implementation,
implementation_timestamp: TimeStamp,
},
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NetworkField {
/// Only the presence moved, by a node added to or implemented by it.
Presence,
Attribute {
key: String,
previous: Option<AttributeValue>,
},
Exports {
previous: Vec<ExportSlot>,
},
}
/// What `op` is about to write in `registry`, in write order. Taken before the op applies.
pub(crate) fn capture(registry: &Registry, op: &RegistryDelta) -> Vec<Prior> {
let mut priors = Vec::new();
let node_input = |input: &NodeInput| match input {
NodeInput::Node { id, .. } => Some(*id),
_ => None,
};
match op {
RegistryDelta::AddNode { id, node } => {
priors.push(network_field(registry, node.network, |_| NetworkField::Presence));
priors.push(whole_node(registry, *id));
}
RegistryDelta::RemoveNode { id, .. } => priors.push(whole_node(registry, *id)),
RegistryDelta::SetNodeInputs { id, inputs } => {
priors.push(node_field(registry, *id, |node| NodeField::Inputs {
previous: node.inputs.clone(),
inputs_timestamp: node.inputs_timestamp,
}));
priors.extend(
inputs
.iter()
.filter_map(|slot| node_input(&slot.input))
.map(|referenced| node_field(registry, referenced, |_| NodeField::Presence)),
);
}
RegistryDelta::ChangeNodeInput { id, index, new_input } => {
priors.push(node_field(registry, *id, |node| {
input_field(node, *index, |slot| NodeField::Input {
index: *index,
previous: slot.clone(),
})
}));
priors.extend(node_input(new_input).map(|referenced| node_field(registry, referenced, |_| NodeField::Presence)));
}
RegistryDelta::SetNodeImplementation { id, implementation } => {
if let Implementation::Network(network) = implementation {
priors.push(network_field(registry, *network, |_| NetworkField::Presence));
}
priors.push(node_field(registry, *id, |node| NodeField::Implementation {
previous: node.implementation.clone(),
implementation_timestamp: node.implementation_timestamp,
}));
}
RegistryDelta::ChangeNodeAttribute { id, delta } => priors.push(node_field(registry, *id, |node| NodeField::Attribute {
key: delta.key.clone(),
previous: node.attributes.get(&delta.key).cloned(),
})),
RegistryDelta::ChangeNodeInputAttribute { id, index, delta } => priors.push(node_field(registry, *id, |node| {
input_field(node, *index, |slot| NodeField::InputAttribute {
index: *index,
key: delta.key.clone(),
previous: slot.attributes.get(&delta.key).cloned(),
})
})),
RegistryDelta::SetNetworkExport { id, export, .. } => {
priors.push(network_field(registry, *id, |network| NetworkField::Exports { previous: network.exports.clone() }));
priors.extend(export.as_ref().and_then(node_input).map(|referenced| node_field(registry, referenced, |_| NodeField::Presence)));
}
RegistryDelta::AddNetwork { id, .. } | RegistryDelta::RemoveNetwork { id, .. } => priors.push(whole_network(registry, *id)),
RegistryDelta::ChangeNetworkAttribute { id, delta } => {
priors.push(network_field(registry, *id, |network| NetworkField::Attribute {
key: delta.key.clone(),
previous: network.attributes.get(&delta.key).cloned(),
}));
}
RegistryDelta::AddResource { id, .. }
| RegistryDelta::RemoveResource { id, .. }
| RegistryDelta::SetResourceHash { id, .. }
| RegistryDelta::AddSource { id, .. }
| RegistryDelta::RemoveSource { id, .. } => priors.push(Prior::Resource {
id: *id,
live: registry.resources.get(id).cloned(),
removed: registry.removed_resources.get(id).cloned(),
}),
RegistryDelta::RegisterPeer { peer, .. } => priors.push(Prior::PeerUser {
peer: *peer,
previous: registry.peer_users.get(peer).copied(),
}),
RegistryDelta::ChangeDocumentAttribute { delta } => priors.push(Prior::DocumentAttribute {
key: delta.key.clone(),
previous: registry.attributes.get(&delta.key).cloned(),
}),
RegistryDelta::Merge { .. } | RegistryDelta::EndTransaction | RegistryDelta::Other(_) => {}
}
priors
}
/// Puts back what `priors` recorded, newest write first.
pub(crate) fn restore(registry: &mut Registry, priors: &[Prior]) {
for prior in priors.iter().rev() {
match prior {
Prior::Node { id, live, removed } => put_whole(&mut registry.node_instances, &mut registry.removed_nodes, *id, live.as_ref(), removed.as_ref()),
Prior::Network { id, live, removed } => put_whole(&mut registry.networks, &mut registry.removed_networks, *id, live.as_ref(), removed.as_ref()),
Prior::Resource { id, live, removed } => put_whole(&mut registry.resources, &mut registry.removed_resources, *id, live.as_ref(), removed.as_ref()),
Prior::NodeField { id, presence, field } => {
let Some(node) = registry.node_instances.get_mut(id) else {
debug_assert!(false, "a field prior is taken from a live node, which the later priors put back");
continue;
};
node.presence = *presence;
match field {
NodeField::Presence => {}
NodeField::Attribute { key, previous } => put_attribute(&mut node.attributes, key, previous.as_ref()),
NodeField::Input { index, previous } => {
if let Some(slot) = node.inputs.get_mut(*index as usize) {
*slot = previous.clone();
}
}
NodeField::InputAttribute { index, key, previous } => {
if let Some(slot) = node.inputs.get_mut(*index as usize) {
put_attribute(&mut slot.attributes, key, previous.as_ref());
}
}
NodeField::Inputs { previous, inputs_timestamp } => {
node.inputs = previous.clone();
node.inputs_timestamp = *inputs_timestamp;
}
NodeField::Implementation { previous, implementation_timestamp } => {
node.implementation = previous.clone();
node.implementation_timestamp = *implementation_timestamp;
}
}
}
Prior::NetworkField { id, presence, field } => {
let Some(network) = registry.networks.get_mut(id) else {
debug_assert!(false, "a field prior is taken from a live network, which the later priors put back");
continue;
};
network.presence = *presence;
match field {
NetworkField::Presence => {}
NetworkField::Attribute { key, previous } => put_attribute(&mut network.attributes, key, previous.as_ref()),
NetworkField::Exports { previous } => network.exports = previous.clone(),
}
}
Prior::DocumentAttribute { key, previous } => put_attribute(&mut registry.attributes, key, previous.as_ref()),
Prior::PeerUser { peer, previous } => match previous {
Some(registration) => _ = registry.peer_users.insert(*peer, *registration),
None => _ = registry.peer_users.remove(peer),
},
}
}
}
fn whole_node(registry: &Registry, id: NodeId) -> Prior {
Prior::Node {
id,
live: registry.node_instances.get(&id).cloned(),
removed: registry.removed_nodes.get(&id).cloned(),
}
}
fn whole_network(registry: &Registry, id: NetworkId) -> Prior {
Prior::Network {
id,
live: registry.networks.get(&id).cloned(),
removed: registry.removed_networks.get(&id).cloned(),
}
}
/// One field of a live node; anything else, a write that lands on a tombstone or a placeholder, records the
/// whole entity.
fn node_field(registry: &Registry, id: NodeId, field: impl FnOnce(&Node) -> NodeField) -> Prior {
match registry.node_instances.get(&id) {
Some(node) => Prior::NodeField {
id,
presence: node.presence,
field: field(node),
},
None => whole_node(registry, id),
}
}
fn network_field(registry: &Registry, id: NetworkId, field: impl FnOnce(&Network) -> NetworkField) -> Prior {
match registry.networks.get(&id) {
Some(network) => Prior::NetworkField {
id,
presence: network.presence,
field: field(network),
},
None => whole_network(registry, id),
}
}
/// A write to one slot, or to the whole list when the slot doesn't exist yet, since writing past the end grows it.
fn input_field(node: &Node, index: u32, field: impl FnOnce(&InputSlot) -> NodeField) -> NodeField {
match node.inputs.get(index as usize) {
Some(slot) => field(slot),
None => NodeField::Inputs {
previous: node.inputs.clone(),
inputs_timestamp: node.inputs_timestamp,
},
}
}
fn put_whole<K: Hash + Eq + Copy, T: Clone>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, was_live: Option<&T>, was_removed: Option<&Tombstone<T>>) {
match was_live {
Some(content) => _ = live.insert(id, content.clone()),
None => _ = live.remove(&id),
}
match was_removed {
Some(mark) => _ = dead.insert(id, mark.clone()),
None => _ = dead.remove(&id),
}
}
fn put_attribute(attributes: &mut crate::Attributes, key: &str, previous: Option<&AttributeValue>) {
match previous {
Some(value) => _ = attributes.insert(key.to_string(), value.clone()),
None => _ = attributes.remove(key),
}
}
+8 -56
View File
@@ -1,13 +1,7 @@
use crate::{Attributes, Network, NetworkId, Node, NodeId, PeerId, ResourceEntry, ResourceId, ResourceStore, SourceKey, TimeStamp, UserId};
use crate::{Attributes, Network, NetworkId, Node, NodeId, PeerId, ResourceId, ResourceStore, SourceKey, TimeStamp, UserId};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// The live document: what exists and what it holds.
///
/// Every field is last-writer-wins on a timestamp, including whether an entity exists, so the registry
/// depends on the set of ops applied and not their order. A removed entity keeps a tombstone stamped with
/// the removal: an op stamped earlier is dropped in either arrival order, and one stamped later revives the
/// entity from it. The live maps hold only what exists.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Registry {
pub node_instances: HashMap<NodeId, Node>,
@@ -15,55 +9,13 @@ pub struct Registry {
/// Content-addressable resources (images, fonts, eventually proto-node declarations) referenced
/// by `ResourceId`. See [`ResourceStore`].
pub resources: ResourceStore,
/// Which person each device is, registered via `RegistryDelta::RegisterPeer` by a device's first
/// contribution and whenever its user changes. Lets undo and history authorship scope by person across
/// the peer ids one person accumulates.
pub peer_users: HashMap<PeerId, PeerRegistration>,
/// Append-only mapping from per-device `PeerId` to per-human `UserId`.
/// Registered by each device's first contribution via `RegistryDelta::RegisterPeer`.
pub peer_users: HashMap<PeerId, UserId>,
pub attributes: Attributes,
/// Tombstones of removed nodes, so an op on one is ordered against its removal whichever arrives first.
#[serde(default)]
pub removed_nodes: HashMap<NodeId, Tombstone<Node>>,
/// Tombstones of removed networks; see [`removed_nodes`](Self::removed_nodes).
#[serde(default)]
pub removed_networks: HashMap<NetworkId, Tombstone<Network>>,
/// Tombstones of removed resources; see [`removed_nodes`](Self::removed_nodes).
#[serde(default)]
pub removed_resources: HashMap<ResourceId, Tombstone<ResourceEntry>>,
}
/// A device's registration to a person, and when it was made.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PeerRegistration {
pub user: UserId,
pub at: TimeStamp,
}
/// A removed entity: its content, for reviving it, and when it was removed, for ordering later-arriving
/// ops against the removal.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Tombstone<T> {
pub content: T,
pub at: TimeStamp,
/// Nothing has added the entity yet, so it stays dead until an addition folds in; the content only holds
/// writes that arrived ahead of it. See [`Registry::removed_nodes`].
#[serde(default)]
pub placeholder: bool,
}
impl Registry {
/// The node under `id`, live or as it was when removed. For a reference to a node the runtime cannot
/// hold, which still needs the id the node had there.
#[cfg(any(feature = "conversion", test))]
pub(crate) fn node_or_removed(&self, id: NodeId) -> Option<&Node> {
self.node_instances.get(&id).or_else(|| self.removed_nodes.get(&id).map(|mark| &mark.content))
}
/// The network under `id`, live or as it was when removed.
#[cfg(any(feature = "conversion", test))]
pub(crate) fn network_or_removed(&self, id: NetworkId) -> Option<&Network> {
self.networks.get(&id).or_else(|| self.removed_networks.get(&id).map(|mark| &mark.content))
}
/// True if both registries agree on every value-bearing field, ignoring per-slot and
/// per-attribute timestamps. Mirrors `compute_deltas`'s value-only semantics, so unchanged
/// state at a stamped slot doesn't count as drift. `peer_users` is excluded: it isn't diffed by
@@ -133,10 +85,10 @@ impl Registry {
}
pub(crate) fn attributes_value_equal(a: &Attributes, b: &Attributes) -> bool {
if crate::attributes::live(a).count() != crate::attributes::live(b).count() {
if a.len() != b.len() {
return false;
}
crate::attributes::live(a).all(|(key, value)| b.get(key).is_some_and(|other| !other.deleted && value.value == other.value))
a.iter().all(|(key, value)| b.get(key).is_some_and(|other| value.value == other.value))
}
/// Value-level resource comparison: same resolved hashes and same source chains (keyed by
@@ -148,8 +100,8 @@ pub(crate) fn resources_value_equal(a: &ResourceStore, b: &ResourceStore) -> boo
a.iter().all(|(id, entry)| {
b.get(id).is_some_and(|other| {
entry.hash == other.hash
&& entry.live_sources().count() == other.live_sources().count()
&& entry.live_sources().all(|(key, value)| other.source(key).is_some_and(|other_value| value.source == other_value.source))
&& entry.sources.len() == other.sources.len()
&& entry.sources.iter().all(|(key, value)| other.source(key).is_some_and(|other_value| value.source == other_value.source))
})
})
}
+69 -136
View File
@@ -1,4 +1,4 @@
use crate::{PeerId, TimeStamp, Value, from_value, to_value};
use crate::{PeerId, TimeStamp};
use graphene_resource::{ResourceHash, ResourceId};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
@@ -11,28 +11,13 @@ pub struct SourceKey {
pub peer: PeerId,
}
/// One entry in a resource's source chain. The `source` body is type-erased (`Value`)
/// One entry in a resource's source chain. The `source` body is type-erased (`serde_json::Value`)
/// so the on-disk `DataSource` shape can evolve through migrations without the storage layer
/// committing to a Rust enum; `timestamp` drives LWW on re-setting this same entry.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceValue {
pub source: Value,
pub source: serde_json::Value,
pub timestamp: TimeStamp,
/// A removed source stays as a stamped tombstone, so an older addition loses in either arrival order;
/// readers see it as absent.
#[serde(default)]
pub deleted: bool,
}
impl SourceValue {
/// The tombstone of a source removed at `timestamp`.
pub fn deleted(timestamp: TimeStamp) -> Self {
Self {
source: Value::None,
timestamp,
deleted: true,
}
}
}
/// A single content-addressable resource: an ordered, conflict-mergeable chain of fallback sources
@@ -41,13 +26,8 @@ impl SourceValue {
/// resource agree by construction, since the hash is content-derived).
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub struct ResourceEntry {
/// The latest addition or write; see [`Node::presence`](crate::Node).
pub(crate) presence: TimeStamp,
/// Fallback chain kept sorted by `SourceKey`, so iteration yields highest-priority first.
pub sources: Vec<(SourceKey, SourceValue)>,
/// When `sources` was last written whole, by an addition of the entry. A key the chain does not hold is
/// deleted as of then, as with [`Attributes`](crate::Attributes).
pub sources_timestamp: TimeStamp,
pub hash: Option<ResourceHash>,
pub hash_timestamp: TimeStamp,
}
@@ -59,22 +39,12 @@ impl<'de> Deserialize<'de> for ResourceEntry {
// collapse any duplicate keys, keeping the higher-timestamp value (LWW).
#[derive(Deserialize)]
struct Raw {
#[serde(default)]
presence: TimeStamp,
sources: Vec<(SourceKey, SourceValue)>,
#[serde(default)]
sources_timestamp: TimeStamp,
hash: Option<ResourceHash>,
hash_timestamp: TimeStamp,
}
let Raw {
presence,
mut sources,
sources_timestamp,
hash,
hash_timestamp,
} = Raw::deserialize(deserializer)?;
let Raw { mut sources, hash, hash_timestamp } = Raw::deserialize(deserializer)?;
sources.sort_by_key(|(a, _)| *a);
sources.dedup_by(|(later_key, later_value), (kept_key, kept_value)| {
// `dedup_by` keeps the first of each run; sorting is stable, so resolve duplicates by LWW.
@@ -87,13 +57,7 @@ impl<'de> Deserialize<'de> for ResourceEntry {
true
});
Ok(Self {
presence,
sources,
sources_timestamp,
hash,
hash_timestamp,
})
Ok(Self { sources, hash, hash_timestamp })
}
}
@@ -102,107 +66,82 @@ impl ResourceEntry {
/// source entry and the resolved hash carry `timestamp` so later LWW writes order against it.
/// The bytes themselves are persisted separately by the caller's byte store.
pub fn embedded(hash: ResourceHash, peer: PeerId, timestamp: TimeStamp) -> Self {
let embedded = to_value(&graphene_resource::DataSource::Embedded).expect("DataSource::Embedded serializes");
let embedded = serde_json::to_value(graphene_resource::DataSource::Embedded).expect("DataSource::Embedded serializes");
let priority = Priority::new(0.).expect("0. is finite");
let sources = vec![(
SourceKey { priority, peer },
SourceValue {
source: embedded,
timestamp,
deleted: false,
},
)];
let sources = vec![(SourceKey { priority, peer }, SourceValue { source: embedded, timestamp })];
Self {
presence: timestamp,
sources,
sources_timestamp: timestamp,
hash: Some(hash),
hash_timestamp: timestamp,
}
}
/// The live source stored under `key`, if any; a tombstone is absent.
/// The source body and timestamp stored under `key`, if any.
pub fn source(&self, key: &SourceKey) -> Option<&SourceValue> {
self.find(key).ok().map(|index| &self.sources[index].1).filter(|value| !value.deleted)
}
/// The live sources in precedence order, tombstones skipped.
pub(crate) fn live_sources(&self) -> impl Iterator<Item = (&SourceKey, &SourceValue)> {
self.sources.iter().filter(|(_, value)| !value.deleted).map(|(key, value)| (key, value))
}
fn find(&self, key: &SourceKey) -> Result<usize, usize> {
self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key))
}
/// The stamp that decides a write to `key`: its entry's, tombstone included, or the chain's floor.
fn decided(&self, key: &SourceKey) -> TimeStamp {
self.find(key).map_or(self.sources_timestamp, |index| self.sources[index].1.timestamp)
}
fn put(&mut self, key: SourceKey, value: SourceValue) {
match self.find(&key) {
Ok(index) => self.sources[index].1 = value,
Err(index) => self.sources.insert(index, (key, value)),
}
}
/// Writes the chain whole at `at`: the floor deletes every other key without a tombstone per key.
pub(crate) fn stamp_sources(&mut self, at: TimeStamp) {
self.sources.retain(|(_, value)| !value.deleted);
self.sources.iter_mut().for_each(|(_, value)| value.timestamp = at);
self.sources_timestamp = at;
}
/// Folds another chain in key by key, the way attribute maps merge: a key only one chain holds is
/// dead when the other chain's floor is newer than it, and the newer entry wins where both hold a key.
pub(crate) fn merge_sources(&mut self, other: Vec<(SourceKey, SourceValue)>, other_floor: TimeStamp) {
self.sources.retain(|(_, value)| value.timestamp >= other_floor);
for (key, value) in other {
match self.find(&key) {
Ok(index) if value.timestamp > self.sources[index].1.timestamp => self.sources[index].1 = value,
Err(index) if value.timestamp >= self.sources_timestamp => self.sources.insert(index, (key, value)),
_ => {}
}
}
self.sources_timestamp = self.sources_timestamp.max(other_floor);
self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)).ok().map(|index| &self.sources[index].1)
}
/// Insert or LWW-overwrite the entry at `key`. A re-set at an existing key wins only if `value`'s
/// timestamp is strictly newer; a fresh key is inserted in sorted position.
pub fn set_source(&mut self, key: SourceKey, value: SourceValue) {
if value.timestamp > self.decided(&key) {
self.put(key, value);
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(&key)) {
Ok(index) => {
if value.timestamp > self.sources[index].1.timestamp {
self.sources[index].1 = value;
}
}
Err(index) => self.sources.insert(index, (key, value)),
}
}
/// Like [`set_source`](Self::set_source) but assigns unconditionally, for building an entry.
/// Like [`set_source`](Self::set_source) but assigns unconditionally (silent-zone rewind), where the
/// precomputed reverse/forward value is authoritative even if its timestamp ties what it replaces.
pub fn force_set_source(&mut self, key: SourceKey, value: SourceValue) {
self.put(key, value);
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(&key)) {
Ok(index) => self.sources[index].1 = value,
Err(index) => self.sources.insert(index, (key, value)),
}
}
/// Remove the source at `key` if what decides it is strictly older than `timestamp` (LWW), leaving a
/// tombstone. Returns whether the removal landed.
/// Remove the entry at `key` if its timestamp is strictly older than `timestamp` (LWW). Returns
/// whether anything was removed.
pub fn remove_source(&mut self, key: &SourceKey, timestamp: TimeStamp) -> bool {
if timestamp <= self.decided(key) {
return false;
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)) {
Ok(index) if timestamp > self.sources[index].1.timestamp => {
self.sources.remove(index);
true
}
_ => false,
}
}
/// Like [`remove_source`](Self::remove_source) but removes unconditionally (silent-zone rewind).
pub fn force_remove_source(&mut self, key: &SourceKey) -> bool {
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)) {
Ok(index) => {
self.sources.remove(index);
true
}
_ => false,
}
self.put(*key, SourceValue::deleted(timestamp));
true
}
/// True if the chain already carries a `DataSource::Embedded` source. Decodes each source body into
/// `DataSource` so a shape change in the serialized form can't slip an embedded source past detection.
pub fn has_embedded_source(&self) -> bool {
self.live_sources()
.any(|(_, value)| matches!(from_value::<graphene_resource::DataSource>(&value.source), Ok(graphene_resource::DataSource::Embedded)))
self.sources.iter().any(|(_, value)| {
matches!(
serde_json::from_value::<graphene_resource::DataSource>(value.source.clone()),
Ok(graphene_resource::DataSource::Embedded)
)
})
}
/// A `SourceKey` ordered strictly ahead of every current source, so an inserted entry becomes the
/// highest-precedence fallback.
pub fn highest_precedence_key(&self, peer: PeerId) -> SourceKey {
let min_priority = self.live_sources().next().map(|(key, _)| key.priority.value()).unwrap_or(0.);
let min_priority = self.sources.first().map(|(key, _)| key.priority.value()).unwrap_or(0.);
SourceKey {
priority: Priority::new(min_priority - 1.).expect("finite priority minus one is finite"),
peer,
@@ -286,15 +225,15 @@ mod tests {
}
/// Deserialization routes through `Priority::new`, so a non-finite value on disk is rejected rather
/// than silently producing an unsound map key. Postcard (the storage format) can carry a
/// than silently producing an unsound map key. MessagePack (the storage format) can carry a
/// non-finite `f64`, unlike JSON, so this guards the real round-trip path.
#[test]
fn priority_deserialize_validates_finiteness() {
let finite = postcard::to_stdvec(&3.5_f64).unwrap();
assert!(postcard::from_bytes::<Priority>(&finite).is_ok());
let finite = rmp_serde::to_vec(&3.5_f64).unwrap();
assert!(rmp_serde::from_slice::<Priority>(&finite).is_ok());
let non_finite = postcard::to_stdvec(&f64::INFINITY).unwrap();
assert!(postcard::from_bytes::<Priority>(&non_finite).is_err(), "a non-finite priority on disk must be rejected");
let non_finite = rmp_serde::to_vec(&f64::INFINITY).unwrap();
assert!(rmp_serde::from_slice::<Priority>(&non_finite).is_err(), "a non-finite priority on disk must be rejected");
}
/// `ResourceEntry`'s accessors rely on `sources` being sorted by `SourceKey`. Deserializing an
@@ -309,23 +248,20 @@ mod tests {
peer: PeerId(1),
},
SourceValue {
source: Value::Float(priority),
source: serde_json::json!(priority),
timestamp: TimeStamp::ORIGIN,
deleted: false,
},
)
};
// Build a deliberately unsorted chain as a literal (bypassing the sorted-insert API), then round-trip it through `Value`.
let unsorted = ResourceEntry {
presence: TimeStamp::ORIGIN,
sources_timestamp: TimeStamp::ORIGIN,
sources: vec![source(2.), source(0.), source(1.)],
hash: None,
hash_timestamp: TimeStamp::ORIGIN,
};
// Serialize a deliberately unsorted chain through the raw shape, then deserialize as `ResourceEntry`.
let unsorted = serde_json::json!({
"sources": [source(2.), source(0.), source(1.)],
"hash": null,
"hash_timestamp": TimeStamp::ORIGIN,
});
let entry: ResourceEntry = from_value(&to_value(&unsorted).expect("serialize")).expect("deserialize");
let entry: ResourceEntry = serde_json::from_value(unsorted).expect("deserialize");
let priorities: Vec<f64> = entry.sources.iter().map(|(key, _)| key.priority.value()).collect();
assert_eq!(priorities, vec![0., 1., 2.], "sources must be sorted by SourceKey after deserialization");
}
@@ -342,23 +278,20 @@ mod tests {
(
key,
SourceValue {
source: Value::Str(body.into()),
source: serde_json::json!(body),
timestamp: TimeStamp { counter, peer: PeerId(1) },
deleted: false,
},
)
};
let with_duplicates = ResourceEntry {
presence: TimeStamp::ORIGIN,
sources_timestamp: TimeStamp::ORIGIN,
sources: vec![entry(5, "newer"), entry(1, "older")],
hash: None,
hash_timestamp: TimeStamp::ORIGIN,
};
let with_duplicates = serde_json::json!({
"sources": [entry(5, "newer"), entry(1, "older")],
"hash": null,
"hash_timestamp": TimeStamp::ORIGIN,
});
let resource: ResourceEntry = from_value(&to_value(&with_duplicates).expect("serialize")).expect("deserialize");
let resource: ResourceEntry = serde_json::from_value(with_duplicates).expect("deserialize");
assert_eq!(resource.sources.len(), 1, "duplicate keys must collapse to one entry");
assert_eq!(resource.sources[0].1.source, Value::Str("newer".into()), "the higher-timestamp value must win");
assert_eq!(resource.sources[0].1.source, serde_json::json!("newer"), "the higher-timestamp value must win");
}
}
+152 -338
View File
@@ -2,9 +2,7 @@
use crate::NodeMetadataSource;
#[cfg(any(feature = "conversion", test))]
use crate::from_runtime;
use crate::{
ApplyMode, Delta, Document, History, Implementation, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, UserId, Value, to_value,
};
use crate::{ApplyMode, Delta, Document, History, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, UserId};
use graphene_resource::{ResourceHash, ResourceId};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
@@ -29,17 +27,22 @@ impl Session {
Self::with_peer(PeerId(core_types::uuid::generate_uuid()))
}
/// A session for `peer` standing for itself as a person. For tests and tools without a stored identity;
/// a working copy wants [`with_identity`](Self::with_identity).
/// Construct a session bound to a specific `PeerId`. Used by tests; production code wants
/// `Session::new`.
pub fn with_peer(peer: PeerId) -> Self {
Self::with_identity(peer, UserId(peer.0))
}
/// A session for device `peer` used by person `user`. The user is what the peer's registration records,
/// and what undo and history authorship scope by.
pub fn with_identity(peer: PeerId, user: UserId) -> Self {
Self {
document: Document::empty(peer, user),
document: Document {
working_registry: Registry::default(),
retired_snapshot: Registry::default(),
history: History::new(),
hot_log: Vec::new(),
head: None,
redo_stack: Vec::new(),
clock: LamportClock::new(peer),
peer,
last_broadcast_rev: None,
next_node_counter: 0,
},
remote_tips: HashMap::new(),
}
}
@@ -48,22 +51,6 @@ impl Session {
self.document.peer
}
pub fn user(&self) -> UserId {
self.document.user
}
/// The person a peer is registered to, if its registration has landed here.
pub fn user_of(&self, peer: PeerId) -> Option<UserId> {
let registered = || self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user);
(peer == self.document.peer).then_some(self.document.user).or_else(registered)
}
/// Whether `peer` is this person: this device, or another registered to the same user. Undo in a
/// session scopes by this, so a fresh copy of a document still undoes what its user did from another.
pub fn is_mine(&self, peer: PeerId) -> bool {
self.user_of(peer) == Some(self.document.user)
}
pub fn registry(&self) -> &Registry {
&self.document.working_registry
}
@@ -77,7 +64,8 @@ impl Session {
/// Diff the current registry against a fresh conversion of `network`, then commit each emitted
/// op as its own `Delta` on the local chain. One `clock.tick()` per op (strictly causal within
/// a commit). Returns the new `Rev`s in commit order (empty if nothing changed) plus the
/// conversion, whose extracted declarations the caller persists and caches.
/// proto-node declaration bytes the conversion extracted, keyed by content hash, for the caller
/// to persist into its byte store (`document-graph-storage` itself is byte-unaware).
///
/// Stages the diff as hot ops rather than retired deltas: each op is applied to the registry and
/// pushed onto the hot log. The caller persists the returned hot frames and then calls `retire`
@@ -88,11 +76,11 @@ impl Session {
network: &graph_craft::document::NodeNetwork,
metadata: &M,
resources: &graphene_resource::ResourceRegistry,
) -> Result<(Vec<HotOp>, from_runtime::RuntimeConversion), CommitError> {
) -> Result<(Vec<HotOp>, from_runtime::DeclarationBytes), CommitError> {
let conversion = Registry::convert_from_runtime(network, metadata, resources, self.document.peer)?;
let ops = crate::delta::compute_deltas(&self.document.working_registry, &conversion.registry);
let hot_ops = self.stage_ops(ops)?;
Ok((hot_ops, conversion))
Ok((hot_ops, conversion.declaration_bytes))
}
/// Resolve each runtime `network_path` to its stable [`NetworkId`] for this document's peer, so the
@@ -117,7 +105,7 @@ impl Session {
/// Used on a throwaway session clone at export time so the exported registry and history agree;
/// callers must guarantee the bytes are available in the export's resource store.
pub fn embed_resource_sources(&mut self, ids: impl IntoIterator<Item = ResourceId>) -> Result<Vec<Rev>, CrdtError> {
let embedded = to_value(&graphene_resource::DataSource::Embedded).expect("DataSource::Embedded serializes");
let embedded = serde_json::to_value(graphene_resource::DataSource::Embedded).expect("DataSource::Embedded serializes");
let mut ops = Vec::new();
for id in ids {
@@ -153,45 +141,25 @@ impl Session {
///
/// 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, since registration rides a real edit.
pub(crate) fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
// A batch is staged whole or not at all: a refused op takes back the ones before it, which reached nothing yet.
/// before any of its edits. A no-op batch doesn't register — registration rides a real edit.
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() {
return Ok(Vec::new());
}
let (peer, user) = (self.document.peer, self.document.user);
if self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user) != Some(user) {
pending.insert(0, RegistryDelta::RegisterPeer { peer, user });
if !self.document.working_registry.peer_users.contains_key(&self.document.peer) {
let user = UserId(self.document.peer.0);
pending.insert(0, RegistryDelta::RegisterPeer { peer: self.document.peer, user });
}
// Reusing a sequence would let retirement marks drop the new op, so a batch that would run past the end is refused whole.
if self.document.last_hot_sequence.0.checked_add(pending.len() as u64).is_none() {
return Err(CrdtError::SequencesExhausted);
}
let sequence_before = self.document.last_hot_sequence;
let mut staged = Vec::with_capacity(pending.len());
for op in pending {
let sequence = HotSequence(self.document.last_hot_sequence.0 + 1);
let hot_op = HotOp {
op,
timestamp: self.document.clock.tick(),
sequence,
};
if let Err(error) = self.document.apply_hot_op(hot_op.clone(), ApplyMode::Live) {
// The run continues where it was, so no sequence goes unused.
self.document.last_hot_sequence = sequence_before;
if !staged.is_empty() {
let taken: HashSet<HotOpId> = staged.iter().map(HotOp::id).collect();
self.document.hot_log.retain(|hot_op| !taken.contains(&hot_op.id()));
self.document.resync_hot_timestamps();
self.document.rebuild_working();
}
return Err(error);
}
self.document.last_hot_sequence = sequence;
self.document.apply_hot_op(hot_op.clone())?;
staged.push(hot_op);
}
Ok(staged)
@@ -199,26 +167,19 @@ impl Session {
/// Wrap each op as a `Delta`, apply it, and chain it onto the local history. One tick per op.
///
/// Operates on the *retired snapshot*: each `reverse` is captured from it and the forward op applied to it, so
/// the reverse holds the true pre-op state rather than the hot-polluted working state. The
/// Operates on the *retired snapshot*: reverses are computed against and forward ops applied to it,
/// so each `reverse` captures the true pre-op value rather than the hot-polluted working state. The
/// working registry already reflects these ops (they were staged as hot ops before retirement, or
/// equal the snapshot when there are none), so it is left untouched.
///
/// `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.
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, authored_at) in ops {
for op 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.
@@ -226,10 +187,10 @@ impl Session {
self.document.redo_stack.clear();
}
let reverse = crate::prior::capture(self.document.registry_ref(target), &op);
let timestamp = authored_at.unwrap_or_else(|| self.document.clock.tick());
let reverse = self.document.compute_reverse_delta(target, &op)?;
let timestamp = self.document.clock.tick();
let parent = self.document.head;
let author = timestamp.peer;
let author = self.document.peer;
let delta = Delta::new(parent, author, timestamp, op, reverse);
let rev = delta.id;
@@ -253,7 +214,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, user: UserId, registry: Registry, history: Vec<Delta>, head: Option<Rev>, redo_stack: Vec<Rev>, next_node_counter: 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);
@@ -266,11 +227,13 @@ impl Session {
retired_snapshot: registry.clone(),
working_registry: registry,
history: History::from_ordered(history),
hot_log: Vec::new(),
head,
redo_stack,
clock,
peer,
last_broadcast_rev: None,
next_node_counter,
..Document::empty(peer, user)
},
remote_tips: HashMap::new(),
}
@@ -278,8 +241,8 @@ impl Session {
/// Rebuild the registry from scratch by applying every delta in causal order.
/// `deltas` must be in causal order (every parent before its children).
pub fn replay_from_history(peer: PeerId, user: UserId, deltas: impl IntoIterator<Item = Delta>, next_node_counter: u64) -> Result<Self, CrdtError> {
let mut session = Self::with_identity(peer, user);
pub fn replay_from_history(peer: PeerId, deltas: impl IntoIterator<Item = Delta>, next_node_counter: u64) -> Result<Self, CrdtError> {
let mut session = Self::with_peer(peer);
session.document.next_node_counter = next_node_counter;
for delta in deltas {
@@ -294,21 +257,9 @@ impl Session {
Ok(session)
}
/// 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.
/// Apply a hot op without going through the broadcast stream.
pub fn apply_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
self.document.replay_hot_op(hot_op)
}
/// Which hot ops are done with, for a peer catching up and for persisting. See [`SettledHotOps`].
pub fn settled_marks(&self) -> &SettledHotOps {
&self.document.settled
}
/// Take on a peer's marks, or this peer's persisted ones: whatever they cover that the hot log still holds is
/// dropped, and the working registry re-derived without it.
pub fn absorb_settled_marks(&mut self, remote: &SettledHotOps) {
self.document.absorb_settled(remote);
self.document.apply_hot_op(hot_op)
}
/// Replay a persisted hot op. Idempotent on structural ops, suitable for crash recovery
@@ -317,52 +268,57 @@ impl Session {
self.document.replay_hot_op(hot_op)
}
/// The retired snapshot as history alone produces it, independent of arrival order and the hot log.
/// Folded 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.
pub fn snapshot_from_history(&self) -> Result<Registry, CrdtError> {
// Every op lands the same whatever order it arrives in, so applying each once is the fold.
let reachable = self.document.history.ancestors(self.document.head);
let mut scratch = Document::empty(self.document.peer, self.document.user);
for delta in self.document.history.iter().filter(|delta| reachable.contains(&delta.id)) {
scratch.apply_op_with(RegistryTarget::Working, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
/// Integrate `incoming` retired deltas from another branch and emit a [`RegistryDelta::Merge`]
/// joining the resulting tips, returning the new merge `Rev` (or `None` if `incoming` adds nothing).
/// Applies each incoming op to the registry, then hands the set to [`History::merge`]. Incoming
/// deltas must arrive in causal order.
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) -> Result<Option<Rev>, CrdtError> {
let mut absorbed: Vec<Delta> = Vec::new();
for delta in incoming {
if self.document.history.contains(delta.id) {
continue;
}
self.document.apply_op_idempotent(delta.kind.clone(), delta.timestamp)?;
absorbed.push(delta);
}
Ok(scratch.working_registry)
if absorbed.is_empty() {
return Ok(None);
}
self.document.history.merge(absorbed);
let tips = self.document.history.tips();
let timestamp = self.document.clock.tick();
let merge = Delta::merge(tips, self.document.peer, timestamp);
let merge_rev = merge.id;
// The merge's parents are the current tips, so it sorts last: `push` preserves the canonical
// order without re-sorting the whole history.
self.document.history.push(merge);
self.document.head = Some(merge_rev);
// Merge runs with an empty hot log; keep the retired snapshot in step with the working registry.
self.document.retired_snapshot = self.document.working_registry.clone();
Ok(Some(merge_rev))
}
pub fn history_len(&self) -> usize {
self.document.history.len()
}
/// The hot ops stamped at or before `up_to`, which [`retire`](Self::retire) drains. Sent with the deltas,
/// since a lagging op can arrive below the cutoff 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()
}
/// Promote the given hot ops into retired deltas, in hot-log order, each keeping the timestamp it was
/// authored at. Markers commit nothing. Ops not in the log are ignored.
/// 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`.
///
/// One retired delta per hot op.
pub fn retire_hot_ops(&mut self, ids: &[HotOpId]) -> Result<Vec<Rev>, CrdtError> {
let wanted: HashSet<HotOpId> = ids.iter().copied().collect();
let (drained, kept): (Vec<HotOp>, Vec<HotOp>) = self.document.hot_log.drain(..).partition(|hot_op| wanted.contains(&hot_op.id()));
self.document.hot_log = kept;
self.document.resync_hot_timestamps();
self.document.settled.extend(drained.iter().map(HotOp::id));
let ops = drained
.into_iter()
.filter(|hot_op| !matches!(hot_op.op, RegistryDelta::EndTransaction))
.map(|hot_op| (hot_op.op, Some(hot_op.timestamp)));
self.commit_ops_authored_at(ops, true)
}
/// Promote every hot op stamped at or before `up_to`, whatever its author.
/// Today: one retired delta per hot op. Coarsening is a future step.
pub fn retire(&mut self, up_to: TimeStamp) -> Result<Vec<Rev>, CrdtError> {
let ids = self.hot_ops_up_to(up_to);
self.retire_hot_ops(&ids)
let mut drained = Vec::new();
let mut remaining = Vec::with_capacity(self.document.hot_log.len());
for hot_op in self.document.hot_log.drain(..) {
if hot_op.timestamp <= up_to {
drained.push(hot_op);
} else {
remaining.push(hot_op);
}
}
self.document.hot_log = remaining;
self.commit_ops(drained.into_iter().map(|hot_op| hot_op.op), true)
}
/// Mark a retired delta as the end of a user interaction, so the undo cursor treats it as a checkpoint.
/// Called once per interaction by the editor-facing commit path (not by resource/internal commits).
pub fn mark_interaction_end(&mut self, rev: Rev) {
@@ -373,36 +329,38 @@ impl Session {
/// Low-level: set a local annotation attribute (e.g. a commit message) on a retired delta in place.
/// Excluded from the delta's content-addressed `Rev`, so identity is unchanged. Returns whether the
/// delta was found. The `Gdd` layer re-persists the affected history frame after calling this.
pub fn annotate_delta(&mut self, rev: Rev, key: &str, value: Value) -> bool {
pub fn annotate_delta(&mut self, rev: Rev, key: &str, value: serde_json::Value) -> bool {
let timestamp = self.document.clock.tick();
self.document.history.annotate(rev, key, value, timestamp)
}
/// Whether the interaction at `head` can be undone in the silent zone: it is this user's own, holds no merge, and
/// nothing in it was published, since rewinding a step peers hold would diverge from them. The document's first
/// interaction is not undoable, as opening a document starts with an empty undo history.
/// Whether there is a retired commit at `head` that can be undone in the silent zone (a commit
/// after `last_broadcast_rev`). `head == 0` is the empty history; published commits aren't
/// silently undoable (that needs a forward reverse-delta op, deferred until transport lands).
///
/// The earliest interaction (the document's loaded/created base) is *not* undoable: undoing it would
/// rewind into the pre-base state, which legacy never offers (opening a document gives an empty undo
/// history). We detect "head is on the earliest interaction" by walking `head`'s interaction back along
/// first-parents and checking whether it bottoms out at the root with no earlier interaction boundary to
/// land on. If so, there is nothing before this interaction to undo to, so undo is disabled.
pub fn can_undo(&self) -> bool {
self.document.head.is_some_and(|head| self.interaction_start_parent(head, true).is_some())
let Some(head) = self.document.head else { return false };
if self.document.last_broadcast_rev == Some(head) {
return false;
}
self.interaction_start_parent(head).is_some()
}
/// The rev the cursor rests on once the interaction ending at `end` is undone: the parent where the previous
/// interaction ended, a merge, or another user's delta begins. `None` when `end` is a merge, the interaction starts
/// at the root, or, for a `silent` undo, it is not this user's or holds a published delta.
fn interaction_start_parent(&self, end: Rev, silent: bool) -> Option<Rev> {
let history = &self.document.history;
let mut current = history.get(end)?;
let user = self.user_of(current.author);
if matches!(current.kind, RegistryDelta::Merge { .. }) || (silent && user != Some(self.document.user)) {
return None;
}
let boundary = |delta: &Delta| delta.is_interaction_end() || matches!(delta.kind, RegistryDelta::Merge { .. }) || self.user_of(delta.author) != user;
/// Walk the interaction containing `rev` back along first-parents to its first delta, returning the
/// rev the cursor would rest on after undoing this interaction, or `None` if that is the root (the
/// earliest interaction, which is not undoable). Mirrors the boundary condition in [`undo`](Self::undo):
/// stop when the parent is an `interaction_end` boundary or the root.
fn interaction_start_parent(&self, rev: Rev) -> Option<Rev> {
let mut current = rev;
loop {
if silent && self.document.last_broadcast_rev == Some(current.id) {
return None;
}
let parent = history.get(current.parent?)?;
if boundary(parent) {
return Some(parent.id);
let parent = self.document.history.get(current)?.parent?;
if self.document.history.get(parent).is_some_and(|d| d.is_interaction_end()) {
return Some(parent);
}
current = parent;
}
@@ -412,22 +370,37 @@ impl Session {
!self.document.redo_stack.is_empty()
}
/// Silent-zone undo of one interaction: put back what its deltas overwrote, newest first, until `head` rests where it
/// began (see [`can_undo`](Self::can_undo)). Its `head` rev goes on the redo stack; the DAG is not rewritten.
/// 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.
pub fn undo(&mut self) -> Result<Rev, CrdtError> {
if !self.can_undo() {
return Err(CrdtError::NothingToUndo);
}
let checkpoint = self.document.head.ok_or(CrdtError::NothingToUndo)?;
let base = self.interaction_start_parent(checkpoint, true).ok_or(CrdtError::NothingToUndo)?;
while let Some(rev) = self.document.head.filter(|&rev| rev != base) {
// Revert this interaction's last delta, then keep going back until `head` rests on the previous
// interaction's boundary (its `interaction_end` delta) or the root.
loop {
let rev = self.document.head.ok_or(CrdtError::NothingToUndo)?;
let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?.clone();
self.document.revert_delta(&delta);
self.document.head = delta.parent;
let parent = delta.parent;
self.document.revert_delta(RegistryTarget::Working, delta)?;
self.document.head = parent;
match parent {
None => break,
Some(parent) if self.document.history.get(parent).is_some_and(|d| d.is_interaction_end()) => break,
Some(_) => {}
}
}
// With ops hot, working is the rewound snapshot plus them.
if !self.document.hot_log.is_empty() {
self.document.rebuild_working();
}
// Undo runs with an empty hot log, so keep the retired snapshot in lockstep with the rewound
// working registry (the next interaction's reverses are computed against it).
self.document.retired_snapshot = self.document.working_registry.clone();
self.document.redo_stack.push(checkpoint);
Ok(checkpoint)
}
@@ -447,28 +420,23 @@ impl Session {
forward.push(delta);
}
// Undo left the snapshot exactly at the fold up to `head`, so applying the deltas as retirement did folds
// them in again, a newer write merged in before them still winning over theirs.
let hot = !self.document.hot_log.is_empty();
// Force-apply so each forward value wins the LWW tie against the reverse that undo force-applied
// at the same timestamp. Symmetric with `revert_delta`.
for delta in forward.into_iter().rev() {
self.document.apply_op_with(RegistryTarget::Snapshot, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
if !hot {
self.document.apply_op_with(RegistryTarget::Working, delta.kind, delta.timestamp, ApplyMode::Idempotent)?;
}
}
if hot {
self.document.rebuild_working();
self.document.force_apply_op(delta.kind.clone(), delta.timestamp)?;
}
self.document.head = Some(checkpoint);
// Redo runs with an empty hot log; keep the retired snapshot in lockstep with the working registry.
self.document.retired_snapshot = self.document.working_registry.clone();
Ok(checkpoint)
}
/// Build a synthetic linear history whose replay reproduces `registry`. Each op gets a
/// freshly-ticked clock timestamp and chains to the previous op's `Rev`.
pub fn bootstrap_from_registry(peer: PeerId, user: UserId, registry: Registry) -> Result<Self, CrdtError> {
pub fn bootstrap_from_registry(peer: PeerId, registry: Registry) -> Result<Self, CrdtError> {
let ops = crate::delta::compute_deltas(&Registry::default(), &registry);
let mut session = Self::with_identity(peer, user);
let mut session = Self::with_peer(peer);
session.commit_ops(ops, false)?;
// No hot ops on this path, so the working registry must mirror the freshly-built snapshot.
session.document.working_registry = session.document.retired_snapshot.clone();
@@ -499,42 +467,16 @@ impl Session {
/// bytes. Walks current resources plus each delta's `AddResource`/`RemoveResource` snapshot.
pub fn all_referenced_resource_hashes(&self) -> HashSet<ResourceHash> {
let mut hashes: HashSet<ResourceHash> = self.document.working_registry.resources.values().filter_map(|entry| entry.hash).collect();
hashes.extend(self.document.history.resource_hashes());
hashes
}
/// Every proto-node declaration resource referenced by the current registry or anywhere in history,
/// with its content hash, or `None` where the hash never resolved.
pub fn all_declaration_resources(&self) -> HashMap<ResourceId, Option<ResourceHash>> {
let registry = &self.document.working_registry;
let mut hashes: HashMap<ResourceId, ResourceHash> = registry.resources.iter().filter_map(|(id, entry)| Some((*id, entry.hash?))).collect();
for delta in self.document.history.iter() {
match &delta.kind {
RegistryDelta::AddResource { id, entry } => hashes.extend(entry.hash.map(|hash| (*id, hash))),
RegistryDelta::RemoveResource { id, snapshot } => hashes.extend(snapshot.hash.map(|hash| (*id, hash))),
RegistryDelta::SetResourceHash { id, hash: Some(hash) } => {
hashes.insert(*id, *hash);
}
RegistryDelta::AddResource { entry, .. } => hashes.extend(entry.hash),
RegistryDelta::RemoveResource { snapshot, .. } => hashes.extend(snapshot.hash),
_ => {}
}
}
let current_nodes = registry.node_instances.values();
let historic_nodes = self.document.history.iter().filter_map(|delta| match &delta.kind {
RegistryDelta::AddNode { node, .. } => Some(node),
RegistryDelta::RemoveNode { snapshot, .. } => Some(snapshot),
_ => None,
});
current_nodes
.chain(historic_nodes)
.filter_map(|node| match node.implementation() {
Implementation::ProtoNode(id) => Some(*id),
Implementation::Network(_) => None,
})
.map(|id| (id, hashes.get(&id).copied()))
.collect()
hashes
}
pub fn hot_log(&self) -> &[HotOp] {
@@ -565,7 +507,7 @@ impl Session {
}
/// Test-only: commit a single op as a retired delta on the local chain, returning the result so a
/// test can observe a failure (e.g. `NotFoundInHistory`).
/// test can observe a resurrection failure (e.g. `NotFoundInHistory`).
#[cfg(test)]
pub(crate) fn commit_op_for_test(&mut self, op: RegistryDelta) -> Result<(), CrdtError> {
self.commit_ops(std::iter::once(op), false).map(|_| ())
@@ -578,29 +520,6 @@ impl Session {
pub fn next_node_counter(&self) -> u64 {
self.document.next_node_counter
}
/// The sequence of the last hot op this peer authored, which is how many it has. Carried across a reload, so no
/// sequence is spent twice.
pub fn last_hot_sequence(&self) -> HotSequence {
self.document.last_hot_sequence
}
/// The Lamport counter, persisted so a reopen never mints a stamp it already spent, even one no op in history or
/// the hot log carries any more.
pub fn clock_counter(&self) -> u64 {
self.document.clock.counter
}
/// Continue the Lamport clock after a load. Raises only, like observing an op.
pub fn restore_clock(&mut self, counter: u64) {
self.document.clock.counter = self.document.clock.counter.max(counter);
}
/// 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.last_hot_sequence = self.document.last_hot_sequence.max(sequence);
}
}
/// Errors from `Session::commit_from_runtime`.
@@ -626,122 +545,10 @@ impl Default for Session {
pub struct HotOp {
pub op: RegistryDelta,
pub timestamp: TimeStamp,
/// Position in its author's run. See [`HotSequence`].
pub sequence: HotSequence,
}
impl HotOp {
/// Identifies the op in the settled marks, which track a contiguous prefix per author.
pub fn id(&self) -> HotOpId {
HotOpId {
peer: self.timestamp.peer,
sequence: self.sequence,
}
}
}
/// 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 position after this one, for adjacency. Saturates: a run ending at the last position has no successor.
pub fn next(self) -> Self {
Self(self.0.saturating_add(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: HotSequence,
}
/// Which hot ops are retired into history: `settled_up_to` is each author's gap-free prefix, and `settled_beyond`
/// the settled ops past it. Gaps exist only while ops are in flight, so an author collapses to its prefix. Replicated and persisted, so a
/// late copy of a settled op is dropped wherever it lands.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SettledHotOps {
pub settled_up_to: HashMap<PeerId, HotSequence>,
/// Settled ops past their author's prefix, as inclusive runs, one per gap in flight.
pub settled_beyond: HashMap<PeerId, Vec<(HotSequence, HotSequence)>>,
}
/// Sort and coalesce runs, joining any that touch or abut.
fn coalesce(runs: &mut Vec<(HotSequence, HotSequence)>) {
runs.sort_unstable();
runs.dedup_by(|(start, end), (_, last_end)| {
let joins = *start <= last_end.next();
if joins {
*last_end = (*last_end).max(*end);
}
joins
});
}
impl SettledHotOps {
/// Whether history already holds this hot op.
pub fn covers(&self, id: HotOpId) -> bool {
self.settled_up_to.get(&id.peer).is_some_and(|&through| id.sequence <= through)
|| self
.settled_beyond
.get(&id.peer)
.is_some_and(|runs| runs.iter().any(|&(start, end)| (start..=end).contains(&id.sequence)))
}
/// Take on `remote`'s coverage as well as this one's.
pub(crate) fn absorb(&mut self, remote: &Self) {
for (&peer, &remote_through) in &remote.settled_up_to {
let through = self.settled_up_to.entry(peer).or_default();
*through = (*through).max(remote_through);
}
for (&peer, runs) in &remote.settled_beyond {
self.settled_beyond.entry(peer).or_default().extend(runs.iter().copied());
}
self.compact();
}
/// Record newly settled ops.
pub fn extend(&mut self, retired: impl IntoIterator<Item = HotOpId>) {
for id in retired {
self.settled_beyond.entry(id.peer).or_default().push((id.sequence, id.sequence));
}
self.compact();
}
/// Fold runs that continue their author's prefix into `settled_up_to`, leaving only those past a gap.
fn compact(&mut self) {
for (&peer, runs) in &mut self.settled_beyond {
coalesce(runs);
let mut through = self.settled_up_to.get(&peer).copied().unwrap_or(HotSequence::NONE);
let joined = runs.iter().take_while(|&&(start, end)| {
let joins = start <= through.next();
if joins {
through = through.max(end);
}
joins
});
let joined = joined.count();
runs.drain(..joined);
if through != HotSequence::NONE {
self.settled_up_to.insert(peer, through);
}
}
self.settled_beyond.retain(|_, runs| !runs.is_empty());
}
}
#[derive(Debug, thiserror::Error)]
pub enum CrdtError {
#[error("This peer has authored every hot op sequence there is")]
SequencesExhausted,
#[error("Target node {0} does not exist")]
TargetNodeDoesNotExist(NodeId),
#[error("Network {0} does not exist")]
@@ -752,6 +559,10 @@ pub enum CrdtError {
ExportSlotOutOfBounds(u32),
#[error("Delta {0} not found in history")]
NotFoundInHistory(Rev),
#[error("No history entry resurrects node {0}")]
NodeNotInHistory(NodeId),
#[error("No history entry resurrects network {0}")]
NetworkNotInHistory(NetworkId),
#[error("Nothing to undo")]
NothingToUndo,
#[error("Nothing to redo")]
@@ -760,6 +571,9 @@ pub enum CrdtError {
NodeAlreadyExists(NodeId),
#[error("Network {0} already exists")]
NetworkAlreadyExists(NetworkId),
/// PeerId is already registered to a different UserId.
#[error("Peer {0:?} is already registered to a different user")]
PeerRegistrationConflict(PeerId),
#[error("Delta stored under {stored} hashes to {expected}")]
RevMismatch { stored: Rev, expected: Rev },
}
@@ -1,165 +0,0 @@
use crate::{AttributeDelta, CrdtError, HotOpId, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, RegistryDelta, Session, UserId, Value};
pub(super) fn set_attribute(key: &str, value: u32) -> RegistryDelta {
RegistryDelta::ChangeDocumentAttribute {
delta: AttributeDelta {
key: key.to_string(),
value: Some(Value::from(serde_json::json!(value))),
},
}
}
pub(super) fn add_network(id: u64) -> RegistryDelta {
RegistryDelta::AddNetwork {
id: NetworkId(id),
network: Network::default(),
}
}
/// Retirement takes the ops under the cutoff in any log order: every op commutes, so the snapshot folds to
/// the working registry's values with a later-stamped op left hot.
#[test]
fn retirement_takes_the_ops_under_the_cutoff_in_any_applied_order() {
let mut host = Session::with_peer(PeerId(1));
// A guest's late-stamped op sits ahead of an earlier-stamped one: the log is in arrival order, stamps
// are the authors' clocks.
let hot = |op, counter, peer| crate::HotOp {
op,
timestamp: crate::TimeStamp { counter, peer: PeerId(peer) },
sequence: crate::HotSequence(1),
};
let (late, own) = (hot(add_network(9), 50, 2), hot(set_attribute("x", 1), 20, 3));
host.apply_hot_op(late.clone()).expect("the late-stamped op lands first");
host.apply_hot_op(own.clone()).expect("the earlier-stamped op lands second");
assert_eq!(host.hot_ops_up_to(own.timestamp).len(), 1, "only the op under the cutoff retires");
host.retire(own.timestamp).expect("retire");
assert_eq!(host.hot_log().len(), 1, "the later-stamped op stays hot");
assert!(!host.retired_registry().networks.contains_key(&NetworkId(9)));
assert!(host.registry().networks.contains_key(&NetworkId(9)));
assert!(host.retired_registry().attributes.get("x").is_some_and(|value| !value.deleted));
host.retire(late.timestamp).expect("retire the rest");
assert!(host.hot_log().is_empty());
assert!(host.registry().value_equal(host.retired_registry()));
}
/// A device's registration to a person is a write like any other: a later one replaces it, and a peer that
/// receives the two in the other order ends up with the same mapping.
#[test]
fn a_peers_registration_is_the_newest_by_stamp_whatever_order_it_lands() {
// Registration rides the staging path, so the steps go through the hot log and retire.
fn stage_and_retire(session: &mut Session, op: RegistryDelta) {
let hot = session.stage_ops([op]).expect("stage");
let ids: Vec<crate::HotOpId> = hot.iter().map(crate::HotOp::id).collect();
session.retire_hot_ops(&ids).expect("retire");
}
let mut device = Session::with_identity(PeerId(1), UserId(10));
stage_and_retire(&mut device, set_attribute("first", 1));
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(10));
// The person at the device changes: the next batch registers again, and the newer registration wins.
device.document.user = UserId(20);
stage_and_retire(&mut device, set_attribute("second", 2));
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(20));
let registrations = device.history().filter(|delta| matches!(delta.kind, RegistryDelta::RegisterPeer { .. })).count();
assert_eq!(registrations, 2, "one registration per person the device stood for");
let mut other = Session::with_peer(PeerId(2));
for delta in device.cloned_deltas().into_iter().rev() {
other.document.apply_op_idempotent(delta.kind, delta.timestamp).unwrap();
}
assert_eq!(other.user_of(PeerId(1)), Some(UserId(20)), "the newest registration wins in any order");
assert_eq!(other.user_of(PeerId(3)), None, "a peer never registered has no user");
}
#[test]
fn a_batch_past_the_last_sequence_is_refused_whole() {
let mut session = Session::with_peer(PeerId(1));
session.restore_hot_sequence(crate::HotSequence(u64::MAX - 1));
assert!(matches!(session.stage_ops([set_attribute("k", 1)]), Err(crate::CrdtError::SequencesExhausted)));
assert!(session.hot_log().is_empty());
}
/// The settled marks carry over a reopen, so a late copy of a retired op is dropped rather than retired again.
#[test]
fn a_reopened_session_drops_a_late_copy_of_a_retired_op() {
let op = crate::HotOp {
op: set_attribute("k", 1),
timestamp: crate::TimeStamp { counter: 3, peer: PeerId(2) },
sequence: crate::HotSequence(1),
};
let mut host = Session::with_peer(PeerId(1));
host.apply_hot_op(op.clone()).unwrap();
host.retire(op.timestamp).unwrap();
let mut reopened = Session::load(PeerId(1), UserId(1), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
reopened.absorb_settled_marks(host.settled_marks());
reopened.apply_hot_op(op.clone()).unwrap();
assert!(reopened.hot_log().is_empty());
assert!(reopened.retire(op.timestamp).unwrap().is_empty());
assert_eq!(reopened.history_len(), host.history_len());
}
/// A local op naming a node never seen is refused before it writes anything, its target included, so the working
/// registry stays the snapshot plus the hot log.
#[test]
fn a_refused_local_op_leaves_the_working_registry_unchanged() {
let mut s = Session::with_peer(PeerId(1));
let node = Node::new(NetworkId(1), Implementation::Network(NetworkId(1)), 1);
s.stage_ops([
RegistryDelta::AddNetwork {
id: NetworkId(1),
network: Network::default(),
},
RegistryDelta::AddNode { id: NodeId(1), node },
])
.unwrap();
let before = s.registry().clone();
let refused = s.stage_ops([RegistryDelta::ChangeNodeInput {
id: NodeId(1),
index: 0,
new_input: NodeInput::Node { id: NodeId(404), index: 0 },
}]);
assert!(matches!(refused, Err(CrdtError::TargetNodeDoesNotExist(_))));
assert_eq!(s.registry(), &before, "the refused op's write to node 1 stayed in the working registry");
}
/// A batch refused partway stages nothing: the caller only gets the error, so ops left staged would never be persisted
/// or sent.
#[test]
fn a_refused_batch_stages_nothing() {
let mut s = Session::with_peer(PeerId(1));
s.stage_ops([RegistryDelta::AddNetwork {
id: NetworkId(1),
network: Network::default(),
}])
.unwrap();
let hot_before = s.hot_log().len();
let refused = s.stage_ops([
set_attribute("lands", 1),
RegistryDelta::ChangeNodeInput {
id: NodeId(404),
index: 0,
new_input: NodeInput::Value {
value: Value::from(serde_json::json!(1)),
exposed: false,
},
},
]);
assert!(refused.is_err());
assert_eq!(s.hot_log().len(), hot_before, "a refused batch stages nothing");
}
#[test]
fn settled_marks_round_trip_through_json() {
let mut marks = crate::SettledHotOps::default();
let id = |peer: u64, sequence: u64| HotOpId {
peer: PeerId(peer),
sequence: crate::HotSequence(sequence),
};
marks.extend([id(1, 1), id(1, 2), id(1, 5), id(u64::MAX, 3)]);
let json = serde_json::to_string(&marks).unwrap();
assert_eq!(serde_json::from_str::<crate::SettledHotOps>(&json).unwrap(), marks);
}
File diff suppressed because it is too large. Load diff
+15 -22
View File
@@ -7,7 +7,7 @@ use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput,
use graph_craft::graphene_compiler::Compiler;
use graph_craft::{ProtoNodeIdentifier, Type, concrete};
use crate::{NetworkId, NodeMetadataSource, PeerId, Position, Registry, from_value};
use crate::{NetworkId, NodeMetadataSource, PeerId, Position, Registry};
/// Helper function to verify a NodeNetwork can be compiled successfully.
/// Note: This only works for complete networks with all inputs resolved.
@@ -20,10 +20,12 @@ fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> {
/// Convert a runtime network to a storage `Registry`, returning the declarations alongside it.
/// Proto-node declaration content is no longer stored in the registry (it lives in a byte store);
/// these tests have no byte store, so they keep the extracted `Declarations` in hand for the back-conversion.
/// these tests have no byte store, so they keep the extracted bytes in hand and rebuild a
/// `Declarations` map for the back-conversion.
fn to_registry(network: &NodeNetwork) -> (Registry, crate::Declarations) {
let conversion = Registry::convert_from_runtime(network, &crate::NoMetadata, &Default::default(), PeerId(0)).expect("Failed to convert NodeNetwork to Registry");
(conversion.registry, conversion.declarations)
let declarations = conversion.declarations().expect("rebuild declarations");
(conversion.registry, declarations)
}
/// A one-node network whose single node references `id` via a `TaggedValue::Resource` input, so
@@ -475,7 +477,7 @@ fn test_ui_metadata_round_trip() {
);
let conversion = Registry::convert_from_runtime(&network, &metadata, &Default::default(), PeerId(0)).expect("Failed to convert to Registry with metadata");
let declarations = conversion.declarations;
let declarations = conversion.declarations().expect("rebuild declarations");
let registry = conversion.registry;
let (converted, entries) = registry.to_runtime_with_metadata(&declarations).expect("Failed to convert Registry back with metadata");
@@ -530,7 +532,7 @@ fn resources_round_trip_through_from_runtime() {
assert_eq!(entry.sources.len(), 2, "both sources carried through");
// The chain iterates in priority order; decode bodies back to DataSource to compare.
let decoded: Vec<DataSource> = entry.sources.iter().map(|(_, v)| from_value(&v.source).expect("source body decodes")).collect();
let decoded: Vec<DataSource> = entry.sources.iter().map(|(_, v)| serde_json::from_value(v.source.clone()).expect("source body decodes")).collect();
assert_eq!(decoded, vec![DataSource::Embedded, DataSource::Url("https://example.com/img.png".parse().unwrap())]);
// All source keys carry the document peer.
@@ -609,9 +611,10 @@ 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::Number` must survive the storage round-trip bit-exact. Inputs are stored
/// type-erased as a `Value`, so this guards against any precision loss in the f64
/// -> Value -> f64 path for a value with a full 17-significant-digit mantissa.
/// A node-input `TaggedValue::F64` 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.
#[test]
fn node_input_f64_round_trips_bit_exact() {
use graph_craft::document::value::TaggedValue;
@@ -622,7 +625,7 @@ fn node_input_f64_round_trips_bit_exact() {
nodes: [(
NodeId(0),
DocumentNode {
inputs: vec![NodeInput::value(TaggedValue::Number(precise), false)],
inputs: vec![NodeInput::value(TaggedValue::F64(precise), false)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::identity::IdentityNode")),
..Default::default()
},
@@ -639,8 +642,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::Number(actual) = &**tagged_value else {
panic!("expected Number, got {:?}", tagged_value)
let TaggedValue::F64(actual) = &**tagged_value else {
panic!("expected F64, got {:?}", tagged_value)
};
assert_eq!(actual.to_bits(), precise.to_bits(), "f64 node input drifted: {actual} != {precise}");
@@ -658,7 +661,7 @@ fn duplicate_runtime_node_id_is_rejected() {
// Force both root-network nodes onto the same runtime ID.
for node in registry.node_instances.values_mut() {
node.attributes.set(crate::attr::node::ORIGINAL_NODE_ID, crate::Value::Int(7), TimeStamp::ORIGIN);
node.attributes.set(crate::attr::node::ORIGINAL_NODE_ID, serde_json::json!(7), TimeStamp::ORIGIN);
}
let error = registry.to_runtime_with_metadata(&declarations).expect_err("duplicate runtime ID must error");
@@ -757,28 +760,18 @@ fn cyclic_network_reference_is_rejected() {
registry.node_instances.insert(
crate::NodeId(0),
Node {
presence: Default::default(),
added: Default::default(),
inputs_timestamp: Default::default(),
implementation: Implementation::Network(child_network_id),
implementation_timestamp: Default::default(),
inputs: Vec::new(),
attributes: crate::Attributes::default(),
attributes_timestamp: Default::default(),
network: crate::ROOT_NETWORK,
},
);
registry.node_instances.insert(
crate::NodeId(1),
Node {
presence: Default::default(),
added: Default::default(),
inputs_timestamp: Default::default(),
implementation: Implementation::Network(crate::ROOT_NETWORK),
implementation_timestamp: Default::default(),
inputs: Vec::new(),
attributes: crate::Attributes::default(),
attributes_timestamp: Default::default(),
network: child_network_id,
},
);
+32 -39
View File
@@ -10,7 +10,7 @@ use rustc_hash::{FxHashMap, FxHashSet};
use crate::attr::*;
use crate::metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NodeMetadataEntry};
use crate::{AttributesRead, Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, ROOT_NETWORK, Registry, ResourceId, Value, from_value};
use crate::{AttributesRead, Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, ROOT_NETWORK, Registry, ResourceId};
#[derive(Debug, thiserror::Error)]
pub enum ConversionError {
@@ -38,8 +38,7 @@ pub enum ConversionError {
pub type Declarations = std::collections::HashMap<ResourceId, ProtoNode>;
impl Registry {
/// Returns the network plus one metadata entry per node, since every node carries an identity to
/// restore even when it has no `ui::*` attribute.
/// Returns the network plus per-node metadata entries (one per node carrying any `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))
@@ -51,7 +50,19 @@ impl Registry {
let mut node_metadata = Some(Vec::new());
let mut network_metadata = Some(Vec::new());
let context = ConversionContext::new(self, declarations);
// Group nodes by their owning network in one pass, so each `convert_network` call (one per
// network, including nested ones) takes its node list by lookup instead of rescanning the whole
// flat `node_instances` map, which would be quadratic on graphs with many networks.
let mut nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &Node)>> = FxHashMap::default();
for (&global_id, node) in &self.node_instances {
nodes_by_network.entry(node.network).or_default().push((global_id, node));
}
let context = ConversionContext {
registry: self,
declarations,
nodes_by_network,
};
// Reject cycles up front so the recursive conversion below can assume the network reference
// graph is acyclic and never blow the stack on a self-referential `Implementation::Network`.
@@ -63,15 +74,15 @@ impl Registry {
/// Rebuild the runtime [`ResourceRegistry`](graphene_resource::ResourceRegistry) from the stored
/// `resources`. Each entry's source chain is restored in priority order (the chain is kept
/// sorted by key) with bodies decoded from their type-erased `Value` form back to
/// sorted by key) with bodies decoded from their type-erased `serde_json::Value` form back to
/// `DataSource`; the resolved hash, if any, is restored last. Inverse of `convert_resources` in
/// `from_runtime`.
pub fn to_resource_registry(&self) -> Result<graphene_resource::ResourceRegistry, ConversionError> {
let mut registry = graphene_resource::ResourceRegistry::new();
for (id, entry) in &self.resources {
for (_, source) in entry.live_sources() {
let decoded: graphene_resource::DataSource = from_value(&source.source).map_err(|error| ConversionError::DeserializationError(error.to_string()))?;
for (_, source) in &entry.sources {
let decoded: graphene_resource::DataSource = serde_json::from_value(source.source.clone()).map_err(|error| ConversionError::DeserializationError(error.to_string()))?;
registry.push_source_back(id, decoded);
}
if let Some(hash) = entry.hash {
@@ -92,26 +103,6 @@ struct ConversionContext<'a> {
nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &'a Node)>>,
}
impl<'a> ConversionContext<'a> {
fn new(registry: &'a Registry, declarations: &'a Declarations) -> Self {
let mut nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &Node)>> = FxHashMap::default();
for (&global_id, node) in &registry.node_instances {
nodes_by_network.entry(node.network).or_default().push((global_id, node));
}
Self {
registry,
declarations,
nodes_by_network,
}
}
}
/// The id the node had in the runtime it was converted from, kept as an attribute so a conversion back
/// lands it under the id the editor's metadata is keyed by.
fn runtime_node_id(global_id: NodeId, node: &Node) -> RuntimeNodeId {
RuntimeNodeId(node.attributes.get_typed(node::ORIGINAL_NODE_ID).unwrap_or(global_id.0))
}
/// Converts a single network. Recurses through `Implementation::Network` owning nodes.
///
/// **ID remapping:** Registry uses globally hashed IDs; runtime networks need local IDs. We pull
@@ -174,7 +165,7 @@ fn convert_network(
node_collector: &mut Option<Vec<NodeMetadataEntry>>,
network_collector: &mut Option<Vec<NetworkMetadataEntry>>,
) -> Result<NodeNetwork, ConversionError> {
let network = context.registry.network_or_removed(network_id).ok_or(ConversionError::NetworkNotFound(network_id))?;
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(context.registry, &network.attributes, metadata_path, network_id));
@@ -182,8 +173,8 @@ fn convert_network(
let mut nodes: FxHashMap<RuntimeNodeId, DocumentNode> = FxHashMap::default();
for &(global_id, node) in context.nodes_by_network.get(&network_id).map(Vec::as_slice).unwrap_or_default() {
let runtime_id = runtime_node_id(global_id, node);
let local_id = runtime_id.0;
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() {
collector.push(extract_ui_metadata(node, global_id, metadata_path, runtime_id));
@@ -240,7 +231,8 @@ fn read_scope_injections(registry: &Registry, network_id: NetworkId, attributes:
});
};
Ok((key, (runtime_node_id(storage_id, referenced), ty)))
let local_id = referenced.attributes.get(node::ORIGINAL_NODE_ID).and_then(|v| v.value.as_u64()).unwrap_or(storage_id.0);
Ok((key, (RuntimeNodeId(local_id), ty)))
})
.collect()
}
@@ -274,11 +266,12 @@ fn extract_ui_metadata(node: &crate::Node, storage_id: NodeId, network_path: &[R
/// 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.
/// rather than failing the conversion: the preview target or 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)?;
Some(runtime_node_id(storage_id, node))
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
@@ -298,7 +291,8 @@ fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes,
/// Reassembles `input_data` by scanning every attribute under `ui::input_data::` and stripping the prefix.
fn extract_input_metadata(attributes: &crate::Attributes) -> InputMetadataEntry {
let input_data: HashMap<String, Value> = crate::attributes::live(attributes)
let input_data: HashMap<String, serde_json::Value> = attributes
.iter()
.filter_map(|(key, value)| key.strip_prefix(node::input::ui::DATA_PREFIX).map(|sub_key| (sub_key.to_owned(), value.value.clone())))
.collect();
@@ -340,9 +334,7 @@ fn convert_node(
fn convert_input(registry: &Registry, network_id: NetworkId, input: &NodeInput, input_attributes: &crate::Attributes) -> Result<GraphCraftNodeInput, ConversionError> {
Ok(match input {
NodeInput::Node { id: node_id, index: output_index } => {
// A node removed concurrently keeps its id, as the editor holds a dangling input; only a node
// never seen has no id to map to.
let referenced = registry.node_or_removed(*node_id).ok_or(ConversionError::NodeNotFound(*node_id))?;
let referenced = registry.node_instances.get(node_id).ok_or(ConversionError::NodeNotFound(*node_id))?;
// Runtime references are local to one network. A cross-network reference would remap to a
// local ID that doesn't exist in the current runtime network, so reject it.
@@ -353,13 +345,14 @@ fn convert_input(registry: &Registry, network_id: NetworkId, input: &NodeInput,
});
}
let local_id = referenced.attributes.get(node::ORIGINAL_NODE_ID).and_then(|v| v.value.as_u64()).unwrap_or(node_id.0);
GraphCraftNodeInput::Node {
node_id: runtime_node_id(*node_id, referenced),
node_id: RuntimeNodeId(local_id),
output_index: *output_index as usize,
}
}
NodeInput::Value { value, exposed } => {
let tagged_value: TaggedValue = from_value(value).map_err(|e| ConversionError::DeserializationError(format!("TaggedValue: {e:?}")))?;
let tagged_value: TaggedValue = serde_json::from_value(value.clone()).map_err(|e| ConversionError::DeserializationError(format!("TaggedValue: {e:?}")))?;
GraphCraftNodeInput::Value {
tagged_value: MemoHash::new(tagged_value),
exposed: *exposed,
-265
View File
@@ -1,265 +0,0 @@
use serde::de::{self, DeserializeOwned, MapAccess, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
pub fn to_value<T: Serialize + ?Sized>(value: &T) -> Result<Value, ValueError> {
serde_json::to_value(value).map(Value::from).map_err(ValueError)
}
pub fn from_value<T: DeserializeOwned>(value: &Value) -> Result<T, ValueError> {
serde_json::from_value(value.clone().into()).map_err(ValueError)
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(remote = "Self")]
pub enum Value {
None,
Bool(bool),
Int(i128),
Float(f64),
Str(String),
Array(Vec<Value>),
Object(Vec<(String, Value)>),
}
// Using `Serializer::is_human_readable` to determine whether to serialize tagged.
// We assume that any human-readable format is self describing and does not need tags.
impl Serialize for Value {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
if !serializer.is_human_readable() {
return Value::serialize(self, serializer);
}
match self {
Value::None => serializer.serialize_unit(),
Value::Bool(boolean) => serializer.serialize_bool(*boolean),
Value::Int(int) => serializer.serialize_i128(*int),
Value::Float(float) => serializer.serialize_f64(*float),
Value::Str(string) => serializer.serialize_str(string),
Value::Array(array) => serializer.collect_seq(array),
Value::Object(object) => serializer.collect_map(object.iter().map(|(key, value)| (key, value))),
}
}
}
// Using `Deserialize::is_human_readable` to determine whether to deserialize tagged.
// We assume that any human-readable format is self describing and does not need tags.
impl<'de> Deserialize<'de> for Value {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
if !deserializer.is_human_readable() {
return Value::deserialize(deserializer);
}
struct Untagged;
impl<'de> Visitor<'de> for Untagged {
type Value = Value;
fn visit_unit<E>(self) -> Result<Value, E> {
Ok(Value::None)
}
fn visit_none<E>(self) -> Result<Value, E> {
Ok(Value::None)
}
fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Value, D::Error> {
Deserialize::deserialize(deserializer)
}
fn visit_bool<E>(self, value: bool) -> Result<Value, E> {
Ok(Value::Bool(value))
}
fn visit_i64<E>(self, value: i64) -> Result<Value, E> {
Ok(Value::Int(value.into()))
}
fn visit_u64<E>(self, value: u64) -> Result<Value, E> {
Ok(Value::Int(value.into()))
}
fn visit_i128<E>(self, value: i128) -> Result<Value, E> {
Ok(Value::Int(value))
}
fn visit_u128<E: de::Error>(self, value: u128) -> Result<Value, E> {
i128::try_from(value).map(Value::Int).map_err(E::custom)
}
fn visit_f64<E>(self, value: f64) -> Result<Value, E> {
Ok(Value::Float(value))
}
fn visit_str<E>(self, value: &str) -> Result<Value, E> {
Ok(Value::Str(value.to_owned()))
}
fn visit_string<E>(self, value: String) -> Result<Value, E> {
Ok(Value::Str(value))
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Value, A::Error> {
let mut array = Vec::with_capacity(seq.size_hint().unwrap_or(0));
while let Some(value) = seq.next_element()? {
array.push(value);
}
Ok(Value::Array(array))
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Value, A::Error> {
let mut object: Vec<(String, Value)> = Vec::with_capacity(map.size_hint().unwrap_or(0));
while let Some(entry) = map.next_entry()? {
object.push(entry);
}
object.sort_by(|a, b| a.0.cmp(&b.0));
object.dedup_by(|b, a| {
let dedup = b.0 == a.0;
if dedup {
std::mem::swap(&mut a.1, &mut b.1);
}
dedup
});
Ok(Value::Object(object))
}
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a valid Value")
}
}
deserializer.deserialize_any(Untagged)
}
}
impl From<serde_json::Value> for Value {
fn from(value: serde_json::Value) -> Self {
use serde_json::Value as Json;
match value {
Json::Null => Value::None,
Json::Bool(boolean) => Value::Bool(boolean),
Json::Number(number) => {
if let Some(int) = number.as_i64() {
Value::Int(int.into())
} else if let Some(int) = number.as_u64() {
Value::Int(int.into())
} else {
Value::Float(number.as_f64().unwrap_or(f64::NAN))
}
}
Json::String(string) => Value::Str(string),
Json::Array(array) => Value::Array(array.into_iter().map(Into::into).collect()),
Json::Object(object) => Value::Object(object.into_iter().map(|(key, value)| (key, value.into())).collect()),
}
}
}
impl From<Value> for serde_json::Value {
fn from(value: Value) -> Self {
use serde_json::Value as Json;
match value {
Value::None => Json::Null,
Value::Bool(boolean) => Json::Bool(boolean),
Value::Int(int) => match (i64::try_from(int), u64::try_from(int)) {
(Ok(int), _) => int.into(),
(_, Ok(int)) => int.into(),
(Err(_), Err(_)) => (int as f64).into(),
},
Value::Float(float) => float.into(),
Value::Str(string) => Json::String(string),
Value::Array(array) => Json::Array(array.into_iter().map(Into::into).collect()),
Value::Object(object) => Json::Object(object.into_iter().map(|(key, value)| (key, value.into())).collect()),
}
}
}
#[derive(Debug, thiserror::Error)]
#[error(transparent)]
pub struct ValueError(serde_json::Error);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trips_through_postcard() {
let value = serde_json::json!({
"null": null,
"bools": [true, false],
"ints": [0, -1, i64::MIN, u64::MAX],
"floats": [1.5, -0.25, 1e300],
"str": "text",
"empty": { "array": [], "object": {} },
"nested": { "b": [{ "c": 1 }], "a": "z" },
});
let bytes = postcard::to_stdvec(&Value::from(value.clone())).unwrap();
let decoded: Value = postcard::from_bytes(&bytes).unwrap();
assert_eq!(serde_json::Value::from(decoded), value);
}
#[test]
fn round_trips_through_json_untagged() {
let json = serde_json::json!({ "a": [1, -2, 2.5, "s", null, true], "b": {}, "c": [] });
let value = Value::from(json.clone());
let text = serde_json::to_string(&value).unwrap();
assert_eq!(text, serde_json::to_string(&json).unwrap());
assert_eq!(serde_json::to_value(&value).unwrap(), json);
assert_eq!(serde_json::from_str::<Value>(&text).unwrap(), value);
}
#[test]
fn json_object_keys_sort_and_last_duplicate_wins() {
let value: Value = serde_json::from_str(r#"{"b": 1, "a": 2, "b": 3}"#).unwrap();
assert_eq!(value, Value::Object(vec![("a".into(), Value::Int(2)), ("b".into(), Value::Int(3))]));
}
#[derive(Debug, PartialEq, Serialize, Deserialize)]
enum Sample {
Unit,
Newtype(u8),
Tuple(i64, String),
Struct { flag: bool, nested: Option<Box<Sample>> },
}
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Record {
samples: Vec<Sample>,
by_id: std::collections::BTreeMap<u32, f64>,
bytes: Vec<u8>,
letter: char,
unit: (),
big: u64,
}
fn record() -> Record {
Record {
samples: vec![
Sample::Unit,
Sample::Newtype(7),
Sample::Tuple(-3, "t".into()),
Sample::Struct {
flag: true,
nested: Some(Box::new(Sample::Unit)),
},
Sample::Struct { flag: false, nested: None },
],
by_id: [(2, 0.5), (10, -1.)].into(),
bytes: vec![0, 255],
letter: 'x',
unit: (),
big: u64::MAX,
}
}
#[test]
fn from_value_round_trips_serde_types() {
assert_eq!(from_value::<Record>(&to_value(&record()).unwrap()).unwrap(), record());
}
#[test]
fn number_variants_map_to_serde_json_numbers() {
let json = |value: Value| serde_json::Value::from(value);
assert_eq!(json(Value::Int(u64::MAX.into())), serde_json::json!(u64::MAX));
assert_eq!(json(Value::Int(-1)), serde_json::json!(-1));
assert_eq!(json(Value::Int(i128::MAX)), serde_json::json!(i128::MAX as f64));
assert_eq!(json(Value::Float(2.)), serde_json::json!(2.));
assert_eq!(Value::from(serde_json::json!(2.)), Value::Float(2.));
assert_eq!(Value::from(serde_json::json!(2)), Value::Int(2));
}
#[test]
fn postcard_tags_follow_declaration_order() {
let encode = |value: Value| postcard::to_stdvec(&value).unwrap();
assert_eq!(encode(Value::None), [0]);
assert_eq!(encode(Value::Bool(true)), [1, 1]);
assert_eq!(encode(Value::Int(-1)), [2, 1]);
assert_eq!(encode(Value::Float(0.)), [3, 0, 0, 0, 0, 0, 0, 0, 0]);
assert_eq!(encode(Value::Str("ab".into())), [4, 2, b'a', b'b']);
assert_eq!(encode(Value::Array(vec![Value::None])), [5, 1, 0]);
assert_eq!(encode(Value::Object(vec![("k".into(), Value::None)])), [6, 1, 1, b'k', 0]);
}
}
-6
View File
@@ -4,15 +4,9 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[features]
default = ["gpu"]
wasm = ["graphene-std/wasm", "interpreted-executor/wasm", "dep:wasm-bindgen"]
+2 -2
View File
@@ -14,14 +14,14 @@ impl Editor {
environment: Environment,
uuid_random_seed: u64,
resource_storage: Arc<dyn ResourceStorage>,
document_store: Arc<dyn document_container::store::DocumentStore>,
working_copy_root: Option<std::path::PathBuf>,
mut application_io: PlatformApplicationIo,
wake: Wake,
) -> Self {
ENVIRONMENT.set(environment).expect("Editor shoud only be initialized once");
graphene_std::uuid::set_uuid_seed(uuid_random_seed);
let mut dispatcher = Dispatcher::new(resource_storage, document_store);
let mut dispatcher = Dispatcher::new(resource_storage, working_copy_root);
dispatcher.message_handlers.future_message_handler.set_wake(wake);
application_io.inject_resource_proxy(dispatcher.message_handlers.resource_storage_message_handler.resources());
crate::node_graph_executor::replace_application_io(application_io);
-4
View File
@@ -193,9 +193,5 @@ pub const UI_SCALE_DEFAULT: f64 = 1.;
pub const UI_SCALE_MIN: f64 = 0.5;
pub const UI_SCALE_MAX: f64 = 3.;
// DIALOGS
pub const MAX_UNSAVED_DOCUMENTS_IN_DIALOG: usize = 5;
pub const MAX_DOCUMENT_NAME_LENGTH_IN_DIALOG: usize = 60;
// ACTIONS
pub const BLEND_COUNT_PER_LAYER: usize = 10;
+3 -6
View File
@@ -89,19 +89,16 @@ const DEBUG_MESSAGE_BLOCK_LIST: &[MessageDiscriminant] = &[
const DEBUG_MESSAGE_ENDING_BLOCK_LIST: &[&str] = &["PointerMove", "PointerOutsideViewport", "Overlays", "Draw", "CurrentTime", "Time"];
impl Dispatcher {
pub fn new(resource_storage: Arc<dyn ResourceStorage>, document_store: Arc<dyn document_container::store::DocumentStore>) -> Self {
pub fn new(resource_storage: Arc<dyn ResourceStorage>, working_copy_root: Option<std::path::PathBuf>) -> Self {
let mut s = Self::default();
s.message_handlers.resource_storage_message_handler = ResourceStorageMessageHandler::new(resource_storage);
s.message_handlers.portfolio_message_handler.set_document_store(document_store);
s.message_handlers.portfolio_message_handler.set_working_copy_root(working_copy_root);
s
}
#[cfg(test)]
pub fn with_executor(executor: crate::node_graph_executor::NodeGraphExecutor) -> Self {
let mut s = Self::new(
Arc::new(graph_craft::application_io::resource::HashMapResourceStorage::new()),
Arc::new(document_container::store::MemoryStore::default()),
);
let mut s = Self::new(Arc::new(graph_craft::application_io::resource::HashMapResourceStorage::new()), None);
s.message_handlers.portfolio_message_handler = PortfolioMessageHandler::with_executor(executor);
s
}
-2
View File
@@ -19,5 +19,3 @@ pub mod node_graph_executor;
pub mod test_utils;
pub mod utility_traits;
pub mod utility_types;
pub use document_container::store as document_store;
@@ -1,10 +1,6 @@
use crate::consts::{MAX_DOCUMENT_NAME_LENGTH_IN_DIALOG, MAX_UNSAVED_DOCUMENTS_IN_DIALOG};
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*;
use std::borrow::Cow;
use std::fmt::Write;
/// A dialog for confirming the closing of all documents viewable via `File -> Close All` in the menu bar.
pub struct CloseAllDocumentsDialog {
pub unsaved_document_names: Vec<String>,
@@ -34,26 +30,7 @@ impl DialogLayoutHolder for CloseAllDocumentsDialog {
impl LayoutHolder for CloseAllDocumentsDialog {
fn layout(&self) -> Layout {
let mut unsaved_list = "• ".to_string()
+ &self
.unsaved_document_names
.iter()
.take(MAX_UNSAVED_DOCUMENTS_IN_DIALOG)
.map(|name| {
if name.chars().count() > MAX_DOCUMENT_NAME_LENGTH_IN_DIALOG {
Cow::Owned(name.chars().take(MAX_DOCUMENT_NAME_LENGTH_IN_DIALOG).chain(std::iter::once('…')).collect())
} else {
Cow::Borrowed(name.as_str())
}
})
.collect::<Vec<_>>()
.join("\n• ");
let remaining = self.unsaved_document_names.len().saturating_sub(MAX_UNSAVED_DOCUMENTS_IN_DIALOG);
if remaining > 0 {
let s = if remaining == 1 { "" } else { "s" };
let _ = write!(unsaved_list, "\n... and {remaining} more document{s}");
}
let unsaved_list = "• ".to_string() + &self.unsaved_document_names.join("\n• ");
Layout(vec![
LayoutGroup::row(vec![TextLabel::new("Save documents before closing them?").bold(true).multiline(true).widget_instance()]),
@@ -118,9 +118,22 @@ pub enum FrontendMessage {
filename: String,
},
TriggerPersistenceReadState,
TriggerPersistenceReadDocument {
#[serde(rename = "documentId")]
document_id: DocumentId,
},
TriggerPersistenceWriteState {
state: PersistedState,
},
TriggerPersistenceDeleteDocument {
#[serde(rename = "documentId")]
document_id: DocumentId,
},
TriggerPersistenceWriteDocument {
#[serde(rename = "documentId")]
document_id: DocumentId,
document: String,
},
TriggerOpenLaunchDocuments,
TriggerLoadPreferences,
TriggerSavePreferences {
@@ -1,5 +1,7 @@
use std::path::PathBuf;
use graph_craft::application_io::resource::ResourceHash;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::utility_types::WorkspacePanelLayout;
use crate::messages::prelude::*;
@@ -10,6 +12,9 @@ pub struct DocumentInfo {
pub id: DocumentId,
pub name: String,
#[serde(default)]
#[cfg_attr(feature = "wasm", tsify(type = "unknown"))]
pub resources: Option<Box<[ResourceHash]>>,
#[serde(default)]
pub path: Option<PathBuf>,
pub is_saved: bool,
}
@@ -1,5 +1,4 @@
pub mod layout_widget;
pub mod tooltip_markdown;
pub mod widgets;
pub mod widget_prelude {
@@ -1,78 +0,0 @@
//! Tooltips render a subset of Markdown: `code` spans, fenced code blocks, `**bold**`, and `*italic*`, where a backslash makes a
//! following backslash, asterisk, or backtick literal. Text from outside the editor goes through these so it shows exactly as written.
/// Escapes text so its backslashes, asterisks, and backticks show as themselves rather than as formatting.
pub fn escape_markdown(text: &str) -> String {
let mut escaped = String::with_capacity(text.len());
for character in text.chars() {
if matches!(character, '\\' | '*' | '`') {
escaped.push('\\');
}
escaped.push(character);
}
escaped
}
/// Wraps text in a code span that nothing inside can close, as in CommonMark: the fence outruns every run of backticks within,
/// and a space pads the text where it would touch the fence or lose its own edge spaces to the span's trimming.
pub fn markdown_code_span(text: &str) -> String {
if text.is_empty() {
return String::new();
}
let longest_run = text.split(|character| character != '`').map(str::len).max().unwrap_or_default();
let fence = "`".repeat(longest_run + 1);
let touches_fence = text.starts_with('`') || text.ends_with('`');
let loses_edge_spaces = text.starts_with(' ') && text.ends_with(' ') && text.contains(|character| character != ' ');
let padding = if touches_fence || loses_edge_spaces { " " } else { "" };
format!("{fence}{padding}{text}{padding}{fence}")
}
/// Wraps text in a fenced code block that nothing inside can close, as in CommonMark: the fence outruns every run of backticks within.
/// The fences are lines of their own, so the block goes at the start of a line.
pub fn markdown_code_block(text: &str) -> String {
if text.is_empty() {
return String::new();
}
let longest_run = text.split(|character| character != '`').map(str::len).max().unwrap_or_default();
let fence = "`".repeat(longest_run.max(2) + 1);
format!("{fence}\n{text}\n{fence}")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn escaped_text_holds_no_formatting() {
assert_eq!(escape_markdown("a*b*c"), "a\\*b\\*c");
assert_eq!(escape_markdown("`code`"), "\\`code\\`");
assert_eq!(escape_markdown("ends with \\"), "ends with \\\\");
assert_eq!(escape_markdown("<b>&amp;</b>"), "<b>&amp;</b>", "HTML is the tooltip's to escape");
}
#[test]
fn code_spans_contain_anything() {
assert_eq!(markdown_code_span("x"), "`x`");
assert_eq!(markdown_code_span("a`b"), "``a`b``");
assert_eq!(markdown_code_span("a``b`"), "``` a``b` ```");
assert_eq!(markdown_code_span("`"), "`` ` ``");
assert_eq!(markdown_code_span(" x "), "` x `");
assert_eq!(markdown_code_span(" "), "` `");
assert_eq!(markdown_code_span("a\\"), "`a\\`", "a backslash is literal inside a span");
assert_eq!(markdown_code_span("**<i>**"), "`**<i>**`");
assert_eq!(markdown_code_span(""), "");
}
#[test]
fn code_blocks_contain_anything() {
assert_eq!(markdown_code_block("x\n^"), "```\nx\n^\n```");
assert_eq!(markdown_code_block("```\n**<i>**"), "````\n```\n**<i>**\n````");
assert_eq!(markdown_code_block("`"), "```\n`\n```");
assert_eq!(markdown_code_block(""), "");
}
}
@@ -215,6 +215,10 @@ 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>,
@@ -271,6 +275,10 @@ 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>,
@@ -569,7 +577,7 @@ impl TableItemLayout for Coverage {
impl TableItemLayout for TransferCurve {
fn type_name() -> &'static str {
"TransferCurve"
"Transfer Curve"
}
fn identifier(&self) -> String {
let points = self.points().len();
@@ -834,12 +842,37 @@ impl TableItemLayout for Gradient {
}
}
impl TableItemLayout for i64 {
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 {
fn type_name() -> &'static str {
"Integer"
"Number (f32)"
}
fn identifier(&self) -> String {
format!("{self}")
// 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}") }
}
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
@@ -935,6 +968,26 @@ 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"
@@ -1219,8 +1272,13 @@ macro_rules! known_item_types {
DVec2,
Affine2,
Vec2,
Option<f64>,
f64,
f32,
u8,
u32,
u64,
i32,
i64,
bool,
String,
@@ -1,12 +1,12 @@
use std::collections::VecDeque;
use std::collections::{BTreeMap, HashSet};
use document_graph_storage::{Declarations, Registry, Value};
use document_graph_storage::Registry;
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};
use super::utility_types::network_interface::storage_metadata::{StorageMetadataView, collect_network_view_settings};
/// Per-document undo/redo state: the legacy snapshot stacks plus the `Gdd` working-copy cursor that is
/// becoming the authoritative history. Owns the dual-stack bookkeeping push/pop/clear and the cursor's stage/retire/move/verify
@@ -25,25 +25,6 @@ pub struct DocumentHistory {
/// future built by `load_document` resolves.
#[derivative(Debug = "ignore")]
storage: Option<document_format::GddV1>,
/// Decoded proto-node declarations for every registry state the cursor can reach, filled at mount
/// 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.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CursorMoveError {
/// Nothing to move to, unmounted, or the move itself failed. The cursor did not move.
NotMoved,
/// The cursor moved but the rebuild from it failed. It stays moved unless the caller reverts it.
RebuildFailed,
}
impl DocumentHistory {
@@ -99,23 +80,9 @@ impl DocumentHistory {
self.storage.as_mut()
}
/// 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;
}
/// Detach the `Gdd` working copy, dropping its declaration cache with it.
pub fn clear_storage(&mut self) {
self.storage = None;
self.declarations.clear();
/// Attach (or clear) the `Gdd` working copy once the mount future resolves.
pub fn set_storage(&mut self, storage: Option<document_format::GddV1>) {
self.storage = storage;
}
/// Retire the pending staged hot ops into durable Gdd history as one undo unit. Called at each undo-step
@@ -128,45 +95,45 @@ impl DocumentHistory {
}
}
/// 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, Value>, byte_store: &dyn ResourceStorage) {
let needs_whole_document_stage = self.needs_whole_document_stage;
/// 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.
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 Some(storage) = self.storage.as_mut() else { return };
let staged = match needs_whole_document_stage {
// A working copy that does not hold the document yet has no baseline for a batch of changes to
// apply to, so the first commit writes the whole document and every later one stages only what
// the store recorded. Reading that from the working copy rather than from the caller means a path
// that mounts storage and then commits does not have to know which of the two it is.
let staged = match storage.registry().node_instances.is_empty() {
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)
}),
false if deltas.is_empty() => Ok(()),
false => Self::stage_recorded(storage, deltas, 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;
}
if let Err(error) = staged {
log::error!("Storage snapshot staging failed: {error}");
return;
}
self.persist_view_state(interface, view_settings);
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> {
fn stage_whole_document(storage: &mut document_format::GddV1, interface: &NodeNetworkInterface, registry: &ResourceRegistry, byte_store: &dyn ResourceStorage) -> Result<(), String> {
let metadata_view = StorageMetadataView::new(interface);
storage
.stage_runtime_snapshot(interface.document_network(), &metadata_view, registry, byte_store)
@@ -185,19 +152,20 @@ impl DocumentHistory {
interface: &NodeNetworkInterface,
registry: &ResourceRegistry,
byte_store: &dyn ResourceStorage,
) -> Result<Declarations, String> {
) -> Result<(), 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)
.stage_constructed_ops(constructed.ops, &constructed.declaration_bytes, byte_store)
.map_err(|error| error.to_string())
}
/// The parts of a commit that are not the graph: the per-peer and per-network view settings.
fn persist_view_state(&mut self, interface: &NodeNetworkInterface, view_settings: BTreeMap<String, Value>) {
/// 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. Both staging paths persist them; they differ
/// only in how the graph ops are derived.
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
@@ -214,51 +182,38 @@ impl DocumentHistory {
{
log::error!("Persisting per-network view settings failed: {error}");
}
if let Err(error) = storage.store_legacy_document(legacy_document.as_bytes()) {
log::error!("Embedding legacy document into working copy failed: {error}");
}
}
/// Move the `Gdd` undo/redo cursor along the retired interaction chain, flushing any open interaction
/// first, and rebuild the interface from the rewound registry using the declaration cache.
pub fn move_cursor(&mut self, undo: bool) -> Result<NodeNetworkInterface, CursorMoveError> {
/// first. Returns a clone of the post-move `Gdd` (`Arc`-shared) so a `'static` rebuild future can read
/// the rewound state while the live document keeps its cursor. `None` when there is nothing to move to,
/// unmounted, or the move failed.
pub fn move_cursor(&mut self, undo: bool) -> Option<document_format::GddV1> {
self.retire_storage_interaction();
let storage = self.storage.as_mut().ok_or(CursorMoveError::NotMoved)?;
let storage = self.storage.as_mut()?;
let moved = if undo {
if !storage.can_undo() {
return Err(CursorMoveError::NotMoved);
return None;
}
storage.undo().map(|_| ())
} else {
if !storage.can_redo() {
return Err(CursorMoveError::NotMoved);
return None;
}
storage.redo().map(|_| ())
};
if let Err(error) = moved {
log::error!("Storage undo/redo cursor move failed: {error}");
return Err(CursorMoveError::NotMoved);
return None;
}
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()))
.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`
/// direction whose rebuild failed.
pub fn revert_cursor(&mut self, undo: bool) {
let Some(storage) = self.storage.as_mut() else { return };
let reverted = if undo { storage.redo() } else { storage.undo() };
if let Err(error) = reverted {
log::error!("Storage undo/redo cursor revert failed: {error}");
}
Some(storage.clone())
}
// Soak round-trip verification (runtime-gated by `validate_storage_round_trip`)
@@ -285,7 +240,13 @@ impl DocumentHistory {
}
};
let target = &conversion.registry;
let declarations = &conversion.declarations;
let declarations = match conversion.declarations() {
Ok(declarations) => declarations,
Err(error) => {
log::error!("storage round-trip: declaration rebuild failed: {error}");
return;
}
};
let stored = storage.registry();
if !stored.value_equal(target) {
@@ -299,7 +260,7 @@ impl DocumentHistory {
panic!("storage round-trip: timestamp order inconsistent between stored and target");
}
let (round_tripped, _entries) = match stored.to_runtime_with_metadata(declarations) {
let (round_tripped, _entries) = match stored.to_runtime_with_metadata(&declarations) {
Ok(result) => result,
Err(error) => {
log::error!("storage round-trip: to_runtime failed: {error}");
@@ -1,10 +1,10 @@
use super::DocumentHistory;
use super::document_diff::diff_networks;
use super::node_graph::document_node_definitions;
use super::utility_types::error::EditorError;
use super::utility_types::misc::{GroupFolderType, SNAP_FUNCTIONS_FOR_BOUNDING_BOXES, SNAP_FUNCTIONS_FOR_PATHS, SnappingOptions, SnappingState};
use super::utility_types::network_interface::{self, NodeNetworkInterface, TransactionStatus};
use super::utility_types::nodes::{CollapsedLayers, LayerStructureEntry, SelectedNodes};
use super::{CursorMoveError, DocumentHistory};
use crate::application::{GRAPHITE_GIT_COMMIT_HASH, generate_uuid};
use crate::consts::{
ASYMPTOTIC_EFFECT, BLEND_COUNT_PER_LAYER, COLOR_OVERLAY_GRAY, DEFAULT_DOCUMENT_NAME, FILE_EXTENSION, GDD_FILE_EXTENSION, LAYER_INDENT_OFFSET, NODE_CHAIN_WIDTH, SCALE_EFFECT, SCROLLBAR_SPACING,
@@ -32,8 +32,6 @@ use crate::messages::tool::tool_messages::select_tool::SelectToolPointerKeys;
use crate::messages::tool::tool_messages::tool_prelude::Key;
use crate::messages::tool::utility_types::ToolType;
use crate::node_graph_executor::NodeGraphExecutor;
use document_container::AnyContainer;
use document_graph_storage::Declarations;
use glam::{DAffine2, DVec2};
use graph_craft::application_io::resource::ResourceId;
use graph_craft::application_io::wgpu_available;
@@ -150,10 +148,6 @@ pub struct DocumentMessageHandler {
/// Undo/redo state: the legacy snapshot stacks plus the `Gdd` working-copy cursor.
#[serde(skip)]
history: DocumentHistory,
/// The document's container in the document store. `None` for a document created this session until its store entry opens.
#[serde(skip)]
#[derivative(Debug = "ignore")]
pub(crate) container: Option<AnyContainer>,
/// Hash of the document snapshot that was most recently saved to disk by the user.
#[serde(skip)]
saved_hash: Option<u64>,
@@ -205,7 +199,6 @@ impl Default for DocumentMessageHandler {
breadcrumb_network_path: Vec::new(),
selection_network_path: Vec::new(),
history: DocumentHistory::default(),
container: None,
saved_hash: None,
auto_saved_hash: None,
layer_range_selection_reference: None,
@@ -413,8 +406,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(document_id, viewport, preferences.validate_storage_round_trip, responses),
DocumentMessage::DocumentHistoryForward => self.redo_with_history(document_id, viewport, preferences.validate_storage_round_trip, responses),
DocumentMessage::DocumentHistoryBackward => self.undo_with_history(document_id, viewport, resource_storage, responses),
DocumentMessage::DocumentHistoryForward => self.redo_with_history(document_id, viewport, resource_storage, responses),
DocumentMessage::DocumentStructureChanged => {
if layers_panel_open {
self.network_interface.load_structure();
@@ -570,7 +563,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
responses.add(DocumentMessage::AbortTransaction);
self.node_graph_handler.drag_start = None;
self.node_graph_handler.select_if_not_dragged = None;
self.node_graph_handler.duplicated_in_drag = false;
}
// Abort box selection
else if self.node_graph_handler.box_selection_start.is_some() {
@@ -1816,7 +1808,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, name: String, path: Option<std::path::PathBuf>) -> Self {
pub fn from_storage(interface: NodeNetworkInterface, storage: document_format::GddV1, name: String, path: Option<std::path::PathBuf>) -> Self {
let mut document = Self {
network_interface: interface,
name,
@@ -1829,7 +1821,7 @@ impl DocumentMessageHandler {
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.history.set_storage(Some(storage));
document
}
@@ -1841,12 +1833,6 @@ 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();
}
@@ -2030,14 +2016,9 @@ impl DocumentMessageHandler {
self.history.storage_mut()
}
/// 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.history.set_storage(storage, declarations);
}
/// Detach the `Gdd` working copy.
pub fn clear_storage(&mut self) {
self.history.clear_storage();
/// Attach (or clear) the `Gdd` working copy once the mount future resolves.
pub fn set_storage(&mut self, storage: Option<document_format::GddV1>) {
self.history.set_storage(storage);
}
/// Retire the pending staged hot ops into durable Gdd history as one undo unit.
@@ -2045,12 +2026,6 @@ impl DocumentMessageHandler {
self.history.retire_storage_interaction();
}
/// 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();
}
/// 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.
@@ -2062,19 +2037,20 @@ impl DocumentMessageHandler {
return;
}
let view_settings = self.storage_view_settings();
self.history.stage_snapshot(&deltas, &self.network_interface, &self.resources.registry, view_settings, byte_store);
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 that ride along with either kind of staging.
fn storage_view_settings(&self) -> std::collections::BTreeMap<String, document_graph_storage::Value> {
/// 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;
DocumentSettings {
let view_settings = DocumentSettings {
document_ptz: &self.document_ptz,
render_mode: &self.render_mode,
overlays_visibility: &self.overlays_visibility_settings,
@@ -2082,15 +2058,17 @@ impl DocumentMessageHandler {
snapping_state: &self.snapping_state,
collapsed: &self.collapsed,
}
.to_view_map()
.to_view_map();
(view_settings, self.serialize_document())
}
/// Restore `view_settings` map into the document.
pub fn apply_stored_document_settings(&mut self, view_settings: &std::collections::BTreeMap<String, document_graph_storage::Value>) {
pub fn apply_stored_document_settings(&mut self, view_settings: &std::collections::BTreeMap<String, serde_json::Value>) {
use document_graph_storage::attr::session::doc;
fn decode<T: serde::de::DeserializeOwned>(view_settings: &std::collections::BTreeMap<String, document_graph_storage::Value>, key: &str) -> Option<T> {
view_settings.get(key).and_then(|value| document_graph_storage::from_value(value).ok())
fn decode<T: serde::de::DeserializeOwned>(view_settings: &std::collections::BTreeMap<String, serde_json::Value>, key: &str) -> Option<T> {
view_settings.get(key).and_then(|value| serde_json::from_value(value.clone()).ok())
}
if let Some(value) = decode(view_settings, doc::PTZ) {
@@ -2113,27 +2091,24 @@ impl DocumentMessageHandler {
}
}
/// Move the `Gdd` undo/redo cursor, swap in the interface rebuilt from it, and autosave so the legacy
/// document matches the cursor. `had_oracle` records whether the legacy snapshot already applied, so the
/// rebuild can be compared against it.
fn drive_storage_undo_redo(&mut self, document_id: DocumentId, had_oracle: bool, undo: bool, validate: bool, responses: &mut VecDeque<Message>) {
match self.history.move_cursor(undo) {
Ok(rebuilt) => {
self.apply_gdd_cursor_rebuild(rebuilt, had_oracle, validate, responses);
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
}
Err(CursorMoveError::NotMoved) => {}
// Without the legacy snapshot the interface stayed put, so the cursor has to follow it back.
Err(CursorMoveError::RebuildFailed) => {
if !had_oracle {
self.history.revert_cursor(undo);
}
}
}
/// Move the `Gdd` undo/redo cursor and spawn the async future that rebuilds the
/// interface from the cursor and swaps it in. `had_oracle` records whether the legacy snapshot already
/// applied, so the completion can compare; it travels with the spawned message. Returns whether the
/// cursor moved, so callers know a rebuild is pending.
fn drive_storage_undo_redo(&mut self, document_id: DocumentId, resource_storage: &ResourceStorageMessageHandler, had_oracle: bool, undo: bool, responses: &mut VecDeque<Message>) -> bool {
let Some(gdd) = self.history.move_cursor(undo) else { return false };
responses.add(crate::messages::portfolio::document_storage_io::rebuild_gdd_cursor(
gdd,
resource_storage.resources_mut(),
document_id,
had_oracle,
));
true
}
/// 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>) {
pub(crate) 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);
std::mem::swap(&mut rebuilt.resolved_types, &mut self.network_interface.resolved_types);
rebuilt.load_structure();
@@ -2444,7 +2419,7 @@ impl DocumentMessageHandler {
paths
}
pub fn undo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
pub fn undo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, resource_storage: &ResourceStorageMessageHandler, responses: &mut VecDeque<Message>) {
let legacy_applied = if let Some(previous_network) = self.undo(viewport, responses) {
self.history.push_redo(previous_network);
true
@@ -2452,7 +2427,7 @@ impl DocumentMessageHandler {
false
};
self.drive_storage_undo_redo(document_id, legacy_applied, true, validate, responses);
self.drive_storage_undo_redo(document_id, resource_storage, legacy_applied, true, responses);
}
/// Installs a history snapshot as the active network interface, carrying over the current view state and structure load, and returns the replaced interface.
@@ -2486,7 +2461,7 @@ impl DocumentMessageHandler {
Some(previous_network)
}
pub fn redo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
pub fn redo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, resource_storage: &ResourceStorageMessageHandler, responses: &mut VecDeque<Message>) {
let legacy_applied = if let Some(previous_network) = self.redo(viewport, responses) {
self.history.push_undo(previous_network);
true
@@ -2494,7 +2469,7 @@ impl DocumentMessageHandler {
false
};
self.drive_storage_undo_redo(document_id, legacy_applied, false, validate, responses);
self.drive_storage_undo_redo(document_id, resource_storage, legacy_applied, false, responses);
}
pub fn redo(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) -> Option<NodeNetworkInterface> {
@@ -2829,9 +2804,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_i64, 1_i64);
let (existing_index, new_index) = (0_f64, 1_f64);
let existing_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Integer(existing_index), false))]);
let existing_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(existing_index), false))]);
let existing_index_id = NodeId::new();
self.network_interface.insert_node(existing_index_id, existing_index_template, &[]);
self.network_interface.move_node_to_chain_start(&existing_index_id, layer, &[], false);
@@ -2853,7 +2828,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::Integer(new_index), false))]);
let new_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(new_index), false))]);
let new_index_id = NodeId::new();
self.network_interface.insert_node(new_index_id, new_index_template, &[]);
self.network_interface.move_node_to_chain_start(&new_index_id, new_layer, &[], false);
@@ -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 i64);
let blend_node_id = modify_inputs.insert_blend_data(layer, count as f64);
(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::Number(diameter), false)),
Some(NodeInput::value(TaggedValue::Number(hardness), false)),
Some(NodeInput::value(TaggedValue::Number(flow), false)),
Some(NodeInput::value(TaggedValue::F64(diameter), false)),
Some(NodeInput::value(TaggedValue::F64(hardness), false)),
Some(NodeInput::value(TaggedValue::F64(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::Number(rotation), false),
NodeInput::value(TaggedValue::F64(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::Number(rotation)) = inputs[2].as_value() { rotation } else { 0. };
let rotation = if let Some(&TaggedValue::F64(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: i64) -> NodeId {
pub fn insert_blend_data(&mut self, layer: LayerNodeIdentifier, count: f64) -> NodeId {
let blend = resolve_network_node_type("Blend")
.expect("Blend node does not exist")
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::Integer(count), false))]);
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::F64(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::Number(0.5), false))]);
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::F64(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::Number(1.), false)), Some(NodeInput::value(TaggedValue::Bool(false), false))]);
.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(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);
@@ -157,13 +157,13 @@ impl<'a> ModifyInputsContext<'a> {
self.network_interface.insert_node(shape_id, shape, &[]);
self.network_interface.move_node_to_chain_start(&shape_id, layer, &[], self.import);
if include_fill {
let fill = resolve_proto_node_type(graphene_std::vector_nodes::fill::IDENTIFIER)
.expect("Fill node does not exist")
if include_transform {
let transform = resolve_proto_node_type(graphene_std::transform_nodes::transform::IDENTIFIER)
.expect("Transform node does not exist")
.default_node_template();
let fill_id = NodeId::new();
self.network_interface.insert_node(fill_id, fill, &[]);
self.network_interface.move_node_to_chain_start(&fill_id, layer, &[], self.import);
let transform_id = NodeId::new();
self.network_interface.insert_node(transform_id, transform, &[]);
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[], self.import);
}
if include_stroke {
@@ -175,14 +175,13 @@ impl<'a> ModifyInputsContext<'a> {
self.network_interface.move_node_to_chain_start(&stroke_id, layer, &[], self.import);
}
// Ensure the transform node occurs after the stroke node.
if include_transform {
let transform = resolve_proto_node_type(graphene_std::transform_nodes::transform::IDENTIFIER)
.expect("Transform node does not exist")
if include_fill {
let fill = resolve_proto_node_type(graphene_std::vector_nodes::fill::IDENTIFIER)
.expect("Fill node does not exist")
.default_node_template();
let transform_id = NodeId::new();
self.network_interface.insert_node(transform_id, transform, &[]);
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[], self.import);
let fill_id = NodeId::new();
self.network_interface.insert_node(fill_id, fill, &[]);
self.network_interface.move_node_to_chain_start(&fill_id, layer, &[], self.import);
}
}
@@ -194,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::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::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::Bool(typesetting.max_width.is_some()), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.max_width.unwrap_or(100.)), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.max_width.unwrap_or(100.)), false)),
Some(NodeInput::value(TaggedValue::Bool(typesetting.max_height.is_some()), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.max_height.unwrap_or(100.)), false)),
Some(NodeInput::value(TaggedValue::F64(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)
@@ -527,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::Number(opacity * 100.), false),
NodeInput::value(TaggedValue::F64(opacity * 100.), false),
false,
);
}
@@ -556,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::Number(fill * 100.), false),
NodeInput::value(TaggedValue::F64(fill * 100.), false),
false,
);
}
@@ -667,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::Numbers(positions), false), false);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64Array(positions), false), false);
}
/// The 'Gradient Midpoints' counterpart of [`Self::gradient_positions_set`], likewise update-only.
@@ -691,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::Numbers(midpoints), false), false);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64Array(midpoints), false), false);
}
/// Update the transform to map the unit gradient ((0,0), (1, 0)) to the geometry's local space.
@@ -866,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::Number(stroke.weight), false), true);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.weight), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::AlignInput);
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);
@@ -874,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::Number(stroke.join_miter_limit), false), false);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.join_miter_limit), false), false);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::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::Number(stroke.dash_offset), false), true);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(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.
@@ -3,7 +3,7 @@ mod document_history;
mod document_message;
mod document_message_handler;
#[cfg(test)]
pub(crate) mod storage_tests;
mod storage_tests;
pub mod data_panel;
pub mod graph_operation;
@@ -15,7 +15,7 @@ pub mod resource;
pub mod utility_types;
pub(crate) use document_diff::diff_networks;
pub(crate) use document_history::{CursorMoveError, DocumentHistory};
pub(crate) use document_history::DocumentHistory;
#[doc(inline)]
pub use document_message::{DocumentMessage, DocumentMessageDiscriminant};
#[doc(inline)]
@@ -422,7 +422,7 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
let half_viewport = viewport.center_in_viewport_space().into_dvec2();
let start_offset = viewport_to_document.transform_vector2(self.mouse_position - half_viewport);
let end_offset = viewport_to_document.transform_vector2(ipp.mouse.position - half_viewport);
let angle = start_offset.try_angle_to(end_offset).unwrap_or(0.);
let angle = start_offset.angle_to(end_offset);
tilt_raw_not_snapped + angle
};
@@ -40,30 +40,17 @@ 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)?;
// 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 {
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");
return 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()
widget_override_lambda(*node_id, index, self)
.map_err(|error| log::error!("Error in widget override lambda: {error}"))
.ok()
} else {
None
}
}
}
@@ -361,14 +348,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::Number(1.), false)],
inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::value(TaggedValue::F64(1.), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 2)),
..Default::default()
},
// 3: As Number (the integer count enters the network's decimal math)
// 3: Floor (integer count per subpath)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER),
inputs: vec![NodeInput::import(item!(i64), 1)],
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::floor::IDENTIFIER),
inputs: vec![NodeInput::import(item!(f64), 1)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 13)),
..Default::default()
},
@@ -382,14 +369,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::Number(1.), false)],
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::F64(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::Integer(0), false)],
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::U32(0), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 7)),
..Default::default()
},
@@ -438,7 +425,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::Number(0.9999999999), false)],
inputs: vec![NodeInput::node(NodeId(12), 0), NodeInput::value(TaggedValue::F64(0.9999999999), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 7)),
..Default::default()
},
@@ -472,14 +459,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::Number(1.), false)],
inputs: vec![NodeInput::node(NodeId(3), 0), NodeInput::value(TaggedValue::F64(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::Number(1.), false)],
inputs: vec![NodeInput::node(NodeId(5), 0), NodeInput::value(TaggedValue::F64(1.), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 14)),
..Default::default()
},
@@ -492,7 +479,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
}),
inputs: vec![
NodeInput::type_default(list!(Vector), true),
NodeInput::value(TaggedValue::Integer(10), false),
NodeInput::value(TaggedValue::F64(10.), false),
NodeInput::value(TaggedValue::Bool(Default::default()), false),
NodeInput::value(TaggedValue::InterpolationDistribution(Default::default()), false),
NodeInput::type_default(item!(Vector), false),
@@ -814,7 +801,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
inputs: vec![
NodeInput::import(item!(String), 0),
NodeInput::import(item!(String), 1),
NodeInput::import(item!(i64), 2),
NodeInput::import(item!(f64), 2),
NodeInput::import(item!(bool), 3),
NodeInput::import(item!(bool), 4),
],
@@ -824,14 +811,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::Integer(0), false)],
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::F64(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::Integer(0), false)],
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::F64(0.), false)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::remove_at_index::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 2)),
..Default::default()
@@ -846,7 +833,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::Integer(0), false),
NodeInput::value(TaggedValue::F64(0.), false),
NodeInput::value(TaggedValue::Bool(false), false),
NodeInput::value(TaggedValue::Bool(false), false),
],
@@ -940,6 +927,7 @@ 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));
@@ -1110,11 +1098,6 @@ 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| {
@@ -1368,7 +1351,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::Number(val)) = input.as_non_exposed_value() {
if let Some(&TaggedValue::F64(val)) = input.as_non_exposed_value() {
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(val))
@@ -1377,7 +1360,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::Number(number_input.value.unwrap()),
|number_input: &NumberInput| TaggedValue::F64(number_input.value.unwrap()),
node_id,
index,
))
@@ -1465,22 +1448,6 @@ fn static_input_properties() -> InputProperties {
"text_area".to_string(),
Box::new(|node_id, index, context| Ok(vec![LayoutGroup::row(node_properties::text_area_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context)))])),
);
map.insert(
// A math expression, flagged with a warning icon while it fails to parse
"math_expression".to_string(),
Box::new(|node_id, index, context| {
let info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
Ok(vec![LayoutGroup::row(node_properties::math_expression_widget(info, false))])
}),
);
map.insert(
// Like `math_expression`, where a lone reducer token like `+` or `min` applied across the node's items is also valid
"math_expression_or_reducer".to_string(),
Box::new(|node_id, index, context| {
let info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
Ok(vec![LayoutGroup::row(node_properties::math_expression_widget(info, true))])
}),
);
map.insert(
"text_font".to_string(),
Box::new(|node_id, index, context| {
@@ -60,7 +60,6 @@ pub enum NodeGraphMessage {
DisconnectInput {
input_connector: InputConnector,
},
DisconnectRootNode,
EnterNestedNetwork,
DuplicateSelectedNodes,
ExposeInput {
@@ -57,8 +57,6 @@ pub struct NodeGraphMessageHandler {
widgets: [LayoutGroup; 2],
/// Used to add a transaction for the first node move when dragging.
begin_dragging: bool,
/// Track if nodes were duplicated during the current drag via Alt-drag.
pub duplicated_in_drag: bool,
/// Used to prevent entering a nested network if the node is dragged after double clicking
node_has_moved_in_drag: bool,
/// If dragging the selected nodes, this stores the starting position both in viewport and node graph coordinates,
@@ -408,12 +406,20 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
NodeGraphMessage::DisconnectInput { input_connector } => {
network_interface.disconnect_input(&input_connector, selection_network_path);
}
NodeGraphMessage::DisconnectRootNode => {
network_interface.start_previewing_without_restore(selection_network_path);
}
NodeGraphMessage::DuplicateSelectedNodes => {
let all_selected_nodes = network_interface.upstream_chain_nodes(selection_network_path);
let copy_ids = all_selected_nodes.iter().enumerate().map(|(new, id)| (*id, NodeId(new as u64))).collect::<HashMap<NodeId, NodeId>>();
// Copy the selected nodes
let nodes = network_interface.copy_nodes(&copy_ids, selection_network_path).collect::<Vec<_>>();
let new_ids = nodes.iter().map(|(id, _)| (*id, NodeId::new())).collect::<HashMap<_, _>>();
responses.add(DocumentMessage::AddTransaction);
Self::duplicate_selected_nodes(network_interface, selection_network_path, responses);
responses.add(NodeGraphMessage::AddNodes { nodes, new_ids: new_ids.clone() });
responses.add(NodeGraphMessage::SelectedNodesSet {
nodes: new_ids.values().cloned().collect(),
});
}
NodeGraphMessage::EnterNestedNetwork => {
// Do not enter the nested network if the node was dragged
@@ -790,7 +796,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
if self.drag_start.is_some() {
self.drag_start = None;
self.select_if_not_dragged = None;
self.duplicated_in_drag = false;
responses.add(DocumentMessage::AbortTransaction);
responses.add(NodeGraphMessage::SelectedNodesSet {
nodes: self.selection_before_pointer_down.clone(),
@@ -1036,7 +1041,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
.collect::<Vec<_>>();
self.begin_dragging = true;
self.node_has_moved_in_drag = false;
self.duplicated_in_drag = false;
self.update_node_graph_hints(responses);
}
@@ -1092,18 +1096,8 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
self.wire_in_progress_to_connector = Some(point);
// Disconnect if the wire was previously connected to an input
if let Some(disconnecting) = &self.disconnecting {
let mut disconnect_root_node = false;
if let Previewing::Yes { root_node_to_restore } = network_interface.previewing(selection_network_path)
&& root_node_to_restore.is_some()
&& *disconnecting == InputConnector::Export(0)
{
disconnect_root_node = true;
}
if disconnect_root_node {
responses.add(NodeGraphMessage::DisconnectRootNode);
} else {
responses.add(NodeGraphMessage::DisconnectInput { input_connector: *disconnecting });
}
// Previewing leaves the export alone, so dragging its wire off is an ordinary disconnect
responses.add(NodeGraphMessage::DisconnectInput { input_connector: *disconnecting });
// Update the frontend that the node is disconnected
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(NodeGraphMessage::SendGraph);
@@ -1164,17 +1158,13 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
if self.begin_dragging {
self.begin_dragging = false;
if ipp.keyboard.get(Key::Alt as usize) {
// Duplicate nodes inline within the existing PointerDown transaction.
// This means a completed Alt-drag is one undo step, and aborting (right-click / Escape)
// rolls back both the duplication and the move with a single plain AbortTransaction.
Self::duplicate_selected_nodes(network_interface, selection_network_path, responses);
responses.add(NodeGraphMessage::DuplicateSelectedNodes);
// Duplicating sets a 2x2 offset, so shift the nodes back to the original position
responses.add(NodeGraphMessage::ShiftSelectedNodesByAmount {
graph_delta: IVec2::new(-2, -2),
rubber_band: false,
});
self.preview_on_mouse_up = None;
self.duplicated_in_drag = true;
}
}
@@ -1480,7 +1470,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
self.drag_start = None;
self.begin_dragging = false;
self.duplicated_in_drag = false;
self.box_selection_start = None;
self.wire_in_progress_from_connector = None;
@@ -1527,17 +1516,15 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
// Collect the distance to move the shaken nodes after the undo
let graph_delta = IVec2::new(((point.x - drag_start.start_x) / 24.).round() as i32, ((point.y - drag_start.start_y) / 24.).round() as i32);
if !self.duplicated_in_drag {
// Keep the incremental rounding baseline in sync with the total shift reapplied below
drag_start.round_x = graph_delta.x;
drag_start.round_y = graph_delta.y;
// Keep the incremental rounding baseline in sync with the total shift reapplied below
drag_start.round_x = graph_delta.x;
drag_start.round_y = graph_delta.y;
// Undo to the state of the graph before shaking (skip for Alt-drag to avoid removing the duplicates)
responses.add(DocumentMessage::AbortTransaction);
// Undo to the state of the graph before shaking
responses.add(DocumentMessage::AbortTransaction);
// Add a history step to abort to the state before shaking if right clicked
responses.add(DocumentMessage::StartTransaction);
}
// Add a history step to abort to the state before shaking if right clicked
responses.add(DocumentMessage::StartTransaction);
let Some(selected_nodes) = network_interface.selected_nodes_in_nested_network(selection_network_path) else {
log::error!("Could not get selected nodes in ShakeNode");
@@ -1622,9 +1609,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
}
}
}
if !self.duplicated_in_drag {
responses.add(NodeGraphMessage::ShiftSelectedNodesByAmount { graph_delta, rubber_band: false });
}
responses.add(NodeGraphMessage::ShiftSelectedNodesByAmount { graph_delta, rubber_band: false });
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(NodeGraphMessage::SendGraph);
}
@@ -2262,20 +2247,6 @@ impl NodeGraphMessageHandler {
common
}
fn duplicate_selected_nodes(network_interface: &NodeNetworkInterface, selection_network_path: &[NodeId], responses: &mut VecDeque<Message>) {
let all_selected_nodes = network_interface.upstream_chain_nodes(selection_network_path);
let copy_ids = all_selected_nodes.iter().enumerate().map(|(new, id)| (*id, NodeId(new as u64))).collect::<HashMap<NodeId, NodeId>>();
let nodes = network_interface.copy_nodes(&copy_ids, selection_network_path).collect::<Vec<_>>();
let new_ids = nodes.iter().map(|(id, _)| (*id, NodeId::new())).collect::<HashMap<_, _>>();
responses.add(NodeGraphMessage::AddNodes { nodes, new_ids: new_ids.clone() });
responses.add(NodeGraphMessage::SelectedNodesSet {
nodes: new_ids.values().cloned().collect(),
});
}
/// Send the cached layout to the frontend for the control bar at the top of the node panel
fn send_node_bar_layout(&self, responses: &mut VecDeque<Message>) {
responses.add(LayoutMessage::SendLayout {
@@ -2707,8 +2678,8 @@ impl NodeGraphMessageHandler {
wire_path_update: None,
}));
if let Some(wire_to_root) = network_interface.wire_to_root(graph_wire_style, breadcrumb_network_path) {
added_wires.push(wire_to_root);
if let Some(wire_to_preview) = network_interface.wire_to_preview(graph_wire_style, breadcrumb_network_path) {
added_wires.push(wire_to_preview);
} else {
added_wires.push(WirePathUpdate {
id: NodeId(u64::MAX),
@@ -2759,11 +2730,8 @@ impl NodeGraphMessageHandler {
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;
// Asked of the preview itself rather than inferred from the export, which previewing no longer rewires
let previewed = matches!(network_interface.previewing(breadcrumb_network_path), Previewing::Yes { previewed } if previewed.node_id == node_id);
let locked = network_interface.is_locked(&node_id, breadcrumb_network_path);
@@ -2945,7 +2913,6 @@ impl Default for NodeGraphMessageHandler {
widgets: [LayoutGroup::row(Vec::new()), LayoutGroup::row(Vec::new())],
drag_start: None,
begin_dragging: false,
duplicated_in_drag: false,
node_has_moved_in_drag: false,
shift_without_push: false,
box_selection_start: None,
@@ -2977,7 +2944,6 @@ impl PartialEq for NodeGraphMessageHandler {
&& self.widgets == other.widgets
&& self.drag_start == other.drag_start
&& self.begin_dragging == other.begin_dragging
&& self.duplicated_in_drag == other.duplicated_in_drag
&& self.node_has_moved_in_drag == other.node_has_moved_in_drag
&& self.box_selection_start == other.box_selection_start
&& self.initial_disconnecting == other.initial_disconnecting
@@ -2,7 +2,6 @@
use super::document_node_definitions::{NODE_OVERRIDES, NodePropertiesContext};
use super::utility_types::FrontendGraphDataType;
use crate::messages::layout::utility_types::tooltip_markdown::{escape_markdown, markdown_code_block, markdown_code_span};
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
@@ -25,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::{CPU, GPU, Image, Raster};
use graphene_std::raster_types::Image;
use graphene_std::text::{Font, TextAlign};
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
use graphene_std::transfer_curve::TransferCurve;
@@ -39,9 +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 math_parser::parser::MessagePart;
use std::path::PathBuf;
pub(crate) fn string_properties(text: &str) -> Vec<LayoutGroup> {
@@ -173,19 +170,14 @@ pub fn start_widgets(parameter_widgets_info: &ParameterWidgetsInfo) -> Vec<Widge
widgets
}
/// The presentation of a parameter's widget, sourced from the node's field metadata: numeric bounds, widget modes, and unit of measure.
/// The numeric bounds and widget mode of a number parameter, sourced from the node's field metadata.
#[derive(Clone, Copy, Default)]
pub(crate) struct ParameterOptions {
pub(crate) struct NumberOptions {
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.
@@ -214,25 +206,29 @@ 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::Number(value) => Some(*value),
TaggedValue::F64(value) => Some(*value),
TaggedValue::F32(value) => Some(*value as f64),
_ => None,
}
}
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 {
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 {
soft_min,
soft_max,
hard_min,
hard_max,
slider,
multiline,
progression,
unit,
display_decimal_places,
step,
} = options;
} = number_options;
let mut number_input = NumberInput::default();
if slider {
number_input = number_input.mode_range();
@@ -247,8 +243,10 @@ pub(crate) fn property_from_type(node_id: NodeId, index: usize, ty: &Type, optio
number_input = number_input.step(step);
}
// 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.
// 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.
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 });
@@ -262,11 +260,12 @@ pub(crate) fn property_from_type(node_id: NodeId, index: usize, ty: &Type, optio
.range_max(Some(extent_max).filter(|bound| bound.is_finite()))
};
// A range-mode number hard-clamped at both ends becomes a range slider beside its number input, unless a soft bound lets typing pass it
// A range-mode number 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.
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| -> LayoutGroup {
let fixed_extent = number_input.mode == NumberInputMode::Range && no_soft_bounds && hard_both_ends;
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);
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);
@@ -299,98 +298,112 @@ pub(crate) fn property_from_type(node_id: NodeId, index: usize, ty: &Type, optio
let mut extra_widgets = vec![];
let widgets = match ty {
Type::Concrete(concrete_type) => {
use std::any::TypeId;
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(),
// 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>()
}
// For all other types, use TypeId-based matching
_ => {
use std::any::TypeId;
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())),
// 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())),
}
}
}
}
Type::Item(element) => return property_from_type(node_id, index, element, options, context),
Type::Item(element) => return property_from_type(node_id, index, element, number_options, unit, display_decimal_places, step, context),
Type::List(element) => match element.as_ref() {
Type::Concrete(element_type) if element_type.name == std::any::type_name::<f64>() => array_of_number_widget(default_info, TextInput::default()).into(),
_ => return Err(unsupported_widgets(default_info, ty.to_string())),
},
Type::Generic(_) => vec![TextLabel::new("Generic Type (Not Supported)").widget_instance()].into(),
Type::Fn(_, out) => return property_from_type(node_id, index, out, options, context),
Type::Future(out) => return property_from_type(node_id, index, out, options, context),
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),
};
extra_widgets.push(widgets);
@@ -417,60 +430,6 @@ pub fn text_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Vec<WidgetIn
widgets
}
/// A math expression's text field, with a warning icon in the assist area giving the error in its tooltip while the expression fails to parse.
pub fn math_expression_widget(mut parameter_widgets_info: ParameterWidgetsInfo, accepts_reducers: bool) -> Vec<WidgetInstance> {
let Some(TaggedValue::String(expression)) = parameter_widgets_info.input().and_then(|input| input.as_non_exposed_value()) else {
return text_widget(parameter_widgets_info);
};
let Some(error) = math_expression_error(expression, accepts_reducers) else {
return text_widget(parameter_widgets_info);
};
// The 12px icon is padded to a checkbox's 16px so the field still lines up with the rows around it
parameter_widgets_info.blank_assist = false;
let mut widgets = start_widgets(&parameter_widgets_info);
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
IconLabel::new("Warning").tooltip_label("Invalid Math Expression").tooltip_description(error).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextInput::new(expression.clone())
.on_update(parameter_widgets_info.update_value(|x: &TextInput| TaggedValue::String(x.value.clone())))
.on_commit(commit_value)
.widget_instance(),
]);
widgets
}
/// Why a math expression fails to parse, as tooltip Markdown, or `None` when it parses. Where the node applies a lone operator or
/// function name like `+` or `min` across its items, that counts as valid too. An error at a place in the expression repeats the
/// expression with carets under that place, as a compiler does.
fn math_expression_error(expression: &str, accepts_reducers: bool) -> Option<String> {
// A blank expression is unfinished rather than wrong, so it goes unflagged like any empty field
if expression.trim().is_empty() || (accepts_reducers && math_parser::reducer::classify_reducer(expression, math_parser::context::NothingMap).is_some()) {
return None;
}
let error = math_parser::ast::Node::try_parse_from_str(expression).err()?;
// The quoted code may be the expression's own text, so it goes in a span nothing inside can close, and the prose is escaped
let messages = error.messages().iter().map(|message| {
let parts = message.parts().iter().map(|part| match part {
MessagePart::Text(text) => escape_markdown(text),
MessagePart::Code(code) => markdown_code_span(code),
});
let prose = parts.collect::<String>();
// The carets and their label line up under the expression's characters, with one caret where the span is empty, like at the end of the input
let Some(span) = message.span() else { return prose };
let indent = " ".repeat(expression.get(..span.start).map_or(0, |text| text.chars().count()));
let carets = "^".repeat(expression.get(span.start..span.end).map_or(0, |text| text.chars().count()).max(1));
format!("{prose}\n{}", markdown_code_block(&format!("{expression}\n{indent}{carets}\n{indent}error here")))
});
Some(messages.collect::<Vec<_>>().join("\n"))
}
pub fn text_area_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Vec<WidgetInstance> {
let mut widgets = start_widgets(&parameter_widgets_info);
@@ -848,7 +807,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.widget_instance(),
]);
}
Some(&TaggedValue::Number(value)) => {
Some(&TaggedValue::F64(value)) => {
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(value))
@@ -887,14 +846,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::Numbers)
.map(TaggedValue::F64Array)
};
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::Numbers(values)) = &input.as_non_exposed_value() {
if let Some(TaggedValue::F64Array(values)) = &input.as_non_exposed_value() {
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
text_input
@@ -1049,7 +1008,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::Number(x)) = input.as_non_exposed_value() {
if let Some(&TaggedValue::F64(x)) = input.as_non_exposed_value() {
let whole_part = x.trunc();
let fractional_part = x.fract();
@@ -1062,7 +1021,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::Number(whole_part + input.value.unwrap())))
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::F64(whole_part + input.value.unwrap())))
.on_commit(commit_value)
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
@@ -1074,7 +1033,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::Number(input.value.unwrap() + fractional_part)))
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::F64(input.value.unwrap() + fractional_part)))
.on_commit(commit_value)
.widget_instance(),
])
@@ -1161,19 +1120,35 @@ pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
return vec![];
};
match input.as_non_exposed_value() {
Some(&TaggedValue::Number(x)) => widgets.extend_from_slice(&[
Some(&TaggedValue::F64(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::Number(x.value.unwrap())))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::F64(x.value.unwrap())))
.on_commit(commit_value)
.widget_instance(),
]),
Some(&TaggedValue::Integer(x)) => widgets.extend_from_slice(&[
Some(&TaggedValue::F32(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::Integer(x.value.unwrap().round() as i64)))
.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_commit(commit_value)
.widget_instance(),
]),
@@ -1182,7 +1157,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::Number(x.value.unwrap())))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::F64(x.value.unwrap())))
.on_commit(commit_value)
.widget_instance(),
]),
@@ -1226,96 +1201,6 @@ 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);
@@ -1834,7 +1719,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::Number(value) = tagged { Some(*value) } else { None })
.and_then(|tagged| if let TaggedValue::F32(value) = tagged { Some(*value as f64) } else { None })
.unwrap_or(0.);
(exposed, value)
})
@@ -1957,7 +1842,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodePropertiesCont
NodeGraphMessage::SetInputValue {
node_id,
input_index,
value: TaggedValue::Number(scale.value(scale_position)).into(),
value: TaggedValue::F32(scale.value(scale_position) as f32).into(),
}
.into()
}
@@ -1993,7 +1878,11 @@ 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::Number(widget.value.unwrap_or(0.)), node_id, input_index))
.on_update(update_value_at_index(
move |widget: &NumberInput| TaggedValue::F32(widget.value.unwrap_or(0.) as f32),
node_id,
input_index,
))
.on_commit(commit_value)
.widget_instance(),
);
@@ -2017,8 +1906,8 @@ pub(crate) fn hue_saturation_properties(node_id: NodeId, context: &mut NodePrope
Some(TaggedValue::HueSaturationRange(range)) => *range,
_ => HueSaturationRange::Master,
};
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,
let f32_value = |parameter: &ParameterRef| match document_node.inputs.get(parameter.input_index).and_then(|input| input.as_value()) {
Some(TaggedValue::F32(value)) => *value,
_ => 0.,
};
@@ -2086,9 +1975,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(slider_value(&hue) / 360.)
toward_hue(f32_value(&hue) / 360.)
} else if let Some([_, range_start, range_end, _]) = &range_values {
let (start, end) = (slider_value(range_start), slider_value(range_end));
let (start, end) = (f32_value(range_start), f32_value(range_end));
let center = start + (end - start).rem_euclid(360.) / 2.;
toward_hue(center / 360.)
} else {
@@ -2232,7 +2121,8 @@ 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::Number(value)) => (value, TaggedValue::Number),
Some(&TaggedValue::F64(value)) => (value, TaggedValue::F64),
Some(&TaggedValue::F32(value)) => (value as f64, |value| TaggedValue::F32(value as f32)),
_ => return widgets,
};
let ParameterWidgetsInfo { node_id, index, .. } = parameter_widgets_info;
@@ -2294,7 +2184,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::Number(value) = tagged { Some(*value) } else { None });
.and_then(|tagged| if let TaggedValue::F32(value) = tagged { Some(*value as f64) } else { None });
// Only add the slider and number widgets when the input is not exposed
if let Some(current) = current {
@@ -2303,7 +2193,7 @@ fn gradient_slider_row(
max: value_max,
default: Some(default_value),
};
let value_at = move |position| TaggedValue::Number(slider.value(position));
let value_at = move |position| TaggedValue::F32(slider.value(position) as f32);
row.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
row.push(
@@ -2326,7 +2216,11 @@ fn gradient_slider_row(
.min_width(60)
.max_width(60)
.display_decimal_places(0)
.on_update(update_value_at_index(move |widget: &NumberInput| TaggedValue::Number(widget.value.unwrap_or(0.)), node_id, input_index))
.on_update(update_value_at_index(
move |widget: &NumberInput| TaggedValue::F32(widget.value.unwrap_or(0.) as f32),
node_id,
input_index,
))
.on_commit(commit_value)
.widget_instance(),
);
@@ -2748,7 +2642,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::Integer(x)) => x,
Some(&TaggedValue::U32(x)) => x,
_ => 2,
};
let decimal_sep = match document_node.input(DecimalSeparatorInput).and_then(|input| input.as_non_exposed_value()) {
@@ -3072,7 +2966,10 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
return Vec::new();
};
let mut options = ParameterOptions::default();
let mut number_options = NumberOptions::default();
let mut display_decimal_places = None;
let mut step = None;
let mut unit_suffix = None;
let input_type = match implementation {
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => 'early_return: {
// Clone to end the `network_interface` borrow held via `implementation`, freeing the mutable borrow `input_type` needs below
@@ -3085,18 +2982,16 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
.get(&proto_node_identifier)
.and_then(|metadata| metadata.fields.get(input_index))
{
options = ParameterOptions {
number_options = NumberOptions {
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();
}
@@ -3124,7 +3019,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, options, context).unwrap_or_else(|value| value)
property_from_type(node_id, input_index, &input_type, number_options, unit_suffix, display_decimal_places, step, context).unwrap_or_else(|value| value)
});
layout.extend(row);
@@ -3509,6 +3404,63 @@ 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,
@@ -3747,53 +3699,3 @@ 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)));
}
#[test]
fn math_expressions_are_flagged_only_when_they_fail_to_parse() {
for (expression, accepts_reducers) in [("x * 2", false), ("", false), (" ", true), ("min", false), ("+", true), ("min", true)] {
assert_eq!(math_expression_error(expression, accepts_reducers), None, "`{expression}`");
}
assert!(math_expression_error("2 +", false).is_some());
assert!(math_expression_error("+", false).is_some(), "a lone reducer is an error where the node applies none");
assert_eq!(math_expression_error("sin(I)", true).as_deref(), Some("A matrix stands where a value is needed"));
}
#[test]
fn math_expression_errors_quote_the_expression_safely() {
// The expression's own text sits in code it can't close, while the message's own code keeps its formatting, and the expression
// repeats in a block below with labeled carets under the error's span
assert_eq!(math_expression_error("`abc", false).as_deref(), Some("`` `abc `` is not recognized\n```\n`abc\n^^^^\nerror here\n```"));
assert_eq!(
math_expression_error("7 % 3", false).as_deref(),
Some("`%` is reserved for percentages, so the remainder is written `mod(a, b)`\n```\n7 % 3\n ^\n error here\n```")
);
assert!(math_expression_error("(1", false).unwrap().ends_with("\n(1\n ^\n error here\n```"));
assert!(math_expression_error("πx @ 2", false).unwrap().ends_with("\nπx @ 2\n ^\n error here\n```"));
assert!(!math_expression_error("sin(I)", false).unwrap().contains('^'), "a sort error has no place to point at");
// A quoted token like `*` is a code span, so it can't pair with another into italics
let error = math_expression_error("2 * * 3", false).unwrap();
let prose = error.lines().next().unwrap();
assert!(prose.starts_with("Found `*`, expected ") && !prose.split('`').step_by(2).any(|text| text.contains('*')), "{error}");
}
}
@@ -33,7 +33,7 @@ impl FrontendGraphDataType {
"Color" => Self::Color,
"Gradient" => Self::Gradient,
"String" => Self::Typography,
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
"f64" | "f32" | "u32" | "u64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
raster if raster.starts_with("Raster") => Self::Raster,
_ => Self::General,
}
@@ -1,215 +0,0 @@
//! Document store lifecycle: discovery, session restore, legacy/storage reconciliation, mode changes, and removal.
use crate::messages::frontend::utility_types::PersistedState;
use crate::messages::portfolio::document_storage_io::document_key;
use crate::messages::prelude::*;
use crate::test_utils::EditorTestUtils;
use document_container::{AnyContainer, AsyncContainer};
fn dispatch(editor: &mut EditorTestUtils, message: impl Into<Message>) -> Vec<FrontendMessage> {
editor.editor.handle_message(message)
}
fn portfolio(editor: &EditorTestUtils) -> &PortfolioMessageHandler {
&editor.editor.dispatcher.message_handlers.portfolio_message_handler
}
fn restart(editor: &mut EditorTestUtils, state: PersistedState) {
dispatch(editor, PortfolioMessage::DestroyAllDocuments);
dispatch(editor, PersistentStateMessage::LoadState { state });
}
fn new_document(editor: &mut EditorTestUtils, name: &str) -> DocumentId {
dispatch(editor, PortfolioMessage::NewDocumentWithName { name: name.into() });
portfolio(editor).active_document_id.unwrap()
}
async fn container(editor: &EditorTestUtils, document_id: DocumentId) -> AnyContainer {
portfolio(editor).document_store().open(document_key(document_id)).await.unwrap()
}
async fn stored_ids(editor: &EditorTestUtils) -> Vec<DocumentId> {
portfolio(editor).document_store().list().await.unwrap().into_iter().map(|key| DocumentId(key.0)).collect()
}
#[tokio::test]
async fn stored_documents_are_discovered_without_session_state() {
let mut editor = EditorTestUtils::create();
let one = new_document(&mut editor, "One");
let two = new_document(&mut editor, "Two");
restart(&mut editor, PersistedState::default());
let state = portfolio(&editor).persisted_state_snapshot();
let mut ids: Vec<_> = state.documents.iter().map(|info| info.id).collect();
ids.sort();
let mut expected = vec![one, two];
expected.sort();
assert_eq!(ids, expected);
assert_ne!(
state.documents[0].name, state.documents[1].name,
"names are not stored in the legacy file, so discovered documents get distinct generated ones"
);
assert_eq!(portfolio(&editor).documents.len(), 2);
assert!(portfolio(&editor).active_document().is_some());
}
#[tokio::test]
async fn session_state_restores_order_names_and_selection() {
let mut editor = EditorTestUtils::create();
new_document(&mut editor, "First");
let selected = new_document(&mut editor, "Second");
let state = portfolio(&editor).persisted_state_snapshot();
let expected: Vec<_> = state.documents.iter().map(|info| (info.id, info.name.clone())).collect();
restart(&mut editor, state);
let restored = portfolio(&editor).persisted_state_snapshot();
assert_eq!(restored.documents.iter().map(|info| (info.id, info.name.clone())).collect::<Vec<_>>(), expected);
assert_eq!(portfolio(&editor).active_document_id, Some(selected));
}
#[tokio::test]
async fn session_entries_without_stored_content_are_dropped() {
let mut editor = EditorTestUtils::create();
let kept = new_document(&mut editor, "Kept");
let mut state = portfolio(&editor).persisted_state_snapshot();
let mut ghost = state.documents[0].clone();
ghost.id = DocumentId(0xdead);
state.documents.push(ghost);
restart(&mut editor, state);
let ids: Vec<_> = portfolio(&editor).persisted_state_snapshot().documents.iter().map(|info| info.id).collect();
assert_eq!(ids, vec![kept]);
}
#[tokio::test]
async fn legacy_only_container_gets_storage() {
let mut editor = EditorTestUtils::create();
let id = DocumentId(0xabc);
let container = container(&editor, id).await;
container.write("legacy.graphite", DocumentMessageHandler::default().serialize_document().as_bytes()).await.unwrap();
restart(&mut editor, PersistedState::default());
assert!(portfolio(&editor).documents.contains_key(&id));
assert!(editor.active_document().storage().is_some());
assert!(container.exists("manifest.json").await);
assert!(container.exists("legacy.graphite").await);
}
#[tokio::test]
async fn legacy_mode_reads_legacy_only_and_leaves_storage_files_alone() {
let mut editor = EditorTestUtils::create();
dispatch(&mut editor, PreferencesMessage::SaveAsGdd { enabled: false });
let id = new_document(&mut editor, "Legacy");
let container = container(&editor, id).await;
assert!(!container.exists("manifest.json").await);
container.write("manifest.json", b"broken").await.unwrap();
restart(&mut editor, PersistedState::default());
assert!(portfolio(&editor).documents.contains_key(&id));
assert!(editor.active_document().storage().is_none());
assert_eq!(container.read("manifest.json").await.unwrap().as_slice(), b"broken");
}
#[tokio::test]
async fn storage_only_container_recovers_and_writes_legacy() {
let mut editor = EditorTestUtils::create();
let id = new_document(&mut editor, "Storage");
let container = container(&editor, id).await;
container.remove("legacy.graphite").await.unwrap();
restart(&mut editor, PersistedState::default());
assert!(portfolio(&editor).documents.contains_key(&id));
assert!(editor.active_document().storage().is_some());
assert!(container.exists("legacy.graphite").await);
}
#[tokio::test]
async fn legacy_wins_over_stale_storage_and_history_is_kept() {
let mut editor = EditorTestUtils::create();
let id = new_document(&mut editor, "Changed");
let container = container(&editor, id).await;
let before = editor.active_document().serialize_document();
let network_before = editor.active_document().document_network().clone();
editor.draw_rect(0., 0., 100., 100.).await;
dispatch(&mut editor, PortfolioMessage::AutoSaveDocument { document_id: id });
container.write("legacy.graphite", before.as_bytes()).await.unwrap();
restart(&mut editor, PersistedState::default());
assert_eq!(editor.active_document().document_network(), &network_before);
let storage = editor.active_document().storage().expect("storage attached");
assert!(storage.can_undo(), "the stale stored state stays reachable as history");
}
#[tokio::test]
async fn unchanged_content_keeps_cursor_and_redo_across_restart() {
let mut editor = EditorTestUtils::create();
let id = new_document(&mut editor, "Undo");
let network_before = editor.active_document().document_network().clone();
editor.draw_rect(0., 0., 100., 100.).await;
dispatch(&mut editor, PortfolioMessage::AutoSaveDocument { document_id: id });
editor.handle_message(DocumentMessage::Undo).await;
assert_eq!(editor.active_document().document_network(), &network_before);
assert!(editor.active_document().storage().unwrap().can_redo());
assert!(editor.active_document().is_auto_saved(), "the rebuild completion autosaves the cursor's network");
restart(&mut editor, PersistedState::default());
assert_eq!(editor.active_document().document_network(), &network_before);
let storage = editor.active_document().storage().expect("storage attached");
assert!(storage.can_redo(), "reopening identical content must not stage a new interaction");
assert!(!storage.can_undo());
}
#[tokio::test]
async fn closing_removes_the_stored_document() {
let mut editor = EditorTestUtils::create();
let id = new_document(&mut editor, "Closed");
assert_eq!(stored_ids(&editor).await, vec![id]);
dispatch(&mut editor, PortfolioMessage::CloseDocument { document_id: id });
assert!(stored_ids(&editor).await.is_empty());
restart(&mut editor, PersistedState::default());
assert!(portfolio(&editor).persisted_state_snapshot().documents.is_empty());
}
#[tokio::test]
async fn storage_preference_attaches_and_drops_sessions() {
let mut editor = EditorTestUtils::create();
dispatch(&mut editor, PreferencesMessage::SaveAsGdd { enabled: false });
let id = new_document(&mut editor, "Toggle");
let container = container(&editor, id).await;
assert!(editor.active_document().storage().is_none());
assert!(container.exists("legacy.graphite").await);
dispatch(&mut editor, PreferencesMessage::SaveAsGdd { enabled: true });
assert!(editor.active_document().storage().is_some());
assert!(container.exists("manifest.json").await);
dispatch(&mut editor, PreferencesMessage::SaveAsGdd { enabled: false });
assert!(editor.active_document().storage().is_none());
}
#[tokio::test]
async fn unreadable_document_is_reported_and_kept_until_discarded() {
let mut editor = EditorTestUtils::create();
let id = DocumentId(7);
container(&editor, id).await.write("legacy.graphite", b"not a document").await.unwrap();
restart(&mut editor, PersistedState::default());
assert!(!portfolio(&editor).documents.contains_key(&id));
assert!(portfolio(&editor).persisted_state_snapshot().documents.is_empty());
assert_eq!(stored_ids(&editor).await, vec![id]);
dispatch(&mut editor, FailedDocumentsMessage::DiscardFailedToLoadDocuments);
assert!(stored_ids(&editor).await.is_empty());
}
@@ -6,7 +6,7 @@
use std::collections::{BTreeSet, HashMap};
use document_graph_storage::{NodeMetadataSource, PeerId, Registry, to_value};
use document_graph_storage::{NodeMetadataSource, PeerId, Registry};
use super::test_support::{load_demo, node_paths};
use crate::messages::portfolio::document::document_message_handler::DocumentMessageHandler;
@@ -28,7 +28,7 @@ fn editor_metadata_round_trip_against_demo() {
let network = interface.document_network().clone();
let conversion = Registry::convert_from_runtime(&network, &source, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
let declarations = conversion.declarations;
let declarations = conversion.declarations().expect("rebuild declarations");
let registry = conversion.registry;
let (_converted_network, entries) = registry.to_runtime_with_metadata(&declarations).expect("to_runtime_with_metadata failed");
@@ -137,7 +137,7 @@ fn editor_interface_rebuild_round_trip() {
let network = original.document_network().clone();
let conversion = Registry::convert_from_runtime(&network, &original_view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
let declarations = conversion.declarations;
let declarations = conversion.declarations().expect("rebuild 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");
@@ -256,7 +256,7 @@ fn rebuilt_interface_keeps_storage_identities() {
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 declarations = conversion.declarations().expect("rebuild 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");
@@ -272,7 +272,10 @@ fn rebuilt_interface_keeps_storage_identities() {
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.
/// Opening an old document runs its upgrades through the ordinary mutators, so the store records them.
/// Those recordings are the document arriving rather than edits to it, so the migration has to leave
/// the buffer empty instead of handing the first commit a pile of changes to the document's own
/// starting state.
#[test]
fn migrating_a_document_records_no_changes() {
let mut document = load_demo("painted-dreams.graphite");
@@ -305,7 +308,7 @@ fn pinned_order_round_trips_through_the_registry() {
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 declarations = conversion.declarations().expect("rebuild 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");
@@ -342,14 +345,26 @@ fn document_settings_round_trip() {
let mut restored = DocumentMessageHandler::default();
restored.apply_stored_document_settings(&view_settings);
assert_eq!(to_value(&restored.render_mode).unwrap(), to_value(&document.render_mode).unwrap(), "render_mode");
assert_eq!(to_value(&restored.rulers_visible).unwrap(), to_value(&document.rulers_visible).unwrap(), "rulers_visible");
assert_eq!(to_value(&restored.document_ptz).unwrap(), to_value(&document.document_ptz).unwrap(), "document_ptz");
assert_eq!(serde_json::to_value(restored.render_mode).unwrap(), serde_json::to_value(document.render_mode).unwrap(), "render_mode");
assert_eq!(
to_value(&restored.overlays_visibility_settings).unwrap(),
to_value(&document.overlays_visibility_settings).unwrap(),
serde_json::to_value(restored.rulers_visible).unwrap(),
serde_json::to_value(document.rulers_visible).unwrap(),
"rulers_visible"
);
assert_eq!(
serde_json::to_value(restored.document_ptz).unwrap(),
serde_json::to_value(document.document_ptz).unwrap(),
"document_ptz"
);
assert_eq!(
serde_json::to_value(restored.overlays_visibility_settings).unwrap(),
serde_json::to_value(document.overlays_visibility_settings).unwrap(),
"overlays"
);
assert_eq!(to_value(&restored.snapping_state).unwrap(), to_value(&document.snapping_state).unwrap(), "snapping_state");
assert_eq!(to_value(&restored.collapsed).unwrap(), to_value(&document.collapsed).unwrap(), "collapsed");
assert_eq!(
serde_json::to_value(restored.snapping_state).unwrap(),
serde_json::to_value(document.snapping_state).unwrap(),
"snapping_state"
);
assert_eq!(serde_json::to_value(restored.collapsed).unwrap(), serde_json::to_value(document.collapsed).unwrap(), "collapsed");
}
@@ -4,7 +4,6 @@
//!
//! Shared fixtures live in [`test_support`].
mod lifecycle_tests;
mod metadata_tests;
mod round_trip_tests;
pub(crate) mod test_support;
mod test_support;
@@ -1,13 +1,13 @@
//! End-to-end storage round-trip tests: drive real edits through the editor, push the document
//! through a fresh in-memory `Gdd` (stage → retire → persist), reopen from the same container, and
//! assert the reopened document matches. Exercises the full persistence pipeline (conversion,
//! postcard codecs, hot-op retirement, file layout, replay-on-open) that the debug-only
//! 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 document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use document_graph_storage::{NodeMetadataSource, PeerId, to_value};
use document_graph_storage::{NodeMetadataSource, PeerId};
use graph_craft::application_io::resource::HashMapResourceStorage;
use super::test_support::{RoundTrip, node_paths, round_trip_through_gdd};
@@ -158,7 +158,9 @@ async fn edit_after_open_commits_cleanly() {
// reopened registry: the editor's .gdd-open path.
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()).expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
let source_network = source.network_interface.document_network().clone();
let source_view = StorageMetadataView::new(&source.network_interface);
gdd.commit_from_runtime(&source_network, &source_view, &source.resources.registry, &byte_store)
@@ -174,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);
document.set_storage(Some(reopened));
document.finalize_storage_load();
}
@@ -208,7 +210,9 @@ async fn edit_after_open_commits_cleanly() {
#[tokio::test]
async fn gdd_undo_redo_walks_interactions() {
let byte_store = HashMapResourceStorage::new();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
// Commit the active document's current runtime state as one interaction.
async fn commit_interaction(gdd: &mut GddV1, document: &DocumentMessageHandler, byte_store: &HashMapResourceStorage) {
@@ -259,7 +263,9 @@ async fn gdd_undo_redo_walks_interactions() {
#[tokio::test]
async fn reopen_after_undo_restores_consistent_registry() {
let byte_store = HashMapResourceStorage::new();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
async fn commit_interaction(gdd: &mut GddV1, document: &DocumentMessageHandler, byte_store: &HashMapResourceStorage) {
let network = document.network_interface.document_network().clone();
@@ -328,7 +334,7 @@ async fn live_undo_shadows_storage_cursor() {
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
let byte_store = mount_in_memory_storage(&mut editor);
let byte_store = mount_in_memory_storage(&mut editor).await;
// Capture the loaded state as the base interaction, then make a real edit (fires CommitTransaction).
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
let before_edit = editor.active_document().network_interface.document_network().clone();
@@ -367,9 +373,9 @@ async fn round_trip_document_settings() {
// The `ui::doc::*` view settings survived the persist/reopen cycle (in session.json, not the registry).
let settings = &round_trip.view_settings;
assert_eq!(settings.get(doc::RENDER_MODE), Some(&to_value(&RenderMode::Outline).unwrap()), "render_mode");
assert_eq!(settings.get(doc::RULERS_VISIBLE), Some(&to_value(&false).unwrap()), "rulers_visible");
assert_eq!(settings.get(doc::SNAPPING), Some(&to_value(&document.snapping_state).unwrap()), "snapping_state");
assert_eq!(settings.get(doc::RENDER_MODE), Some(&serde_json::to_value(RenderMode::Outline).unwrap()), "render_mode");
assert_eq!(settings.get(doc::RULERS_VISIBLE), Some(&serde_json::to_value(false).unwrap()), "rulers_visible");
assert_eq!(settings.get(doc::SNAPPING), Some(&serde_json::to_value(&document.snapping_state).unwrap()), "snapping_state");
}
/// The exported `.gdd` archive must carry `session.json` so view settings (notably the document PTZ)
@@ -381,13 +387,15 @@ async fn gdd_archive_round_trips_view_settings() {
use document_graph_storage::attr::session::doc;
let byte_store = HashMapResourceStorage::new();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
// Stage a distinctive PTZ into the working copy's `view_settings`, as `commit_storage_snapshot` does.
let mut ptz = crate::messages::portfolio::document::utility_types::misc::PTZ::default();
ptz.pan = glam::DVec2::new(-960., -540.);
ptz.set_zoom(0.459);
let view_settings = std::collections::BTreeMap::from([(doc::PTZ.to_string(), to_value(&ptz).unwrap())]);
let view_settings = std::collections::BTreeMap::from([(doc::PTZ.to_string(), serde_json::to_value(ptz).unwrap())]);
gdd.set_view_settings(view_settings).expect("set_view_settings");
// Export to an in-memory archive, then reopen it from bytes into a fresh container.
@@ -402,7 +410,7 @@ async fn gdd_archive_round_trips_view_settings() {
assert_eq!(
reopened.view_settings().get(doc::PTZ),
Some(&to_value(&ptz).unwrap()),
Some(&serde_json::to_value(ptz).unwrap()),
"the document PTZ must survive a .gdd archive export/open (session.json travels in the archive)"
);
}
@@ -429,7 +437,9 @@ async fn per_network_navigation_round_trips_via_session_not_registry() {
let expected_pan = editor.active_document().network_interface.node_graph_ptz(&[]).unwrap().pan;
// Commit the document into a fresh `Gdd`, collecting the per-network view state the editor persists.
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
let document = editor.active_document();
let network = document.network_interface.document_network().clone();
let view = StorageMetadataView::new(&document.network_interface);
@@ -462,14 +472,14 @@ async fn per_network_navigation_round_trips_via_session_not_registry() {
}
/// Mirror the real "new document, draw a rect, press undo" flow: mount storage and capture the
/// new-document base as the attach-time snapshot (as `StorageAttached` does), then draw a rect
/// new-document base as the mount-time snapshot (as `DocumentStorageMounted` does), then draw a rect
/// (one `CommitTransaction` interaction) and undo. The shadow must reproduce the legacy-restored interface.
#[tokio::test]
async fn live_undo_new_document_draw_rect() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let byte_store = mount_in_memory_storage(&mut editor);
let byte_store = mount_in_memory_storage(&mut editor).await;
// Mount-time snapshot: capture the new-document graph as the base interaction.
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
@@ -559,7 +569,7 @@ async fn undo_image_paste_resources_subset_of_runtime() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let byte_store = mount_in_memory_storage(&mut editor);
let byte_store = mount_in_memory_storage(&mut editor).await;
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
editor.handle_message(paste_named_image()).await;
@@ -591,7 +601,7 @@ async fn undo_twice_steps_cursor_two_interactions() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let byte_store = mount_in_memory_storage(&mut editor);
let byte_store = mount_in_memory_storage(&mut editor).await;
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
let base = editor.active_document().network_interface.document_network().clone();
@@ -664,9 +674,11 @@ 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.
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()).expect("create_in");
editor.active_document_mut().set_storage(gdd, Default::default());
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");
editor.active_document_mut().set_storage(Some(gdd));
HashMapResourceStorage::new()
}
@@ -689,7 +701,7 @@ async fn demo_artwork_edit_autosaves_and_round_trips() {
})
.await;
let byte_store = mount_in_memory_storage(&mut editor);
let byte_store = mount_in_memory_storage(&mut editor).await;
// First autosave: captures the loaded document. `verify_storage_round_trip` panics on drift.
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
@@ -757,7 +769,7 @@ async fn none_fill_survives_document_reopen() {
// Reopen through the editor's real open path, which runs the document migrations
let serialized = editor.active_document().serialize_document();
editor
.handle_message(PortfolioMessage::OpenLegacyDocumentFile {
.handle_message(PortfolioMessage::OpenDocumentFile {
document_name: None,
document_path: None,
document_serialized_content: serialized,
@@ -780,7 +792,7 @@ async fn legacy_four_input_fill_migrates_to_the_split_transform_shape() {
let mut editor = EditorTestUtils::create();
editor
.handle_message(PortfolioMessage::OpenLegacyDocumentFile {
.handle_message(PortfolioMessage::OpenDocumentFile {
document_name: None,
document_path: None,
document_serialized_content: LEGACY_DOCUMENT.to_string(),
@@ -838,7 +850,7 @@ async fn eight_input_fill_migrates_the_spread_input_into_the_ramp() {
let mut editor = EditorTestUtils::create();
editor
.handle_message(PortfolioMessage::OpenLegacyDocumentFile {
.handle_message(PortfolioMessage::OpenDocumentFile {
document_name: None,
document_path: None,
document_serialized_content: EIGHT_INPUT_DOCUMENT.to_string(),
@@ -46,7 +46,7 @@ pub fn node_paths(interface: &NodeNetworkInterface) -> Vec<(Vec<NodeId>, NodeId)
pub struct RoundTrip {
pub rebuilt: NodeNetworkInterface,
pub registry: document_graph_storage::Registry,
pub view_settings: std::collections::BTreeMap<String, document_graph_storage::Value>,
pub view_settings: std::collections::BTreeMap<String, serde_json::Value>,
}
/// Push `document`'s current runtime state through a fresh in-memory `Gdd` and reopen it. The commit goes
@@ -56,7 +56,9 @@ pub struct RoundTrip {
pub async fn round_trip_through_gdd(document: &DocumentMessageHandler) -> RoundTrip {
let byte_store = HashMapResourceStorage::new();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
let network = document.network_interface.document_network().clone();
let view = StorageMetadataView::new(&document.network_interface);
@@ -1,6 +1,11 @@
use super::*;
use graph_craft::runtime_delta::RuntimeDelta;
// Replay: putting a delta back into the interface, the inverse of the store recording one.
//
// Mechanism only. A mutator decides policy, validates, and lays nodes out, then records what it
// settled on; replaying reproduces that outcome rather than deciding it again. A peer running
// different layout rules must still end up with the state the delta describes.
impl NodeNetworkInterface {
/// Mirrors a delta into the interface without recording it.
///
@@ -18,7 +23,8 @@ impl NodeNetworkInterface {
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
// snapshot then fills in. Replacing an entry and adding one are the same write here; they
// differ only in what the storage side has to remove first.
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);
@@ -30,10 +30,11 @@ impl NodeNetworkInterface {
self.unload_stack_dependents(network_path);
let Some(history) = self.selection_history_mut(network_path) else {
log::error!("Could not get nested network_metadata in selected_nodes_mut");
log::error!("Could not get nested network_metadata in selected_nodes");
return None;
};
// Initialize default value if selection_undo_history is empty
if history.undo.is_empty() {
history.undo.push_back(SelectedNodes::default());
}
@@ -80,7 +81,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 try_load_stack_dependents");
log::error!("Could not get nested network_metadata in stack_dependents");
return;
};
@@ -100,7 +101,7 @@ impl NodeNetworkInterface {
return None;
};
let Some(stack_dependents) = transient.stack_dependents.get_loaded_mut() else {
log::error!("Could not load stack dependents in try_get_stack_dependents");
log::error!("could not load stack_dependents");
return None;
};
Some(stack_dependents)
@@ -147,7 +148,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_for_nodes");
log::error!("Cannot load outward wires in load_stack_dependents");
return;
};
let Some(first_downstream_input) = first_downstream_input else {
@@ -187,7 +188,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_for_nodes");
log::error!("Could not get layer node in load_stack_dependents");
continue;
};
layer_node.transient_metadata.owned_nodes.store(new_owned_nodes);
@@ -231,7 +232,7 @@ impl NodeNetworkInterface {
}
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get current network in load_stack_dependents_for_nodes");
log::error!("Could not get current network in load_stack_dependents");
return;
};
@@ -276,11 +277,11 @@ impl NodeNetworkInterface {
self.load_import_export_ports(network_path);
let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in import_export_ports");
log::error!("Could not get nested network_metadata in export_ports");
return None;
};
let Some(ports) = transient.import_export_ports.get_loaded_mut() else {
log::error!("Could not load import export ports in import_export_ports");
log::error!("could not load import ports");
return None;
};
Some(ports)
@@ -296,7 +297,7 @@ impl NodeNetworkInterface {
pub fn 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 load_import_export_ports");
log::error!("Could not get nested network_metadata in export_ports");
return;
};
network_metadata.transient_metadata.import_export_ports.ensure_loaded(|| self.compute_import_export_ports(network_path));
@@ -304,7 +305,7 @@ impl NodeNetworkInterface {
pub(crate) fn unload_import_export_ports(&mut self, network_path: &[NodeId]) {
let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in unload_import_export_ports");
log::error!("Could not get nested network_metadata in unload_export_ports");
return;
};
transient.import_export_ports.unload();
@@ -312,13 +313,13 @@ impl NodeNetworkInterface {
// 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 unload_import_export_ports");
log::error!("Could not get outward wires in remove_import");
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 unload_import_export_ports");
log::error!("Could not get outward wires for import in remove_import");
return;
};
input_connectors.extend(outward_wires_for_import);
@@ -342,7 +343,7 @@ impl NodeNetworkInterface {
return None;
};
let Some(click_targets) = transient.modify_import_export.get_loaded_mut() else {
log::error!("Could not load modify import export in modify_import_export");
log::error!("could not load modify import export ports");
return None;
};
Some(click_targets)
@@ -350,7 +351,7 @@ impl NodeNetworkInterface {
pub fn 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 load_modify_import_export");
log::error!("Could not get nested network_metadata in modify_import_export");
return;
};
network_metadata
@@ -361,7 +362,7 @@ impl NodeNetworkInterface {
pub(crate) fn unload_modify_import_export(&mut self, network_path: &[NodeId]) {
let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in unload_modify_import_export");
log::error!("Could not get nested network_metadata in unload_export_ports");
return;
};
transient.modify_import_export.unload();
@@ -387,7 +388,7 @@ impl NodeNetworkInterface {
.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 in all_nodes_bounding_box");
log::error!("could not load all nodes bounding box");
}
bounding_box
}
@@ -423,7 +424,7 @@ impl NodeNetworkInterface {
return None;
};
let Some(outward_wires) = transient.outward_wires.get_loaded_mut() else {
log::error!("Could not load outward wires in outward_wires");
log::error!("could not load outward wires");
return None;
};
@@ -440,14 +441,14 @@ impl NodeNetworkInterface {
fn 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 load_outward_wires");
log::error!("Could not get nested network_metadata in 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.
pub(super) fn compute_outward_wires(&self, network_path: &[NodeId]) -> Option<HashMap<OutputConnector, Vec<InputConnector>>> {
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");
@@ -468,7 +469,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 compute_outward_wires");
log::error!("Output connector {output_connector:?} should be initialized in load_outward_wires");
Vec::new()
});
outward_wires_entry.push(input_connector);
@@ -509,72 +510,23 @@ 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 drained = {
let Some(transient) = self.network_transient_mut(network_path) else { return };
let Some(outward_wires) = transient.outward_wires.get_loaded_mut() else { return };
unhook_outward_wire(outward_wires, input_connector, old_input);
hook_outward_wire(outward_wires, input_connector, new_input);
drained_outward_wire(outward_wires, old_input)
};
if let Some(output) = drained {
self.delist_vacated_output(network_path, output);
}
}
/// The same update for a node whose whole input list was swapped.
pub(crate) fn update_outward_wires_for_inputs(&mut self, network_path: &[NodeId], node_id: &NodeId, old_inputs: &[NodeInput], new_inputs: &[NodeInput]) {
let drained = {
let Some(transient) = self.network_transient_mut(network_path) else { return };
let Some(outward_wires) = transient.outward_wires.get_loaded_mut() else { return };
for (input_index, old_input) in old_inputs.iter().enumerate() {
unhook_outward_wire(outward_wires, &InputConnector::node_at_index(*node_id, input_index), old_input);
}
for (input_index, new_input) in new_inputs.iter().enumerate() {
hook_outward_wire(outward_wires, &InputConnector::node_at_index(*node_id, input_index), new_input);
}
old_inputs.iter().filter_map(|old_input| drained_outward_wire(outward_wires, old_input)).collect::<Vec<_>>()
};
for output in drained {
self.delist_vacated_output(network_path, output);
}
}
/// Drops an emptied entry for an output the network no longer has, which a fresh computation keys only while a wire still reaches it.
fn delist_vacated_output(&mut self, network_path: &[NodeId], output: OutputConnector) {
let still_exists = match output {
OutputConnector::Node { node_id, output_index } => output_index < self.number_of_outputs(&node_id, network_path),
OutputConnector::Import(import_index) => import_index < self.number_of_imports(network_path),
};
if still_exists {
let Some(transient) = self.network_transient_mut(network_path) else {
return;
};
let Some(outward_wires) = transient.outward_wires.get_loaded_mut() else {
return;
};
// Remove the input_connector from the old output's downstream list
if let Some(old_output) = OutputConnector::from_input(old_input)
&& let Some(connections) = outward_wires.get_mut(&old_output)
{
connections.retain(|c| c != input_connector);
}
let Some(transient) = self.network_transient_mut(network_path) else { return };
let Some(outward_wires) = transient.outward_wires.get_loaded_mut() else { return };
outward_wires.remove(&output);
}
/// Lists or delists a node's outputs after their count changed, since every output is keyed even with no consumers.
pub(crate) fn update_outward_wires_for_outputs(&mut self, network_path: &[NodeId], node_id: &NodeId, old_output_count: usize, new_output_count: usize) {
let Some(transient) = self.network_transient_mut(network_path) else { return };
let Some(outward_wires) = transient.outward_wires.get_loaded_mut() else { return };
// A consumer still wired to a vanished output keeps the entry, as a fresh computation lists it too
for output_index in new_output_count..old_output_count {
let output = OutputConnector::node(*node_id, output_index);
if outward_wires.get(&output).is_some_and(Vec::is_empty) {
outward_wires.remove(&output);
}
}
for output_index in old_output_count..new_output_count {
outward_wires.entry(OutputConnector::node(*node_id, output_index)).or_default();
// Add the input_connector to the new output's downstream list
if let Some(new_output) = OutputConnector::from_input(new_input) {
outward_wires.entry(new_output).or_default().push(*input_connector);
}
}
@@ -594,7 +546,7 @@ impl NodeNetworkInterface {
.with_loaded_or(|| Some(self.compute_layer_width(node_id, network_path)), |layer_width| *layer_width)
}
/// 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);
@@ -602,6 +554,7 @@ impl NodeNetworkInterface {
return;
};
// If the node is a layer, then the width and click targets need to be recalculated
if is_layer {
transient.layer_width.unload();
}
@@ -646,8 +599,14 @@ impl NodeNetworkInterface {
}
fn load_wire(&self, input: &InputConnector, graph_wire_style: GraphWireStyle, network_path: &[NodeId]) {
// 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 {
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 {
log::error!("Could not load wire path from input");
return;
};
@@ -704,7 +663,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 unload_wires_for_node");
log::error!("Could not get outward wires in reorder_export");
return;
};
let mut input_connectors = Vec::new();
@@ -729,26 +688,27 @@ impl NodeNetworkInterface {
network_metadata.transient_metadata.wires.borrow_mut().remove(input);
}
/// When previewing, there may be a second path to the root node.
pub fn wire_to_root(&self, graph_wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option<WirePathUpdate> {
/// The dashed wire from the previewed node to the export, drawn alongside the solid wire the export
/// is really connected to.
///
/// Previewing does not rewire the export, so both are shown: the solid wire says what the document
/// renders, and this one says what this peer is looking at instead.
pub fn wire_to_preview(&self, graph_wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option<WirePathUpdate> {
let input = InputConnector::Export(0);
let current_export = self.upstream_output_connector(&input, network_path)?;
let root_node = match self.previewing(network_path) {
Previewing::Yes { root_node_to_restore } => root_node_to_restore,
Previewing::No => None,
}?;
let Previewing::Yes { previewed } = self.previewing(network_path) else { return None };
if Some(root_node.node_id) == current_export.node_id() {
// The export already reaches it, so a second wire would land on top of the solid one
if self.upstream_output_connector(&input, network_path).and_then(|export| export.node_id()) == Some(previewed.node_id) {
return None;
}
let Some(input_position) = self.get_input_center(&input, network_path) else {
log::error!("Could not get input position for wire end in root node: {input:?}");
log::error!("Could not get input position for wire end in preview: {input:?}");
return None;
};
let upstream_output = OutputConnector::node(root_node.node_id, root_node.output_index);
let upstream_output = OutputConnector::node(previewed.node_id, previewed.output_index);
let Some(output_position) = self.get_output_center(&upstream_output, network_path) else {
log::error!("Could not get output position for wire start in root node: {upstream_output:?}");
log::error!("Could not get output position for wire start in preview: {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);
@@ -766,7 +726,7 @@ impl NodeNetworkInterface {
path_string,
data_type,
thick,
dashed: true,
dashed: false,
is_list,
center_path_string,
});
@@ -789,7 +749,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);
@@ -826,7 +786,7 @@ impl NodeNetworkInterface {
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");
log::error!("Could not load node type metadata when getting click targets");
return None;
};
Some(click_targets)
@@ -834,7 +794,7 @@ impl NodeNetworkInterface {
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 load_node_click_targets");
log::error!("Could not get nested node_metadata in node_click_targets");
return;
};
node_metadata.transient_metadata.click_targets.ensure_loaded(|| self.compute_node_click_targets(node_id, network_path));
@@ -861,18 +821,16 @@ 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 click targets in with_node_click_targets_if_loaded");
log::error!("Could not load node type metadata when getting click targets");
}
result
}
pub fn node_bounding_box(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
self.with_node_click_targets(node_id, network_path, |click_targets| click_targets.node_click_target.bounding_box())
.flatten()
self.load_node_click_targets(node_id, network_path);
self.try_get_node_bounding_box(node_id, network_path)
}
/// 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()
@@ -890,7 +848,7 @@ impl NodeNetworkInterface {
pub fn unload_node_click_targets(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
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");
log::error!("Could not get nested node_metadata in unload_node_click_target");
return;
};
transient.click_targets.unload();
@@ -917,24 +875,3 @@ impl NodeNetworkInterface {
}
}
}
/// Drops `input_connector` from the consumers of the output that `input` was wired to.
fn unhook_outward_wire(outward_wires: &mut HashMap<OutputConnector, Vec<InputConnector>>, input_connector: &InputConnector, input: &NodeInput) {
if let Some(output) = OutputConnector::from_input(input)
&& let Some(connections) = outward_wires.get_mut(&output)
{
connections.retain(|connection| connection != input_connector);
}
}
/// Adds `input_connector` to the consumers of the output that `input` is wired to.
fn hook_outward_wire(outward_wires: &mut HashMap<OutputConnector, Vec<InputConnector>>, input_connector: &InputConnector, input: &NodeInput) {
if let Some(output) = OutputConnector::from_input(input) {
outward_wires.entry(output).or_default().push(*input_connector);
}
}
/// The output `input` was wired to, once it has lost its last consumer.
fn drained_outward_wire(outward_wires: &HashMap<OutputConnector, Vec<InputConnector>>, input: &NodeInput) -> Option<OutputConnector> {
OutputConnector::from_input(input).filter(|output| outward_wires.get(output).is_some_and(Vec::is_empty))
}
@@ -1,4 +1,4 @@
use super::{InputConnector, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, OutputConnector, Previewing, RootNode, TransactionStatus};
use super::{InputConnector, OutputConnector, Previewing, RootNode, TransactionStatus};
use crate::messages::portfolio::document::node_graph::utility_types::Direction;
use crate::test_utils::test_prelude::*;
use graph_craft::document::NodeInput;
@@ -127,7 +127,7 @@ async fn cyclic_connection_is_rejected_without_side_effects() {
}
/// 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.
/// closes through intermediate nodes rather than only one that connects two neighbours.
#[tokio::test]
async fn a_cycle_closing_through_a_chain_is_rejected() {
let mut editor = EditorTestUtils::create();
@@ -172,31 +172,6 @@ async fn connecting_an_export_is_never_cyclic() {
assert_invariants(&editor, "after connecting the export");
}
#[tokio::test]
async fn toggling_preview_on_a_disconnected_export() {
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.disconnect_input(&InputConnector::Export(0), &[]);
// Previewing a node while the export is disconnected is a preview with nothing to restore
network_interface.toggle_preview(node, &[]);
assert_eq!(network_interface.previewing(&[]), Previewing::Yes { root_node_to_restore: None });
let export = network_interface.input_from_connector(&InputConnector::Export(0), &[]);
assert_eq!(export.and_then(|input| input.as_node()), Some(node), "The previewed node should be wired to the export");
// Ending the preview restores the disconnected export
network_interface.toggle_preview(node, &[]);
assert_eq!(network_interface.previewing(&[]), Previewing::No);
let export = network_interface.input_from_connector(&InputConnector::Export(0), &[]);
assert!(export.is_some_and(|input| input.as_node().is_none()), "Ending the preview should disconnect the export again");
assert_invariants(&editor, "after toggling preview twice");
}
#[tokio::test]
async fn artboard_identity_is_independent_of_scene_connectivity() {
let mut editor = EditorTestUtils::create();
@@ -406,8 +381,10 @@ async fn signature_edits_keep_parallel_metadata_in_sync() {
assert_invariants(&editor, "after removing the added export");
}
/// Previewing renders a different node without rewiring anything: the export keeps whatever it is
/// connected to, so ending a preview has nothing to restore and cannot disconnect anything.
#[tokio::test]
async fn toggle_preview_transitions_with_a_connected_export() {
async fn previewing_leaves_the_export_alone() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
@@ -419,212 +396,125 @@ async fn toggle_preview_transitions_with_a_connected_export() {
let export_node = |network_interface: &super::NodeNetworkInterface| network_interface.input_from_connector(&InputConnector::Export(0), &[]).and_then(|input| input.as_node());
assert_eq!(export_node(network_interface), Some(artboard));
// Previewing a node remembers the artboard as the connection to restore
// Previewing a node names it without touching the export
network_interface.toggle_preview(node, &[]);
assert_eq!(export_node(network_interface), Some(node));
assert_eq!(
network_interface.previewing(&[]),
Previewing::Yes {
root_node_to_restore: Some(RootNode { node_id: artboard, output_index: 0 })
previewed: RootNode { node_id: node, output_index: 0 }
}
);
assert_eq!(export_node(network_interface), Some(artboard), "Previewing must not rewire the export");
// Toggling the previewed node again restores the artboard connection
network_interface.toggle_preview(node, &[]);
assert_eq!(export_node(network_interface), Some(artboard));
assert_eq!(network_interface.previewing(&[]), Previewing::No);
// Toggling the restore node while previewing promotes it to the export with nothing left to restore
network_interface.toggle_preview(node, &[]);
// Previewing a different node moves the preview, still without touching the export
network_interface.toggle_preview(artboard, &[]);
assert_eq!(
network_interface.previewing(&[]),
Previewing::Yes {
previewed: RootNode { node_id: artboard, output_index: 0 }
}
);
assert_eq!(export_node(network_interface), Some(artboard));
assert_eq!(network_interface.previewing(&[]), Previewing::Yes { root_node_to_restore: None });
// Toggling it once more ends the preview by disconnecting the export entirely
// Toggling the previewed node again ends the preview, leaving the export as it always was
network_interface.toggle_preview(artboard, &[]);
assert_eq!(export_node(network_interface), None);
assert_eq!(network_interface.previewing(&[]), Previewing::No);
assert_eq!(export_node(network_interface), Some(artboard));
assert_invariants(&editor, "after cycling through the preview states");
}
fn assert_interface_invariants(network_interface: &NodeNetworkInterface, context: &str) {
let violations = network_interface.validate_invariants();
assert!(violations.is_empty(), "Invariant violations {context}:\n{}", violations.join("\n"));
}
/// The graph handed to the compiler renders the previewed node, which is the whole point of a preview
/// that does not rewire the document.
#[tokio::test]
async fn the_evaluated_network_renders_the_previewed_node() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
fn value_input() -> NodeInput {
NodeInput::value(TaggedValue::None, false)
}
let artboard = NodeId::new();
editor.handle_message(new_artboard_message(artboard)).await;
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 20).await;
/// A source feeding a node that feeds a consumer, with the outward wire cache loaded so every later mutation has to keep it current.
fn wired_interface() -> (NodeNetworkInterface, NodeId, NodeId, NodeId) {
let (source, node, consumer) = (NodeId(1), NodeId(2), NodeId(3));
let mut network_interface = NodeNetworkInterface::default();
network_interface.insert_node(
source,
NodeTemplate {
inputs: vec![value_input()],
..Default::default()
},
&[],
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.toggle_preview(node, &[]);
let evaluated = network_interface.network_to_evaluate();
assert_eq!(
evaluated.exports.first().and_then(|export| export.as_node()),
Some(node),
"The network being evaluated should export the previewed node"
);
network_interface.insert_node(
node,
NodeTemplate {
inputs: vec![value_input(), value_input()],
..Default::default()
},
&[],
);
network_interface.insert_node(
consumer,
NodeTemplate {
inputs: vec![value_input()],
..Default::default()
},
&[],
);
network_interface.set_input(&InputConnector::node_at_index(node, 0), NodeInput::node(source, 0), &[]);
network_interface.set_input(&InputConnector::node_at_index(consumer, 0), NodeInput::node(node, 0), &[]);
assert!(network_interface.outward_wires(&[]).is_some());
assert_interface_invariants(&network_interface, "after wiring the fixture");
(network_interface, source, node, consumer)
}
#[test]
fn replacing_inputs_keeps_the_loaded_wire_cache_exact() {
let (mut network_interface, source, node, _) = wired_interface();
let mut template = NodeTemplate {
inputs: vec![value_input(); 3],
..Default::default()
};
template.normalize_input_metadata();
network_interface.replace_inputs(&node, &[], &mut template);
assert_interface_invariants(&network_interface, "after replacing the inputs of a wired node");
// The wire returns at a new index, as a migration restores the inputs it keeps
network_interface.set_input(&InputConnector::node_at_index(node, 2), NodeInput::node(source, 0), &[]);
assert_interface_invariants(&network_interface, "after rewiring the source into the replaced node");
}
#[test]
fn replacing_an_implementation_keeps_its_outputs_listed_in_the_wire_cache() {
let (mut network_interface, _, node, _) = wired_interface();
let second_output = OutputConnector::node(node, 1);
// An implementation swap leaves the output names to the open path, so restore them as it does before validating
let swap_implementation = |network_interface: &mut NodeNetworkInterface, template: &mut NodeTemplate, context: &str| {
network_interface.replace_implementation(&node, &[], template);
let document_node = network_interface.document_node(&node, &[]).cloned().unwrap();
network_interface.validate_output_names(&node, &document_node, &[]);
assert_interface_invariants(network_interface, context);
};
let two_exports = NodeNetworkTemplate {
exports: vec![value_input(), value_input()],
..Default::default()
};
let mut template = NodeTemplate {
implementation: NodeTemplateImplementation::Network(two_exports),
..Default::default()
};
swap_implementation(&mut network_interface, &mut template, "after giving a node a second output");
assert!(
network_interface.outward_wires(&[]).is_some_and(|wires| wires.contains_key(&second_output)),
"a gained output should be listed"
);
swap_implementation(&mut network_interface, &mut NodeTemplate::default(), "after taking the second output away");
assert!(
network_interface.outward_wires(&[]).is_some_and(|wires| !wires.contains_key(&second_output)),
"a lost output should be delisted"
assert_eq!(
network_interface.document_network().exports.first().and_then(|export| export.as_node()),
Some(artboard),
"The document itself should be unchanged"
);
}
// A vanished output keeps its entry while a consumer is still wired to it, so the entry has to go when that consumer leaves
#[test]
fn rewiring_off_a_vanished_output_delists_it_from_the_wire_cache() {
let (mut network_interface, source, node, consumer) = wired_interface();
let second_output = OutputConnector::node(node, 1);
/// The previewed node is marked for the frontend so it can be highlighted. Derived from the preview
/// itself: it used to be inferred from the export, which previewing no longer rewires, so inferring it
/// would silently mark nothing.
#[tokio::test]
async fn the_previewed_node_is_flagged_for_the_frontend() {
use crate::messages::portfolio::document::node_graph::NodeGraphMessageHandler;
let restore_output_names = |network_interface: &mut NodeNetworkInterface| {
let document_node = network_interface.document_node(&node, &[]).cloned().unwrap();
network_interface.validate_output_names(&node, &document_node, &[]);
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let artboard = NodeId::new();
editor.handle_message(new_artboard_message(artboard)).await;
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 20).await;
let handler = NodeGraphMessageHandler::default();
let network_interface = &mut editor.active_document_mut().network_interface;
let flagged = |handler: &NodeGraphMessageHandler, network_interface: &mut super::NodeNetworkInterface| {
handler
.collect_nodes(network_interface, &[])
.into_iter()
.filter(|node| node.previewed)
.map(|node| node.id)
.collect::<Vec<_>>()
};
// Give the node a second output and move the consumer onto it
let two_exports = NodeNetworkTemplate {
exports: vec![value_input(), value_input()],
..Default::default()
};
let mut template = NodeTemplate {
implementation: NodeTemplateImplementation::Network(two_exports),
..Default::default()
};
network_interface.replace_implementation(&node, &[], &mut template);
restore_output_names(&mut network_interface);
network_interface.set_input(&InputConnector::node_at_index(consumer, 0), NodeInput::node(node, 1), &[]);
assert_interface_invariants(&network_interface, "after wiring a consumer to the second output");
assert!(flagged(&handler, network_interface).is_empty(), "Nothing is previewed to begin with");
// Taking that output away leaves the consumer dangling, which a fresh computation still lists
network_interface.replace_implementation(&node, &[], &mut NodeTemplate::default());
restore_output_names(&mut network_interface);
assert!(
network_interface.outward_wires(&[]).is_some_and(|wires| wires.contains_key(&second_output)),
"a vanished output should keep its entry while something is still wired to it"
);
network_interface.toggle_preview(node, &[]);
assert_eq!(flagged(&handler, network_interface), vec![node], "The previewed node should be the one flagged");
network_interface.set_input(&InputConnector::node_at_index(consumer, 0), NodeInput::node(source, 0), &[]);
assert!(
network_interface.outward_wires(&[]).is_some_and(|wires| !wires.contains_key(&second_output)),
"the entry should go once the last consumer leaves a vanished output"
);
assert_interface_invariants(&network_interface, "after rewiring off a vanished output");
network_interface.toggle_preview(node, &[]);
assert!(flagged(&handler, network_interface).is_empty(), "Ending the preview should unflag it");
}
#[test]
fn inserting_and_deleting_nodes_keeps_the_loaded_wire_cache_exact() {
let (mut network_interface, _, node, _) = wired_interface();
/// Resolving a batch of positions shares one downstream walk, so it has to agree with resolving each
/// node on its own. A stack is the case that matters: every layer walks through the ones below it, so
/// a shared memo is what keeps the batch from being quadratic.
#[tokio::test]
async fn batched_positions_agree_with_resolving_each_node() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.handle_message(new_artboard_message(NodeId::new())).await;
network_interface.insert_node(NodeId(4), NodeTemplate::default(), &[]);
assert_interface_invariants(&network_interface, "after inserting a node while the cache is loaded");
for offset in 0..4 {
editor.draw_rect(0., offset as f64 * 20., 100., offset as f64 * 20. + 10.).await;
}
network_interface.delete_nodes(vec![node], false, &[]);
assert_interface_invariants(&network_interface, "after deleting a wired node");
}
let network_interface = &editor.active_document().network_interface;
let node_ids = network_interface.document_network().nodes.keys().copied().collect::<Vec<_>>();
assert!(node_ids.len() > 4, "the fixture should build a stack, found {} nodes", node_ids.len());
#[test]
fn adding_an_import_ahead_of_a_wired_input_keeps_the_loaded_wire_cache_exact() {
let (source, node) = (NodeId(1), NodeId(2));
let mut network_interface = NodeNetworkInterface::default();
network_interface.insert_node(
source,
NodeTemplate {
inputs: vec![value_input()],
..Default::default()
},
&[],
);
let network = NodeNetworkTemplate {
exports: vec![value_input()],
..Default::default()
};
let template = NodeTemplate {
implementation: NodeTemplateImplementation::Network(network),
inputs: vec![value_input()],
output_names: vec![String::new()],
..Default::default()
};
network_interface.insert_node(node, template, &[]);
network_interface.set_input(&InputConnector::node_at_index(node, 0), NodeInput::node(source, 0), &[]);
assert!(network_interface.outward_wires(&[]).is_some());
let batched = network_interface.positions(node_ids.iter().copied(), &[]);
let individually = node_ids
.iter()
.filter_map(|node_id| network_interface.position(node_id, &[]).map(|position| (*node_id, position)))
.collect::<Vec<_>>();
// Inserting ahead of the wired input moves that wire to index 1
network_interface.add_import(TaggedValue::None, true, 0, "", "", &[node]);
assert_interface_invariants(&network_interface, "after adding an import ahead of a wired input");
let consumers = network_interface.outward_wires(&[]).and_then(|wires| wires.get(&OutputConnector::node(source, 0)).cloned());
assert_eq!(consumers.as_deref(), Some([InputConnector::node_at_index(node, 1)].as_slice()));
assert_eq!(batched.len(), individually.len(), "The batch should resolve exactly the nodes that resolve on their own");
for (node_id, position) in individually {
assert_eq!(
batched.iter().find(|(batched_id, _)| *batched_id == node_id).map(|(_, position)| *position),
Some(position),
"Batched position disagrees for node {node_id}"
);
}
}
@@ -4,7 +4,7 @@ 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, Value};
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;
@@ -82,15 +82,7 @@ pub enum NetworkMetadataChange {
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,
pub declaration_bytes: DeclarationBytes,
}
/// Constructs the storage ops for one gesture's deltas, in delta order. Removal closures and
@@ -108,67 +100,57 @@ pub fn construct_batch(
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 resolver = PathResolver::new(Some(&identities), peer);
let mut batch = BatchRegistry::new(working);
let mut ops = Vec::new();
let mut declarations = BatchDeclarations::default();
let mut declaration_bytes = DeclarationBytes::new();
let mut batch_removed_nodes = Vec::new();
// In delta order, so each delta reads what the ones before it did
// In delta order, so each delta reads what the ones before it did. Removals accumulate as they are
// met rather than being gathered up front, since a removal can name a node an earlier delta added.
for delta in deltas {
delta.construct(&context, &mut batch, &mut batch_removed_nodes, &mut ops, &mut declarations)?;
delta.construct(resources, peer, &identities, &resolver, &mut batch, &mut batch_removed_nodes, &mut ops, &mut declaration_bytes)?;
}
batch_removed_nodes.sort_by_key(|(id, _)| *id);
batch_removed_nodes.dedup_by_key(|(id, _)| *id);
batch_removed_nodes.sort();
batch_removed_nodes.dedup();
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,
Ok(ConstructedOps { ops, declaration_bytes })
}
impl EditorDelta {
#[allow(clippy::too_many_arguments)]
fn construct(
&self,
context: &ConversionContext,
resources: &ResourceRegistry,
peer: document_graph_storage::PeerId,
identities: &dyn NodeMetadataSource,
resolver: &PathResolver,
batch: &mut BatchRegistry,
batch_removed_nodes: &mut Vec<(document_graph_storage::NodeId, document_graph_storage::Node)>,
batch_removed_nodes: &mut Vec<document_graph_storage::NodeId>,
ops: &mut Vec<RegistryDelta>,
declarations: &mut BatchDeclarations,
declaration_bytes: &mut DeclarationBytes,
) -> 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)?;
construct_structural_additions(network_path, *node_id, node, batch, resources, identities, peer, ops, declaration_bytes)?;
}
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)?;
construct_removals(resolver.node_id(network_path, *node_id), batch, batch_removed_nodes, ops);
construct_structural_additions(network_path, *node_id, node, batch, resources, identities, peer, ops, declaration_bytes)?;
}
EditorDelta::Graph(RuntimeDelta::RemoveNode { network_path, node_id }) => {
construct_removals(context.resolver.node_id(network_path, *node_id), batch, batch_removed_nodes, ops);
construct_removals(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),
id: resolver.node_id(network_path, *node_id),
delta: AttributeDelta {
key: node_attr::VISIBLE.to_string(),
value: (!visible).then_some(Value::Bool(false)),
value: (!visible).then_some(serde_json::Value::Bool(false)),
},
});
}
@@ -179,32 +161,24 @@ impl EditorDelta {
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),
id: resolver.node_id(network_path, *node_id),
index: (*input_index).try_into().map_err(|_| ConversionError::IndexOverflow(*input_index))?,
new_input,
new_input: resolver.convert_input_at(input, network_path)?,
});
}
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),
id: resolver.network_id(network_path),
index: (*export_index).try_into().map_err(|_| ConversionError::IndexOverflow(*export_index))?,
export,
export: input.as_ref().map(|input| resolver.convert_input_at(input, network_path)).transpose()?,
});
}
EditorDelta::Graph(RuntimeDelta::SetCallArgument { network_path, node_id, call_argument }) => {
ops.push(RegistryDelta::ChangeNodeAttribute {
id: context.resolver.node_id(network_path, *node_id),
id: resolver.node_id(network_path, *node_id),
delta: document_graph_storage::from_runtime::encode_call_argument(call_argument)?,
});
}
@@ -215,41 +189,38 @@ impl EditorDelta {
context_features,
}) => {
ops.push(RegistryDelta::ChangeNodeAttribute {
id: context.resolver.node_id(network_path, *node_id),
id: 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)?;
construct_metadata_snapshot(network_path, *node_id, metadata, batch, resolver, ops)?;
}
EditorDelta::Graph(RuntimeDelta::SetInputs { network_path, node_id, inputs }) => {
// The slots' `ui::*` attributes arrive with the paired input metadata delta
// Only the slots are written, so the node's attributes and everything nested under it are
// left as they are: an edit made earlier in this batch is not reverted by the rebuild.
// 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)?,
input: resolver.convert_input_at(input, network_path)?,
timestamp: TimeStamp::ORIGIN,
attributes: convert_input_attributes(input)?,
attributes_timestamp: TimeStamp::ORIGIN,
})
})
.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),
id: 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)?);
ops.extend(node_metadata_ops(resolver.node_id(network_path, *node_id), change)?);
}
EditorDelta::NodeInputMetadata {
@@ -257,10 +228,12 @@ impl EditorDelta {
node_id,
input_metadata,
} => {
let global_id = context.resolver.node_id(network_path, *node_id);
let global_id = resolver.node_id(network_path, *node_id);
let source = InputMetadataSource(input_metadata);
let working_node = batch.node(global_id);
// An insert shifts every later slot, so the array is asserted whole: a `ui::` key the slot
// no longer carries is cleared rather than left behind at its old index.
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)?;
@@ -280,10 +253,10 @@ impl EditorDelta {
let delta = match change {
NetworkMetadataChange::Reference(reference) => AttributeDelta {
key: node_attr::ui::REFERENCE.to_string(),
value: reference.clone().map(Value::Str),
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();
let stored: Vec<_> = order.iter().map(|node_id| 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()?,
@@ -292,7 +265,7 @@ impl EditorDelta {
};
ops.push(RegistryDelta::ChangeNetworkAttribute {
id: context.resolver.network_id(network_path),
id: resolver.network_id(network_path),
delta,
});
}
@@ -302,8 +275,8 @@ impl EditorDelta {
}
}
fn serialize_attribute<T: serde::Serialize>(key: &str, value: &T) -> Result<Value, ConversionError> {
document_graph_storage::to_value(value).map_err(|error| ConversionError::SerializationError(format!("{key}: {error:?}")))
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.
@@ -311,11 +284,11 @@ fn serialize_attribute<T: serde::Serialize>(key: &str, value: &T) -> Result<Valu
/// 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<Value>| RegistryDelta::ChangeNodeAttribute {
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<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))?,
@@ -323,9 +296,10 @@ fn node_metadata_ops(global_id: document_graph_storage::NodeId, change: &NodeMet
})
};
// The empty string is the runtime's own sentinel for an unset name
let flag = |value: bool| value.then_some(Value::Bool(true));
let non_empty = |value: &str| (!value.is_empty()).then(|| Value::Str(value.to_string()));
// Absence is how the encoder spells an unset flag, and 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);
@@ -351,67 +325,36 @@ fn node_metadata_ops(global_id: document_graph_storage::NodeId, change: &NodeMet
/// 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.
#[allow(clippy::too_many_arguments)]
fn construct_structural_additions(
network_path: &[NodeId],
node_id: NodeId,
node: &graph_craft::document::DocumentNode,
batch: &mut BatchRegistry,
context: &ConversionContext,
resources: &ResourceRegistry,
identities: &dyn NodeMetadataSource,
peer: document_graph_storage::PeerId,
ops: &mut Vec<RegistryDelta>,
declarations: &mut BatchDeclarations,
declaration_bytes: &mut DeclarationBytes,
) -> Result<(), ConversionError> {
let mut scoped = ScopedConversion::new(context.identities, context.peer);
let mut scoped = ScopedConversion::new(identities, 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);
declaration_bytes.extend(scoped.finish());
let mut networks: Vec<_> = scratch.networks.iter().map(|(id, network)| (*id, network.clone())).collect();
networks.sort_by_key(|(id, _)| *id);
let mut networks: Vec<_> = scratch.networks.iter().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);
ops.push(RegistryDelta::AddNetwork { id: *id, network: network.clone() });
}
// Recorded as well as emitted, so a later delta in this batch can read these nodes back
// Recorded as well as emitted, so a later delta in this batch that reads one of these nodes back
// finds it rather than looking only at the registry the batch started from.
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) {
Some(held) => {
// The swap did not write the slots' `ui::*` attributes; a whole-slot assignment would drop the
// names and descriptions held for the slots that survive it.
let inputs = node
.inputs()
.iter()
.enumerate()
.map(|(index, slot)| {
let mut slot = slot.clone();
if let Some(previous) = held.inputs().get(index) {
slot.attributes.extend(
previous
.attributes
.iter()
.filter(|(key, value)| key.starts_with("ui::") && !value.deleted)
.map(|(key, value)| (key.clone(), value.clone())),
);
}
slot
})
.collect();
ops.push(RegistryDelta::SetNodeImplementation {
id,
implementation: node.implementation().clone(),
});
ops.push(RegistryDelta::SetNodeInputs { id, inputs });
}
None => ops.push(RegistryDelta::AddNode { id, node: node.clone() }),
}
ops.push(RegistryDelta::AddNode { id, node: node.clone() });
batch.record_addition(id, node);
}
@@ -433,7 +376,7 @@ fn construct_structural_additions(
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)?
&& let Some(entry) = convert_resource_entry(resources, id, peer)?
{
batch.record_resource(id, entry.clone());
ops.push(RegistryDelta::AddResource { id, entry });
@@ -443,31 +386,6 @@ fn construct_structural_additions(
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,
@@ -511,12 +429,11 @@ fn construct_metadata_snapshot(
nested_path.push(id);
let network_id = resolver.network_id(&nested_path);
let target = network_metadata.persistent_metadata.reference.clone().map(Value::Str);
// 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 target = network_metadata.persistent_metadata.reference.clone().map(serde_json::Value::String);
let current = batch
.network(network_id)
.working
.networks
.get(&network_id)
.and_then(|network| network.attributes.get(node_attr::ui::REFERENCE))
.map(|value| value.value.clone());
if current != target {
@@ -529,22 +446,6 @@ fn construct_metadata_snapshot(
});
}
// 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));
}
@@ -585,69 +486,37 @@ fn ui_attribute_writes(current: Option<&Attributes>, encoded: &Attributes) -> Ve
/// 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>,
) {
fn construct_removals(node_id: document_graph_storage::NodeId, batch: &BatchRegistry, batch_removed_nodes: &mut Vec<document_graph_storage::NodeId>, 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 };
let Some(snapshot) = batch.node(*id) 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 };
let Some(snapshot) = batch.working.networks.get(id) else { continue };
ops.push(RegistryDelta::RemoveNetwork { id: *id, snapshot: snapshot.clone() });
}
batch_removed_nodes.extend(removed_nodes);
}
/// 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.
fn construct_resource_removals(batch_removed_nodes: &[document_graph_storage::NodeId], batch: &BatchRegistry, ops: &mut Vec<RegistryDelta>) {
let removed_node_set: HashSet<_> = batch_removed_nodes.iter().copied().collect();
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| {
.filter_map(|id| batch.node(*id))
.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();
@@ -657,18 +526,16 @@ fn construct_resource_removals(batch_removed_nodes: &[(document_graph_storage::N
// 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() {
for (id, node) in batch.working.node_instances.iter().chain(&batch.added) {
if removed_node_set.contains(id) {
continue;
}
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()) {
for network in batch.working.networks.values() {
still_referenced.extend(network.exports.iter().filter_map(|slot| slot.target.as_ref().and_then(value_resource_ref)));
}
@@ -685,24 +552,20 @@ fn construct_resource_removals(batch_removed_nodes: &[(document_graph_storage::N
}
/// 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.
/// earlier in the same batch have added.
///
/// A delta that reads a node back cannot read only the starting registry. A node added and removed
/// within one batch is not in it, and a later delta that rebuilds a node would rebuild the version
/// that predates the batch. Additions are tracked rather than the whole registry copied, so the cost
/// is the size of the batch rather than of the document.
///
/// 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> {
@@ -714,38 +577,17 @@ impl<'a> BatchRegistry<'a> {
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 {
@@ -753,29 +595,9 @@ impl<'a> BatchRegistry<'a> {
}
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))
}
@@ -840,10 +662,8 @@ impl NodeMetadataSource for InputMetadataSource<'_> {
self.persistent(input_index)?.widget_override.as_deref()
}
fn input_data(&self, _network_path: &[NodeId], _local_id: NodeId, input_index: usize) -> HashMap<String, Value> {
self.persistent(input_index)
.map(|metadata| metadata.input_data.iter().map(|(key, value)| (key.clone(), value.clone().into())).collect())
.unwrap_or_default()
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()
}
}
@@ -933,10 +753,10 @@ impl document_graph_storage::NodeMetadataSource for MetadataCopySource<'_> {
.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, Value> {
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.iter().map(|(key, value)| (key.clone(), value.clone().into())).collect())
.map(|input| input.persistent_metadata.input_data.clone())
.unwrap_or_default()
}
@@ -78,7 +78,7 @@ async fn set_input_value_constructs_the_exact_diff_op() {
let node = editor.create_node_by_name(rectangle_definition()).await;
let working = convert(&editor);
let input = NodeInput::value(TaggedValue::Number(42.), false);
let input = NodeInput::value(TaggedValue::F64(42.), false);
editor.active_document_mut().network_interface.set_input(&InputConnector::node_at_index(node, 1), input.clone(), &[]);
let delta = EditorDelta::Graph(RuntimeDelta::SetInput {
@@ -195,8 +195,9 @@ async fn per_field_metadata_edits_match_the_diff() {
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.
/// The encoding spells "unset" as an absent attribute, so a field set back to its unset value has to
/// clear the key rather than write a sentinel. The wholesale copy got this by omitting the key; a
/// per-field delta has to say it, and saying it wrong leaves the old value stored.
#[tokio::test]
async fn clearing_a_metadata_field_removes_the_attribute() {
let mut editor = EditorTestUtils::create();
@@ -226,9 +227,9 @@ async fn clearing_a_metadata_field_removes_the_attribute() {
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.
/// The gate emission exists for: what the store says it wrote has to be what a whole-document
/// conversion of the result would show. Hand-written deltas cannot catch a setter that forgets to
/// emit, or emits the wrong field; taking them from the interface after a real edit can.
#[tokio::test]
async fn emitted_deltas_reproduce_the_diff() {
let mut editor = EditorTestUtils::create();
@@ -337,7 +338,7 @@ async fn emitted_deltas_reproduce_the_diff_for_an_arity_change() {
editor
.active_document_mut()
.network_interface
.add_import(TaggedValue::Number(7.), true, -1, "Added", "An added import", &[group]);
.add_import(TaggedValue::F64(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");
@@ -378,7 +379,7 @@ async fn an_arity_change_keeps_an_earlier_edit_to_the_same_node() {
editor
.active_document_mut()
.network_interface
.add_import(TaggedValue::Number(7.), true, -1, "Added", "An added import", &[group]);
.add_import(TaggedValue::F64(7.), true, -1, "Added", "An added import", &[group]);
let emitted = editor.active_document_mut().network_interface.take_deltas();
let constructed = construct(&editor, &emitted, &working);
@@ -386,9 +387,10 @@ async fn an_arity_change_keeps_an_earlier_edit_to_the_same_node() {
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.
/// The gate replay exists for: what the store recorded has to be enough to reproduce the write that
/// produced it. Clone the interface before an edit, apply what the edit recorded onto the clone, and
/// the two should agree. Something the store failed to record, or recorded wrongly, 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;
@@ -452,7 +454,7 @@ async fn replaying_an_arity_change_reproduces_the_interface() {
editor
.active_document_mut()
.network_interface
.add_import(TaggedValue::Number(7.), true, -1, "Added", "An added import", &[group]);
.add_import(TaggedValue::F64(7.), true, -1, "Added", "An added import", &[group]);
})
.await;
}
@@ -550,85 +552,3 @@ async fn removing_a_nested_network_node_matches_the_diff() {
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"
);
// The slots that survive the swap keep the names and descriptions the registry holds for them.
let Some((id, inputs)) = ops.iter().find_map(|op| match op {
RegistryDelta::SetNodeInputs { id, inputs } => Some((id, inputs)),
_ => None,
}) else {
panic!("the swap should restate the slots")
};
let held: Vec<_> = working.node_instances[id]
.inputs()
.iter()
.take(inputs.len())
.flat_map(|slot| document_graph_storage::attributes::live(&slot.attributes).filter(|(key, _)| key.starts_with("ui::")))
.collect();
assert!(!held.is_empty(), "the surviving slots should hold ui attributes for this to check anything");
for (index, slot) in inputs.iter().enumerate() {
for (key, value) in document_graph_storage::attributes::live(&working.node_instances[id].inputs()[index].attributes).filter(|(key, _)| key.starts_with("ui::")) {
assert_eq!(slot.attributes.get(key), Some(value), "slot {index} lost {key}");
}
}
}
@@ -21,6 +21,7 @@ impl NodeNetworkInterface {
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() {
@@ -58,6 +59,7 @@ impl NodeNetworkInterface {
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);
@@ -65,7 +67,7 @@ impl NodeNetworkInterface {
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");
log::error!("Could not get layer width in load_node_click_targets");
0
});
let width = layer_width_cells * GRID_SIZE;
@@ -77,6 +79,7 @@ impl NodeNetworkInterface {
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,
@@ -98,7 +101,8 @@ impl NodeNetworkInterface {
None
};
// The grip sits to the left of the leftmost icon, 8px wide but spanning the full layer-vertical-center band
// 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);
@@ -109,8 +113,8 @@ impl NodeNetworkInterface {
);
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
// 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;
@@ -143,7 +147,7 @@ impl NodeNetworkInterface {
}
};
// The layer click target spans the layer and its chain background
// 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);
@@ -176,7 +180,7 @@ impl NodeNetworkInterface {
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");
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.);
@@ -196,7 +200,7 @@ impl NodeNetworkInterface {
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");
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.);
@@ -271,16 +275,16 @@ impl NodeNetworkInterface {
}
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");
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 import_export_position");
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 import_export_position");
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;
@@ -9,14 +9,19 @@ 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)
{
///
/// Takes the changed nodes as a batch, so a run of moves walks the upstream cone once.
pub(crate) fn invalidate_positions(&mut self, node_ids: Vec<NodeId>, network_path: &[NodeId]) {
let encapsulating_layers = node_ids
.iter()
.filter(|node_id| self.is_chain(node_id, network_path))
.filter_map(|node_id| self.downstream_layer_for_chain_node(node_id, network_path))
.collect::<Vec<_>>();
for downstream_layer in encapsulating_layers {
self.unload_node_click_targets(&downstream_layer, network_path);
}
self.unload_upstream_node_click_targets(vec![*node_id], network_path);
self.unload_upstream_node_click_targets(node_ids, network_path);
self.unload_all_nodes_bounding_box(network_path);
}
Loaded 100 of 279 files, more files were not shown because too many files have changed in this diff. Show more